code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
function image(emitFile) { return (context, {addLoader}) => addLoader( Object.assign( { test: /\.(jpe?g|png|gif)$/i, exclude: /ui\/favicons/, use: [ { loader: 'file-loader', options: { emitFile: emitFile, hash: 'sha512', digest: 'hex', name: '[hash].[ext]' } } // { // loader: 'image-webpack-loader', // options: { // optipng: {optimizationLevel: 7}, // gifsicle: {interlaced: false} // } // } ] }, context.match ) ); } module.exports = image;
javascript
17
0.364954
51
22.71875
32
starcoderdata
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include #include #include #include #include namespace AZ { namespace Render { void ImageBasedLightFeatureProcessor::Reflect(ReflectContext* context) { if (auto* serializeContext = azrtti_cast { serializeContext ->Class<ImageBasedLightFeatureProcessor, FeatureProcessor>() ->Version(0); } } void ImageBasedLightFeatureProcessor::Activate() { m_sceneSrg = GetParentScene()->GetShaderResourceGroup(); // Load default specular and diffuse cubemaps // These are assigned when Global IBL is disabled or removed from the scene to prevent a Vulkan TDR. // [GFX-TODO][ATOM-4181] This can be removed after Vulkan is changed to automatically handle this issue. LoadDefaultCubeMaps(); } void ImageBasedLightFeatureProcessor::Deactivate() { m_iblOrientationConstantIndex.Reset(); m_iblExposureConstantIndex.Reset(); m_diffuseEnvMapIndex.Reset(); m_specularEnvMapIndex.Reset(); m_sceneSrg = {}; } void ImageBasedLightFeatureProcessor::Simulate(const FeatureProcessor::SimulatePacket& packet) { AZ_PROFILE_SCOPE(RPI, "ImageBasedLightFeatureProcessor: Simulate"); AZ_UNUSED(packet); m_sceneSrg->SetImage(m_specularEnvMapIndex, m_specular); m_sceneSrg->SetImage(m_diffuseEnvMapIndex, m_diffuse); m_sceneSrg->SetConstant(m_iblExposureConstantIndex, m_exposure); m_sceneSrg->SetConstant(m_iblOrientationConstantIndex, m_orientation); } void ImageBasedLightFeatureProcessor::SetSpecularImage(const Data::Asset imageAsset) { m_specular = GetInstanceForImage(imageAsset, m_defaultSpecularImage); } void ImageBasedLightFeatureProcessor::SetDiffuseImage(const Data::Asset imageAsset) { m_diffuse = GetInstanceForImage(imageAsset, m_defaultDiffuseImage); } void ImageBasedLightFeatureProcessor::SetExposure(float exposure) { m_exposure = exposure; } void ImageBasedLightFeatureProcessor::SetOrientation(const Quaternion& orientation) { m_orientation = orientation; } void ImageBasedLightFeatureProcessor::Reset() { m_specular = m_defaultSpecularImage; m_diffuse = m_defaultDiffuseImage; m_exposure = 0; } void ImageBasedLightFeatureProcessor::LoadDefaultCubeMaps() { const constexpr char* DefaultSpecularCubeMapPath = "textures/default/default_iblglobalcm_iblspecular.dds.streamingimage"; const constexpr char* DefaultDiffuseCubeMapPath = "textures/default/default_iblglobalcm_ibldiffuse.dds.streamingimage"; Data::AssetId specularAssetId; Data::AssetCatalogRequestBus::BroadcastResult( specularAssetId, &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, DefaultSpecularCubeMapPath, azrtti_typeid false); Data::AssetId diffuseAssetId; Data::AssetCatalogRequestBus::BroadcastResult( diffuseAssetId, &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, DefaultDiffuseCubeMapPath, azrtti_typeid false); auto specularAsset = Data::AssetManager::Instance().GetAsset AZ::Data::AssetLoadBehavior::PreLoad); auto diffuseAsset = Data::AssetManager::Instance().GetAsset AZ::Data::AssetLoadBehavior::PreLoad); specularAsset.BlockUntilLoadComplete(); diffuseAsset.BlockUntilLoadComplete(); m_defaultSpecularImage = RPI::StreamingImage::FindOrCreate(specularAsset); AZ_Assert(m_defaultSpecularImage, "Failed to load default specular cubemap"); m_defaultDiffuseImage = RPI::StreamingImage::FindOrCreate(diffuseAsset); AZ_Assert(m_defaultDiffuseImage, "Failed to load default diffuse cubemap"); } Data::Instance ImageBasedLightFeatureProcessor::GetInstanceForImage(const Data::Asset imageAsset, const Data::Instance defaultImage) { Data::Instance image; if (imageAsset.GetId().IsValid()) { image = RPI::StreamingImage::FindOrCreate(imageAsset); if (image && !ValidateIsCubemap(image)) { image = defaultImage; } } return image; } bool ImageBasedLightFeatureProcessor::ValidateIsCubemap(Data::Instance image) { const RHI::ImageDescriptor& desc = image->GetRHIImage()->GetDescriptor(); return (desc.m_isCubemap || desc.m_arraySize == 6); } } // namespace Render } // namespace AZ
c++
17
0.639029
192
39.314685
143
starcoderdata
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using Spine.Unity.Editor; using Spine.Unity.Playables; using UnityEditor; using UnityEngine; [CustomPropertyDrawer(typeof(SpineAnimationStateBehaviour))] public class SpineAnimationStateDrawer : PropertyDrawer { public override float GetPropertyHeight (SerializedProperty property, GUIContent label) { const int fieldCount = 16; return fieldCount * EditorGUIUtility.singleLineHeight; } public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) { SerializedProperty animationReferenceProp = property.FindPropertyRelative("animationReference"); SerializedProperty loopProp = property.FindPropertyRelative("loop"); SerializedProperty customDurationProp = property.FindPropertyRelative("customDuration"); SerializedProperty useBlendDurationProp = property.FindPropertyRelative("useBlendDuration"); SerializedProperty mixDurationProp = property.FindPropertyRelative("mixDuration"); SerializedProperty holdPreviousProp = property.FindPropertyRelative("holdPrevious"); SerializedProperty alphaProp = property.FindPropertyRelative("alpha"); SerializedProperty dontPauseWithDirectorProp = property.FindPropertyRelative("dontPauseWithDirector"); SerializedProperty dontEndWithClip = property.FindPropertyRelative("dontEndWithClip"); SerializedProperty endMixOutDuration = property.FindPropertyRelative("endMixOutDuration"); SerializedProperty eventProp = property.FindPropertyRelative("eventThreshold"); SerializedProperty attachmentProp = property.FindPropertyRelative("attachmentThreshold"); SerializedProperty drawOrderProp = property.FindPropertyRelative("drawOrderThreshold"); // initialize useBlendDuration parameter according to preferences SerializedProperty isInitializedProp = property.FindPropertyRelative("isInitialized"); if (!isInitializedProp.hasMultipleDifferentValues && isInitializedProp.boolValue == false) { useBlendDurationProp.boolValue = SpineEditorUtilities.Preferences.timelineUseBlendDuration; isInitializedProp.boolValue = true; } Rect singleFieldRect = new Rect(position.x, position.y, position.width, EditorGUIUtility.singleLineHeight); float lineHeightWithSpacing = EditorGUIUtility.singleLineHeight + 2f; EditorGUI.PropertyField(singleFieldRect, animationReferenceProp); singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, loopProp); singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, dontPauseWithDirectorProp, new GUIContent("Don't Pause with Director", "If set to true, the animation will continue playing when the Director is paused.")); singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, dontEndWithClip, new GUIContent("Don't End with Clip", "Normally when empty space follows the clip on the timeline, the empty animation is set on the track. " + "Set this parameter to true to continue playing the clip's animation instead.")); singleFieldRect.y += lineHeightWithSpacing; using (new EditorGUI.DisabledGroupScope(dontEndWithClip.boolValue == true)) { EditorGUI.PropertyField(singleFieldRect, endMixOutDuration, new GUIContent("Clip End Mix Out Duration", "When 'Don't End with Clip' is false, and the clip is followed by blank space or stopped, " + "the empty animation is set with this MixDuration. When set to a negative value, " + "the clip is paused instead.")); } singleFieldRect.y += lineHeightWithSpacing * 0.5f; singleFieldRect.y += lineHeightWithSpacing; EditorGUI.LabelField(singleFieldRect, "Mixing Settings", EditorStyles.boldLabel); singleFieldRect.y += lineHeightWithSpacing; customDurationProp.boolValue = !EditorGUI.Toggle(singleFieldRect, new GUIContent("Default Mix Duration", "Use the default mix duration as specified at the SkeletonDataAsset."), !customDurationProp.boolValue); bool greyOutCustomDurations = (!customDurationProp.hasMultipleDifferentValues && customDurationProp.boolValue == false); using (new EditorGUI.DisabledGroupScope(greyOutCustomDurations)) { singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, useBlendDurationProp); singleFieldRect.y += lineHeightWithSpacing; bool greyOutMixDuration = (!useBlendDurationProp.hasMultipleDifferentValues && useBlendDurationProp.boolValue == true); using (new EditorGUI.DisabledGroupScope(greyOutMixDuration)) { EditorGUI.PropertyField(singleFieldRect, mixDurationProp); } } singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, holdPreviousProp); singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, eventProp); singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, attachmentProp); singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, drawOrderProp); singleFieldRect.y += lineHeightWithSpacing; EditorGUI.PropertyField(singleFieldRect, alphaProp); } }
c#
17
0.780142
109
48.40146
137
starcoderdata
mpz_class newton(int a, int n) { mpf_set_default_prec(1000000); // Increase this number. mpz_class x, aMPZ; aMPZ = a; x = a; for (int i=0; i<n; i++) { x = x - (x*x - aMPZ)/(2.0*x); } gmp_printf("%.10Ff\n", x.get_mpz_t()); // increase this number. return x; }
c++
12
0.513423
67
26.181818
11
inline
#include<bits/stdc++.h> using namespace std; using UL = unsigned int; using ULL = unsigned long long; using LL = long long; #define rep(i, n) for(UL i = 0; i < (n); i++) UL G[200000]; string AL = "abcdefghijklmnopqrstuvwxyz"; struct RSQ { UL N; vector<UL> V; void init(UL n) { N = 1; while (N < n) N <<= 1; V.resize(N * 2 - 1); rep(i, n) V[i + N - 1] = 1; for (UL i = N - 2; i != ~0u; i--) V[i] = V[(i << 1) + 1] + V[(i << 1) + 2]; } void upd(UL p, UL v) { UL i = p + N - 1; V[i] += v; while (i) { i = (i - 1) >> 1; V[i] += v; } } UL query(UL l, UL r, UL a = ~0u, UL b = ~0u, UL i = ~0u) { if (i == ~0u) { a = i = 0; b = N; } if (r <= a || b <= l) { return 0; } if (l <= a && b <= r) { return V[i]; } auto q1 = query(l, r, a, (a + b) >> 1, (i << 1) + 1); auto q2 = query(l, r, (a + b) >> 1, b, (i << 1) + 2); return q1 + q2; } UL search(UL v, UL a = ~0u, UL b = ~0u, UL i = ~0u) { if (i == ~0u) { a = i = 0; b = N; } if (v == 0) { return 0; } if (v >= V[i]) { return b - a; } if (b - a == 1) { return 0; } auto q1 = search(v, a, (a + b) >> 1, (i << 1) + 1); if (q1 != (b - a) >> 1) return q1; auto q2 = search(v - V[(i << 1) + 1], (a + b) >> 1, b, (i << 1) + 2); return q1 + q2; } }; struct RMQ { UL N; vector<pair<UL, UL>> V; void init(UL n) { N = 1; while (N < n) N <<= 1; V.resize(N * 2 - 1); rep(i, n) V[i + N - 1] = { G[i], i }; for (UL i = N - 2; i != ~0u; i--) V[i] = min(V[(i << 1) + 1], V[(i << 1) + 2]); } void upd(UL p, UL v = ~0u) { UL i = p + N - 1; V[i].first = v; while (i) { i = (i - 1) >> 1; V[i] = min(V[(i << 1) + 1], V[(i << 1) + 2]); } } pair<UL, UL> query(UL l, UL r, UL a = ~0u, UL b = ~0u, UL i = ~0u) { if (i == ~0u) { a = i = 0; b = N; } if (r <= a || b <= l) { return { ~0u, ~0u }; } if (l <= a && b <= r) { return V[i]; } auto q1 = query(l, r, a, (a + b) >> 1, (i << 1) + 1); auto q2 = query(l, r, (a + b) >> 1, b, (i << 1) + 2); return min(q1, q2); } }; RMQ Q; RSQ I; RSQ J; string ans; int main() { string S; UL K; cin >> S >> K; UL N; N = S.size(); { vector<pair<UL, UL>> D(N); rep(i, N) D[i] = { AL.find(S[i]), i }; sort(D.begin(), D.end()); rep(i, N) G[D[i].second] = i; } Q.init(N); I.init(N); J.init(N); rep(i, N) { auto p = Q.query(0, min(N, J.search(min(K + 1, N)))).second; //printf("J=%u, ", min(N, J.search(min(K + 1, N)))); ans.push_back(S[p]); UL k = J.query(0, p); I.upd(k, 1); J.upd(p, (UL)-1); Q.upd(p); K -= k; //printf("p=%u, k=%u, K=%u, ans=%s\n", p, k, K, ans.c_str()); } cout << ans << endl; return 0; }
c++
17
0.417848
71
21.903509
114
codenet
import numpy as np import pytest import torch from layers.DPLayer import DPLayer from microstructure import utils from scipy.optimize import approx_fprime from torchvision import transforms, datasets _epsilon = np.sqrt(np.finfo(float).eps) PARAMS=[('diff_squared',0),('sum_squared',0),('diff_squared',1),('sum_squared',1)] PARAMS=[('diff_squared',1)] def make_data(): dir = '/data/datasets/two_phase_morph/morph_global_64_train_255.h5' dataset = utils.MicrostructureDataset(dir) train_loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True) data=next(iter(train_loader)) return data.squeeze(0) def make_mnist_data(): data_transform = transforms.Compose([ transforms.Resize(32), transforms.ToTensor(), transforms.Normalize(mean=[0.1307], std=[0.3801]) ]) data_dir = '/data/MNIST' print('data_dir:', data_dir) mnist_data = datasets.MNIST(data_dir, download=False, transform=data_transform) train_loader = torch.utils.data.DataLoader(mnist_data, batch_size=1, shuffle=True) images, _ = next(iter(train_loader)) return images.squeeze(0) def custom_check_grad(func, grad, x0, *args, **kwargs): """Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient. Parameters ---------- func : callable ``func(x0, *args)`` Function whose derivative is to be checked. grad : callable ``grad(x0, *args)`` Gradient of `func`. x0 : ndarray Points to check `grad` against forward difference approximation of grad using `func`. args : \\*args, optional Extra arguments passed to `func` and `grad`. epsilon : float, optional Step size used for the finite difference approximation. It defaults to ``sqrt(np.finfo(float).eps)``, which is approximately 1.49e-08. Returns ------- err : float The square root of the sum of squares (i.e., the 2-norm) of the difference between ``grad(x0, *args)`` and the finite difference approximation of `grad` using func at the points `x0`. See Also -------- approx_fprime Examples -------- 2.9802322387695312e-08 """ step = kwargs.pop('epsilon', _epsilon) if kwargs: raise ValueError("Unknown keyword arguments: %r" % (list(kwargs.keys()),)) true_grad= approx_fprime(x0, func, step, *args) approx_grad=grad(x0, *args) return np.sqrt(sum((true_grad- approx_grad)**2)) @pytest.mark.parametrize("edge_fn,max_op",PARAMS) def test_sp_backward(edge_fn,max_op): device = "cuda:0" torch.cuda.set_device(device) data = make_mnist_data() dp_layer=DPLayer(edge_fn,max_op,32,32,True) def grad(X): X = torch.tensor(X).detach() X = X.reshape(data.shape).type(torch.float64).to(device) X.requires_grad = True X.retain_grad() p1 = dp_layer(X) output=p1.mean() output.backward() grad=X.grad.cpu() return grad.view(-1).detach().numpy() def func(X): with torch.no_grad(): Y = torch.tensor(X,dtype=torch.float64,device=device).detach() Y = Y.reshape(data.shape) output = dp_layer(Y) output=output.sum().cpu() np.array(output,dtype=np.float64) return output.numpy() err = custom_check_grad(func, grad, (data.detach().numpy()).ravel()) assert err < 1e-6
python
16
0.623196
86
31.178571
112
starcoderdata
<?php use App\Http\Controllers\AdminController; use App\Http\Controllers\AssesmentController; use App\Http\Controllers\BioetikController; use App\Http\Controllers\HistoryAssesmentController; use App\Http\Controllers\KonselorController; use App\Http\Controllers\KonsultasiController; use App\Http\Controllers\KritikSaranController; use App\Http\Controllers\MahasiswaController; use App\Http\Controllers\RekamMedikController; use App\Http\Controllers\ArtikelController; use App\Http\Controllers\AuthController; use App\Http\Middleware\Authenticate; use Doctrine\DBAL\Schema\Index; use Illuminate\Support\Facades\Route; use PharIo\Manifest\AuthorCollection; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', [ AuthController::class, 'index' ])->name('login')->middleware('guest'); Route::post('/authenticate', [ AuthController::class, 'authenticate' ]); Route::post('/logout', [ AuthController::class, 'logout' ]); // Middelware Route::group(['middleware' => ['auth', 'cekrole:admin']], function () { Route::resource('/admin/dashboard', AdminController::class); Route::resource('/admin/assesment', AssesmentController::class); Route::resource('/admin/konselor', KonselorController::class); Route::resource('/admin/mahasiswa', MahasiswaController::class); Route::resource('/admin/bioetik', BioetikController::class); Route::resource('/admin/rekam_medik', RekamMedikController::class); Route::resource('/admin/kritik_saran', KritikSaranController::class); Route::resource('/admin/konsultasi', KonsultasiController::class); Route::resource('/admin/artikel', ArtikelController::class); });
php
12
0.698246
75
31.177419
62
starcoderdata
const { uniq } = require('lodash') const { getEntitiesLabels } = require('./get_entities_labels') const formatJsObj = text => { return text .split('\n') .map((line, index) => { const indentation = index === 0 ? '' : ' ' return indentation + line // Remove keys quotes when possible .replace(/^(\s+)"([a-zA-Z]\w+)":\s/, '$1$2: ') // Alternatively, replace them by single quotes .replace(/^(\s+)"([^"']+)":\s/, '$1\'$2\': ') // Remove values quotes when possible .replace(/:\s"([^"']+)"(,?)$/g, ': \'$1\'$2') // Even when the value is on its own line .replace(/^(\s+)"([^"']+)"(,?)$/g, '$1\'$2\'$3') }) .join('\n') } const entityIdPattern = /(Q|P|L)[1-9]\d*/g const collectEntitiesIds = json => { const ids = json.match(entityIdPattern) return uniq(ids) } const enrichLine = entitiesLabels => line => { const commentLine = getCommentLine(line, entitiesLabels) if (commentLine) return `${commentLine}\n${line}` else return line } const snakPropertyWithDirectEntityValuePattern = /^(\s+)(P[1-9]\d*): '((Q|P|L)[1-9]\d*)'/ const snakPropertyPattern = /^(\s+)(P[1-9]\d*): / const entityRichValuePattern = /^(\s+)value: '((Q|P|L)[1-9]\d*)'/ const directEntityValuePerLinePattern = /^(\s+)'((Q|P|L)[1-9]\d*)',?$/ const getCommentLine = (line, entitiesLabels) => { const snakPropertyWithDirectEntityValueMatch = line.match(snakPropertyWithDirectEntityValuePattern) if (snakPropertyWithDirectEntityValueMatch) { const indentation = snakPropertyWithDirectEntityValueMatch[1] const propertyId = snakPropertyWithDirectEntityValueMatch[2] const entityId = snakPropertyWithDirectEntityValueMatch[3] const propertyLabel = entitiesLabels[propertyId] const entityLabel = entitiesLabels[entityId] if (propertyLabel) return `${indentation}// ${propertyLabel}: ${entityLabel}` } let commentLine commentLine = getPatternComment(line, snakPropertyPattern, entitiesLabels) if (commentLine) return commentLine commentLine = getPatternComment(line, entityRichValuePattern, entitiesLabels) if (commentLine) return commentLine commentLine = getPatternComment(line, directEntityValuePerLinePattern, entitiesLabels) if (commentLine) return commentLine } const getPatternComment = (line, pattern, entitiesLabels) => { const match = line.match(pattern) if (match) { const indentation = match[1] const id = match[2] const label = entitiesLabels[id] if (label) return `${indentation}// ${label}` } } module.exports = async (entity, lang) => { const json = JSON.stringify(entity, null, 2) // Use the classic syntax function to avoid the implicit return syntax // which might be confusion to users unfamiliar with JS const file = `module.exports = function () { return ${formatJsObj(json)} }` const entitiesIds = collectEntitiesIds(json) const entitiesLabels = await getEntitiesLabels(entitiesIds, lang) return file.split('\n').map(enrichLine(entitiesLabels)).join('\n') }
javascript
23
0.68238
101
35.036145
83
starcoderdata
""" Test the steps needed to generate wild type and mutant data for use in the statistical analysis Usage: pytest -qq -m "not notest" test_data_generation.py The use of -m "not notest" is to be able to omit certain tests with the @pytest.mark.notest decorator """ from pathlib import Path from lama.registration_pipeline import run_lama import logzero import os import shutil import pytest import logging from lama.scripts import lama_job_runner from lama.tests import (registration_root, mut_registration_dir, wt_registration_dir) def delete_previous_files(): """ Remove the output generated from previous tests. This does not occur directly after the test as we may want to look at the results. """ def delete(root: Path): shutil.rmtree(root / 'output', ignore_errors=True) for p in root.iterdir(): if str(p).endswith(('.log', 'jobs.csv', 'csv.lock', '.yaml')): p.unlink() delete(wt_registration_dir) delete(mut_registration_dir) # @pytest.mark.notest def test_lama_job_runner(): """ Test the lama job runner which was made to utilise multiple machines or the grid. This test just uses one machine for the tests at the moment. test_make_jobs_file() should run before this to create a jobs file that can be consumed. This test should be run before the stats test as it creates data that the stats test needs. NOTE this test should be at bottom of file as it should be ru last The oututs of these tests are consumed by the stats test. """ configs = registration_root.glob('*.toml') for cfg in configs: delete_previous_files() print(f"\n{'#'*8} Doing config {cfg.name} {'#'*8}") lama_job_runner.lama_job_runner(cfg, wt_registration_dir, make_job_file=True, log_level=logging.ERROR) lama_job_runner.lama_job_runner(cfg, wt_registration_dir, log_level=logging.ERROR) lama_job_runner.lama_job_runner(cfg, mut_registration_dir, make_job_file=True, log_level=logging.ERROR) lama_job_runner.lama_job_runner(cfg, mut_registration_dir, log_level=logging.ERROR) # return # Just do the first #TODO # QC subset test # # @pytest.mark.notest # def test_make_jobs_file(): # # # config_file = registration_root / 'registration_config.toml' # # lama_job_runner.lama_job_runner(config_file, wt_registration_dir, make_job_file=True) # lama_job_runner.lama_job_runner(config_file, mut_registration_dir, make_job_file=True) # # @pytest.mark.notest # def test_lama_job_runner_reverse_reg_only(): # """ # Tests out doing only the propagation of atlas to input images. The first stage of the noraml foraward registration # of input the pop abg is carried out. This creates the rigid registered input which is then used as target to # map atlas to. # """ # config_file = registration_root / 'registration_config_reverse_reg_only.toml' # assert lama_job_runner.lama_job_runner(config_file, mut_registration_dir) is True # # @pytest.mark.notest # def test_lama_job_runner_pyramid(): # """ # map atlas to. # """ # config_file = registration_root / 'registration_config.toml' # assert lama_job_runner.lama_job_runner(config_file, mut_registration_dir) is True # # # @pytest.mark.notest # def test_lama_reg(): # """ # Test using the lama registration script without jaob runner wrapepr # Returns # ------- # # """ # # delete_previous_files() # config_file = registration_root / 'registration_config.toml' # # Needs to be in same folder as inputs # dest = wt_registration_dir / 'registration_config.toml' # # shutil.copyfile(config_file, dest) # assert run_lama.run(dest) is True # # # # # @pytest.mark.notest # def test_lama_job_runner_secondary_segmentation(): # """ # Tests out doing only the propagation of atlas to input images. The first stage of the noraml foraward registration # of input the pop abg is carried out. This creates the rigid registered input which is then used as target to # map atlas to. # """ # config_file = registration_root / 'registration_config_reverse_reg_only.toml' # assert lama_job_runner.lama_job_runner(config_file, mut_registration_dir) is True
python
12
0.689583
120
32.787402
127
starcoderdata
package com.openalpr.jni; import java.io.File; import java.net.InetSocketAddress; /** * App specific configuration. * * @author arun */ public class Constants { public static final String SERVER_DIRECTORY = "./"; public static final int MAX_NUM_OF_PLATES = 50; public static final String RUNTIME_ASSET_DIR_LINUX = "/usr/share/openalpr/runtime_data"; public static final String OPEN_ALPR_CONF_FILE_LINUX = "/etc/openalpr/openalpr.conf"; // Max size of pixels to process either at width or height (original picture should be compressed to this max size). public static int maxSizeOfPictureToProcess = 1600; }
java
6
0.731975
120
30.9
20
starcoderdata
using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { string[] lines = System.IO.File.ReadAllLines("in.txt"); // MapExercise me = new MapExercise(); // me.run(lines); // PriorityQueue pq = new PriorityQueue // pq.Add(12, 12); // pq.Add(13, 13); // pq.Add(2, 2); // Console.WriteLine(pq.RemoveMin()); // Console.WriteLine(pq.Peek()); // Console.WriteLine(pq.RemoveMin()); // Console.WriteLine(pq.RemoveMin()); // CustomSort cs = new CustomSort(); // cs.manageCustomSort(lines); // SegmentTree sg = new SegmentTree(); // sg.manageSegmentTree(); // string s = " // char[] sc = s.ToCharArray(); // int[] occ = new int[26]; // for (int i = 0; i < 26; i++) occ[i] = 0; // for (int i = 0; i < sc.Length; i++) { // if (sc[i] == ' ') continue; // if (sc[i] >= 'A' && sc[i] <= 'Z') sc[i] = (char) ((int) sc[i] - (int) 'A' + (int) 'a'); // occ[(int) sc[i] - (int) 'a']++; // } // for (int i = 0; i < 26; i++) { // if (occ[i] > 0) { // Console.WriteLine("{0} {1}", (char) (i + (int) 'a'), occ[i]); // } // } BinarySearchTree bst = new BinarySearchTree(); bst.manageBinarySearch(); } }
c#
13
0.449529
102
31.818182
44
starcoderdata
public static void save(Object obj, File file) { if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } Writer w = null; try { w = getWriter(file); XStreamUtils.serialiseToXml(w, obj); } finally { close(w); // release the file handle } }
java
9
0.630435
48
22.083333
12
inline
/** * */ package jflow.iterators.impl.fold; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.OptionalLong; import java.util.function.LongBinaryOperator; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import jflow.iterators.AbstractLongFlow; import jflow.testutilities.IteratorExampleProvider; /** * @author ThomasB */ class AbstractLongFlowReductionConsumptionTest extends IteratorExampleProvider { @ParameterizedTest @MethodSource("reductionWithoutIdTestDataProvider") void testReductionWithoutId(final LongBinaryOperator reducer, final Long expectedPopulatedResult) { final AbstractLongFlow populated = getLongTestIteratorProvider().iterator(); final OptionalLong reduction = populated.foldOption(reducer); assertTrue(reduction.isPresent()); assertEquals(expectedPopulatedResult.longValue(), reduction.getAsLong()); final AbstractLongFlow empty = getEmptyLongTestIteratorProvider().iterator(); assertFalse(empty.foldOption(reducer).isPresent()); } static Stream reductionWithoutIdTestDataProvider() { return Stream.of( Arguments.of((LongBinaryOperator) (x1, x2) -> x1 + x2, 10L) ); } @ParameterizedTest @MethodSource("reductionWithIdTestDataProvider") void testReductionWithId(final Long id, final LongBinaryOperator reducer, final Long expectedPopulatedResult) { final AbstractLongFlow populated = getLongTestIteratorProvider().iterator(); final long reduction = populated.fold(id.longValue(), reducer); assertEquals(expectedPopulatedResult.longValue(), reduction); final AbstractLongFlow empty = getEmptyLongTestIteratorProvider().iterator(); assertEquals(id.longValue(), empty.fold(id.longValue(), reducer)); } static Stream reductionWithIdTestDataProvider() { return Stream.of( Arguments.of(0L, (LongBinaryOperator) (x1, x2) -> x1 + x2, 10L) ); } @ParameterizedTest @MethodSource("countReductionTestDataProvider") void testCounting(final AbstractLongFlow iterator, final Integer expectedCount) { assertEquals(expectedCount.longValue(), iterator.count()); } static Stream countReductionTestDataProvider() { return Stream.of( Arguments.of(getLongTestIteratorProvider().iterator(), 5), Arguments.of(getSmallLongTestIteratorProvider().iterator(), 2), Arguments.of(getLargeLongTestIteratorProvider().iterator(), 6), Arguments.of(getEmptyLongTestIteratorProvider().iterator(), 0) ); } }
java
11
0.790393
110
32.512195
82
starcoderdata
import numpy as np import sys import scipy.integrate as integrate from scipy.integrate import cumtrapz from scipy import special,stats from .function import * class Post_nested: ''' ##################### # Function for MCMC ##################### ''' def __init__(self, mainbody, params=None): self.mb = mainbody self.params = params def residual(self, pars, fy, ey, wht, f_fir=False, out=False): ''' Input: ====== out : model as second output. For lnprob func. f_fir : Bool. If dust component is on or off. Returns: ======== residual of model and data. ''' vals = pars #.valuesdict() model, x1 = self.mb.fnc.tmp04(vals) if self.mb.f_dust: model_dust, x1_dust = self.mb.fnc.tmp04_dust(vals) n_optir = len(model) # Add dust flux to opt/IR grid. model[:] += model_dust[:n_optir] # then append only FIR flux grid. model = np.append(model,model_dust[n_optir:]) x1 = np.append(x1,x1_dust[n_optir:]) if self.mb.ferr: try: f = vals['f'] except: f = 0 else: f = 0 # temporary... (if f is param, then take from vals dictionary.) #con_res = (model>0) & (wht>0) #& (ey>0) sig = np.sqrt(1./wht + (f**2*model**2)) if fy is None: print('Data is none') resid = model #[con_res] else: resid = (model - fy) / sig if not out: return resid # i.e. residual/sigma. Because is_weighted = True. else: return resid, model # i.e. residual/sigma. Because is_weighted = True. def get_dict(self, pars): ii = 0 for key in self.params: if self.params[key].vary: self.params[key].value = pars[ii] ii += 1 return self.params def residual_nest(self, pars, fy, ey, wht, f_fir=False, out=False): ''' Input: ====== out : model as second output. For lnprob func. f_fir : Bool. If dust component is on or off. Returns: ======== residual of model and data. ''' vals = self.get_dict(pars) model, x1 = self.mb.fnc.tmp04(vals) if self.mb.f_dust: model_dust, x1_dust = self.mb.fnc.tmp04_dust(vals) n_optir = len(model) # Add dust flux to opt/IR grid. model[:] += model_dust[:n_optir] # then append only FIR flux grid. model = np.append(model,model_dust[n_optir:]) x1 = np.append(x1,x1_dust[n_optir:]) if self.mb.ferr: try: f = vals['f'] except: f = 0 else: f = 0 # temporary... (if f is param, then take from vals dictionary.) #con_res = (model>0) & (wht>0) #& (ey>0) sig = np.sqrt(1./wht + (f**2*model**2)) if fy is None: print('Data is none') resid = model #[con_res] else: resid = (model - fy) / sig if not out: return resid # i.e. residual/sigma. Because is_weighted = True. else: return resid, model # i.e. residual/sigma. Because is_weighted = True. def func_tmp(self, xint, eobs, fmodel): ''' A function used for chi2 calculation for non-detection in lnprob. ''' int_tmp = np.exp(-0.5 * ((xint-fmodel)/eobs)**2) return int_tmp def prior_transform(self, pars): """ A function defining the tranform between the parameterisation in the unit hypercube to the true parameters. Args: theta (tuple): a tuple containing the parameters. Returns: tuple: a new tuple or array with the transformed parameters. """ #prior = np.zeros(len(pars),'float') if True: ii = 0 for key in self.params: if self.params[key].vary: cmin = self.params[key].min cmax = self.params[key].max cprim = pars[ii] pars[ii] = cprim*(cmax-cmin) + cmin ii += 1 ''' mmu = 0. # mean of Gaussian prior on m msigma = 10. # standard deviation of Gaussian prior on m m = mmu + msigma*ndtri(mprime) # convert back to m ''' return pars def lnlike(self, pars, fy, ey, wht, f_fir, f_chind=True, SNlim=1.0, lnpreject=-np.inf): ''' Returns: ======== log likelihood Note: ===== This is a copy from lnprob, with respr=0. ''' vals = pars#.valuesdict() if self.mb.ferr == 1: f = vals['f'] else: f = 0 resid, model = self.residual_nest(pars, fy, ey, wht, f_fir, out=True) con_res = (model>=0) & (wht>0) & (fy>0) & (ey>0) # Instead of model>0; model>=0 is for Lyman limit where flux=0. This already exclude upper limit. sig_con = np.sqrt(1./wht[con_res]+f**2*model[con_res]**2) # To avoid error message. chi_nd = 0.0 con_up = (ey>0) & (fy/ey<=SNlim) if f_chind and len(fy[con_up])>0: x_erf = (ey[con_up]/SNlim - model[con_up]) / (np.sqrt(2) * ey[con_up]/SNlim) f_erf = special.erf(x_erf) if np.min(f_erf) <= -1: return lnpreject else: chi_nd = np.sum( np.log(np.sqrt(np.pi / 2) * ey[con_up]/SNlim * (1 + f_erf)) ) lnlike = -0.5 * (np.sum(resid[con_res]**2 + np.log(2 * 3.14 * sig_con**2)) - 2 * chi_nd) else: lnlike = -0.5 * (np.sum(resid[con_res]**2 + np.log(2 * 3.14 * sig_con**2))) return lnlike def lnprob(self, pars, fy, ey, wht, f_fir, f_chind=True, SNlim=1.0, lnpreject=-np.inf): ''' Returns: ======== log posterior ''' vals = pars #.valuesdict() if self.mb.ferr == 1: f = vals['f'] else: f = 0 resid, model = self.residual(pars, fy, ey, wht, f_fir, out=True) con_res = (model>=0) & (wht>0) & (fy>0) & (ey>0) # Instead of model>0; model>=0 is for Lyman limit where flux=0. This already exclude upper limit. sig_con = np.sqrt(1./wht[con_res]+f**2*model[con_res]**2) # To avoid error message. chi_nd = 0.0 con_up = (ey>0) & (fy/ey<=SNlim) if f_chind and len(fy[con_up])>0: x_erf = (ey[con_up]/SNlim - model[con_up]) / (np.sqrt(2) * ey[con_up]/SNlim) f_erf = special.erf(x_erf) if np.min(f_erf) <= -1: return lnpreject else: chi_nd = np.sum( np.log(np.sqrt(np.pi / 2) * ey[con_up]/SNlim * (1 + f_erf)) ) lnlike = -0.5 * (np.sum(resid[con_res]**2 + np.log(2 * 3.14 * sig_con**2)) - 2 * chi_nd) else: lnlike = -0.5 * (np.sum(resid[con_res]**2 + np.log(2 * 3.14 * sig_con**2))) respr = 0 # Flat prior... lnposterior = lnlike + respr return lnposterior
python
23
0.48908
154
29.525
240
starcoderdata
dk_close(chan) { register struct dkchan *dkp; register s ; int init; if (dkkaddr == 0) return(-ENODEV); /* if no init, can't close */ /* ie: can't do dkmaint */ s = splimp() ; dkp = &dkit[chan] ; if (chan == 0) { for (dkp = &dkit[1]; dkp < &dkit[dk_nchan]; dkp++) { if (dkp->dk_state & (DK_OPEN|DK_BUSY|DK_RCV)) { dkp->dk_state |= DK_RESET ; flushall(dkp, 0) ; dkp->dk_state = DK_RESET ; } } dkpanic++ ; kseq = 0 ; pseq = 0 ; #ifdef notdef if(dkubmbuf){ /* only deallocate mem if still allocated */ ubarelse(ui->ui_ubanum, &dkubmbuf); dkubmbuf = NULL; } #endif /* wait for protocols to close channels */ dkactive = -1 ; DELAY(4 * hz) ; /* do a dk_free for all channels */ for (dkp = &dkit[1]; dkp < &dkit[dk_nchan]; dkp++) { dkp->dk_state &= ~DK_LINGR ; } dkactive = 0 ; csr0 = 0 ; /* set kmc to idle mode */ if ((init = dk_init()) < 0) { splx(s) ; return init ; } } else { flushall(dkp, 0) ; dkp->dk_state = DK_LINGR ; /* set while UNIXP protocol closes up channel with DK */ } splx(s) ; return 0; }
c
13
0.551317
65
21.489796
49
inline
#include #include void *thread(void *arg){ printf("Thread : Hello Thread!\n"); return arg; } void main(){ pthread_t tid; int status; status = pthread_create(&tid, NULL, thread, NULL); if(status != 0) perror("Create thread"); pthread_exit(NULL); }
c
8
0.67101
51
16.055556
18
starcoderdata
fn penalty_msat(&self, amount_msat: u64, params: ProbabilisticScoringParameters) -> u64 { let max_liquidity_msat = self.max_liquidity_msat(); let min_liquidity_msat = core::cmp::min(self.min_liquidity_msat(), max_liquidity_msat); if amount_msat <= min_liquidity_msat { 0 } else if amount_msat >= max_liquidity_msat { if amount_msat > max_liquidity_msat { u64::max_value() } else if max_liquidity_msat != self.capacity_msat { // Avoid using the failed channel on retry. u64::max_value() } else { // Equivalent to hitting the else clause below with the amount equal to the // effective capacity and without any certainty on the liquidity upper bound. let negative_log10_times_2048 = NEGATIVE_LOG10_UPPER_BOUND * 2048; self.combined_penalty_msat(amount_msat, negative_log10_times_2048, params) } } else { let numerator = (max_liquidity_msat - amount_msat).saturating_add(1); let denominator = (max_liquidity_msat - min_liquidity_msat).saturating_add(1); if amount_msat - min_liquidity_msat < denominator / PRECISION_LOWER_BOUND_DENOMINATOR { // If the failure probability is < 1.5625% (as 1 - numerator/denominator < 1/64), // don't bother trying to use the log approximation as it gets too noisy to be // particularly helpful, instead just round down to 0 and return the base penalty. params.base_penalty_msat } else { let negative_log10_times_2048 = approx::negative_log10_times_2048(numerator, denominator); self.combined_penalty_msat(amount_msat, negative_log10_times_2048, params) } } }
rust
16
0.70529
90
48.65625
32
inline
public void run() { try { if (requestedFile.startsWith("/@")) { deliverSpecial(); } else if (requestedFile.endsWith("/")) {// this is a directory deliverDir(); } else { // this is a file deliverFile(); } } catch (IOException e) { System.err.println(e); } finally { try { client.close(); } catch (IOException e) { } ; } }
java
11
0.354561
73
22.28
25
inline
enum class RaliColorFormat { RGB24 = 0, BGR24, U8, RGB_PLANAR, }; /*! \brief Memory type, host or device * * Currently supports HOST and OCL, will support HIP in future */ enum class RaliMemType { HOST = 0, OCL }; struct Timing { // The following timings are accumulated timing not just the most recent activity long long unsigned image_read_time= 0; long long unsigned image_decode_time= 0; long long unsigned to_device_xfer_time= 0; long long unsigned from_device_xfer_time= 0; long long unsigned copy_to_output = 0; long long unsigned image_process_time= 0; long long unsigned bb_process_time= 0; long long unsigned mask_process_time= 0; long long unsigned label_load_time= 0; long long unsigned bb_load_time= 0; long long unsigned mask_load_time = 0; }
c
9
0.679809
85
24.393939
33
inline
import sys import json import aiohttp import asyncpg import discord import traceback from datetime import datetime from discord import Embed from packaging import version from discord.ext import commands, tasks class MyClient(commands.Bot): def __init__(self, conf_data: dict, *args, **kwargs): super().__init__(*args, command_prefix=conf_data["prefix"], intents=discord.Intents().all(), application_id=conf_data["application_id"], **kwargs) self.session = None self.db = None self.__TOKEN = conf_data.pop("TOKEN") self.conf_data = conf_data self.owner_id = self.conf_data["owner_id"] self.update_channels = None self.remove_command("help") async def on_ready(self) -> None: print(f'Logged in as {self.user} (ID: {self.user.id})') print('------') @tasks.loop(minutes=5) async def update_apps(self) -> None: await self.wait_until_ready() sources = [s['url'] for s in await self.db.fetch("SELECT url FROM sources")] for url in sources: async with self.session.get(url) as response: data = json.loads(await response.text()) for app in data["apps"]: old_app = await self.db.fetchrow(f"SELECT * FROM apps WHERE id = '{app['bundleIdentifier']}'") if old_app is None: await self.db.execute(f"INSERT INTO apps VALUES('{app['bundleIdentifier']}', '{app['name']}', " f"'{app['version']}', '{data['identifier']}')") continue else: if version.parse(app["version"]) > version.parse(old_app['version']): await self.db.execute(f"UPDATE apps SET version='{app['version']}', name='{app['name']}'" f"WHERE id = '{app['bundleIdentifier']}'") emb = Embed(title=f"New {app['name']} update!", color=int(app['tintColor'], 16), timestamp=datetime.now()) emb.add_field(name="Version:", value=f"{old_app['version']} -> {app['version']}", inline=False) emb.add_field(name="Changelog:", value=app['versionDescription'], inline=False) emb.set_thumbnail(url=app['iconURL']) emb.set_footer(text=f"AltBot v. 1.0") for channel in self.update_channels: ping_roles = await self.db.fetch(f"SELECT role_id FROM ping_roles " f"WHERE guild_id = {channel.guild.id} AND " f"appbundle_id = '{app['bundleIdentifier']}'") guild = self.get_guild(channel.guild.id) ret_msg = " ".join([guild.get_role(r["role_id"]).mention for r in ping_roles]) await channel.send(content=ret_msg, embed=emb) async def setup_hook(self) -> None: self.db = await asyncpg.connect(**self.conf_data["postgres"]) print("Connected to postgres!") update_channels = await self.db.fetch("SELECT * FROM update_channels") self.update_channels = [await self.fetch_channel(channel["channel_id"]) for channel in update_channels] self.update_apps.start() for ext in self.conf_data["modules"]: try: await self.load_extension(ext) print(ext) except Exception as e: print(f'Failed to load extension {ext}.', file=sys.stderr) print(f"{type(e).__name__} - {e}") traceback.print_exc() self.session = aiohttp.ClientSession() async def close(self): await self.session.close() await super().close() def run(self): super().run(self.__TOKEN) MyClient(json.load(open("conf.json"))).run()
python
29
0.519932
123
46.837209
86
starcoderdata
module.exports = { server : { host : '127.0.0.1', port : 3002 }, vue : { host : '127.0.0.1', port : 3003 } }
javascript
8
0.493151
61
17.333333
12
starcoderdata
public Matrix4f initTranslation(float x, float y, float z) { // x = -x; data[0][0] = 1; data[0][1] = 0; data[0][2] = 0; data[0][3] = x; data[1][0] = 0; data[1][1] = 1; data[1][2] = 0; data[1][3] = y; data[2][0] = 0; data[2][1] = 0; data[2][2] = 1; data[2][3] = z; data[3][0] = 0; data[3][1] = 0; data[3][2] = 0; data[3][3] = 1; return this; }
java
7
0.444156
60
17.380952
21
inline
import openeo import geopandas as gpd import pandas as pd import time from helper import compute_indices, lin_scale_range from openeo.processes import ProcessBuilder, if_, array_concat from openeo.util import deep_get temporal_partition_options = { "indexreduction": 0, "temporalresolution": "None", "tilesize": 256 } col_palette = {0: (0.9450980392156862, 0.403921568627451, 0.27058823529411763, 1.0), 1: (1.0, 0.7764705882352941, 0.36470588235294116, 1.0), 2: (0.4823529411764706, 0.7843137254901961, 0.6431372549019608, 1.0), 3: (0.2980392156862745, 0.7647058823529411, 0.8509803921568627, 1.0), 4: (0.5764705882352941, 0.39215686274509803, 0.5529411764705883, 1.0), 99: (0.25098039215686274, 0.25098039215686274, 0.25098039215686274, 1.0)} udf_rf = """ from typing import Dict from openeo_udf.api.datacube import DataCube import pickle import urllib.request import xarray import sklearn from openeo.udf.xarraydatacube import XarrayDataCube import functools @functools.lru_cache(maxsize=25) def load_model(): return pickle.load(urllib.request.urlopen("https://artifactory.vgt.vito.be:443/auxdata-public/openeo/rf_model_s2only.pkl")) def impute(a): a[np.isnan(a)] = np.int16(np.nanmean(a)) return a def apply_datacube(cube: XarrayDataCube, context: dict) -> XarrayDataCube: array = cube.get_array() stacked_array = array.stack(pixel=("x","y")) stacked_array = stacked_array.transpose() stacked_array_f = stacked_array[~np.isnan(stacked_array).all(axis=1)] nr_feats = 10 int_ars = [] for rng in [range(nr_feats*i,nr_feats*i+nr_feats) for i in range(len(stacked_array_f[0])//nr_feats)]: ar = stacked_array_f[:,rng] np.apply_along_axis(impute, 1, ar) int_ars.append(ar) stacked_array_filtered = np.concatenate(int_ars,axis=1) if len(stacked_array_filtered) == 0: result = np.full(np.multiply(*array.shape[1:]),np.nan) else: clf = load_model() probs = clf.predict_proba(stacked_array_filtered) pred_array = np.argmax(probs,axis=1) none_indices = np.where(np.amax(probs,axis=1)<0.5) pred_array[none_indices] = 99 result = np.full(len(stacked_array),np.nan) result[~np.isnan(stacked_array).all(axis=1)] = pred_array da = xarray.DataArray(np.transpose(result.reshape(array.shape[1:])),coords=[array.coords["x"],array.coords["y"]], dims=["x","y"]) return DataCube(da) """ def read_or_create_csv(grid, index): try: status_df = pd.read_csv(csv_path.format(index), index_col=0) except FileNotFoundError: status_df = pd.DataFrame(columns=["name", "status", "id", "cpu", "memory", "duration"]) for i in range(len(grid)): status_df = status_df.append( {"name": grid.name[i], "status": "pending", "id": None, "cpu": None, "memory": None, "duration": None}, ignore_index=True) status_df.to_csv(csv_path.format(index)) return status_df def computeStats(input_timeseries:ProcessBuilder): tsteps = list([input_timeseries.array_element(6*index) for index in range(0,6)]) return array_concat(array_concat(input_timeseries.quantiles(probabilities=[0.1,0.5,0.9]),input_timeseries.sd()),tsteps) def rf_classification(bbox, con=None, udf=udf_rf, year=2020): temp_ext = [str(year-1)+"-09-01", str(year+1)+"-04-30"] spat_ext = bbox ### Sentinel 2 data s2 = con.load_collection("TERRASCOPE_S2_TOC_V2", temporal_extent=temp_ext, spatial_extent=spat_ext, bands=["B03","B04","B05","B06","B07","B08","B11","B12","SCL"]) s2._pg.arguments['featureflags'] = temporal_partition_options s2 = s2.process("mask_scl_dilation", data=s2, scl_band_name="SCL").filter_bands(s2.metadata.band_names[:-1]) ### Cropland mask cropland_mask = con.load_collection("TEST_LAYER", temporal_extent=temp_ext, spatial_extent=spat_ext, bands=["Map"] ) cropland_mask._pg.arguments['featureflags'] = temporal_partition_options cropland_mask = cropland_mask.band("Map") != 40 s2 = s2.mask(cropland_mask.resample_cube_spatial(s2).max_time()) ### Base feature calculation idx_list = ["NDVI","NDMI","NDGI","ANIR","NDRE1","NDRE2","NDRE5"] s2_list = ["B06","B12"] indices = compute_indices(s2, idx_list, 250).filter_bands(s2_list+idx_list) idx_dekad = indices.aggregate_temporal_period(period="dekad", reducer="mean") idx_dekad = idx_dekad.apply_dimension(dimension="t", process="array_interpolate_linear").filter_temporal([str(year)+"-01-01", str(year)+"-12-31"]) base_features = idx_dekad.rename_labels("bands",s2_list+idx_list) ### Advanced feature calculation features = base_features.apply_dimension(dimension='t',target_dimension='bands', process=computeStats) tstep_labels = [ "t"+ str(6*index) for index in range(0,6) ] features = features.rename_labels('bands',[band + "_" + stat for band in base_features.metadata.band_names for stat in ["p10","p50","p90","sd"] + tstep_labels ]) clf_results = features.apply_dimension(code=udf_rf, runtime="Python", dimension="bands").rename_labels("bands",["pixel"]).apply(lambda x: x.linear_scale_range(0,250,0,250)) return clf_results def process_area(con=None, area=None, callback=None, tmp_ext=None, folder_path=None, frm="GTiff", minimum_area=0.5, parallel_jobs=1): """ TODO: maak iets waarmee het asynchroon kan draaien? TODO: callback functie maken ipv hier in dit script draaien This function processes splits up the processing of large areas in several batch jobs. The function does not return anything but saves the batch jobs in a folder specified by folder_path and in the format specified by format :param con: a connection with one of the openeo backends :param area: a path to a geojson file :param nr_jobs: amount of batch jobs in which you want to split the area :param callback: a callback function with the operations that need to be run :param tmp_ext: the temporal extent for which to run the operation :param folder_path: folder_path in which to save the resulting batch jobs :param frm: the format in which to save the results """ if frm=="netCDF": ext = ".nc" elif frm=="GTiff": ext = ".tif" else: raise NotImplementedError("This format is not yet implemented") geoms = gpd.read_file(area) # selective reading, requires geopandas>=0.7.0 grid_tot = gpd.read_file("https://s3.eu-central-1.amazonaws.com/sh-batch-grids/tiling-grid-2.zip", mask=geoms) for index, geom in enumerate(geoms.geometry): intersection = grid_tot.geometry.intersection(geom) # filter on area grid_tot = grid_tot[intersection.area > minimum_area] bounds = geom.bounds grid = grid_tot.cx[bounds[0]:bounds[2], bounds[1]:bounds[3]].reset_index() print("The bounding box of the geometry you selected contains a total of " + str( len(grid)) + " grid tiles. Not all of these will actually overlap with the specific geometry shape you supplied") status_df = read_or_create_csv(grid, index) not_finished = len(status_df[status_df["status"] != "finished"]) downloaded_results = [] printed_errors = [] while not_finished: def running_jobs(): return status_df.loc[(status_df["status"] == "queued") | (status_df["status"] == "running")].index def update_statuses(): default_usage = { 'cpu':{'value':0, 'unit':''}, 'memory':{'value':0, 'unit':''} } for i in running_jobs(): job_id = status_df.loc[i, 'id'] job = con.job(job_id).describe_job() usage = job.get('usage',default_usage) status_df.loc[i, "status"] = job["status"] status_df.loc[i, "cpu"] = f"{deep_get(usage,'cpu','value',default=0)} {deep_get(usage,'cpu','unit',default='')}" status_df.loc[i, "memory"] = f"{deep_get(usage,'memory','value',default=0)} {deep_get(usage,'memory','unit',default='')}" status_df.loc[i, "duration"] = deep_get(usage,'duration','value',default=0) print(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime()) + "\tCurrent status of job " + job_id + " is : " + job["status"]) def start_jobs(nb_jobs): pending_jobs = status_df[status_df["status"] == "pending"].index for i in range(min(len(pending_jobs), nb_jobs)): tile = grid.geometry[pending_jobs[i]] if geom.intersects(tile): print("Starting job... current grid tile: " + str(pending_jobs[i])) bbox = tile.bounds lst = ('west', 'south', 'east', 'north') bbox_dict = dict(zip(lst, bbox)) cube = callback(bbox=bbox_dict, con=con) s2_res = cube.save_result(format=frm) job = s2_res.send_job(job_options={ "driver-memory": "2G", "driver-memoryOverhead": "1G", "driver-cores": "2", "executor-memory": "3G", "executor-memoryOverhead": "3G", "executor-cores": "3", "max-executors": "90", }, title="5 countries using S2-only model, tile "+str(pending_jobs[i])+" with bbox "+str(bbox), overviews="ALL", colormap=col_palette ) job.start_job() status_df.loc[pending_jobs[i], "status"] = job.describe_job()["status"] status_df.loc[pending_jobs[i], "id"] = job.describe_job()["id"] else: status_df.loc[pending_jobs[i], "status"] = "finished" def download_results(downloaded_results): finished_jobs = status_df[status_df["status"] == "finished"].index for i in finished_jobs: if i not in downloaded_results: downloaded_results += [i] job_id = status_df.loc[i, 'id'] job = con.job(job_id) print("Finished job: {}, Starting to download...".format(job_id)) results = job.get_results() results.download_file(folder_path + grid.name[i] + ext) def print_errors(printed_errors): error_jobs = status_df[status_df["status"] == "error"].index for i in error_jobs: if i not in printed_errors: printed_errors += [i] print("Encountered a failed job: " + status_df.loc[i, 'id']) update_statuses() start_jobs(parallel_jobs - len(running_jobs())) download_results(downloaded_results) print_errors(printed_errors) not_finished = len(status_df[status_df["status"] != "finished"]) average_duration = status_df.duration.mean() time_left = not_finished * average_duration / parallel_jobs print("Jobs not finished: " + str(not_finished)) print("Average duration: " + str(average_duration) + " time left: " + str(time_left) + " seconds") status_df.to_csv(csv_path.format(index)) time.sleep(45) connection = openeo.connect("https://openeo-dev.vito.be") connection.authenticate_oidc() geom = 'UC3_resources/processing_area.geojson' csv_path = "./data/uc3_job_status.csv" process_area(con=connection, area=geom, callback=rf_classification, folder_path="./data/large_areas/", minimum_area=0.7, parallel_jobs=2)
python
24
0.581839
176
46.30303
264
starcoderdata
namespace FriendlyLocale.Configs { public class AssetsContentConfig : BaseContentConfig { public string ResourceFolder { get; set; } = "Locales"; } }
c#
8
0.682353
63
23.428571
7
starcoderdata
/** * Γράψτε μια περιγραφή της κλάσης Cruiser εδώ. * * @author ( * @version (Αριθμός έκδοσης ή ημερομηνία εδώ) */ public class Cruiser extends Ship { public Cruiser() { super(3); } }
java
5
0.652015
55
17.266667
15
starcoderdata
using System.Collections.Generic; using System.Diagnostics; using ISAAR.MSolve.Analyzers; using ISAAR.MSolve.Discretization.FreedomDegrees; using ISAAR.MSolve.FEM.Entities; using ISAAR.MSolve.LinearAlgebra.Reordering; using ISAAR.MSolve.LinearAlgebra.Vectors; using ISAAR.MSolve.Problems; using ISAAR.MSolve.Solvers.Direct; using ISAAR.MSolve.Solvers.DomainDecomposition.Dual; using ISAAR.MSolve.Solvers.DomainDecomposition.Dual.Feti1; using ISAAR.MSolve.Solvers.DomainDecomposition.Dual.Feti1.Matrices; using ISAAR.MSolve.Solvers.DomainDecomposition.Dual.Preconditioning; using Xunit; namespace ISAAR.MSolve.Solvers.Tests.DomainDecomposition.Dual.Feti1 { /// /// Tests the correctness of the FETI-1 solver, with lumped preconditioner in a simple homogeneous problem. /// Authors: /// public static class SimplePlateTest { private const int singleSubdomainID = 0; [Fact] internal static void Run() { int numElementsX = 20, numElementsY = 10; double factorizationTolerance = 1E-4; // Defining the rigid body modes is very sensitive to this. TODO: The user shouldn't have to specify such a volatile parameter. double equalityTolerance = 1E-6; IVectorView expectedDisplacements = SolveModelWithoutSubdomains(numElementsX, numElementsY); (IVectorView computedDisplacements, SolverLogger logger) = SolveModelWithSubdomains(numElementsX, numElementsY, factorizationTolerance); int pcgIterations = logger.GetNumIterationsOfIterativeAlgorithm(analysisStep: 0); Debug.WriteLine($"Iterations: {pcgIterations}"); Assert.True(expectedDisplacements.Equals(computedDisplacements, equalityTolerance)); } private static Model CreateModel(int numElementsX, int numElementsY) { // if numElementsX = numElementsy: 2: // 6 ----- 7 ----- 8 --> // | (2) | (3) | // | | | // 3 ----- 4 ----- 5 --> // | (0) | (1) | // | | | // 0 ----- 1 ----- 2 --> // Δ Δ // - o var builder = new Uniform2DModelBuilder(); builder.DomainLengthX = 2.0; builder.DomainLengthY = 2.0; builder.NumSubdomainsX = 2; builder.NumSubdomainsY = 2; builder.NumTotalElementsX = numElementsX; builder.NumTotalElementsY = numElementsY; builder.YoungModulus = 2.1E7; builder.PrescribeDisplacement(Uniform2DModelBuilder.BoundaryRegion.LowerLeftCorner, StructuralDof.TranslationX, 0.0); builder.PrescribeDisplacement(Uniform2DModelBuilder.BoundaryRegion.LowerLeftCorner, StructuralDof.TranslationY, 0.0); builder.PrescribeDisplacement(Uniform2DModelBuilder.BoundaryRegion.LowerRightCorner, StructuralDof.TranslationY, 0.0); builder.DistributeLoadAtNodes(Uniform2DModelBuilder.BoundaryRegion.RightSide, StructuralDof.TranslationX, 100.0); return builder.BuildModel(); } private static Model CreateSingleSubdomainModel(int numElementsX, int numElementsY) { // Replace the existing subdomains with a single one Model model = CreateModel(numElementsX, numElementsY); model.SubdomainsDictionary.Clear(); var subdomain = new Subdomain(singleSubdomainID); model.SubdomainsDictionary.Add(singleSubdomainID, subdomain); foreach (Element element in model.Elements) subdomain.Elements.Add(element); return model; } private static (IVectorView U, SolverLogger logger) SolveModelWithSubdomains(int numElementsX, int numElementsY, double factorizationTolerance) { Model multiSubdomainModel = CreateModel(numElementsX, numElementsY); // Solver var factorizationTolerances = new Dictionary<int, double>(); foreach (Subdomain s in multiSubdomainModel.Subdomains) factorizationTolerances[s.ID] = factorizationTolerance; //var fetiMatrices = new DenseFeti1SubdomainMatrixManager.Factory(); //var fetiMatrices = new SkylineFeti1SubdomainMatrixManager.Factory(); var fetiMatrices = new SkylineFeti1SubdomainMatrixManager.Factory(new OrderingAmdSuiteSparse()); var solverBuilder = new Feti1Solver.Builder(fetiMatrices, factorizationTolerances); //solverBuilder.PreconditionerFactory = new LumpedPreconditioner.Factory(); solverBuilder.PreconditionerFactory = new DirichletPreconditioner.Factory(); solverBuilder.ProblemIsHomogeneous = true; Feti1Solver fetiSolver = solverBuilder.BuildSolver(multiSubdomainModel); // Linear static analysis var provider = new ProblemStructural(multiSubdomainModel, fetiSolver); var childAnalyzer = new LinearAnalyzer(multiSubdomainModel, fetiSolver, provider); var parentAnalyzer = new StaticAnalyzer(multiSubdomainModel, fetiSolver, provider, childAnalyzer); // Run the analysis parentAnalyzer.Initialize(); parentAnalyzer.Solve(); // Gather the global displacements var sudomainDisplacements = new Dictionary<int, IVectorView>(); foreach (var ls in fetiSolver.LinearSystems) sudomainDisplacements[ls.Key] = ls.Value.Solution; return (fetiSolver.GatherGlobalDisplacements(sudomainDisplacements), fetiSolver.Logger); } private static IVectorView SolveModelWithoutSubdomains(int numElementsX, int numElementsY) { Model model = CreateSingleSubdomainModel(numElementsX, numElementsY); // Solver SkylineSolver solver = (new SkylineSolver.Builder()).BuildSolver(model); // Linear static analysis var provider = new ProblemStructural(model, solver); var childAnalyzer = new LinearAnalyzer(model, solver, provider); var parentAnalyzer = new StaticAnalyzer(model, solver, provider, childAnalyzer); // Run the analysis parentAnalyzer.Initialize(); parentAnalyzer.Solve(); return solver.LinearSystems[singleSubdomainID].Solution; } } }
c#
16
0.668734
177
48.221374
131
starcoderdata
// SPDX-License-Identifier: GPL-2.0+ /* Interrupt support for Dialog DA9063 * * Copyright 2012 Dialog Semiconductor Ltd. * Copyright 2013 Philipp Zabel, Pengutronix * * Author: Michal Hajduk, Dialog Semiconductor */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/irq.h> #include <linux/mfd/core.h> #include <linux/interrupt.h> #include <linux/regmap.h> #include <linux/mfd/da9063/core.h> #define DA9063_REG_EVENT_A_OFFSET 0 #define DA9063_REG_EVENT_B_OFFSET 1 #define DA9063_REG_EVENT_C_OFFSET 2 #define DA9063_REG_EVENT_D_OFFSET 3 static const struct regmap_irq da9063_irqs[] = { /* DA9063 event A register */ REGMAP_IRQ_REG(DA9063_IRQ_ONKEY, DA9063_REG_EVENT_A_OFFSET, DA9063_M_ONKEY), REGMAP_IRQ_REG(DA9063_IRQ_ALARM, DA9063_REG_EVENT_A_OFFSET, DA9063_M_ALARM), REGMAP_IRQ_REG(DA9063_IRQ_TICK, DA9063_REG_EVENT_A_OFFSET, DA9063_M_TICK), REGMAP_IRQ_REG(DA9063_IRQ_ADC_RDY, DA9063_REG_EVENT_A_OFFSET, DA9063_M_ADC_RDY), REGMAP_IRQ_REG(DA9063_IRQ_SEQ_RDY, DA9063_REG_EVENT_A_OFFSET, DA9063_M_SEQ_RDY), /* DA9063 event B register */ REGMAP_IRQ_REG(DA9063_IRQ_WAKE, DA9063_REG_EVENT_B_OFFSET, DA9063_M_WAKE), REGMAP_IRQ_REG(DA9063_IRQ_TEMP, DA9063_REG_EVENT_B_OFFSET, DA9063_M_TEMP), REGMAP_IRQ_REG(DA9063_IRQ_COMP_1V2, DA9063_REG_EVENT_B_OFFSET, DA9063_M_COMP_1V2), REGMAP_IRQ_REG(DA9063_IRQ_LDO_LIM, DA9063_REG_EVENT_B_OFFSET, DA9063_M_LDO_LIM), REGMAP_IRQ_REG(DA9063_IRQ_REG_UVOV, DA9063_REG_EVENT_B_OFFSET, DA9063_M_UVOV), REGMAP_IRQ_REG(DA9063_IRQ_DVC_RDY, DA9063_REG_EVENT_B_OFFSET, DA9063_M_DVC_RDY), REGMAP_IRQ_REG(DA9063_IRQ_VDD_MON, DA9063_REG_EVENT_B_OFFSET, DA9063_M_VDD_MON), REGMAP_IRQ_REG(DA9063_IRQ_WARN, DA9063_REG_EVENT_B_OFFSET, DA9063_M_VDD_WARN), /* DA9063 event C register */ REGMAP_IRQ_REG(DA9063_IRQ_GPI0, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI0), REGMAP_IRQ_REG(DA9063_IRQ_GPI1, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI1), REGMAP_IRQ_REG(DA9063_IRQ_GPI2, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI2), REGMAP_IRQ_REG(DA9063_IRQ_GPI3, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI3), REGMAP_IRQ_REG(DA9063_IRQ_GPI4, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI4), REGMAP_IRQ_REG(DA9063_IRQ_GPI5, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI5), REGMAP_IRQ_REG(DA9063_IRQ_GPI6, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI6), REGMAP_IRQ_REG(DA9063_IRQ_GPI7, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI7), /* DA9063 event D register */ REGMAP_IRQ_REG(DA9063_IRQ_GPI8, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI8), REGMAP_IRQ_REG(DA9063_IRQ_GPI9, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI9), REGMAP_IRQ_REG(DA9063_IRQ_GPI10, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI10), REGMAP_IRQ_REG(DA9063_IRQ_GPI11, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI11), REGMAP_IRQ_REG(DA9063_IRQ_GPI12, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI12), REGMAP_IRQ_REG(DA9063_IRQ_GPI13, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI13), REGMAP_IRQ_REG(DA9063_IRQ_GPI14, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI14), REGMAP_IRQ_REG(DA9063_IRQ_GPI15, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI15), }; static const struct regmap_irq_chip da9063_irq_chip = { .name = "da9063-irq", .irqs = da9063_irqs, .num_irqs = ARRAY_SIZE(da9063_irqs), .num_regs = 4, .status_base = DA9063_REG_EVENT_A, .mask_base = DA9063_REG_IRQ_MASK_A, .ack_base = DA9063_REG_EVENT_A, .init_ack_masked = true, }; static const struct regmap_irq da9063l_irqs[] = { /* DA9063 event A register */ REGMAP_IRQ_REG(DA9063_IRQ_ONKEY, DA9063_REG_EVENT_A_OFFSET, DA9063_M_ONKEY), REGMAP_IRQ_REG(DA9063_IRQ_ADC_RDY, DA9063_REG_EVENT_A_OFFSET, DA9063_M_ADC_RDY), REGMAP_IRQ_REG(DA9063_IRQ_SEQ_RDY, DA9063_REG_EVENT_A_OFFSET, DA9063_M_SEQ_RDY), /* DA9063 event B register */ REGMAP_IRQ_REG(DA9063_IRQ_WAKE, DA9063_REG_EVENT_B_OFFSET, DA9063_M_WAKE), REGMAP_IRQ_REG(DA9063_IRQ_TEMP, DA9063_REG_EVENT_B_OFFSET, DA9063_M_TEMP), REGMAP_IRQ_REG(DA9063_IRQ_COMP_1V2, DA9063_REG_EVENT_B_OFFSET, DA9063_M_COMP_1V2), REGMAP_IRQ_REG(DA9063_IRQ_LDO_LIM, DA9063_REG_EVENT_B_OFFSET, DA9063_M_LDO_LIM), REGMAP_IRQ_REG(DA9063_IRQ_REG_UVOV, DA9063_REG_EVENT_B_OFFSET, DA9063_M_UVOV), REGMAP_IRQ_REG(DA9063_IRQ_DVC_RDY, DA9063_REG_EVENT_B_OFFSET, DA9063_M_DVC_RDY), REGMAP_IRQ_REG(DA9063_IRQ_VDD_MON, DA9063_REG_EVENT_B_OFFSET, DA9063_M_VDD_MON), REGMAP_IRQ_REG(DA9063_IRQ_WARN, DA9063_REG_EVENT_B_OFFSET, DA9063_M_VDD_WARN), /* DA9063 event C register */ REGMAP_IRQ_REG(DA9063_IRQ_GPI0, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI0), REGMAP_IRQ_REG(DA9063_IRQ_GPI1, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI1), REGMAP_IRQ_REG(DA9063_IRQ_GPI2, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI2), REGMAP_IRQ_REG(DA9063_IRQ_GPI3, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI3), REGMAP_IRQ_REG(DA9063_IRQ_GPI4, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI4), REGMAP_IRQ_REG(DA9063_IRQ_GPI5, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI5), REGMAP_IRQ_REG(DA9063_IRQ_GPI6, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI6), REGMAP_IRQ_REG(DA9063_IRQ_GPI7, DA9063_REG_EVENT_C_OFFSET, DA9063_M_GPI7), /* DA9063 event D register */ REGMAP_IRQ_REG(DA9063_IRQ_GPI8, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI8), REGMAP_IRQ_REG(DA9063_IRQ_GPI9, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI9), REGMAP_IRQ_REG(DA9063_IRQ_GPI10, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI10), REGMAP_IRQ_REG(DA9063_IRQ_GPI11, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI11), REGMAP_IRQ_REG(DA9063_IRQ_GPI12, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI12), REGMAP_IRQ_REG(DA9063_IRQ_GPI13, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI13), REGMAP_IRQ_REG(DA9063_IRQ_GPI14, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI14), REGMAP_IRQ_REG(DA9063_IRQ_GPI15, DA9063_REG_EVENT_D_OFFSET, DA9063_M_GPI15), }; static const struct regmap_irq_chip da9063l_irq_chip = { .name = "da9063l-irq", .irqs = da9063l_irqs, .num_irqs = ARRAY_SIZE(da9063l_irqs), .num_regs = 4, .status_base = DA9063_REG_EVENT_A, .mask_base = DA9063_REG_IRQ_MASK_A, .ack_base = DA9063_REG_EVENT_A, .init_ack_masked = true, }; int da9063_irq_init(struct da9063 *da9063) { const struct regmap_irq_chip *irq_chip; int ret; if (!da9063->chip_irq) { dev_err(da9063->dev, "No IRQ configured\n"); return -EINVAL; } if (da9063->type == PMIC_TYPE_DA9063) irq_chip = &da9063_irq_chip; else irq_chip = &da9063l_irq_chip; ret = devm_regmap_add_irq_chip(da9063->dev, da9063->regmap, da9063->chip_irq, IRQF_TRIGGER_LOW | IRQF_ONESHOT | IRQF_SHARED, da9063->irq_base, irq_chip, &da9063->regmap_irq); if (ret) { dev_err(da9063->dev, "Failed to reguest IRQ %d: %d\n", da9063->chip_irq, ret); return ret; } return 0; }
c
9
0.675382
60
34.527919
197
research_code
/** * */ #include "adaptions_glpk.h" namespace hypro { inline void printProblem( glp_prob* glpkProblem ) { int cols = glp_get_num_cols( glpkProblem ); int* ind = new int[unsigned( cols ) + 1]; double* val = new double[unsigned( cols ) + 1]; for ( int i = 1; i <= glp_get_num_rows( glpkProblem ); ++i ) { int nonZeroCount = glp_get_mat_row( glpkProblem, i, ind, val ); for ( int colIndex = 1; colIndex <= cols; ++colIndex ) { bool found = false; // glpk always starts indexing at 1 -> we can skip the element at 0 for ( int arrayIndex = 1; arrayIndex < nonZeroCount + 1; ++arrayIndex ) { if ( ind[arrayIndex] == colIndex ) { found = true; std::cout << val[arrayIndex] << "\t"; } } if ( !found ) { std::cout << "0\t"; } } /* if( glp_get_row_type(glpkProblem,i) == GLP_UP ) { //std::cout << " <= " << glp_get_row_ub(glpkProblem,i) << std::endl; } else if ( glp_get_row_type(glpkProblem,i) == GLP_FR ) { //std::cout << " <= +INF" << std::endl; } */ } delete[] ind; delete[] val; } template <typename Number> vector_t refineSolution( glpk_context& context, const matrix_t constraints, const vector_t constants ) { matrix_t exactSolutionMatrix = matrix_t constraints.cols(), constraints.cols() ); vector_t exactSolutionVector = vector_t constraints.cols() ); unsigned pos = 0; if ( glp_get_obj_dir( context.lp ) == GLP_MAX ) { for ( unsigned i = 1; i <= constraints.rows(); ++i ) { // we search for d non-basic variables at their upper bound, which define the optimal point. if ( glp_get_row_stat( context.lp, i ) == GLP_NU ) { exactSolutionMatrix.row( pos ) = constraints.row( i - 1 ); exactSolutionVector( pos ) = constants( i - 1 ); ++pos; } } } else { assert( glp_get_obj_dir( context.lp ) == GLP_MIN ); for ( unsigned i = 1; i <= constraints.rows(); ++i ) { // we search for d non-basic variables at their lower bound, which define the optimal point. if ( glp_get_row_stat( context.lp, i ) == GLP_NL ) { exactSolutionMatrix.row( pos ) = constraints.row( i - 1 ); exactSolutionVector( pos ) = constants( i - 1 ); ++pos; } } } // solve and return return Eigen::FullPivLU exactSolutionMatrix ).solve( exactSolutionVector ); } template <typename Number> EvaluationResult glpkOptimizeLinearPostSolve( glpk_context& context, const vector_t _direction, const matrix_t constraints, const vector_t constants, bool useExact, const EvaluationResult preSolution ) { // Add presolution as new row constraint to the lp // Create row: glp_add_rows( context.lp, 1 ); int* rowIndices = new int[constraints.cols() + 1]; double* rowValues = new double[constraints.cols() + 1]; for ( int i = 0; i <= constraints.cols(); ++i ) { rowValues[i] = carl::toDouble( _direction( i - 1 ) ); rowIndices[i] = i; } // Add row to problem: glp_set_mat_row( context.lp, constraints.rows() + 1, constraints.cols(), rowIndices, rowValues ); // Set presolution bound: if ( glp_get_obj_dir( context.lp ) == GLP_MAX ) { glp_set_row_bnds( context.lp, constraints.rows() + 1, GLP_LO, carl::toDouble( preSolution.supportValue ), 0.0 ); } else { assert( glp_get_obj_dir( context.lp ) == GLP_MIN ); glp_set_row_bnds( context.lp, constraints.rows() + 1, GLP_UP, 0.0, carl::toDouble( preSolution.supportValue ) ); } EvaluationResult res = glpkOptimizeLinear( context, _direction, constraints, constants, useExact ); if ( res.errorCode == SOLUTION::INFEAS ) { // glpk thinks the solution is infeasible, so we don't get an improvement res = preSolution; } // Restore original problem. Glp starts indexing at 1 so the first index does not matter int delRow[] = { 0, (int)constraints.rows() + 1 }; glp_del_rows( context.lp, 1, delRow ); delete[] rowIndices; delete[] rowValues; return res; } template <typename Number> EvaluationResult glpkOptimizeLinear( glpk_context& context, const vector_t _direction, const matrix_t constraints, const vector_t constants, bool useExact ) { /* std::cout << __func__ << " in direction " << convert << std::endl; std::cout << __func__ << " constraints: " << std::endl << constraints << std::endl << "constants: " << std::endl << constants << std::endl << "Glpk Problem: " << std::endl; //printProblem(glpkProblem); */ // setup glpk for ( unsigned i = 0; i < constraints.cols(); i++ ) { glp_set_col_bnds( context.lp, i + 1, GLP_FR, 0.0, 0.0 ); glp_set_obj_coef( context.lp, i + 1, carl::toDouble( _direction( i ) ) ); } /* solve problem */ if ( useExact ) { glp_exact( context.lp, &context.parm ); } else { glp_simplex( context.lp, &context.parm ); } vector_t exactSolution; switch ( glp_get_status( context.lp ) ) { case GLP_OPT: case GLP_FEAS: { // if satisfiable, derive exact solution by intersecting all constraints, which are at their upper respectively lower bounds . exactSolution = refineSolution( context, constraints, constants ); return EvaluationResult _direction.dot( exactSolution ), exactSolution, SOLUTION::FEAS ); break; } case GLP_UNBND: { vector_t glpkModel( constraints.cols() ); for ( unsigned i = 1; i <= constraints.cols(); ++i ) { glpkModel( i - 1 ) = carl::rationalize glp_get_col_prim( context.lp, i ) ); } return EvaluationResult 1, glpkModel, SOLUTION::INFTY ); break; } default: return EvaluationResult 0, vector_t 1 ), SOLUTION::INFEAS ); } } template <typename Number> bool glpkCheckPoint( glpk_context& context, const matrix_t constraints, const vector_t const Point point ) { // set point assert( constraints.cols() == point.rawCoordinates().rows() ); for ( unsigned i = 0; i < constraints.cols(); ++i ) { glp_set_col_bnds( context.lp, i + 1, GLP_FX, carl::toDouble( point.rawCoordinates()( i ) ), 0.0 ); glp_set_obj_coef( context.lp, i + 1, 1.0 ); // not needed? } glp_simplex( context.lp, &context.parm ); glp_exact( context.lp, &context.parm ); return ( glp_get_status( context.lp ) != GLP_NOFEAS ); } template <typename Number> std::vector glpkRedundantConstraints( glpk_context& context, matrix_t constraints, vector_t constants, std::vector relations ) { std::vector res; // TODO: ATTENTION: This relies upon that glpk maintains the order of the constraints! for ( unsigned i = 0; i < constraints.cols(); ++i ) { glp_set_col_bnds( context.lp, i + 1, GLP_FR, 0.0, 0.0 ); glp_set_obj_coef( context.lp, i + 1, 1.0 ); // not needed? } // first call to check satisfiability glp_simplex( context.lp, &context.parm ); glp_exact( context.lp, &context.parm ); switch ( glp_get_status( context.lp ) ) { case GLP_INFEAS: case GLP_NOFEAS: return res; default: break; } for ( std::size_t constraintIndex = std::size_t( constraints.rows() - 1 );; --constraintIndex ) { bool redundant = true; carl::Relation relation = relations[constraintIndex]; EvaluationResult actualRes; EvaluationResult updatedRes; if ( relation == carl::Relation::LEQ || relation == carl::Relation::EQ ) { // test if upper bound is redundant glp_set_obj_dir( context.lp, GLP_MAX ); actualRes = glpkOptimizeLinear( context, vector_t constraints.row( constraintIndex ) ), constraints, constants, true ); glp_set_row_bnds( context.lp, int( constraintIndex ) + 1, GLP_FR, 0.0, 0.0 ); updatedRes = glpkOptimizeLinear( context, vector_t constraints.row( constraintIndex ) ), constraints, constants, true ); // actual solution is always bounded because of the constraint, so updated should still be bounded if redundant if ( actualRes.errorCode != updatedRes.errorCode || actualRes.supportValue != updatedRes.supportValue ) { redundant = false; } } if ( relation == carl::Relation::GEQ || relation == carl::Relation::EQ ) { // test if lower bound is redundant glp_set_obj_dir( context.lp, GLP_MIN ); actualRes = glpkOptimizeLinear( context, vector_t constraints.row( constraintIndex ) ), constraints, constants, true ); glp_set_row_bnds( context.lp, int( constraintIndex ) + 1, GLP_FR, 0.0, 0.0 ); updatedRes = glpkOptimizeLinear( context, vector_t constraints.row( constraintIndex ) ), constraints, constants, true ); // actual solution is always bounded because of the constraint, so updated should still be bounded if redundant if ( actualRes.errorCode != updatedRes.errorCode || actualRes.supportValue != updatedRes.supportValue ) { redundant = false; } } if ( redundant ) { res.push_back( constraintIndex ); } else { // restore bound switch ( relation ) { case carl::Relation::LEQ: // set upper bounds, lb-values (here 0.0) are ignored. glp_set_row_bnds( context.lp, int( constraintIndex ) + 1, GLP_UP, 0.0, carl::toDouble( constants( constraintIndex ) ) ); break; case carl::Relation::GEQ: // if it is an equality, the value is read from the lb-value, ub.values (here 0.0) are ignored. glp_set_row_bnds( context.lp, int( constraintIndex ) + 1, GLP_LO, carl::toDouble( constants( constraintIndex ) ), 0.0 ); break; case carl::Relation::EQ: // if it is an equality, the value is read from the lb-value, ub.values (here 0.0) are ignored. glp_set_row_bnds( context.lp, int( constraintIndex ) + 1, GLP_FX, carl::toDouble( constants( constraintIndex ) ), 0.0 ); break; default: // glpk cannot handle strict inequalities. assert( false ); std::cout << "This should not happen." << std::endl; } } if ( constraintIndex == 0 ) { break; } } // restore original problem for ( const auto idx : res ) { switch ( relations[idx] ) { case carl::Relation::LEQ: // set upper bounds, lb-values (here 0.0) are ignored. glp_set_row_bnds( context.lp, int( idx ) + 1, GLP_UP, 0.0, carl::toDouble( constants( idx ) ) ); break; case carl::Relation::GEQ: // if it is an equality, the value is read from the lb-value, ub.values (here 0.0) are ignored. glp_set_row_bnds( context.lp, int( idx ) + 1, GLP_LO, carl::toDouble( constants( idx ) ), 0.0 ); break; case carl::Relation::EQ: // if it is an equality, the value is read from the lb-value, ub.values (here 0.0) are ignored. glp_set_row_bnds( context.lp, int( idx ) + 1, GLP_FX, carl::toDouble( constants( idx ) ), 0.0 ); break; default: // glpk cannot handle strict inequalities. assert( false ); std::cout << "This should not happen." << std::endl; } } return res; } template <typename Number> EvaluationResult glpkGetInternalPoint( glpk_context& context, std::size_t dimension, bool useExact ) { glp_simplex( context.lp, &context.parm ); if ( useExact ) { glp_exact( context.lp, &context.parm ); } vector_t glpkModel( dimension ); for ( int i = 1; i <= int( dimension ); ++i ) { glpkModel( i - 1 ) = glp_get_col_prim( context.lp, i ); } switch ( glp_get_status( context.lp ) ) { case GLP_OPT: case GLP_FEAS: return EvaluationResult glp_get_obj_val( context.lp ), glpkModel, SOLUTION::FEAS ); break; case GLP_UNBND: return EvaluationResult 1, glpkModel, SOLUTION::INFTY ); break; default: return EvaluationResult 0, vector_t 1 ), SOLUTION::INFEAS ); } } } // namespace hypro
c++
21
0.657795
247
39.444444
288
starcoderdata
import sys import os import json from tokenizations import tokenization_bert def _is_chinese_char(char): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is NOT all Japanese and Korean characters, # despite its name. The modern Korean Hangul alphabet is a different block, # as is Japanese Hiragana and Katakana. Those alphabets are used to write # space-separated words, so they are not treated specially and handled # like the all of the other languages. cp = ord(char) if ((cp >= 0x4E00 and cp <= 0x9FFF) or # (cp >= 0x3400 and cp <= 0x4DBF) or # (cp >= 0x20000 and cp <= 0x2A6DF) or # (cp >= 0x2A700 and cp <= 0x2B73F) or # (cp >= 0x2B740 and cp <= 0x2B81F) or # (cp >= 0x2B820 and cp <= 0x2CEAF) or (cp >= 0xF900 and cp <= 0xFAFF) or # (cp >= 0x2F800 and cp <= 0x2FA1F)): # return True return False def token_pad(line,full_tokenizer,subline,n_ctx): punc = '.;!?。;!?' tmp = [full_tokenizer.convert_tokens_to_ids('[MASK]')] tmp = tmp + subline if len(tmp) > n_ctx - 1: tmp = tmp[:n_ctx - 1] idx_b = n_ctx-1 else: tmp = tmp + (n_ctx - 1 - len(tmp)) * [full_tokenizer.convert_tokens_to_ids('[PAD]')] idx_b = len(line) line = line[idx_b:] idx0 = 0 for p in punc: if p in line: idx0 = line.index(p)+1 break line = line[idx0:] tmp = tmp + [full_tokenizer.convert_tokens_to_ids('[CLS]')] return tmp,line def build_files(full_tokenizer,path_source,path_target,padding,n_ctx=64,min_length=6,maxNb=1000000): if not os.path.exists(path_target): os.mkdir(path_target) full_line = [] print('reading lines') nb_lines = 0 files = os.listdir(path_source) idx = 0 for file in files: f = open(os.path.join(path_source,file),'r') for line in f: line_zh = [tt for tt in line if _is_chinese_char(tt)] if len(line_zh)<min_length or len(line)>len(line_zh)*2: continue nb_lines+=1 subline = full_tokenizer.convert_tokens_to_ids(list(line)) if padding: tmp,line = token_pad(line,full_tokenizer,subline,n_ctx) full_line.extend(tmp) while len(line)>n_ctx: tmp, line = token_pad(line,full_tokenizer,subline,n_ctx) full_line.extend(tmp) else: tmp = [full_tokenizer.convert_tokens_to_ids('[MASK]')] tmp = tmp + subline tmp = tmp + [full_tokenizer.convert_tokens_to_ids('[CLS]')] full_line.extend(tmp) if nb_lines%100000==0: print('processing file %s and get %d lines'%(file,nb_lines)) if nb_lines>=maxNb: nb_lines = 0 with open(os.path.join(path_target, 'godTokenizer_' + str(idx) + '.txt'), 'w') as f: f.write(' '.join(full_line)) idx+=1 full_line = [] if len(full_line)>0: with open(os.path.join(path_target, 'godTokenizer_' + str(idx) + '.txt'), 'w') as f: f.write(' '.join(full_line)) print('finish') def main(path_source,path_target,padding,path_vocab,n_ctx): #tokenizer_path = '../data/vocab/vocab_god_userdata.txt' #tokenized_data_path = '../data/userdata_tokenized_new/' full_tokenizer = tokenization_bert.BertTokenizer(vocab_file=path_vocab) build_files(full_tokenizer,path_source,path_target,padding,n_ctx=n_ctx) #shutil.rmtree(data_path) if __name__=='__main__': path_source,path_target,padding,path_vocab,n_ctx = sys.argv[1:6] padding = padding=='1' main(path_source,path_target,padding,path_vocab,int(n_ctx))
python
21
0.575087
100
42.258065
93
starcoderdata
package com.tf.reusable.demoapplication.network; import android.content.ContentValues; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import com.tf.reusable.demoapplication.util.Logger; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; import java.util.Set; /** * Created by kamran on 10/17/16. */ public class Network { private static final String TAG = "Network"; private static final int TIMEOUT = 30000; private static final String POST = "POST"; private static final String GET = "GET"; private static final String PUT = "PUT"; public static NetworkResponse getRequest(Context context, String urlString, ContentValues queryParameters) throws IOException, JSONException, NoInternetException { return request(context, urlString, queryParameters, null, GET); } public static NetworkResponse postRequest(Context context, String urlString, ContentValues queryParameters, JSONObject body) throws IOException, JSONException, NoInternetException { return request(context, urlString, queryParameters, body, POST); } public static NetworkResponse putRequest(Context context, String urlString, ContentValues queryParameters, JSONObject body) throws IOException, JSONException, NoInternetException { return request(context, urlString, queryParameters, body, PUT); } public static NetworkResponse request(Context context, String urlString, ContentValues queryParameters, JSONObject body, String method) throws IOException, JSONException, NoInternetException { if (isConnectedToInternet(context)) { InputStream inputStream = null; try { urlString += getQueryString(queryParameters); URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIMEOUT); conn.setConnectTimeout(TIMEOUT); conn.setRequestMethod(method); conn.setDoInput(true); if (body != null && body.length() > 0) { conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(body.toString()); writer.flush(); writer.close(); } // Starts the query conn.connect(); int responseCode = conn.getResponseCode(); if (responseCode < 400) { inputStream = conn.getInputStream(); } else { inputStream = conn.getErrorStream(); } // Convert the InputStream into a string String contentAsString = inputStreamToString(inputStream); Logger.i(TAG, urlString); Logger.i(TAG, body != null ? body.toString() : ""); Logger.i(TAG, contentAsString); return new NetworkResponse(responseCode, contentAsString); } finally { try { if (inputStream != null) inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } else { throw new NoInternetException(); } } private static String getQueryString(ContentValues queryParameters) { String queryString = ""; if (queryParameters != null) { for (Map.Entry<String, Object> map : queryParameters.valueSet()) { queryString += "&" + map.getKey() + "=" + map.getValue(); } } queryString = queryString.replaceFirst("&", "?"); return queryString; } public static boolean isConnectedToInternet(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } public static String inputStreamToString(InputStream stream) throws IOException { StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream)); String read; while ((read = bufferedReader.readLine()) != null) { stringBuilder.append(read); } bufferedReader.close(); return stringBuilder.toString(); } public static class NetworkResponse { private int code; private String response; public NetworkResponse(int code, String response) { this.code = code; this.response = response; } public int getCode() { return code; } public String getResponse() { return response; } } public static class NoInternetException extends RuntimeException { } }
java
17
0.62736
196
33.851613
155
starcoderdata
package gameengine.model.settings; import java.util.List; import gameengine.model.interfaces.Rule; import javafx.scene.image.Image; import javafx.scene.image.ImageView; public class GameData { private Music currentBackgroundMusic; private ImageView backgroundImage; public GameData(String backgroundImageURL, String backgroundMusicURL){ this.currentBackgroundMusic = new Music(backgroundMusicURL); setNewBackground(backgroundImageURL); } //TODO: These setter methods should be unnecessary after adding in the observables public void setNewBackground(String backgroundURL){ Image background = new Image(getClass().getClassLoader() .getResourceAsStream(backgroundURL)); this.backgroundImage = new ImageView(background); } public void updateTrack(String backgroundMusicURL){ currentBackgroundMusic.updateCurrentPlayingTrack(backgroundMusicURL); } }
java
11
0.819192
109
32
30
starcoderdata
<?php // include inclui todo o código que estiver no arquivo conexao.php include 'conexao.php'; // variaveis para receber dados que vem da outra página $id_cnpj = $_POST["cnpj"]; $nome_fantasia = $_POST["nome_fant"]; $n_cnes = $_POST["cnes_est"]; $nome_estabelecimento = $_POST["empresa"]; /*echo" print_r($_POST); echo" die;*/ // Usamos variavel $cadastro_usuario para receber TRUE ou FALSE da sintase SQL // mysqli_query função para executar script sql //$conexao é a variavel de conexao do arquivo conexao.php $listar_empresa = mysqli_query($conexao, "SELECT * FROM estabelecimento"); $pesquisa = mysqli_fetch_assoc($listar_empresa); if ($pesquisa["id_cnpj"] == $id_cnpj) { echo " alert ('Empresa já possui cadastro!') echo " location.href='cadastro_emp_executante.php' } $cadastro_empresa = mysqli_query($conexao, "INSERT INTO `estabelecimento` (`id_cnpj`, `nome_fantasia`, `n_cnes`, `nome_estabelecimento`) VALUES ('$id_cnpj', '$nome_fantasia', '$n_cnes', '$nome_estabelecimento');"); // Verificamos se a variavel $cadastro_usuario recebeu TRUE para sucesso no cadastro if ($cadastro_empresa == TRUE){ echo " alert ('Empresa cadastrada Sucesso!') echo " location.href='cadastro_emp_executante.php' } // Caso FALSE ou outro damos erro else{ echo " alert ('Não foi possivel Cadastrar a empresa!') echo " location.href='cadastro_emp_executante.php' } ?>
php
8
0.666457
137
33.630435
46
starcoderdata
void TranslationWidget(ImMat4* M, float axes_size, ImGuiControlPointFlags control_point_flags, bool include_planes) { ImVec4 t{ 0, 0, 0, 0 }; // The translation vector (only three coords are used) ImGui::PushTranslationAlongX(&t.x); ImGui::PushTranslationAlongY(&t.y); ImGui::PushTranslationAlongZ(&t.z); // We don't change any parameters in the control points, instead wait until the deferral slot is popped ImGui::PushDeferralSlot(); ImGui::StaticControlPoint(M->col4, control_point_flags, 0, 0.025f, { 1, 1, 1, 1 }); ImGui::ControlPoint(*M * ImVec4{ axes_size, 0, 0, 1 }, &t.x, control_point_flags, 0, 0.025f, { 1, 0, 0, 1 }); ImGui::ControlPoint(*M * ImVec4{ 0, axes_size, 0, 1 }, &t.y, control_point_flags, 0, 0.025f, { 0, 1, 0, 1 }); ImGui::ControlPoint(*M * ImVec4{ 0, 0, axes_size, 1 }, &t.z, control_point_flags, 0, 0.025f, { 0, 0, 1, 1 }); if (include_planes) { ImGui::ControlPoint(*M * ImVec4{ axes_size / 2, axes_size / 2, 0, 1 }, &t.x, &t.y, control_point_flags, 0, 0.02f, { 1, 1, 0, 1 }); ImGui::ControlPoint(*M * ImVec4{ 0, axes_size / 2, axes_size / 2, 1 }, &t.y, &t.z, control_point_flags, 0, 0.02f, { 0, 1, 1, 1 }); ImGui::ControlPoint(*M * ImVec4{ axes_size / 2, 0, axes_size / 2, 1 }, &t.z, &t.x, control_point_flags, 0, 0.02f, { 1, 0, 1, 1 }); } ImGui::PopTransform(); // Z-translation ImGui::PopTransform(); // Y-translation ImGui::PopTransform(); // X-translation // This will apply any changes made to t as intended, without the unintended consequence of // applying any previously made changes. ImGui::PopDeferralSlot(); // Update the matrix if any of our parameters are non-zero M->col4 += *M * t; }
c++
12
0.589995
142
56.5
32
inline
package id3.gui.functionpanel.panels; import id3.functions.Functions; import id3.gui.customui.FileBrowserPanel; import id3.gui.customui.InfoTextArea; import id3.gui.functionpanel.FunctionPanel; import javax.swing.*; import java.awt.*; import java.io.File; import java.util.Map; import java.util.Map.Entry; public class ExportArtworkPanel extends FunctionPanel { private static final String INFO_TEXT = "Every album that has artwork in the selected\r\n" + "library file will have a copy of its artwork saved\r\nin the selected export directory.\r\n\r\n" + "See HELP for more info."; private FileBrowserPanel fileBrowser = new FileBrowserPanel(JFileChooser.DIRECTORIES_ONLY); private JCheckBox chckSplit; /** Creates a new {@code ExportArtworkPanel} * @see FunctionPanel */ public ExportArtworkPanel() { fileBrowser.setBounds(10, 206, 500, 25); this.add(fileBrowser); JLabel lblDir = new JLabel("Select Export Directory:"); lblDir.setFont(new Font("Verdana", Font.BOLD, 12)); lblDir.setBounds(10, 180, 193, 14); this.add(lblDir); chckSplit = new JCheckBox("Split files by artist"); chckSplit.setBounds(10, 233, 193, 23); this.add(chckSplit); InfoTextArea infoTextArea = new InfoTextArea(INFO_TEXT, new Rectangle(6, 11, 388, 138)); this.add(infoTextArea); } public String getExportDirectory() { File file = new File(fileBrowser.getSelectedFilePath()); if(file.exists()) { if(file.isDirectory()) { return file.getAbsolutePath(); } } return null; } public boolean isSplitByArtist() { return chckSplit.isSelected(); } @Override public void runFunction(Entry<String, Map> entry) { Functions.exportArtwork(entry, getExportDirectory(), isSplitByArtist()); } @Override public boolean checkForErrors() { return getExportDirectory() == null; } }
java
12
0.727174
102
23.864865
74
starcoderdata
const { rcon } = require("../startup/rcon"); const test = require("../test/test"); const utils = require("./utils"); function say(str) { return rcon(`say ${str}`); } function getPlayers() { return rcon("listplayers") .then(function ({ stdout }) { // stdout = test.listPlayers(stdout); // TEST: Uncomment to test const myRegex = /\s(\d\d\d)\s.+?\|\s(.+?)\s\|\s(765\d{14})\s+?\|\s(\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b)\s+\|\s(\d+)\s+\|/g; let listPlayers = {}; let roster = []; let numPlayers = 0; let match; while (match = myRegex.exec(stdout)) { let obj = {}; obj.id = match[1]; obj.steamName = match[2].trim(); obj.steamId = match[3]; obj.ip = match[4]; obj.score = match[5]; roster.push(obj); } numPlayers = roster.length; listPlayers.roster = roster; listPlayers.numPlayers = numPlayers; return listPlayers; }); } /** * If the user types "!kick jame", this function will return the associated Steam ID. Multiple * or zero results will return immediately. Apparently, rcon already has the ability to filter * a single result and ignore multiple results when kicking. * @param {String} input * @return {String} */ async function getPlayerId(partialSteamName) { const players = await getPlayers(); if (players.numPlayers === 0) return; if (partialSteamName.length <= 3) return console.log("Your input's gotta be at least 4 characters long."); let matches = []; let i = 0; while (i < players.numPlayers) { const steamName = players.roster[i].steamName; const regex = new RegExp(partialSteamName, "gi"); const match = steamName.match(regex); if (match) matches.push(players.roster[i]); if (matches.length > 1) return console.log("Multiple matches."); i++; } if (matches.length === 0) return console.log("No matches."); const { steamId } = matches[0]; matches.map(function ({ steamName }) { console.log(steamName); }); return steamId; } // In the event a player teamkilled another and immediately disconnects // (Alternative to looking at Recent Players list on Steam to grab their // Steam ID). function getRecent() { } function kickid(steamId, reason = "") { let result = utils.isValidSteamId(steamId); // TODO: Send a chat message stating that the ID was invalid. if (!result) return new Error("Error: Invalid Steam ID"); return rcon(`kick \\"${steamId}\\" \\"${reason}\\"`); } function kick(steamName, reason = "") { if (steamName.length === 0 || steamName === null || steamName === undefined) { return new Error("Error: No Steam name specified."); } return rcon(`kick \\"${steamName}\\" \\"${reason}\\"`); } // Move to separate file as a log watcher function readLog() { } module.exports = { say, getPlayers, kick, kickid, getPlayerId }
javascript
19
0.627404
127
26.742857
105
starcoderdata
<?php namespace App\Http\Controllers; use App\Models\{Notice}; use App\Http\Requests\NoticeRequest; use Illuminate\Http\Request; use Exception; class NoticeController extends Controller { public function index() { $user = auth()->user(); $notices = Notice::where('user_id', '=', $user->id)->paginate(15); return view('notice.index', ['notices' => $notices]); } public function search(Request $request) { try { $data = $request->all(); if (empty($data['search-type']) || $data['search-type'] != 'author' && $data['search-type'] != 'title') { throw new Exception("Opção Author ou Title obrigatória!"); } if (empty($data['search'])) { throw new Exception("Campo search obrigatório!"); } $user = auth()->user(); $notices = Notice::where('user_id', '=', $user->id) ->where("{$data['search-type']}", '=', "{$data['search']}") ->paginate(15); return view('notice.index', ['notices' => $notices]); } catch (Exception $e) { $msg = [ 'success' => false, 'error' => true, 'msg' => $e->getMessage() ]; return redirect('/notice')->with('msg', $msg); } } public function create() { return view('notice.create'); } public function store(NoticeRequest $request) { $msg = [ 'success' => true, 'error' => false, 'msg' => 'Registro salvo com sucesso!' ]; try { $notice = new Notice($request->all()); $notice->user_id = auth()->user()->id; $notice->save(); } catch (\Throwable $th) { $msg = [ 'success' => false, 'error' => true, 'msg' => 'Algo deu errado, tente novamente!' ]; } return redirect('/notice')->with('msg', $msg); } public function show($id) { try { $user = auth()->user(); $notice = Notice::where('id', '=', $id) ->where('user_id', '=', $user->id)->first(); if (!$notice) { throw new Exception("Algo deu errado, tente novamente!"); } return view('notice.show', ['notice' => $notice]); } catch (Exception $e) { $msg = [ 'success' => false, 'error' => true, 'msg' => $e->getMessage() ]; return redirect('/notice')->with('msg', $msg); } } public function edit($id) { try { $user = auth()->user(); $notice = Notice::where('id', '=', $id) ->where('user_id', '=', $user->id)->first(); if (!$notice) { throw new Exception("Algo deu errado, tente novamente!"); } return view('notice.edit', ['notice' => $notice]); } catch (Exception $e) { $msg = [ 'success' => false, 'error' => true, 'msg' => $e->getMessage() ]; return redirect('/notice')->with('msg', $msg); } } public function update($id, NoticeRequest $request) { $msg = [ 'success' => true, 'error' => false, 'msg' => 'Registro salvo com sucesso!' ]; try { $user = auth()->user(); $notice = Notice::where('id', '=', $id) ->where('user_id', '=', $user->id)->first(); if (!$notice) { throw new Exception("Algo deu errado, tente novamente!"); } $notice->update($request->all()); } catch (Exception $e) { $msg = [ 'success' => false, 'error' => true, 'msg' => $e->getMessage() ]; } return redirect('/notice')->with('msg', $msg); } public function destroy($id) { $msg = [ 'success' => true, 'error' => false, 'msg' => 'Registro deletado com sucesso!' ]; try { $user = auth()->user(); $notice = Notice::where('id', '=', $id) ->where('user_id', '=', $user->id)->first(); $notice->delete(); } catch (\Throwable $th) { $msg = [ 'success' => false, 'error' => true, 'msg' => 'Algo deu errado, tente novamente!' ]; } return redirect('/notice')->with('msg', $msg); } }
php
16
0.420071
117
26.119318
176
starcoderdata
using System; using System.Linq; using System.Linq.Expressions; namespace Composable.ServiceBus { internal class MessageHandlerMethod { private Action<object, object> HandlerMethod { get; set; } public MessageHandlerMethod(Type implementingClass, Type genericInterfaceImplemented) { HandlerMethod = CreateHandlerMethodInvoker(implementingClass, genericInterfaceImplemented); } public void Invoke(object handler, object message) { HandlerMethod(handler, message); } //Returns an action that can be used to invoke this handler for a specific type of message. private static Action<object, object> CreateHandlerMethodInvoker(Type implementingClass, Type genericInterfaceImplemented) { var methodInfo = implementingClass.GetInterfaceMap(genericInterfaceImplemented).TargetMethods.Single(); var messageHandlerParameter = Expression.Parameter(typeof(object)); var messageParameter = Expression.Parameter(typeof(object)); var convertMessageHandlerParameter = Expression.Convert(messageHandlerParameter, implementingClass); var convertMessageParameter = Expression.Convert(messageParameter, methodInfo.GetParameters().Single().ParameterType); var callMessageHandlerExpression = Expression.Call(instance: convertMessageHandlerParameter, method: methodInfo, arguments: convertMessageParameter); return Expression.Lambda<Action<object, object>>( body: callMessageHandlerExpression, parameters: new[] { messageHandlerParameter, messageParameter }).Compile(); } } }
c#
19
0.658747
161
44.170732
41
starcoderdata
'use strict'; const Joi = require('joi'); const internals = {}; internals.schema = Joi.object().keys({ errorFiles: Joi.object().optional(), staticRoute: Joi.object().optional() }); exports.plugin = { pkg: require('../package.json'), register: (server, options) => { const validateOptions = internals.schema.validate(options); if (validateOptions.error) { return Promise.reject(new Error(validateOptions.error.message)); } if (options.errorFiles) { // use onPreResponse or onPostHandler server.ext('onPreResponse', (request, h) => { if (request.route.settings.plugins.errorh === false) { return h.continue; } const response = request.response; if (response.isBoom) { if (options.errorFiles[response.output.statusCode]) { return h.file(options.errorFiles[response.output.statusCode]) .code(response.output.statusCode) .type('text/html'); } else if (options.errorFiles.default) { return h.file(options.errorFiles.default) .code(response.output.statusCode) .type('text/html'); } } return h.continue; }); } if (options.staticRoute) { server.route(options.staticRoute); } } };
javascript
27
0.500313
85
26.5
58
starcoderdata
def _spawn_actors(self, spawn_wps): """Spawns several actors in batch""" spawn_transforms = [] for wp in spawn_wps: spawn_transforms.append( carla.Transform(wp.transform.location + carla.Location(z=self._spawn_vertical_shift), wp.transform.rotation) ) actors = CarlaDataProvider.request_new_batch_actors( 'vehicle.*', len(spawn_transforms), spawn_transforms, True, False, 'background', safe_blueprint=True, tick=False) if not actors: return actors for actor in actors: self._tm.auto_lane_change(actor, False) if self._night_mode: for actor in actors: actor.set_light_state(carla.VehicleLightState( carla.VehicleLightState.Position | carla.VehicleLightState.LowBeam)) return actors
python
15
0.579062
101
35.72
25
inline
package com.atlassian.clover.reporters.pdf; import java.awt.Color; public class PDFColours { public final Color COL_TABLE_BORDER; public final Color COL_HEADER_BG; public final Color COL_LINK_TEXT; public final Color COL_BAR_COVERED; public final Color COL_BAR_UNCOVERED; public final Color COL_BAR_BORDER; public final Color COL_BAR_NA; private PDFColours(Color table_border, Color header_bg, Color link_text, Color bar_covered, Color bar_uncovered, Color bar_border, Color bar_na) { COL_TABLE_BORDER = table_border; COL_HEADER_BG = header_bg; COL_LINK_TEXT = link_text; COL_BAR_COVERED = bar_covered; COL_BAR_UNCOVERED = bar_uncovered; COL_BAR_BORDER = bar_border; COL_BAR_NA = bar_na; } public static final PDFColours BW_COLOURS = new PDFColours( new Color(0x9c, 0x9c, 0x9c), new Color(0xf7, 0xf7, 0xf7), new Color(0, 0, 0), new Color(0xbc, 0xbc, 0xbc), new Color(0xff, 0xff, 0xff), new Color(0x5a, 0x5a, 0x5a), new Color(0xe6, 0xe6, 0xe6)); public static final PDFColours COL_COLOURS = new PDFColours( new Color(0x9c, 0x9c, 0x9c), new Color(0xef, 0xf7, 0xff), new Color(0, 0, 0xff), new Color(0, 0xdc, 0), new Color(0xdc, 0, 0), new Color(0x5a, 0x5a, 0x5a), new Color(0xe6, 0xe6, 0xe6)); }
java
9
0.549969
64
29.396226
53
starcoderdata
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ int bar() { auto func = []() { int i = 0; return i; }; return 7 / func(); } int foo() { auto unused = []() { return 1 / 0; }; auto y = [](int i) { return ++i; }; return 5 / (4 - y(3)); } int fooOK() { auto y = [](int i) { return i++; }; return 5 / (4 - y(3)); } int normal_capture() { int x = 1; int y = 2; return [x, y]() { return x + y; }(); } int capture_by_ref() { int x = 0; [&x]() { x++; }(); return x; } int init_capture1() { return [i = 0]() { return i; }(); } int init_capture2() { int i = 0; return [a = i, b = 0, c = 3]() { return a + b + c; }(); } class Capture { void capture_this_explicit() { auto lambda = [this]() { return this; }; } void capture_star_this() { auto lambda = [*this]() { }; } void capture_this_with_equal() { auto lambda = [=]() { return this; }; } void capture_this_with_auto() { auto lambda = [&]() { return this; }; } }; struct SomeStruct { int f; ~SomeStruct(); }; int struct_capture() { SomeStruct x; SomeStruct y; auto f = [x, y]() { return x.f + y.f; }; return f(); }
c++
10
0.513846
66
15.455696
79
starcoderdata
private void textWizzardToolStripMenuItem_Click(object sender, EventArgs e) { if (_text_form == null) { _text_form = new GCodeFromText(); _text_form.FormClosed += formClosed_TextToGCode; _text_form.btnApply.Click += getGCodeFromText; // assign btn-click event } else { _text_form.Visible = false; } _text_form.Show(this); }
c#
10
0.473267
93
34.214286
14
inline
export default function (fc) { const circles = fc._selector.querySelector('.fc-container').querySelectorAll('.fc-circle'); for (let index = 0; index < circles.length; index += 1) { circles[index].classList.remove('fc-is-active'); } circles[Math.floor(fc._currentPage / fc._options.slidesScrolling)].classList.add('fc-is-active'); }
javascript
11
0.701878
101
41.6
10
starcoderdata
package com.frame.baselib.application; import android.app.Application; import com.blankj.utilcode.util.Utils; import com.facebook.stetho.Stetho; import com.frame.baselib.BuildConfig; import com.frame.baselib.utils.preference.PreferencesUtil; import com.frame.baselib.view.loadsir.CustomCallback; import com.frame.baselib.view.loadsir.EmptyCallback; import com.frame.baselib.view.loadsir.ErrorCallback; import com.frame.baselib.view.loadsir.LoadingCallback; import com.frame.baselib.view.loadsir.LottieEmptyCallback; import com.frame.baselib.view.loadsir.LottieLoadingCallback; import com.frame.baselib.view.loadsir.TimeoutCallback; import com.kingja.loadsir.core.LoadSir; import com.squareup.leakcanary.LeakCanary; public class BaseApplication extends Application { public static Application sAppContext; public static boolean sDebug; public void setDebug(boolean isDebug) { sDebug = isDebug; } @Override public void onCreate() { super.onCreate(); sAppContext = this; PreferencesUtil.init(this); Utils.init(this); LoadSir.beginBuilder() .addCallback(new ErrorCallback())//添加各种状态页 .addCallback(new EmptyCallback()) .addCallback(new LoadingCallback()) .addCallback(new TimeoutCallback()) .addCallback(new CustomCallback()) .addCallback(new LottieEmptyCallback()) .addCallback(new LottieLoadingCallback()) .setDefaultCallback(LoadingCallback.class)//设置默认状态页 .commit(); if (sDebug) { Stetho.initializeWithDefaults(this); if (!LeakCanary.isInAnalyzerProcess(this)) { LeakCanary.install(this); } } } }
java
16
0.697614
136
35.377358
53
starcoderdata
/**************************************************************************** * graphics/nxsu/nx_drawcircle.c * * Copyright (C) 2011 All rights reserved. * Author: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include #include #include #include #include #include /**************************************************************************** * Pre-Processor Definitions ****************************************************************************/ /* Named indices into the 16 circle points generated by nxgl_circlepts */ #define POINT_0p0 0 #define POINT_22p5 1 #define POINT_45p0 2 #define POINT_67p5 3 #define POINT_90p0 4 #define POINT_112p5 5 #define POINT_135p0 6 #define POINT_157p5 7 #define POINT_180p0 8 #define POINT_202p5 9 #define POINT_225p0 10 #define POINT_247p5 11 #define POINT_270p0 12 #define POINT_292p5 13 #define POINT_315p0 14 #define POINT_337p5 15 #define NCIRCLE_POINTS 16 /**************************************************************************** * Private Types ****************************************************************************/ /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Public Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: nx_drawcircle * * Description: * Draw a circular outline using the specified line thickness and color. * * Input Parameters: * hwnd - The window handle * center - A pointer to the point that is the center of the circle * radius - The radius of the circle in pixels. * width - The width of the line * color - The color to use to fill the line * * Return: * OK on success; ERROR on failure with errno set appropriately * ****************************************************************************/ int nx_drawcircle(NXWINDOW hwnd, FAR const struct nxgl_point_s *center, nxgl_coord_t radius, nxgl_coord_t width, nxgl_mxpixel_t color[CONFIG_NX_NPLANES]) { struct nxgl_point_s pts[NCIRCLE_POINTS]; FAR struct nxgl_vector_s vector; int i; int ret; /* Convert the circle to a set of 16 points */ nxgl_circlepts(center, radius, pts); /* Draw each pair of points as a vector */ for (i = POINT_0p0; i < POINT_337p5; i++) { vector.pt1.x = pts[i].x; vector.pt1.y = pts[i].y; vector.pt2.x = pts[i+1].x; vector.pt2.y = pts[i+1].y; ret = nx_drawline(hwnd, &vector, width, color); if (ret != OK) { return ret; } } /* The final, closing vector is a special case */ vector.pt1.x = pts[POINT_337p5].x; vector.pt1.y = pts[POINT_337p5].y; vector.pt2.x = pts[POINT_0p0].x; vector.pt2.y = pts[POINT_0p0].y; return nx_drawline(hwnd, &vector, width, color); }
c
10
0.505309
78
35.372414
145
starcoderdata
import telegram import requests import time import os import dns.resolver from telegram.ext import Updater, CommandHandler TOKEN = os.environ.get('TELEGRAM_TOKEN',' bot = telegram.Bot(token=TOKEN) print(bot.get_me()) updater = Updater(token=TOKEN) dispatcher = updater.dispatcher def start(bot, update): global d bot.send_message(chat_id=update.message.chat_id, text='Checking status every 60 seconds:') working = check_web_working() d[update.message.chat_id] = working send_working_message(bot, working, update.message.chat_id) job_queue.run_repeating(check_status, 60, first = 60, context=update.message.chat_id) start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) import random global r def check_web_working(): global r r = (r+1)%2 print(r) print('rand') return r name = 'niclabs.cl' my_resolver = dns.resolver.Resolver() # 8.8.8.8 is Google's public DNS server my_resolver.nameservers = ['8.8.8.8'] try: answer = my_resolver.query(name) return True except: print("something is wrong") return False #try: # r = requests.get(name) # if(r.status_code==200): # return True # else: # return False #except: # return False def send_working_message(bot, working_now,chat_id): if(working_now): bot.send_message(chat_id=chat_id, text='It\'s all good, man.') else: bot.send_message(chat_id=chat_id, text='Something is wrong...') global d d = {} #dictionary that saves last status check for every chat def check_status(bot, job): global d working = check_web_working() if(d[job.context] != working): send_working_message(bot, working,job.context) d[job.context] = working bot.send_message(chat_id=job.context, text=working) def check_status_timer(bot, update, job_queue): global d bot.send_message(chat_id=update.message.chat_id, text='Checking status every 60 seconds:') working = check_web_working() send_working_message(bot, working,update.message.chat_id) d[update.message.chat_id] = working bot.send_message(chat_id=update.message.chat_id, text=update.message.chat_id) job_queue.run_repeating(check_status, 60, first = 0, context=update.message.chat_id) check_status_timer_handler = CommandHandler('check_web', check_status_timer, pass_job_queue=True) dispatcher.add_handler(check_status_timer_handler) def stop_check_status(bot, update, job_queue): bot.send_message(chat_id=update.message.chat_id, text="Stop checking the status") job_queue.stop() stop_check_status_handler = CommandHandler('stop_check_status', stop_check_status, pass_job_queue=True) dispatcher.add_handler(stop_check_status_handler) updater.start_polling() print('running') updater.idle() exit() #import logging #logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) #def caps(bot, update, args): # if(args): # stop=False # else: # stop=True #text_caps = ' '.join(args).upper() # bot.send_message(chat_id=update.message.chat_id, text=args) #caps_handler = CommandHandler('caps', caps, pass_args=True) #dispatcher.add_handler(caps_handler) #def hello(bot, update): # print('hello') #print(stop) #stop = True #print(stop) # d[update.message.chat_id]=True # update.message.reply_text('Hello {}'.format(update.message.from_user.first_name)) #dispatcher.add_handler(CommandHandler('hello', hello)) #def bye(bot, update): #print('bye') #print(stop) #stop = False #d[update.message.chat_id]=False #print(stop) # update.message.reply_text('Bye {}'.format(update.message.from_user.first_name)) #dispatcher.add_handler(CommandHandler('bye', bye)) #stop=True #def callback_alarm(bot, job): # bot.send_message(chat_id=job.context, text='BEEP') #def callback_timer(bot, update, job_queue): #stop=False # bot.send_message(chat_id=update.message.chat_id, text='Setting a timer for 1 minute!') #run_repeating(callback, interval, first=None, context=None, name=None) # job_queue.run_repeating(callback_alarm, 5, first = 0, context=update.message.chat_id, name = "timer") #if(stop): # job_queue.stop() #timer_handler = CommandHandler('timer', callback_timer, pass_job_queue=True) #dispatcher.add_handler(timer_handler) #def stop_timer(bot, update, job_queue): # job_queue.stop() #stop = True # bot.send_message(chat_id=update.message.chat_id, text="Timer stopped.") #stop_timer_handler = CommandHandler('stop_timer', stop_timer, pass_job_queue=True) #dispatcher.add_handler(stop_timer_handler)
python
11
0.725709
103
26.133333
165
starcoderdata
package concurrent; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; /** * Tests for {@link DeferredRunnable} */ public class DeferredRunnableTest { private DeferredRunnable deferredRunnable; @Mock private Deferrer deferrer; private int delayInMillis; @Mock private Runnable command; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); delayInMillis = 3000; deferredRunnable = new DeferredRunnable(deferrer, delayInMillis, command); } @Test public void testThatRunMethodIsExecutedAfterDeferrer() throws Exception { deferredRunnable.run(); InOrder inOrder = inOrder(deferrer, command); inOrder.verify(deferrer).defer(delayInMillis); inOrder.verify(command).run(); } }
java
7
0.701382
82
25.15
40
starcoderdata
// CvPlot - https://github.com/Profactor/cv-plot // Copyright (c) 2019 by PROFACTOR GmbH - https://www.profactor.at/ #pragma once #include #include #include #include namespace CvPlot { class LineBase::Impl { public: LineType _lineType = LineType::None; cv::Scalar _color = cv::Scalar(255, 0, 0); int _lineWidth = 1; }; CVPLOT_DEFINE_FUN LineBase::~LineBase() { } CVPLOT_DEFINE_FUN LineBase::LineBase(const std::string &lineSpec) { setLineSpec(lineSpec); } CVPLOT_DEFINE_FUN void LineBase::render(RenderTarget & renderTarget){ } CVPLOT_DEFINE_FUN bool LineBase::getBoundingRect(cv::Rect2d &rect) { return false; } CVPLOT_DEFINE_FUN LineBase& LineBase::setLineSpec(const std::string &lineSpec) { if (lineSpec.find_first_of('-') != std::string::npos) { setLineType(LineType::Solid); }else{ setLineType(LineType::None); } const std::vector colors { { 'b',cv::Scalar(255,0,0) }, { 'g',cv::Scalar(0,255,0) }, { 'r',cv::Scalar(0,0,255) }, { 'c',cv::Scalar(255,255,0) }, { 'y',cv::Scalar(0,255,255) }, { 'm',cv::Scalar(255,0,255) }, { 'k',cv::Scalar(0,0,0) }, { 'w',cv::Scalar(255,255,255) } }; for (const auto &color : colors) { if (lineSpec.find_first_of(color.first) != std::string::npos) { setColor(color.second); } } return *this; } CVPLOT_DEFINE_FUN LineBase& LineBase::setLineType(LineType lineType){ impl->_lineType = lineType; return *this; } CVPLOT_DEFINE_FUN LineBase& LineBase::setColor(cv::Scalar color) { impl->_color = color; return *this; } CVPLOT_DEFINE_FUN LineBase& LineBase::setLineWidth(int lineWidth){ impl->_lineWidth = lineWidth; return *this; } CVPLOT_DEFINE_FUN LineType LineBase::getLineType(){ return impl->_lineType; } CVPLOT_DEFINE_FUN cv::Scalar LineBase::getColor(){ return impl->_color; } CVPLOT_DEFINE_FUN int LineBase::getLineWidth(){ return impl->_lineWidth; } }
c++
15
0.639945
71
21.505155
97
starcoderdata
package com.booknara.problem.union; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; /** * 1202. Smallest String With Swaps (Medium) * https://leetcode.com/problems/smallest-string-with-swaps/ */ public class SmallestStringWithSwaps { public String smallestStringWithSwaps(String s, List pairs) { // input check int n = s.length(); int[] root = new int[n]; for (int i = 0; i < n; i++) { root[i] = i; } for (List p: pairs) { union(root, p.get(0), p.get(1)); } Map<Integer, PriorityQueue pq = new HashMap<>(); for (int i = 0; i < n; i++) { int r = find(root, i); pq.putIfAbsent(r, new PriorityQueue<>()); pq.get(r).offer(s.charAt(i)); } StringBuilder builder = new StringBuilder(); for (int i = 0; i < n; i++) { int r = find(root, i); builder.append(pq.get(r).poll()); } return builder.toString(); } public int find(int[] root, int node) { while (root[node] != node) { root[node] = root[root[node]]; node = root[node]; } return node; } public void union(int[] root, int node1, int node2) { int root1 = find(root, node1); int root2 = find(root, node2); if (root1 < root2) { root[root2] = root1; } else { root[root1] = root2; } } }
java
13
0.58053
78
22.283333
60
starcoderdata
#include #include #include #define INACCURACY 0.001 void test(); boolean testCalculation(); boolean testCalculation_firstBranch(); boolean testCalculation_secondBranch(); boolean assertEquals(double actual, double expected); double calculate(double x, double y); /** * Точка входа в программу. * 1) Ввод данных пользователем * 2) Тест в конце, для удостоверения что все работает хорошо * * @return */ int main() { // 1) double x, y; puts("\n\t x,y = "); scanf("%lf %lf", &x, &y); double result = calculate(x, y); printf("Result: %lf", result); // 2) test(); return 0; } /** * Основные рассчеты по заданной формуле * * @param x первая переменная * @param y вторая переменная * @return */ double calculate(double x, double y) { double result = 0; const boolean fitForTheFirstCase = fabs(x) < 5 * fabs(y); const boolean fitForTheSecondCase = 5 * fabs(y) < fabs(x) <= 7.5 * fabs(y); if (fitForTheFirstCase) { printf("\nFirst branch has been chosen\n"); result = log(fabs(2 * x - 3 * pow(exp(1), 2) * y)); return result; } else if (fitForTheSecondCase) { printf("\nSecond branch has been chosen\n"); result = log(fabs(2 * pow(x, 2) - 3 * y)); return result; } else { printf("\nThe entered values (%lf, %lf)" " do not fit for any mentioned in exercise case, so result is equal to 0.0", x, y); return result; } } void test() { printf("\n\n********TEST*********\n"); boolean result = testCalculation(); printf("\nTest passed: %s", result ? "Yes" : "No"); printf("\n********TEST*********\n\n"); } /** * Тест * Сверяет верность рассчетов метода calculate * * @return верно, или не верно */ boolean testCalculation() { return testCalculation_firstBranch() && testCalculation_secondBranch(); } /** * Тестирование первой ветки алгоритма * * @return успешность прохождения теста */ boolean testCalculation_firstBranch() { double x = 2; double y = -10; const double expected = 5.419081; double actual = calculate(x, y); return assertEquals(actual, expected); } /** * Тестирование второй ветки алгоритма * * @return успешность прохождения теста */ boolean testCalculation_secondBranch() { double x = 7; double y = 1; const double expected = 4.553877; double actual = calculate(x, y); return assertEquals(actual, expected); } /** * Убеждаемся в равенстве ожидаемого и полученного значения * С учетом погрешности рассчетов с использованием double * * @param actual Полученное значение * @param expected Ожидаемое значение * @return */ boolean assertEquals(double actual, double expected) { return (expected == actual) || (expected - actual <= INACCURACY && expected - actual > 0) || (actual - expected <= INACCURACY && actual - expected > 0); }
c
18
0.621886
99
21.507576
132
starcoderdata
//go:build mage // +build mage package main import ( "fmt" "path/filepath" "strings" "github.com/magefile/mage/sh" ) // Lint runs code linters on current directory and all // subdirectories func Lint() error { linter := sh.OutCmd(filepath.Join(RepoRoot(), "bin", "golangci-lint")) version := "1.39.0" currentVersion, err := linter("--version") if err != nil || !strings.Contains(currentVersion, version) { fmt.Println("linter binary outdated or missing, downloading a new one now") err := updateLinter(version) if err != nil { return err } } out, err := linter("run", "--deadline=2m", "--config="+RepoRoot()+"/.golangci.yml", "./...") if out != "" { fmt.Println(out) } return err } // Test tests all go code in the current directory and // all subdirectories func Test() error { return sh.RunV("go", "test", "./...") } func updateLinter(version string) error { return sh.Run("bash", "-c", "curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "+ RepoRoot()+"/bin v"+version, ) } func RepoRoot() string { path, err := sh.Output("git", "rev-parse", "--show-toplevel") if err != nil { panic(err) } return path }
go
12
0.644813
104
20.517857
56
starcoderdata
using System; namespace WelcomeDotnetCore { class Program { static void Main(string[] args) { string firstStatement = "Hello World!"; string secondStatement = "Welcome, .NET Core!"; PrintStatements(firstStatement, secondStatement); } private static void PrintStatements(string s1, string s2) { Console.WriteLine(s1 + " " + s2); } } }
c#
14
0.543478
65
20.904762
21
starcoderdata
namespace DigitalLearningSolutions.Data.Models.Frameworks { public class Collaborator { public int ID { get; set; } public int FrameworkID { get; set; } public int? AdminID { get; set; } public bool CanModify { get; set; } } }
c#
8
0.610294
58
26.2
10
starcoderdata
int CServer::SendMsgEx(CMsgPacker *pMsg, int Flags, int ClientID, bool System) { CNetChunk Packet; if(!pMsg) return -1; if(ClientIsDummy(ClientID)) return 1; mem_zero(&Packet, sizeof(CNetChunk)); Packet.m_ClientID = ClientID; Packet.m_pData = pMsg->Data(); Packet.m_DataSize = pMsg->Size(); // HACK: modify the message id in the packet and store the system flag *((unsigned char*)Packet.m_pData) <<= 1; if(System) *((unsigned char*)Packet.m_pData) |= 1; if(Flags&MSGFLAG_VITAL) Packet.m_Flags |= NETSENDFLAG_VITAL; if(Flags&MSGFLAG_FLUSH) Packet.m_Flags |= NETSENDFLAG_FLUSH; // write message to demo recorder if(!(Flags&MSGFLAG_NORECORD)) m_DemoRecorder.RecordMessage(pMsg->Data(), pMsg->Size()); if(!(Flags&MSGFLAG_NOSEND)) { if(ClientID == -1) { // broadcast int i; for(i = 0; i < MAX_CLIENTS; i++) if(m_aClients[i].m_State == CClient::STATE_INGAME) { Packet.m_ClientID = i; m_NetServer.Send(&Packet); } } else m_NetServer.Send(&Packet); } return 0; }
c++
14
0.652469
78
21
47
inline
<?php class Theme { public static function title() { global $Site; return $Site->title(); } public static function description() { global $Site; return $Site->description(); } public static function slogan() { global $Site; return $Site->slogan(); } public static function footer() { global $Site; return $Site->footer(); } public static function rssUrl() { if (pluginEnabled('pluginRSS')) { return DOMAIN_BASE.'rss.xml'; } return false; } public static function sitemapUrl() { if (pluginEnabled('pluginSitemap')) { return DOMAIN_BASE.'sitemap.xml'; } return false; } public static function siteUrl() { global $Site; return $Site->url(); } public static function adminUrl() { return DOMAIN_ADMIN; } // Return the metatag with a predefine structure public static function headTitle() { global $Url; global $Site; global $dbTags; global $dbCategories; global $WHERE_AM_I; global $page; $title = $Site->title(); if (Text::isNotEmpty($Site->slogan())) { $title = $Site->slogan().' | '.$Site->title(); } if ($WHERE_AM_I=='page') { $title = $page->title().' | '.$Site->title(); } elseif ($WHERE_AM_I=='tag') { $tagKey = $Url->slug(); $tagName = $dbTags->getName($tagKey); $title = $tagName.' | '.$Site->title(); } elseif ($WHERE_AM_I=='category') { $categoryKey = $Url->slug(); $categoryName = $dbCategories->getName($categoryKey); $title = $categoryName.' | '.$Site->title(); } return ' } // Return the metatag with a predefine structure public static function headDescription() { global $Site; global $WHERE_AM_I; global $page; $description = $Site->description(); if( $WHERE_AM_I=='page' ) { $description = $page->description(); } return '<meta name="description" content="'.$description.'">'.PHP_EOL; } public static function charset($charset) { return '<meta charset="'.$charset.'">'.PHP_EOL; } public static function viewport($content) { return '<meta name="viewport" content="'.$content.'">'.PHP_EOL; } public static function css($files) { if( !is_array($files) ) { $files = array($files); } $links = ''; foreach($files as $file) { $links .= '<link rel="stylesheet" type="text/css" href="'.DOMAIN_THEME.$file.'">'.PHP_EOL; } return $links; } public static function javascript($files) { if( !is_array($files) ) { $files = array($files); } $scripts = ''; foreach($files as $file) { $scripts .= '<script src="'.DOMAIN_THEME.$file.'"> } return $scripts; } public static function js($files) { return self::javascript($files); } public static function plugins($type) { global $plugins; foreach ($plugins[$type] as $plugin) { echo call_user_func(array($plugin, $type)); } } public static function favicon($file='favicon.png', $typeIcon='image/png') { return '<link rel="shortcut icon" href="'.DOMAIN_THEME.$file.'" type="'.$typeIcon.'">'.PHP_EOL; } public static function fontAwesome($cdn=false) { if ($cdn) { return '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">'.PHP_EOL; } return '<link rel="stylesheet" href="'.DOMAIN_CORE_CSS.'font-awesome/css/font-awesome.min.css'.'">'.PHP_EOL; } public static function jquery($cdn=false) { if ($cdn) { return '<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity=" crossorigin="anonymous"> } return '<script src="'.DOMAIN_CORE_JS.'jquery.min.js'.'"> } public static function keywords($keywords) { if (is_array($keywords)) { $keywords = implode(',', $keywords); } return '<meta name="keywords" content="'.$keywords.'">'.PHP_EOL; } } ?>
php
14
0.630102
127
19.962567
187
starcoderdata
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include #include #include namespace facebook { namespace react { /* * Default template-based implementation of ComponentDescriptor. * Use your `ShadowNode` type as a template argument and override any methods * if necessary. */ template <typename ShadowNodeT> class ConcreteComponentDescriptor: public ComponentDescriptor { static_assert(std::is_base_of<ShadowNode, ShadowNodeT>::value, "ShadowNodeT must be a descendant of ShadowNode"); using SharedShadowNodeT = std::shared_ptr<const ShadowNodeT>; using SharedConcreteProps = typename ShadowNodeT::SharedConcreteProps; public: ComponentHandle getComponentHandle() const override { return typeid(ShadowNodeT).hash_code(); } SharedShadowNode createShadowNode( const Tag &tag, const Tag &rootTag, const InstanceHandle &instanceHandle, const RawProps &rawProps ) const override { auto props = ShadowNodeT::Props(rawProps); return std::make_shared rootTag, instanceHandle, props); } SharedShadowNode cloneShadowNode( const SharedShadowNode &shadowNode, const SharedRawProps &rawProps = nullptr, const SharedShadowNodeSharedList &children = nullptr ) const override { const SharedConcreteProps props = rawProps ? ShadowNodeT::Props(*rawProps, shadowNode->getProps()) : nullptr; return std::make_shared ShadowNodeT>(shadowNode), props, children); } void appendChild( const SharedShadowNode &parentShadowNode, const SharedShadowNode &childShadowNode ) const override { auto concreteParentShadowNode = std::static_pointer_cast<const ShadowNodeT>(parentShadowNode); auto concreteNonConstParentShadowNode = std::const_pointer_cast concreteNonConstParentShadowNode->appendChild(childShadowNode); } }; } // namespace react } // namespace facebook
c
14
0.765742
115
32.895522
67
starcoderdata
using System.Collections.Generic; using LinCms.Zero.Domain; namespace LinCms.Web.Models.Cms.Groups { public class GroupDto:Entity { public List Auths { get; set; } public string Name { get; set; } public string Info { get; set; } } }
c#
10
0.653333
67
24
12
starcoderdata
import React, { useState, useContext } from "react"; import { Input, Stack, FormControl, Button, FormHelperText, FormLabel, Alert, AlertIcon, AlertDescription, CloseButton, } from "@chakra-ui/core"; import UserInfoContext from "../utils/UserInfoContext"; import { loginUser } from "../utils/API"; import AuthService from "../utils/auth"; function LoginForm() { const [userFormData, setUserFormData] = useState({ username: "", password: "", }); const [showAlert, setShowAlert] = useState(false); const [errorText, setErrorText] = useState(""); const userData = useContext(UserInfoContext); const handleInputChange = (e) => { const { name, value } = e.target; setUserFormData({ ...userFormData, [name]: value }); }; const handleFormSubmit = (e) => { e.preventDefault(); loginUser(userFormData) .then(({ data }) => { // console.log(data); AuthService.login(data.token); userData.getUserData(); //onClose(); }) .catch((err) => { console.log(err.response); setShowAlert(true); setErrorText(err.response.data.message); }); }; return ( <form onSubmit={handleFormSubmit}> {showAlert ? ( <Alert status='error'> <AlertIcon /> {errorText || "Something went wrong with your login credentials!"} <CloseButton onClick={() => setShowAlert(false)} position='absolute' right='8px' top='8px' /> ) : ( "" )} <Stack spacing={3} my={3}> <FormControl isRequired> <Input name='username' placeholder='Username' aria-label='username' onChange={handleInputChange} value={userFormData.username} /> <FormControl isRequired> <Input name='password' type='password' placeholder='Password' aria-label='password' onChange={handleInputChange} value={userFormData.password} /> <Button type='submit' rounded='lg' backgroundImage='linear-gradient(315deg, rgba(255,255,255,0) 0%, rgba(254,37,194,0.20211834733893552) 100%)' > Log in <FormHelperText textAlign='center'>Welcome! ); } export default LoginForm;
javascript
18
0.55833
118
23.614679
109
starcoderdata
import 'babel/polyfill'; class MessageRoutes extends React.Component { render() { console.log('render MessageRoutes'); return ( <table className="table table-striped table-hover"> <th className="per60">Name <th className="per20">Date <th className="per20">Machine {this.renderRows()} ); } renderRows() { return this.props.routes.map((item, index) => this.renderRow(item)); } renderRow(item) { var boundClick = this.props.onRouteItemSelected.bind(this, item.id); return ( <tr onClick={boundClick}> ); } } export default Relay.createContainer(MessageRoutes, { fragments: { routes: () => Relay.QL` fragment on MessageRoute @relay(plural: true) { id, createdOn, machine, root { name } }, `, }, });
javascript
12
0.54047
72
21.529412
51
starcoderdata
function drawCircle(v1,radius){ circle(v1.x,v1.y,radius); } function drawLine(v1,v2,color=undefined){ if(color){ stroke(color); } line(v1.x,v1.y,v2.x,v2.y); }
javascript
6
0.669355
60
21.636364
11
starcoderdata
/*++ Copyright (c) 1995 Intel Corp File Name: huerror.cpp Abstract: Error functions. Author: --*/ #include "nowarn.h" /* turn off benign warnings */ #include #include "huerror.h" static ErrorCode_e HULastError = ENONE; void HUSetLastError(ErrorCode_e ErrorCode) { HULastError = ErrorCode; } ErrorCode_e HUGetLastError() { return HULastError; } void HUPrintError(char *func,ErrorCode_e ErrorCode) { if(func == NULL){ printf("Error: - - "); }else{ printf("Error: %s - - ",func); } switch(ErrorCode){ case ENONE: printf("No error\n"); break; case ALLOCERROR: printf("Allocation error\n"); break; case INVALIDARG: printf("Invalid arguement passed in\n"); break; case OBJNOTINIT: printf("Object not initialized\n"); break; case OBJEFFERROR: printf("Object becoming ineffecient. Trying making it large\n"); break; case ALREADYCONN: printf("Already connected\n"); break; default: printf("ErrorCode not defined\n"); } }
c++
10
0.608266
65
15.390625
64
starcoderdata
def initializeSimModel(self, client_ID): try: print ('Connected to remote API server') client_ID != -1 except: print ('Failed connecting to remote API server') self.client_ID = client_ID return_code, self.joint_1_handle = vrep_sim.simxGetObjectHandle(client_ID, 'joint_1', vrep_sim.simx_opmode_blocking) if (return_code == vrep_sim.simx_return_ok): print('get object joint 1 ok.') return_code, self.joint_2_handle = vrep_sim.simxGetObjectHandle(client_ID, 'joint_2', vrep_sim.simx_opmode_blocking) if (return_code == vrep_sim.simx_return_ok): print('get object joint 2 ok.') # Get the joint position return_code, q = vrep_sim.simxGetJointPosition(self.client_ID, self.joint_1_handle, vrep_sim.simx_opmode_streaming) return_code, q = vrep_sim.simxGetJointPosition(self.client_ID, self.joint_2_handle, vrep_sim.simx_opmode_streaming) self.setJointTorque(0)
python
10
0.633528
124
46.952381
21
inline
// import * as matter from 'gray-matter'; import { URL_PARAMS } from '../common/config'; export const store = { cdnRoot: '', version: '', locale: '', darkMode: URL_PARAMS.theme === 'dark', enableDecal: 'decal' in URL_PARAMS, renderer: URL_PARAMS.renderer || 'canvas', typeCheck: URL_PARAMS.editor === 'monaco', useDirtyRect: 'useDirtyRect' in URL_PARAMS, runCode: '', sourceCode: '', runHash: '', isMobile: window.innerWidth < 600, editorStatus: { type: '', message: '' } }; export function loadExampleCode() { return new Promise((resolve) => { $.ajax( `/src/${URL_PARAMS.c}.js`, { dataType: 'text', success: (data) => { resolve(data); } } ); }); } export function parseSourceCode(code) { return code.replace(/\/\*[\w\W]*?\*\//, '').trim(); } let hashId = 123; export function updateRunHash() { store.runHash = hashId++; }
javascript
19
0.51489
55
19.431373
51
starcoderdata
package com.hans.wanandroid.view.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.hans.wanandroid.R; import com.hans.wanandroid.databinding.FragmentUserCenterBinding; import com.hans.wanandroid.libpack.BaseFragment; import com.hans.wanandroid.viewmodel.UserCenterFVM; /** * A simple {@link Fragment} subclass. */ public class UserCenterFragment extends BaseFragment { private UserCenterFVM userCenterFVM; public UserCenterFragment() { // Required empty public constructor } @Override protected int getLayoutId() { return R.layout.fragment_user_center; } @Override protected void init() { userCenterFVM = new UserCenterFVM(context, viewBinding); viewBinding.setUserCenterFVM(userCenterFVM); } @Override public void onResume() { super.onResume(); userCenterFVM.refreshLoginStatus(); } }
java
7
0.740545
85
24.840909
44
starcoderdata
public static Material getMaterial(Item item) { // TODO: Don't use ID Material material = Material.getMaterial(Item.getIdFromItem(item)); if (material == null) { return Material.AIR; } return material; }
java
9
0.586207
75
25.2
10
inline
import java.util.ArrayList; public class LaBoucleForEach { public static void main(String[] args) { System.out.println("Les couleurs présentes dans le tableau:"); String[] tablo={"rouge","vert","bleu","blanc"}; /*for (int cpt = 0; cpt < tablo.length; cpt++) { System.out.println(tablo[cpt]); }*/ for (String s : tablo) { System.out.println(s); } System.out.println(); System.out.println("Liste de clients et tentative de modification dans une boucle foreach"); ArrayList lst=new ArrayList lst.add("client 1"); lst.add("client 2"); lst.add("client 3"); lst.add("client 5"); for(String st:lst) { System.out.println(st); if(st.endsWith("3")) { //La ligne suivante provoque une erreur car pendant l'itération lst est en lecture seule lst.add("client 4"); } } } }
java
13
0.612761
94
22.921053
38
starcoderdata
public bool Write(bool val) { if (currentBitByte == -1) { //CheckRealloc(1); // except when the capacity is 0 this is useless currentBitByte = Position++; } if (bitsWritten == 8) // old byte is full { CheckRealloc(1); data[currentBitByte] = (byte)bitByte; currentBitByte = Position++; bitsWritten = 0; bitByte = 0; } if (val) { bitByte |= (1 << bitsWritten); } bitsWritten++; return val; }
c#
11
0.398801
83
26.833333
24
inline
public override void EnterPackageClause(GoParser.PackageClauseContext context) { base.EnterPackageClause(context); // Go package clause is the first keyword encountered - cache details that // will be written out after imports. C# import statements (i.e., usings) // typically occur before namespace and class definitions string[] paths = PackageImport.Split('/').Select(SanitizedIdentifier).ToArray(); string packageNamespace = $"{RootNamespace}.{string.Join(".", paths)}"; PackageUsing = $"{Package} = {packageNamespace}{ClassSuffix}"; PackageNamespace = packageNamespace.Substring(0, packageNamespace.LastIndexOf('.')); // Track file name associated with package AddFileToPackage(Package, TargetFileName, PackageNamespace); // Define namespaces List<string> packageNamespaces = new List<string> { RootNamespace }; if (paths.Length > 1) { packageNamespaces.AddRange(paths); packageNamespaces.RemoveAt(packageNamespaces.Count - 1); } PackageNamespaces = packageNamespaces.ToArray(); string headerLevelComments = CheckForCommentsLeft(context); m_packageLevelComments = CheckForCommentsRight(context); if (!string.IsNullOrWhiteSpace(headerLevelComments)) { if (m_targetFile.Length == 0) headerLevelComments = headerLevelComments.TrimStart(); m_targetFile.Append(headerLevelComments); if (!EndsWithLineFeed(headerLevelComments)) m_targetFile.AppendLine(); } if (!Options.ExcludeHeaderComments) { m_targetFile.AppendLine($"// package {Package} -- go2cs converted at {DateTime.UtcNow:yyyy MMMM dd HH:mm:ss} UTC"); if (!PackageImport.Equals("main")) m_targetFile.AppendLine($"// import \"{PackageImport}\" ==> using {PackageUsing}"); m_targetFile.AppendLine($"// Original source: {SourceFileName}"); } // Add commonly required using statements RequiredUsings.Add("static go.builtin"); }
c#
16
0.602769
131
41.814815
54
inline
#!/usr/bin/node var argv = require('minimist')(process.argv.slice(2)); //rename as needed. function main(argv) { //parse args //do stuff //display output console.log(argv); } main(argv);
javascript
5
0.661017
55
13.75
16
starcoderdata
const { formatEther } = require("ethers/lib/utils"); const { ethers, network } = require("hardhat"); const { replaceInFile } = require("replace-in-file"); const { parseEther } = ethers.utils; const { BN } = require("@openzeppelin/test-helpers"); const replaceTokenAddress = async (name, address) => { address = await ethers.utils.getAddress(address); const result = await replaceInFile({ files: "test/tokens/" + name + ".json", from: new RegExp('"31337": "0x([0-9a-fA-F]{40})"'), to: '"31337": "' + address + '"', }); return result.filter(file => file.hasChanged); }; module.exports = async ({ getNamedAccounts, deployments }) => { const { deployer } = await getNamedAccounts(); const { deploy } = deployments; console.log("deploying 01erc20", network.name); if (network.name === "hardhat" || network.name === "localhost") { const TestWrbtc = await ethers.getContractFactory("TestWrbtc"); const wrbtcToken = await TestWrbtc.deploy(); await wrbtcToken.deployed(); await replaceTokenAddress("WRBTC", wrbtcToken.address); console.log("wrbtc:", wrbtcToken.address) const TestToken = await ethers.getContractFactory("TestToken"); const protocolToken = await TestToken.deploy('PROTOCOL', 'PROTOCOL', 18, parseEther('1000')); await protocolToken.deployed(); const xusdToken = await TestToken.deploy('XUSD', 'XUSD', 18, parseEther('10000000')) await xusdToken.deployed(); await replaceTokenAddress("XUSD", xusdToken.address); console.log("usd: ",xusdToken.address) const sovToken = await TestToken.deploy('SOV', 'SOV', 18, parseEther('10000000')) await sovToken.deployed(); await replaceTokenAddress("SOV", sovToken.address); console.log("sov: ", sovToken.address) const simulatorPriceFeeds = await deploy("PriceFeedsLocal", { args: [wrbtcToken.address, protocolToken.address], from: deployer, log: true, }); const priceFeeds = await ethers.getContract("PriceFeedsLocal", deployer); const wei = web3.utils.toWei; const oneEth = new BN(wei("1", "ether")); await priceFeeds.setRates(wrbtcToken.address, protocolToken.address, oneEth.toString()); await priceFeeds.setRates(wrbtcToken.address, xusdToken.address, new BN(10).pow(new BN(21)).toString()); await priceFeeds.setRates(protocolToken.address, xusdToken.address, new BN(10).pow(new BN(21)).toString()); await priceFeeds.setRates(sovToken.address, xusdToken.address, new BN(10).pow(new BN(18)).toString()); const artifact = await deployments.getArtifact("TestSovrynSwap"); const contract = { abi: artifact.abi, bytecode: artifact.bytecode, }; await deploy("TestSovrynSwap", { contract, args: [simulatorPriceFeeds.address], from: deployer, log: true, }); const swap = await ethers.getContract("TestSovrynSwap", deployer); const path = await swap.conversionPath(wrbtcToken.address, xusdToken.address); const rbtcRate = await swap.rateByPath(path, parseEther('1')); console.log('rbtc rate', formatEther(rbtcRate)); } };
javascript
17
0.638522
115
42.789474
76
starcoderdata
/////////////////////////////////////////////////////////////////////////////// // For information as to what this class does, see the Javadoc, below. // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, // // 2007, 2008, 2009, 2010, 2014, 2015, 2022 by Peter Spirtes, Richard // // Scheines, Joseph Ramsey, and Clark Glymour. // // // // This program is free software; you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation; either version 2 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program; if not, write to the Free Software // // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // /////////////////////////////////////////////////////////////////////////////// package edu.cmu.tetradapp.editor; import edu.cmu.tetrad.data.Knowledge; import javax.swing.*; import java.awt.*; import java.util.Iterator; import java.util.LinkedList; import java.util.List; /** * The actual area which displays a knowledge constraint * * @author Shane Harwood */ class Tier extends JPanel { private final TierList knowList; //knowlist constraint is contained in private final int num; private final String[] tierNames; private final JPanel view = new JPanel(); private final JScrollPane jsp; private static Knowledge know; /** * A panel with a tier name, and all vars in that tier. */ public Tier(TierList kn, int thisTier, String[] tierNames) { this.jsp = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); this.knowList = kn; this.num = thisTier; this.tierNames = tierNames; setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); this.jsp.setViewportView(this.view); } public static void setKnowledge(Knowledge k) { Tier.know = k; } /** * tell tier what info it should hold and represent, used for constant * updating of tiers */ public void loadInfo() { removeAll(); this.view.removeAll(); add(new JLabel("Tier " + this.num)); add(this.jsp); List<String> t = Tier.know.getTier(this.num); this.view.setLayout(new BoxLayout(this.view, BoxLayout.X_AXIS)); Iterator it = t.iterator(); String temp; while (it.hasNext()) { temp = (String) it.next(); String[] names = new String[this.tierNames.length + 1]; names[0] = temp; System.arraycopy(this.tierNames, 0, names, 1, this.tierNames.length); JComboBox cBox = new JComboBox(names); cBox.setMaximumSize(new Dimension(80, 50)); this.view.add(cBox); cBox.addActionListener(e -> { JComboBox cb = (JComboBox) e.getSource(); int newTier = cb.getSelectedIndex() - 2; String s = (String) cb.getItemAt(0); if (newTier == -2) { return; } //know.unspecifyTier(s); Tier.know.removeFromTiers(s); if (newTier >= 0) { Tier.know.addToTier(newTier, s); } Tier.this.knowList.refreshInfo(); }); } } public void setUnspecified(List<String> varNames) { removeAll(); this.view.removeAll(); add(new JLabel("Unspecified")); add(this.jsp); List<String> vNames = new LinkedList<>(varNames); System.out.println("edit unspecified list"); System.out.println("vNames Contains: " + vNames); for (int i = 0; i < Tier.know.getNumTiers(); i++) { System.out.println("Tier " + i); List t = Tier.know.getTier(i); System.out.println("Tier contains: " + t); Iterator it = t.iterator(); String temp; while (it.hasNext()) { temp = (String) it.next(); System.out.println("Try removing: " + temp); vNames.remove(temp); } } System.out.println("vNames now Contains: " + vNames); this.view.setLayout(new BoxLayout(this.view, BoxLayout.X_AXIS)); Iterator it = vNames.iterator(); String temp; while (it.hasNext()) { temp = (String) it.next(); String[] names = new String[this.tierNames.length + 1]; names[0] = temp; System.arraycopy(this.tierNames, 0, names, 1, this.tierNames.length); JComboBox cBox = new JComboBox(names); cBox.setMaximumSize(new Dimension(80, 50)); this.view.add(cBox); cBox.addActionListener(e -> { JComboBox cb = (JComboBox) e.getSource(); int newTier = cb.getSelectedIndex() - 2; String s = (String) cb.getItemAt(0); if (newTier == -2) { return; } //know.unspecifyTier(s); Tier.know.removeFromTiers(s); if (newTier >= 0) { Tier.know.addToTier(newTier, s); } Tier.this.knowList.refreshInfo(); }); } } // ======= The following make sure constraint is the proper size ======// public Dimension getPreferredSize() { return new Dimension(1000, 60); } public Dimension getMinimumSize() { return new Dimension(250, 60); } public Dimension getMaximumSize() { return new Dimension(2000, 60); } }
java
17
0.519552
81
29.050691
217
research_code
import React from 'react'; import { Link } from 'react-router-dom'; const MenuItem = ({text, iconPath, url}) => ( <li className="menu-item"> <img alt="" className="icon" src={iconPath} /> {url ? <Link to={url}>{text} : text} {styles} ); const styles = <style jsx>{` li.menu-item { box-sizing: border-box; height: 20px; margin: 4px 0; padding: 5px; position: relative; text-indent: 30px; } .icon { position: absolute; left: 10px; top: 4px; } `} export default MenuItem;
javascript
9
0.602024
50
18.766667
30
starcoderdata
class L2_8{ public static void main(String[] args){ int num /*maior data*/ = datam(22,05,74,22,03,74); System.out.println("A data cronologicamente maior de duas datas e = "+num); } static int datam(int d1, int m1, int a1, int d2, int m2, int a2){ /* d1m1a1(dia, mes e ano 1); d2m2a2(dia, mes e ano 2)*/ String maior1 = "" + d1+m1+a1;/*maior data*/ String maior2 = "" + d2+m2+a2;/*maior data*/ int ma1 = Integer.parseInt (maior1); int ma2 = Integer.parseInt (maior2); if (a1<a2) return (ma1); if (a2<a1) return (ma2); if (a1==a2 && m1>m2) return (ma1); if (a1==a2 && m1<m2) return (ma2); if (a1==a2 && m1==m2 && d1>d2) return (ma1); if (a1==a2 && m1==m2 && d1<d2) return (ma2); if (a1==a2 && m1==m2 && d1==d2) return (ma1); else { return -1; } } }
java
9
0.564773
77
26.483871
31
starcoderdata
module.exports = { CreatedAgent: require('./src/agent/CreatedAgent'), CreatedAgentConnection: require('./src/agent/CreatedAgentConnection'), DestroyedAgent: require('./src/agent/DestroyedAgent'), KeptSocketAliveOfAgent: require('./src/agent/KeptSocketAliveOfAgent'), MaxFreeSocketsOfAgent: require('./src/agent/MaxFreeSocketsOfAgent'), MaxSocketsOfAgent: require('./src/agent/MaxSocketsOfAgent'), NameOfAgent: require('./src/agent/NameOfAgent'), RequestsOfAgent: require('./src/agent/RequestsOfAgent'), ReusedSocketOfAgent: require('./src/agent/ReusedSocketOfAgent'), SocketsOfAgent: require('./src/agent/SocketsOfAgent'), CreatedHttpServer: require('./src/http/CreatedHttpServer'), HttpGetRequest: require('./src/http/HttpGetRequest'), HttpRequest: require('./src/http/HttpRequest'), ResponseBody: require('./src/http/ResponseBody'), ResponseFromHttpGetRequest: require('./src/http/ResponseFromHttpGetRequest'), ResponseFromHttpRequest: require('./src/http/ResponseFromHttpRequest'), ResponseHeaders: require('./src/http/ResponseHeaders'), ResponseStatusCode: require('./src/http/ResponseStatusCode'), DestroyedIncomingMessage: require('./src/incoming-message/DestroyedIncomingMessage'), HeadersOfIncomingMessage: require('./src/incoming-message/HeadersOfIncomingMessage'), HttpVersionOfIncomingMessage: require('./src/incoming-message/HttpVersionOfIncomingMessage'), IncomingMessageWithAbortedEvent: require('./src/incoming-message/IncomingMessageWithAbortedEvent'), IncomingMessageWithCloseEvent: require('./src/incoming-message/IncomingMessageWithCloseEvent'), IncomingMessageWithTimeout: require('./src/incoming-message/IncomingMessageWithTimeout'), MethodOfIncomingMessage: require('./src/incoming-message/MethodOfIncomingMessage'), RawHeadersOfIncomingMessage: require('./src/incoming-message/RawHeadersOfIncomingMessage'), RawTrailersOfIncomingMessage: require('./src/incoming-message/RawTrailersOfIncomingMessage'), SocketOfIncomingMessage: require('./src/incoming-message/SocketOfIncomingMessage'), StatusCodeOfIncomingMessage: require('./src/incoming-message/StatusCodeOfIncomingMessage'), StatusMessageOfIncomingMessage: require('./src/incoming-message/StatusMessageOfIncomingMessage'), TrailersOfIncomingMessage: require('./src/incoming-message/TrailersOfIncomingMessage'), UrlOfIncomingMessage: require('./src/incoming-message/UrlOfIncomingMessage'), CreatedOptions: require('./src/options/CreatedOptions'), OptionsWithAgent: require('./src/options/OptionsWithAgent'), AbortedRequest: require('./src/request/AbortedRequest'), EndedRequest: require('./src/request/EndedRequest'), RequestAbortedTime: require('./src/request/RequestAbortedTime'), RequestHeader: require('./src/request/RequestHeader'), RequestWithAbortEvent: require('./src/request/RequestWithAbortEvent'), RequestWithConnectEvent: require('./src/request/RequestWithConnectEvent'), RequestWithContinueEvent: require('./src/request/RequestWithContinueEvent'), RequestWithDataEvent: require('./src/request/RequestWithDataEvent'), RequestWithEndEvent: require('./src/request/RequestWithEndEvent'), RequestWithErrorEvent: require('./src/request/RequestWithErrorEvent'), RequestWithFlushedHeaders: require('./src/request/RequestWithFlushedHeaders'), RequestWithHeader: require('./src/request/RequestWithHeader'), RequestWithNoDelay: require('./src/request/RequestWithNoDelay'), RequestWithRemovedHeader: require('./src/request/RequestWithRemovedHeader'), RequestWithResponseEvent: require('./src/request/RequestWithResponseEvent'), RequestWithSocketEvent: require('./src/request/RequestWithSocketEvent'), RequestWithSocketKeepAlive: require('./src/request/RequestWithSocketKeepAlive'), RequestWithTimeout: require('./src/request/RequestWithTimeout'), RequestWithTimeoutEvent: require('./src/request/RequestWithTimeoutEvent'), RequestWithUpgradeEvent: require('./src/request/RequestWithUpgradeEvent'), SocketOfRequest: require('./src/request/SocketOfRequest'), WrittenRequest: require('./src/request/WrittenRequest'), ConnectionOfResponse: require('./src/response/ConnectionOfResponse'), EndedResponse: require('./src/response/EndedResponse'), HasResponseHeader: require('./src/response/HasResponseHeader'), HeaderNamesOfResponse: require('./src/response/HeaderNamesOfResponse'), HeaderOfResponse: require('./src/response/HeaderOfResponse'), HeadersOfResponse: require('./src/response/HeadersOfResponse'), IsResponseFinished: require('./src/response/IsResponseFinished'), ResponseWithAddedTrailers: require('./src/response/ResponseWithAddedTrailers'), ResponseWithCloseEvent: require('./src/response/ResponseWithCloseEvent'), ResponseWithFinishEvent: require('./src/response/ResponseWithFinishEvent'), ResponseWithHeader: require('./src/response/ResponseWithHeader'), ResponseWithHeaders: require('./src/response/ResponseWithHeaders'), ResponseWithRemovedHeader: require('./src/response/ResponseWithRemovedHeader'), ResponseWithStatusCode: require('./src/response/ResponseWithStatusCode'), ResponseWithStatusMessage: require('./src/response/ResponseWithStatusMessage'), ResponseWithTimeout: require('./src/response/ResponseWithTimeout'), ResponseWithWrittenHead: require('./src/response/ResponseWithWrittenHead'), SendDateOfResponse: require('./src/response/SendDateOfResponse'), SocketOfResponse: require('./src/response/SocketOfResponse'), StatusCodeOfResponse: require('./src/response/StatusCodeOfResponse'), StatusMessageOfResponse: require('./src/response/StatusMessageOfResponse'), WereResponseHeadersSent: require('./src/response/WereResponseHeadersSent'), WrittenContinueResponse: require('./src/response/WrittenContinueResponse'), WrittenResponse: require('./src/response/WrittenResponse'), ClosedServer: require('./src/server/ClosedServer'), IsServerListening: require('./src/server/IsServerListening'), KeepAliveTimeoutOfServer: require('./src/server/KeepAliveTimeoutOfServer'), ListeningServer: require('./src/server/ListeningServer'), MaxHeadersCountOfServer: require('./src/server/MaxHeadersCountOfServer'), ServerWithCheckContinueEvent: require('./src/server/ServerWithCheckContinueEvent'), ServerWithCheckExpectationEvent: require('./src/server/ServerWithCheckExpectationEvent'), ServerWithClientErrorEvent: require('./src/server/ServerWithClientErrorEvent'), ServerWithCloseEvent: require('./src/server/ServerWithCloseEvent'), ServerWithConnectEvent: require('./src/server/ServerWithConnectEvent'), ServerWithConnectionEvent: require('./src/server/ServerWithConnectionEvent'), ServerWithRequestEvent: require('./src/server/ServerWithRequestEvent'), ServerWithTimeout: require('./src/server/ServerWithTimeout'), ServerWithUpgradeEvent: require('./src/server/ServerWithUpgradeEvent'), TimeoutOfServer: require('./src/server/TimeoutOfServer') }
javascript
8
0.803839
101
64.980952
105
starcoderdata
/** * Personium * Copyright 2014-2021 - Personium Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.personium.client; import java.util.HashMap; import io.personium.client.http.IRestAdapter; import io.personium.client.http.PersoniumResponse; import io.personium.client.http.RestAdapterFactory; ///** // * EventLog取得のためのクラス. // */ /** * THis is the class for EventLog acquisition. */ public abstract class LogManager { // /** アクセス主体. */ /** Reference to Accessor. */ Accessor accessor; // /** // * イベントログのURLを取得します. // * @param filename イベントログのファイル名 // * @return イベントログのURL // */ /** * This method is used to get the URL of the event log. * @param filename File Name of the event log * @return Event Log URL * @throws DaoException DaoException */ protected abstract String getLogUrl(String filename) throws DaoException; // /** // * コンストラクタ. // * @param as アクセス主体 // */ /** * This is the parameterized constructor with one argument initializing the accessor. * @param as Accessor */ public LogManager(Accessor as) { this.accessor = as.clone(); } // /** // * イベントログをString形式で取得します. // * @param filename 取得するファイル名 // * @return イベントログ情報 // * @throws DaoException DAO例外 // */ /** * This method is used to get a String representation of the event log. * @param filename File Name * @return Event Log Information * @throws DaoException Exception thrown */ public WebDAV getString(String filename) throws DaoException { return getString(filename, null); } // /** // * イベントログをString形式で取得します. // * @param filename 取得するファイル名 // * @param personiumKey X-Personium-RequestKeyヘッダの値 // * @return イベントログ情報 // * @throws DaoException DAO例外 // */ /** * This method is used to get a String representation of the event log. * @param filename File Name * @param personiumKey X-Personium-RequestKey Header * @return Event Log Information * @throws DaoException Exception thrown */ public WebDAV getString(String filename, String personiumKey) throws DaoException { String url = this.getLogUrl(filename); return getStringEventLog(url, personiumKey); } // /** // * イベントログをStream形式で取得します. // * @param filename 取得するファイル名 // * @return イベントログ情報 // * @throws DaoException DAO例外 // */ /** * This method is used to get event log in the Stream format. * @param filename File Name * @return Event Log Information * @throws DaoException Exception thrown */ public WebDAV getStream(String filename) throws DaoException { return getStream(filename, null); } // /** // * イベントログをStream形式で取得します. // * @param filename 取得するファイル名 // * @param personiumKey X-Personium-RequestKeyヘッダの値 // * @return イベントログ情報 // * @throws DaoException DAO例外 // */ /** * This method is used to get event log in the Stream format. * @param filename File Name * @param personiumKey X-Personium-RequestKey Header * @return Event Log Information * @throws DaoException Exception thrown */ public WebDAV getStream(String filename, String personiumKey) throws DaoException { String url = this.getLogUrl(filename); return getStreamEventLog(url, personiumKey); } /** * This method is used to get event log in the Stream format. * @param url Value * @param personiumKey X-Personium-RequestKey Header * @return Event Log Information * @throws DaoException Exception thrown */ private WebDAV getStreamEventLog(String url, String personiumKey) throws DaoException { IRestAdapter rest = RestAdapterFactory.create(accessor); HashMap<String, String> headers = new HashMap<String, String>(); if (personiumKey != null) { headers.put("X-Personium-RequestKey", personiumKey); } PersoniumResponse res; try { res = rest.get(url, headers, "application/octet-stream"); } catch (DaoException e) { throw e; } WebDAV webDAV = new WebDAV(); webDAV.setStreamBody(res.bodyAsStream()); webDAV.setResHeaders(res.getHeaderList()); return webDAV; } /** * This method is used to get event log in the String format. * @param url Value * @param personiumKey X-Personium-RequestKey Header * @return Event Log Information * @throws DaoException Exception thrown */ private WebDAV getStringEventLog(String url, String personiumKey) throws DaoException { IRestAdapter rest = RestAdapterFactory.create(accessor); HashMap<String, String> headers = new HashMap<String, String>(); if (personiumKey != null) { headers.put("X-Personium-RequestKey", personiumKey); } PersoniumResponse res; try { res = rest.get(url, headers, "text/plain"); } catch (DaoException e) { throw e; } // レスポンスボディを取得 /** Get the response body. */ String body = res.bodyAsString(); WebDAV webDAV = new WebDAV(); webDAV.setStringBody(body); webDAV.setResHeaders(res.getHeaderList()); return webDAV; } }
java
12
0.640662
91
30.168421
190
starcoderdata
package lorikeet.core; import org.junit.Test; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import static org.assertj.core.api.Assertions.assertThat; public class FallibleStreamTest { @Test public void testYieldOkCoalesce() { var r = new FallibleStream() .include(new Ok<>(2)) .coalesce((num) -> num * 2); assertThat(r.orPanic()).isEqualTo(4); } @Test public void testYieldErrCoalesce() { AtomicInteger counter = new AtomicInteger(0); var r = new FallibleStream() .include(new Err RuntimeException())) .coalesce((num) -> { counter.incrementAndGet(); return num * 2; }); assertThat(r.failure()).isTrue(); assertThat(counter.get()).isEqualTo(0); } @Test public void testYieldOptionalCoalesce() { var r = new FallibleStream() .include(Optional.of(2)) .coalesce((num) -> num * 2); assertThat(r.orPanic()).isEqualTo(4); } @Test public void testCoalesceFallibleOk() { var r = new FallibleStream() .include(Optional.of(2)) .coalescef((num) -> new Ok<>(num * 2)); assertThat(r.orPanic()).isEqualTo(4); } @Test public void testCoalesceFallibleErr() { var r = new FallibleStream() .include(Optional.of(2)) .coalescef((num) -> new Err<>(new RuntimeException())); assertThat(r.failure()).isTrue(); } @Test public void testCoalesceOptionalOf() { var r = new FallibleStream() .include(Optional.of(2)) .coalesceo((num) -> Optional.of(num * 2)); assertThat(r.orPanic()).isEqualTo(4); } @Test public void testCoalesceOptionalEmpty() { var r = new FallibleStream() .include(Optional.of(2)) .coalesceo((num) -> Optional.empty()); assertThat(r.failure()).isTrue(); } @Test public void testCoalesce2FallibleOk() { var r = new FallibleStream() .include(new Ok<>(4)) .include((a) -> a * 2) .coalesce(Integer::sum) .orPanic(); assertThat(r).isEqualTo(12); } @Test public void testCoalesce2FallibleErr() { var r = new FallibleStream() .include(new Ok<>(4)) .include((a) -> a * 2) .coalescef((a, b) -> new Err RuntimeException())) .failure(); assertThat(r).isTrue(); } @Test public void testCoalesce2OptionalOf() { var r = new FallibleStream() .include(new Ok<>(4)) .include((a) -> a * 2) .coalesceo((a, b) -> Optional.of(a + b)) .orPanic(); assertThat(r).isEqualTo(12); } @Test public void testInclude3() { var r = new FallibleStream() .include(new Ok<>(4)) .include((a) -> a * 2) .includef((a, b) -> new Ok<>(a + b)) .coalescef((a, b, c) -> new Ok<>(a + b + c)) .orPanic(); assertThat(r).isEqualTo(24); } @Test public void testInclude3CoalesceValue() { var r = new FallibleStream() .include(new Ok<>(4)) .includeo((a) -> Optional.of(a * 2)) .includef((a, b) -> new Ok<>(a + b)) .coalesce((a, b, c) -> a + b + c) .orPanic(); assertThat(r).isEqualTo(24); } }
java
14
0.529102
74
25.152174
138
starcoderdata
def mobilenet_base(scope, inputs, conv_defs, batch_norm_decay=0.95, is_training=True, reuse=None): end_points = {} with tf.variable_scope(scope, inputs, reuse=reuse): with slim.arg_scope([slim.conv2d, slim.separable_conv2d], padding='SAME'): with slim.arg_scope([slim.batch_norm], is_training=is_training, decay=batch_norm_decay): net = inputs for i, conv_def in enumerate(conv_defs): end_point_base = 'Conv2d_%d' % i if isinstance(conv_def, Conv): end_point = end_point_base net = slim.conv2d(net, conv_def.depth, conv_def.kernel, stride=conv_def.stride, normalizer_fn=slim.batch_norm, scope=end_point) end_points[end_point] = net elif isinstance(conv_def, DepthSepConv): end_point = end_point_base + '_depthwise' # By passing filters=None separable_conv2d produces # only a depthwise convolution layer net = slim.separable_conv2d(net, None, conv_def.kernel, depth_multiplier=1, stride=conv_def.stride, normalizer_fn=slim.batch_norm, scope=end_point) end_points[end_point] = net end_point = end_point_base + '_pointwise' net = slim.conv2d(net, conv_def.depth, [1, 1], stride=1, normalizer_fn=slim.batch_norm, scope=end_point) end_points[end_point] = net else: raise ValueError('Unknown convolution type %s for ' 'layer %d' % (conv_def.ltype, i)) return net, end_points
python
20
0.441948
79
47.568182
44
inline
uint8_t Si4703_Init_I2C(uint32_t I2C_Clock_Speed) { GPIO_InitTypeDef PORT; // Enable peripheral clocks for PortB RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); // Set RST(PB5) and SDIO(PB7/SDA) as output PORT.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_7; PORT.GPIO_Mode = GPIO_Mode_Out_PP; PORT.GPIO_Speed = GPIO_Speed_2MHz; GPIO_Init(GPIOB,&PORT); GPIO_WriteBit(GPIOB,GPIO_Pin_5,Bit_RESET); // Pull RST low (Si4703 reset operation) GPIO_WriteBit(GPIOB,GPIO_Pin_7,Bit_RESET); // Select 2-wire interface (I2C) Delay_ms(1); // Just wait GPIO_WriteBit(GPIOB,GPIO_Pin_5,Bit_SET); // Pull RST high (Si4703 normal operation) Delay_ms(1); // Give Si4703 some time to rise after reset // Init I2C RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); PORT.GPIO_Pin = I2C_SDA_PIN | I2C_SCL_PIN; PORT.GPIO_Mode = GPIO_Mode_AF_OD; PORT.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(I2C_GPIO_PORT,&PORT); I2C_InitTypeDef I2CInit; RCC_APB1PeriphClockCmd(I2C_CLOCK,ENABLE); // Enable I2C clock RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); I2C_DeInit(I2C_PORT); // I2C reset to initial state I2CInit.I2C_Mode = I2C_Mode_I2C; // I2C mode is I2C I2CInit.I2C_DutyCycle = I2C_DutyCycle_2; // I2C fast mode duty cycle (WTF is this?) I2CInit.I2C_OwnAddress1 = 1; // This device address (7-bit or 10-bit) I2CInit.I2C_Ack = I2C_Ack_Disable; // Acknowledgment I2CInit.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; // choose 7-bit address for acknowledgment I2CInit.I2C_ClockSpeed = I2C_Clock_Speed; I2C_Cmd(I2C_PORT,ENABLE); // Enable I2C I2C_Init(I2C_PORT,&I2CInit); // Configure I2C // WARNING: THERE WILL HANG IF NO RESPOND FROM I2C DEVICE while (I2C_GetFlagStatus(I2C_PORT,I2C_FLAG_BUSY)); // Wait until I2C free return 0; }
c
7
0.726602
107
41
42
inline
void QtTableView::updateTableSize() { bool updateOn = autoUpdate(); setAutoUpdate( FALSE ); int xofs = xOffset(); xOffs++; //so that setOffset will not return immediately setOffset(xofs,yOffset(),FALSE); //to calculate internal state correctly setAutoUpdate(updateOn); updateScrollBars( horSteps | horRange | verSteps | verRange ); showOrHideScrollBars(); }
c++
9
0.6875
76
29.846154
13
inline
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Confuser.Core; using Confuser.Core.Services; using dnlib.DotNet; using dnlib.DotNet.Emit; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ILogger = Microsoft.Extensions.Logging.ILogger; namespace Confuser.Protections.Constants { using ReferenceList = List<(MethodDef, Instruction)>; using BlockReferenceList = List<(MethodDef Method, Instruction Instruction, TypeSig TypeSig, int Size)>; using ReferenceEnumerable = IEnumerable<(MethodDef, Instruction)>; internal class EncodePhase : IProtectionPhase { public EncodePhase(ConstantProtection parent) => Parent = parent ?? throw new ArgumentNullException(nameof(parent)); public ConstantProtection Parent { get; } IConfuserComponent IProtectionPhase.Parent => Parent; public ProtectionTargets Targets => ProtectionTargets.Methods; public bool ProcessAll => false; public string Name => "Constants encoding"; void IProtectionPhase.Execute(IConfuserContext context, IProtectionParameters parameters, CancellationToken token) { var moduleCtx = context.Annotations.Get ConstantProtection.ContextKey); if (!parameters.Targets.Any() || moduleCtx?.EncodedReferences is null) return; var ldc = new Dictionary<object, ReferenceList>(); var ldInit = new Dictionary<byte[], ReferenceList>(); var logger = context.Registry.GetRequiredService moduleCtx.ReferenceRepl = new Dictionary<MethodDef, List<(Instruction TargetInstruction, uint Argument, IMethod DecoderMethod)>>(); var cmp = new SigComparer(0, moduleCtx.Module); foreach (var kvp in moduleCtx.EncodedReferences) { var bufferIndex = kvp.Key; foreach (var byType in kvp.Value.GroupBy(t => t.TypeSig)) { Func<DecoderDesc, byte> typeIdFunc; if (cmp.Equals(byType.Key, moduleCtx.Module.CorLibTypes.Int32) || cmp.Equals(byType.Key, moduleCtx.Module.CorLibTypes.Int64) || cmp.Equals(byType.Key, moduleCtx.Module.CorLibTypes.Single) || cmp.Equals(byType.Key, moduleCtx.Module.CorLibTypes.Double)) typeIdFunc = desc => desc.NumberID; else if (cmp.Equals(byType.Key, moduleCtx.Module.CorLibTypes.String)) typeIdFunc = desc => desc.StringID; else if (byType.Key is SZArraySig) typeIdFunc = desc => desc.InitializerID; else throw new InvalidOperationException("Unexpected type for constant: " + byType.Key.ToString()); UpdateReference(moduleCtx, byType.Key, byType.Select(t => (t.Method, t.Instruction)), bufferIndex, typeIdFunc); } } var encodedDataFields = new HashSet FieldEqualityComparer.CompareDeclaringTypes); var encodedFieldInstructions = new HashSet => i)); RemoveDataFieldRefs(context, encodedDataFields, encodedFieldInstructions); if (!ReferenceReplacer.ReplaceReference(Parent, moduleCtx, parameters)) return; var encodedBuff = moduleCtx.EncodedData; uint compressedLen = (uint)(encodedBuff.Length + 3) / 4; compressedLen = (compressedLen + 0xfu) & ~0xfu; var compressedBuff = new uint[compressedLen]; Buffer.BlockCopy(encodedBuff.ToArray(), 0, compressedBuff, 0, encodedBuff.Length); Debug.Assert(compressedLen % 0x10 == 0); // encrypt uint keySeed = moduleCtx.Random.NextUInt32(); var key = new uint[0x10]; uint state = keySeed; for (int i = 0; i < 0x10; i++) { state ^= state >> 12; state ^= state << 25; state ^= state >> 27; key[i] = state; } var encryptedBuffer = new byte[compressedBuff.Length * sizeof(int)]; var buffIndex = 0; while (buffIndex < compressedBuff.Length) { uint[] enc = moduleCtx.ModeHandler.Encrypt(compressedBuff, buffIndex, key); for (int j = 0; j < 0x10; j++) key[j] ^= compressedBuff[buffIndex + j]; Buffer.BlockCopy(enc, 0, encryptedBuffer, buffIndex * 4, 0x40); buffIndex += 0x10; } Debug.Assert(buffIndex == compressedBuff.Length); moduleCtx.DataField.InitialValue = encryptedBuffer; moduleCtx.DataField.HasFieldRVA = true; moduleCtx.DataType.ClassLayout = new ClassLayoutUser(0, (uint)encryptedBuffer.Length); moduleCtx.EncodingBufferSizeUpdate.ApplyValue(encryptedBuffer.Length / 4); moduleCtx.KeySeedUpdate.ApplyValue((int)keySeed); } private void UpdateReference(CEContext moduleCtx, TypeSig valueType, ReferenceEnumerable references, int buffIndex, Func<DecoderDesc, byte> typeId) { foreach (var instr in references) { var (method, decoderDesc) = moduleCtx.Decoders[moduleCtx.Random.NextInt32(moduleCtx.Decoders.Count)]; var id = (uint)(buffIndex | (typeId(decoderDesc) << 30)); id = moduleCtx.ModeHandler.Encode(decoderDesc.Data, moduleCtx, id); Debug.Assert((method.ReturnType as GenericSig)?.Number == 0); var targetDecoder = new MethodSpecUser(method, new GenericInstMethodSig(valueType)); Debug.Assert(instr.Item2.OpCode != OpCodes.Ldc_I4 || valueType == method.Module.CorLibTypes.Int32); Debug.Assert(instr.Item2.OpCode != OpCodes.Ldc_I8 || valueType == method.Module.CorLibTypes.Int64); Debug.Assert(instr.Item2.OpCode != OpCodes.Ldc_R4 || valueType == method.Module.CorLibTypes.Single); Debug.Assert(instr.Item2.OpCode != OpCodes.Ldc_R8 || valueType == method.Module.CorLibTypes.Double); Debug.Assert(instr.Item2.OpCode != OpCodes.Ldstr || valueType == method.Module.CorLibTypes.String); Debug.Assert(instr.Item2.OpCode != OpCodes.Call || valueType.IsSZArray); moduleCtx.ReferenceRepl.AddListEntry(instr.Item1, (instr.Item2, id, targetDecoder)); } } private static void RemoveDataFieldRefs(IConfuserContext context, ICollection dataFields, ICollection fieldRefs) { var instructions = context.CurrentModule.GetTypes() .SelectMany(type => type.Methods) .Where(method => method.HasBody) .SelectMany(method => method.Body.Instructions); foreach (var instr in instructions) if (instr.Operand is FieldDef fieldDef && !fieldRefs.Contains(instr)) dataFields.Remove(fieldDef); foreach (var fieldToRemove in dataFields) fieldToRemove.DeclaringType.Fields.Remove(fieldToRemove); } } }
c#
22
0.741173
139
42.147651
149
starcoderdata
func (mgr *flushManager) flushManagerWithLock() roleBasedFlushManager { switch mgr.electionState { case FollowerState: return mgr.followerMgr case LeaderState: return mgr.leaderMgr default: // We should never get here. panic(fmt.Sprintf("unknown election state %v", mgr.electionState)) } }
go
11
0.764901
71
26.545455
11
inline
import request from '@/router/axios'; export const loginByUsername = (data) => request({ url: '/api/login', method: 'post', meta: { isToken: false }, data: data }) export const getUserInfo = (data) => request({ url: `/api/users/${data}?include=groups`, method: 'get' }) // 获取微信登录二维码 export const getWxImagesCode = () => request({ url: `/api/oauth/wechat/pc/qrcode`, method: 'get' }) // 获取用户扫描状态 export const getWxImagesCodeSearch = (data) => request({ url: `/api/oauth/wechat/pc/login/${data}`, method: 'get' }) // 获取短信登陆验证码 export const getPhoneCode = (data) => request({ url: `/api/sms/send`, method: 'post', data }) // 短信登陆 export const loginByPhoneCode = (data) => request({ url: `/api/sms/verify`, method: 'post', data })
javascript
8
0.648718
56
17.139535
43
starcoderdata
private int handleCompound( CompoundStatement startNode, ASTNode endNode, int childnum) { // Note: These may be all kinds of AST nodes: instances of Statement, but also // instances of Expression, PHPFunctionDef, or even null nodes. startNode.addStatement(endNode); return 0; }
java
6
0.760417
87
35.125
8
inline
<?php namespace app\Home\controller; use think\Controller; use think\facade\Session; use think\Db; use think\facade\Request; class Chat extends Controller{ public function index(){ return $this->fetch(); } } ?>
php
8
0.750943
46
19.461538
13
starcoderdata
def dumptree(self, pn, indent=0): """ dump all nodes of the current b-tree """ page = self.readpage(pn) print(" " * indent, page) if page.isindex(): print(" " * indent, end="") self.dumptree(page.preceeding, indent + 1) for p in range(len(page.index)): print(" " * indent, end="") self.dumptree(page.getpage(p), indent + 1)
python
12
0.502347
58
41.7
10
inline
<div class="tabber" id="tab5" style="display: none;"> <div class="titleBar"> <i class="fa fa-youtube" style="float: right; font-size: 55px; padding: 10px 10px"> #2 - Video Your Video Content <?php // Add Your Options Here display_field_image( $_GET['id'], $results->step2Image, "Background Image", "step2Image", "Optionals" ); echo '<h2 class="headline">Video Content display_option( $_GET['id'], $results->videoType, "Video Type", "videoType", "Choose between Youtube and Vimeo for video.", "YouTube [youtube], Vimeo [vimeo]" ); display_field( $_GET['id'], $results->videoID, "YouTube or Vimeo ID", "videoID", "The ID for Your YouTube or Vimeo ID. Found in the URL." ); display_option( $_GET['id'], $results->videoStyle, "Style of Video Box", "videoStyle", "Choose The Style of The Video Box", "None [none], White [white], Black [black]" ); display_field( $_GET['id'], $results->skipButton, "Skip Button Text", "skipButton", "The Text for The Skip Video Button" ); display_option( $_GET['id'], $results->showSkip, "Show / Hide Skip", "showSkip", "Show or Hide the Skip Button", "Show [show], Hide [hide]" ); echo '<h2 class="headline">Facebook Comments display_option( $_GET['id'], $results->showFB, "Show / Hide Comments", "showFB", "Show or Hide the Comments", " Hide [hide],Show [show]" ); display_field( $_GET['id'], $results->fbURL, "FB Comment URL", "fbURL", "URL to Your Page or Another Page" ); display_option( $_GET['id'], $results->fbColor , "Light or Dark Comments", "fbColor", "Fit comments to your design.", "Light [light], Dark [dark]" ); ?>
php
7
0.588871
89
20.776471
85
starcoderdata
package athena.api; /** * Created by seunghyeon on 4/7/16. */ public interface ModelResult { DetectionAlgorithmType getDetectionAlgorithmType(); DetectionStrategy getDetectionStrategy(); }
java
5
0.766284
58
20.75
12
starcoderdata
namespace profile { static const uint64_t kUndefinedEventID = LLONG_MAX; /// @class ProfileEvent /// @brief Registers an event, for a thread, with the profiler class ProfileEvent { public: ProfileEvent(uint64_t& id, const char* label); /// @brief Get the unique ID for this Event (in the current thread) uint64_t getID() const; private: uint64_t& id; }; }
c
11
0.700535
69
19.833333
18
inline
<?php namespace Daalder\Exact\Commands; use Daalder\Exact\Jobs\PushProductToExact as PushProductToExactJob; use Illuminate\Console\Command; use Pionect\Daalder\Models\Product\Product; class PushProductToExact extends Command { /** * The console command name. * * @var string */ protected $signature = 'exact:push-product {sku}'; /** * The console command description. * * @var string */ protected $description = 'Pushes a Daalder product to Exact. Matches Daalder sku and Exact Item Code. Creates a new Exact Item if no matches are found.'; /** * Execute the console command. * * @return mixed */ public function handle() { $sku = $this->argument('sku'); $product = Product::firstWhere('sku', $sku); if(is_null($product)) { $this->error("Daalder product with sku '". $sku . "' not found. Exiting..."); return; } PushProductToExactJob::dispatchSync($product); } }
php
14
0.613833
157
23.785714
42
starcoderdata
#ifndef CHECKER_DYLIB_H #define CHECKER_DYLIB_H #include std::string checkers_process(std::string& board, const char player); #endif
c
7
0.762238
68
19.571429
7
starcoderdata
def submit_to_queue(self, script_file): """ Public API: wraps the concrete implementation _submit_to_queue Raises: `self.MaxNumLaunchesError` if we have already tried to submit the job max_num_launches `self.Error` if generic error """ if not os.path.exists(script_file): raise self.Error('Cannot find script file located at: {}'.format(script_file)) if self.num_launches == self.max_num_launches: raise self.MaxNumLaunchesError("num_launches %s == max_num_launches %s" % (self.num_launches, self.max_num_launches)) # Call the concrete implementation. s = self._submit_to_queue(script_file) self.record_launch(s.qid) if s.qid is None: raise self.Error("Error in job submission with %s. file %s \n" % (self.__class__.__name__, script_file) + "The error response reads:\n %s \n " % s.err + "The out response reads:\n %s \n" % s.out) # Here we create a concrete instance of QueueJob return QueueJob.from_qtype_and_id(self.QTYPE, s.qid, self.qname), s.process
python
14
0.581531
129
45.269231
26
inline
/** * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const React = require('react'); const CompLibrary = require('../../core/CompLibrary.js'); const Container = CompLibrary.Container; class Users extends React.Component { render() { const {config: siteConfig} = this.props; if ((siteConfig.users || []).length === 0) { return null; } const editUrl = `${siteConfig.repoUrl}/edit/master/website/siteConfig.js`; const showcase = siteConfig.users.map(user => ( < a href = {user.infoLink} key = {user.infoLink} > < img src = {user.image} alt = {user.caption} title = {user.caption} /> < /a> )) ; return ( < div className = "mainContainer" > < Container padding = {['bottom', 'top' ] }> < div className = "showcaseSection" > < div className = "prose" > < h1 > Who is Using This ? < /h1> < p > This project is used by many folks < /p> < /div> < div className = "logos" > {showcase} < /div> < p > Are you using this project ? < /p> < a href = {editUrl} className = "button" > Add your company < /a> < /div> < /Container> < /div> ) ; } } module.exports = Users;
javascript
8
0.451106
82
19.211765
85
starcoderdata
package br.com.sica.sicaativosservice.components; import br.com.sica.sicaativosservice.enums.CondicaoManutencao; import br.com.sica.sicaativosservice.models.Ativo; import br.com.sica.sicaativosservice.repositories.AtivoRepository; import br.com.sica.sicaativosservice.service.AtivoService; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.List; @Component @EnableScheduling public class ChecadorStatusAtivos { private final Logger LOGGER = LoggerFactory.getLogger(ChecadorStatusAtivos.class); private final long SEGUNDO = 1000; private final long MINUTO = SEGUNDO * 60; private final long SEIS_HORAS = MINUTO * 60 * 6; @Autowired private AtivoRepository ativoRepository; @Autowired private AtivoService ativoService; @Scheduled(fixedDelay = SEIS_HORAS) public void checarStatusAtivos() { LOGGER.info("Iniciando checagem de status de ativos..."); List ativosEmDia = ativoRepository.findByStatusManutencao(CondicaoManutencao.EM_DIA); LOGGER.info("{} ativos selecionados", ativosEmDia.size()); ativosEmDia.parallelStream().forEach(at -> { if (isCondicaoManutencaoAtrasada(at)) { LOGGER.info("O ativo {} esta atrasado. Alterando status", at.getId()); at.setStatusManutencao(CondicaoManutencao.ATRASADA); ativoRepository.save(at); } }); LOGGER.info("Checagem concluida", ativosEmDia.size()); } private Boolean isCondicaoManutencaoAtrasada(Ativo ativo) { if (ativo.getIntervaloManutencao() != null) { DateTime ultimaManutencao = ativoService.pesquisarUltimaManutencao(ativo.getId()); if (ultimaManutencao == null) { ultimaManutencao = ativo.getDataCadastro(); } switch (ativo.getIntervaloManutencao()) { case DIARIO: if (ultimaManutencao.plusDays(2).isBeforeNow()) { return true; } case MENSAL: if (ultimaManutencao.plusMonths(2).isBeforeNow()) { return true; } case ANUAL: if (ultimaManutencao.plusYears(2).isBeforeNow()) { return true; } case EVENTO: case NAO_SE_APLICA: break; default: throw new RuntimeException("TipoAgenda invalido"); } } return false; } }
java
17
0.617737
100
36.723684
76
starcoderdata
/* * @Descripttion: userReducer * @version: 1.0.0 * @Author: jimmiezhou * @Date: 2019-10-22 11:50:14 * @LastEditors: jimmiezhou * @LastEditTime: 2019-10-22 13:49:15 */ import { LOGOUT } from "../constant/userConstant"; const userInitialState = {}; const userReducer = (state = userInitialState, action) => { switch (action.type) { case LOGOUT: return {}; default: return state; } }; export default userReducer;
javascript
6
0.665254
59
22.6
20
starcoderdata
package cn.emitor.chesspro; public interface HeroBuffSetter { void setHeroBuff(); }
java
5
0.735294
33
13.571429
7
starcoderdata
// ### TopLink Mapping Workbench 9.0.3 generated source code ### package com.profitera.descriptor.db.payment; public class PaymentCheck extends com.profitera.descriptor.db.payment.Payment implements java.io.Serializable { // Generated constants public static final String CHECK_STATUS_REF = "checkStatusRef"; public static final String PAYMENT_ID = "paymentId"; public static final String PAYMENT_REALIZATION_DAYS = "paymentRealizationDays"; // End of generated constants private oracle.toplink.indirection.ValueHolderInterface checkStatusRef= new oracle.toplink.indirection.ValueHolder(); private java.lang.Double paymentId; private java.lang.Double paymentRealizationDays; public PaymentCheck() { // Fill in method body here. } public com.profitera.descriptor.db.reference.CheckStatusRef getCheckStatusRef() { return (com.profitera.descriptor.db.reference.CheckStatusRef) checkStatusRef.getValue(); } public java.lang.Double getPaymentId() { return paymentId; } public java.lang.Double getPaymentRealizationDays() { return paymentRealizationDays; } public void setCheckStatusRef(com.profitera.descriptor.db.reference.CheckStatusRef checkStatusRef) { this.checkStatusRef.setValue(checkStatusRef); } public void setPaymentId(java.lang.Double paymentId) { this.paymentId = paymentId; } public void setPaymentRealizationDays(java.lang.Double paymentRealizationDays) { this.paymentRealizationDays = paymentRealizationDays; } }
java
12
0.791357
118
26.943396
53
starcoderdata
<?php /** * Copyright © Vaimo Group. All rights reserved. * See LICENSE_VAIMO.txt for license details. */ namespace Vaimo\ComposerPatches\Composer\Commands; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Input\InputOption; use Vaimo\ComposerPatches\Composer\ConfigKeys; use Vaimo\ComposerPatches\Config; class ValidateCommand extends \Composer\Command\BaseCommand { protected function configure() { parent::configure(); $this->setName('patch:validate'); $this->setDescription('Validate that all patches have proper target configuration'); $this->addOption( '--from-source', null, InputOption::VALUE_NONE, 'Apply patches based on information directly from packages in vendor folder' ); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(' packages for orphan patches $composer = $this->getComposer(); $io = $this->getIO(); $configDefaults = new \Vaimo\ComposerPatches\Config\Defaults(); $defaults = $configDefaults->getPatcherConfig(); $config = array( Config::PATCHER_SOURCES => array_fill_keys(array_keys($defaults[Config::PATCHER_SOURCES]), true) ); $loaderComponentsPool = new \Vaimo\ComposerPatches\Patch\DefinitionList\Loader\ComponentPool( $composer, $io ); $configFactory = new \Vaimo\ComposerPatches\Factories\ConfigFactory($composer, array( Config::PATCHER_FROM_SOURCE => (bool)$input->getOption('from-source') )); $loaderFactory = new \Vaimo\ComposerPatches\Factories\PatchesLoaderFactory($composer); $repository = $composer->getRepositoryManager()->getLocalRepository(); $config = $configFactory->create(array($config)); $skippedComponents = array('constraints', 'targets-resolver', 'local-exclude', 'global-exclude'); foreach ($skippedComponents as $componentName) { $loaderComponentsPool->registerComponent($componentName, false); } $patchesLoader = $loaderFactory->create($loaderComponentsPool, $config, true); $patches = $patchesLoader->loadFromPackagesRepository($repository); $patchesWithTargets = array_reduce($patches, function (array $result, array $items) { return array_merge( $result, array_values( array_map(function ($item) { return $item['path']; }, $items) ) ); }, array()); $sourcesResolverFactory = new \Vaimo\ComposerPatches\Factories\SourcesResolverFactory($composer); $packageListUtils = new \Vaimo\ComposerPatches\Utils\PackageListUtils(); $sourcesResolver = $sourcesResolverFactory->create($config); $sources = $sourcesResolver->resolvePackages($repository); $repositoryUtils = new \Vaimo\ComposerPatches\Utils\RepositoryUtils(); $pluginPackage = $repositoryUtils->resolveForNamespace($repository, __NAMESPACE__); $pluginName = $pluginPackage->getName(); $pluginUsers = array_merge( $repositoryUtils->filterByDependency($repository, $pluginName), array($composer->getPackage()) ); $matches = array_intersect_key( $packageListUtils->listToNameDictionary($sources), $packageListUtils->listToNameDictionary($pluginUsers) ); $installationManager = $composer->getInstallationManager(); $fileSystemUtils = new \Vaimo\ComposerPatches\Utils\FileSystemUtils(); $projectRoot = getcwd(); $vendorRoot = $composer->getConfig()->get(ConfigKeys::VENDOR_DIR); $vendorPath = ltrim( substr($vendorRoot, strlen($projectRoot)), DIRECTORY_SEPARATOR ); $fileMatches = array(); $filterUtils = new \Vaimo\ComposerPatches\Utils\FilterUtils(); $installPaths = array(); foreach ($matches as $packageName => $package) { if ($package instanceof \Composer\Package\RootPackage) { $installPath = $projectRoot; } else { $installPath = $installationManager->getInstallPath($package); } $installPaths[$packageName] = $installPath; } foreach ($matches as $packageName => $package) { $installPath = $installPaths[$packageName]; $skippedPaths = array( $installPath . DIRECTORY_SEPARATOR . $vendorPath, $installPath . DIRECTORY_SEPARATOR . '.hg', $installPath . DIRECTORY_SEPARATOR . '.git' ); $filter = $filterUtils->composeRegex($filterUtils->invertRules($skippedPaths), '/'); $filter = rtrim($filter, '/') . '.+\.patch' . '/i'; $result = $fileSystemUtils->collectPathsRecursively($installPath, $filter); $fileMatches = array_replace($fileMatches, array_fill_keys($result, $packageName)); } $groups = $this->collectOrphans($fileMatches, $patchesWithTargets, $installPaths); $this->generateOutput($output, $groups); } private function collectOrphans($fileMatches, $patchesWithTargets, $installPaths) { $orphanFiles = array_diff_key($fileMatches, array_flip($patchesWithTargets)); $groups = array_fill_keys(array_keys($installPaths), array()); foreach ($orphanFiles as $path => $ownerName) { $installPath = $installPaths[$ownerName]; $groups[$ownerName][] = ltrim(substr($path, strlen($installPath)), DIRECTORY_SEPARATOR); } return $groups; } private function generateOutput(OutputInterface $output, array $groups) { if ($groups = array_filter($groups)) { foreach ($groups as $packageName => $paths) { $output->writeln(sprintf(' - $packageName)); foreach ($paths as $path) { $output->writeln(sprintf(' ~ %s', $path)); } } $output->writeln(' found! exit(1); } else { $output->writeln(' completed successfully } } }
php
27
0.613366
108
34.048128
187
starcoderdata
package frc.libs.math; public class MovingAverage { private int _in; private int _ou; private int _cnt; private int _cap; private float _sum; private float _min; private float[] _d; public MovingAverage(int capacity) { _cap = capacity; _d = new float[_cap]; clear(); } public float process(float input) { push(input); return _sum / (float) _cnt; } public void clear() { _in = 0; _ou = 0; _cnt = 0; _sum = 0; } public void push(float d) { /* process it */ _sum += d; /* if full, pop one */ if (_cnt >= _cap) { pop(); } /* push new one */ _d[_in] = d; if (++_in >= _cap) { _in = 0; } ++_cnt; /* calc new min - slow */ calcMin(); } public void pop() { /* get the oldest */ float d = _d[_ou]; /* process it */ _sum -= d; /* pop it */ if (++_ou >= _cap) { _ou = 0; } --_cnt; } private void calcMin() { _min = Float.MAX_VALUE; int ou = _ou; int cnt = _cnt; while (cnt > 0) { float d = _d[ou]; /* process sample */ if (_min > d) { _min = d; } /* iterate */ if (++ou >= _cnt) { ou = 0; } --cnt; } } // -------------- Properties --------------// public float getSum() { return _sum; } public int getCount() { return _cnt; } public float getMinimum() { return _min; } }
java
11
0.50366
46
12.66
100
starcoderdata
package runner import ( "fmt" "os/exec" "path/filepath" "time" "github.com/jpillora/backoff" "github.com/kardianos/service" "github.com/octoblu/go-meshblu-connector-ignition/connector" "github.com/octoblu/go-meshblu-connector-ignition/interval" "github.com/octoblu/go-meshblu-connector-ignition/logger" "github.com/octoblu/go-meshblu-connector-ignition/status" "github.com/octoblu/go-meshblu-connector-ignition/updateconnector" "github.com/octoblu/process" uuid "github.com/satori/go.uuid" ) // Program inteface that is real type Program struct { config *Config cmd *exec.Cmd cmdGroup *process.Group connector connector.Connector currentRun string status status.Status uc updateconnector.UpdateConnector boff *backoff.Backoff timeStarted time.Time errLog logger.Logger outLog logger.Logger interval interval.Interval started bool shouldRestart bool restartChan chan bool } // NewProgram creates a new program cient func NewProgram(config *Config) (*Program, error) { if mainLogger == nil { mainLogger = logger.GetMainLogger() } outLog, err := logger.NewLogger(config.Stdout, false) if err != nil { return nil, err } errLog, err := logger.NewLogger(config.Stderr, true) if err != nil { return nil, err } return &Program{ config: config, boff: &backoff.Backoff{ Min: time.Second, Max: time.Minute, }, errLog: errLog, outLog: outLog, started: false, shouldRestart: true, restartChan: make(chan bool, 1), }, nil } // Start service but really func (prg *Program) Start(_ service.Service) error { mainLogger.Info("program.Start", fmt.Sprintf("starting %v", prg.config.DisplayName)) prg.shouldRestart = true go prg.restartLoop() prg.restartChan <- true return nil } // Stop service but really func (prg *Program) Stop(_ service.Service) error { mainLogger.Info("program.Stop", fmt.Sprintf("stopping %v", prg.config.DisplayName)) defer prg.errLog.Close() defer prg.outLog.Close() prg.started = false prg.shouldRestart = false return nil } func (prg *Program) restart() { mainLogger.Info("program.restart", "restart called") prg.restartChan <- true } func (prg *Program) restartLoop() error { for range prg.restartChan { if !prg.shouldRestart { mainLogger.Info("program.restartLoop", "should not restart") return nil } if prg.started { mainLogger.Info("program.restartLoop", "restart signal received") } backoffDuration := prg.boff.Duration() currentRun := uuid.NewV4().String() prg.currentRun = currentRun if prg.started { mainLogger.Info("program.restartLoop", fmt.Sprintf("waiting for %v due to backoff", backoffDuration)) time.Sleep(backoffDuration) } err := prg.stop() if err != nil { mainLogger.Error("program.restartLoop", "failed to stop existing child", err) return err } if prg.started { mainLogger.Info("program.restartLoop", "existing child stopped") } err = prg.update() if err != nil { mainLogger.Error("program.restartLoop", "failed to prg.update", err) } else { mainLogger.Info("program.restartLoop", "updated") } commandPath := prg.getCommandPath() nodeCommand, err := prg.getExecutable("node") if err != nil { mainLogger.Error("program.restartLoop", "the executable error", err) return err } prg.cmd = exec.Command(nodeCommand, commandPath) prg.cmd.Dir = prg.config.Dir prg.cmd.Env = prg.getEnv() prg.cmd.SysProcAttr = sysProcAttrForOS() prg.cmd.Stderr = prg.errLog.Stream() prg.cmd.Stdout = prg.outLog.Stream() prg.cmdGroup, err = process.Background(prg.cmd) go func() { if waitErr := prg.cmdGroup.Wait(); waitErr != nil { mainLogger.Error("prg.cmd.Wait", "connector Runner error'd", waitErr) if currentRun != prg.currentRun { mainLogger.Info("prg.cmd.Wait", "not the currentRun, ignoring") return } prg.restart() } }() go func() { time.Sleep(time.Second * 30) if currentRun == prg.currentRun { mainLogger.Info("program.restartLoop", "ran for 30s without dying, resetting backoff") prg.boff.Reset() } }() prg.checkForChangesOnInterval() if err != nil { return err } if prg.started { mainLogger.Info("program.restartLoop", "restarted") } prg.started = true } return prg.stop() } func (prg *Program) updateErrors() error { err := prg.status.UpdateErrors(prg.errLog.Get()) if err != nil { mainLogger.Error("program.updateErrors", "Error updating errors", err) } else { mainLogger.Info("program.updateErrors", "Updated status device with errors") } return nil } func (prg *Program) stop() error { if prg.started { mainLogger.Info("program.stop", "stopping connector") } if prg.cmdGroup == nil { return nil } err := prg.cmdGroup.Terminate(time.Second * 30) if _, isExitError := err.(*exec.ExitError); isExitError { return nil } return err } func (prg *Program) getCommandPath() string { return fmt.Sprintf(".%s%s", string(filepath.Separator), filepath.Join("node_modules", "meshblu-connector-runner", "command.js")) } func (prg *Program) checkForChanges() error { err := prg.connector.Fetch() if err != nil { mainLogger.Error("program.checkForChanges", "Device Update Error", err) return err } versionChange := prg.connector.DidVersionChange() if versionChange { mainLogger.Info("program.checkForChanges", fmt.Sprintf("Device Version Change %v", prg.connector.Version())) prg.boff.Reset() prg.restart() } return nil } func (prg *Program) update() error { err := prg.connector.Fetch() if err != nil { mainLogger.Error("program.update", "Failed to run prg.connector.Fetch", err) return err } tag := prg.connector.VersionWithV() needsUpdate, err := prg.uc.NeedsUpdate(tag) if err != nil { mainLogger.Error("program.update", "Failed to run prg.uc.needsUpdate", err) return err } if !needsUpdate { mainLogger.Info("program.update", fmt.Sprintf("no update needed (%s)", tag)) return nil } err = prg.uc.Do(tag) if err != nil { mainLogger.Error("program.update", "Failed to run uc.Do", err) return err } return nil } func (prg *Program) checkForChangesOnInterval() { mainLogger.Info("program.checkForChangesOnInterval", "started") if prg.interval != nil { prg.interval.Clear() } duration := time.Minute prg.interval = interval.SetInterval(duration, func() { prg.checkForChanges() }) } func (prg *Program) getFullConnectorName() string { return fmt.Sprintf("meshblu-%s", prg.config.ConnectorName) } func (prg *Program) getEnv() []string { pathEnv := GetPathEnv(prg.config.BinPath) return GetEnviron(pathEnv) } // getExecutable should return the correct executable func (prg *Program) getExecutable(name string) (string, error) { thePath := filepath.Join(prg.config.BinPath, name) file, err := exec.LookPath(thePath) if err != nil { mainLogger.Error("program.getExecutable", "Error getting executable", err) return "", err } mainLogger.Info("program.getExectuable", fmt.Sprintf("using executable %s", file)) return file, nil }
go
17
0.694713
129
25.120879
273
starcoderdata
import Vue from 'vue' import VueRouter from 'vue-router' import BasicLayout from '../layouts/BasicLayout.vue' import AdminLayout from '../layouts/AdminLayout.vue' import local from './local' Vue.use(VueRouter) const routes = [{ path: '/', name: 'home', component: BasicLayout, redirect: '/login', children: [ { path:'/project/:code', component: () => import('@/views/index/Main') }, { path: '/project/:code/Authorize/:groupName', component: () => import('@/views/settings/Authorize') }, { path: '/project/:code/:groupName/:controller/:summary', component: () => import('@/views/api/index') }, { path: '/project/:code/SwaggerModels/:groupName', component: () => import('@/views/settings/SwaggerModels') }, { path: '/project/:code/documentManager/GlobalParameters-:groupName', component: () => import('@/views/settings/GlobalParameters') }, { path: '/project/:code/documentManager/OfficelineDocument-:groupName', component: () => import('@/views/settings/OfficelineDocument') }, { path: '/project/:code/documentManager/Settings', component: () => import('@/views/settings/Settings') }, { path: '/project/:code/otherMarkdowns/:id', component: () => import('@/views/othermarkdown/index') } ] },{ path:'/home', component: () => import('@/views/index/Index') },{ path:'/', component:AdminLayout, children:[{ path:'/index', component: () => import('@/views/admin/WorkPlan') },{ path:'/product', component: () => import('@/views/admin/Product') },{ path:'/item', component: () => import('@/views/admin/Item') },{ path:'/item/form', component: () => import('@/views/admin/ItemForm') },{ path:'/item/form/:id', component: () => import('@/views/admin/ItemForm') },{ path:'/help', component: () => import('@/views/admin/Help') },{ path:'/info', component: () => import('@/views/admin/Info') },{ path:'/resetPwd', component: () => import('@/views/admin/ResetPwd') }] },{ path:'/login', component: () => import('@/views/admin/Login') }] const router = new VueRouter({ routes }) function getCookie(name){ var value=null; if(document.cookie!=null&&document.cookie!=undefined){ var cookieArrs=document.cookie.split(";"); for(var i=0;i<cookieArrs.length;i++){ var cocLists=cookieArrs[i].split("="); var cname=cocLists[0]; cname = cname.replace(/\s+/g,''); if(cname==name){ value=cocLists[1]; } } } return value; } //无需登录界面 const whiteRouterList = ['/login'] //const reg = new RegExp('/project/.*', 'g'); router.beforeEach((to, form, next) => { //window.console.log(document.cookie+",path:"+to.path) if (new RegExp('/project/.*', 'ig').test(to.path)) { //预览页面,不用登录 next(); } else { if (whiteRouterList.indexOf(to.path) < 0) { var tkvalue=getCookie('TK_KNIFE4J'); //window.console.log("cookieValue:"+tkvalue); if(tkvalue!=null&&tkvalue!=''){ next(); }else{ next('/login'); } } else { next() } } }) export default router
javascript
18
0.583151
75
25.38843
121
starcoderdata