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
const express = require("express"); const router = express.Router(); const sales_api = require("../api/sales_api"); router.get("/", sales_api.getActiveReceipts); /** * @swagger * /api/sales: * post: * summary: Submitted a Sales Transaction * description: Save all sales transaction * tags: * - Sales * responses: * 200: * description: Saved all submitted sales * schema: * type: object * properties: * Sales: * type: array * description: Saved necessary sales transactions * items: * type: object * properties: * SalesDateTime: * type: string * SalesCustomerType: * type: string * PatientLicenseNumber: * type: string * IdentificationMethod: * type: string * Transactions: * type: object * properties: * PackageLabel: * type: string * Quantity: * type: integer * UnitOfMeasure: * type: string * TotalAmount: * type: integer * 401: * description: Incorrect API Key Or METRC User Key * */ router.post("/", sales_api.saveReceipt); router.put("/", sales_api.editReceipt); router.delete("/:id", sales_api.deleteReceipt); module.exports = router;
javascript
3
0.451184
64
28.338983
59
starcoderdata
#import "BaseLineUIView.h" NS_ASSUME_NONNULL_BEGIN @interface BaseInterval2UIView : BaseLineUIView @end NS_ASSUME_NONNULL_END
c
4
0.805031
47
13.454545
11
starcoderdata
<?php /* * This file is part of YaEtl * (c) / https://github.com/fab2s/YaEtl * This source file is licensed under the MIT license which you will * find in the LICENSE file or at https://opensource.org/licenses/MIT */ namespace fab2s\YaEtl\Extractors; use fab2s\NodalFlow\Nodes\ExecNodeInterface; /** * Interface JoinableInterface * A joinable is an extractor that can be joined against * and / or can join against another joinable */ interface JoinableInterface extends ExtractorInterface, ExecNodeInterface { /** * Generate record map, used to allow joiner to join * * @param string|null $fromKeyAlias The from unique key to get the map against * as exposed in the record * * @return mixed whatever you need to represent the record collection * Could be something as simple as an array of all * extracted record ids for Joiners to query * against, and know what to do when one of their record * is missing from their own extract collection */ public function getRecordMap(?string $fromKeyAlias = null); /** * Set the extractor to get record map from * * @param JoinableInterface $joinFrom * * @return static */ public function setJoinFrom(self $joinFrom): self; /** * Set Joiner's ON clause. Only used in Join mode * * @param OnClauseInterface $onClause * * @return static */ public function setOnClause(OnClauseInterface $onClause): self; /** * Get Joiner's ON clause. Only used in Join mode * * @return OnClauseInterface|null */ public function getOnClause(): ?OnClauseInterface; /** * exec will join incoming $record with the joined record from its * matching extracted record collection * exec is supposed to call $this->carrier->continueFlow() when the desired * action is to skip record in join mode and return the record with default * join values in left join mode * * @param mixed $record * * @return mixed the result of the join */ public function exec($record = null); /** * Register ON clause field mapping. Used by an eventual joiner to this * to build relevant recordMap * * @param OnClauseInterface $onClause * * @return static */ public function registerJoinerOnClause(OnClauseInterface $onClause): self; }
php
9
0.643825
82
29.609756
82
starcoderdata
#include <bits/stdc++.h> #define all(x) (x).begin(), (x).end() typedef long long ll; #define MOD 1000000007 using namespace std; vector<int> tobit(ll n, int keta) { vector<int> res(keta, 0); for(int i = 0; i < keta; i++) { res[i] = n % 2; n /= 2; } return res; } int main() { ll h, w, k; cin >> h >> w >> k; if(w == 1) { cout << 1 << endl; return 0; } vector<int> pm(w); for(int i = 0; i < w; i++) { pm[i] = i; } vector<vector<int>> pats; for(int i = 0; i < (1LL << (w - 1)); i++) { auto tmp = tobit(i, w - 1); bool flag = true; for(int j = 0; j < tmp.size() - 1; j++) { if(tmp[j] == 1 && tmp[j + 1] == 1) { flag = false; break; } } if(flag) { pats.push_back(tmp); } } vector<vector<int>> state; do { state.push_back(pm); } while(next_permutation(all(pm))); int sn = state.size(); vector<vector<int>> seni(sn); map<vector<int>, int> mp; for(int i = 0; i < state.size(); i++) { mp[state[i]] = i; } for(int i = 0; i < state.size(); i++) { for(auto &pat : pats) { auto next = state[i]; for(int x = 0; x < pat.size(); x++) { if(pat[x] == 1) { swap(next[x], next[x + 1]); } } seni[i].push_back(mp[next]); } } vector<vector<ll>> dp(h + 1, vector<ll>(sn, 0)); dp[0][0] = 1; for(int i = 0; i < h; i++) { for(int j = 0; j < sn; j++) { for(int x = 0; x < seni[j].size(); x++) { dp[i + 1][seni[j][x]] += dp[i][j]; dp[i + 1][seni[j][x]] %= MOD; } } } k--; ll ans = 0; for(int i = 0; i < sn; i++) { if(state[i][k] == 0) { ans += dp[h][i]; ans %= MOD; } } cout << ans << endl; }
c++
17
0.378568
53
23.975
80
codenet
from collections import OrderedDict from typing import Iterator, Tuple from torch import nn def flatten(module: nn.Sequential) -> nn.Sequential: """Flattens a nested sequential module.""" if not isinstance(module, nn.Sequential): raise TypeError('not sequential') return nn.Sequential(OrderedDict(_flatten(module))) def _flatten(module: nn.Sequential) -> Iterator[Tuple[str, nn.Module]]: for name, child in module.named_children(): # Flatten child sequential layers only. if isinstance(child, nn.Sequential): for sub_name, sub_child in _flatten(child): yield ('%s_%s' % (name, sub_name), sub_child) else: yield (name, child)
python
14
0.657858
71
31.681818
22
starcoderdata
Simulator/InputFormPopulator.h // // InputFormHelper.h // Retirement Simulator // // Created by on 10/7/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import #import "FormPopulator.h" #import "ItemizedTaxAmtCreator.h" @class Input; @class MultiScenarioInputValue; @class MultiScenarioAmount; @class MultiScenarioGrowthRate; @class SectionInfo; @class Scenario; @class RepeatFrequencyFieldEditInfo; @class MultiScenarioSimDate; @class MultiScenarioSimEndDate; @class NumberFieldValidator; @class LoanInput; @class VariableValue; @class TableHeaderWithDisclosure; @class FormContext; @class ItemizedTaxAmt; @class ItemizedTaxAmtsInfo; @class ItemizedTaxAmtsSelectionFormInfoCreator; @class StaticNavFieldEditInfo; @class Account; @class MultiScenarioPercent; @class BoolFieldEditInfo; @class BoolFieldShowHideCondition; @protocol FieldShowHideCondition; @interface InputFormPopulator : FormPopulator { @private Scenario *inputScenario; BOOL isForNewObject; } @property(nonatomic,retain) Scenario *inputScenario; @property BOOL isForNewObject; -(id)initWithScenario:(Scenario*)theInputScenario andFormContext:(FormContext*)theFormContext; -(id)initForNewObject:(BOOL)isNewObject andFormContext:(FormContext*)theFormContext; - (void)populateInputNameField:(Input*)theInput withIconList:(NSArray*)inputIcons; -(BoolFieldEditInfo *)populateMultiScenBoolField:(MultiScenarioInputValue*)boolVal withLabel:(NSString*)label; -(BoolFieldEditInfo *)populateMultiScenBoolField:(MultiScenarioInputValue*)boolVal withLabel:(NSString*)label andSubtitle:(NSString*)subTitle; // subTitle is optional and can be nil for no subtitle -(void)populateMultiScenBoolField:(MultiScenarioInputValue*)boolVal withLabel:(NSString*)label andShowHideCondition:(id -(BoolFieldShowHideCondition *)populateConditionalFieldVisibilityMultiScenBoolField: (MultiScenarioInputValue*)boolVal withLabel:(NSString*)label; -(void)populateMultiScenFixedValField:(MultiScenarioInputValue*)inputVal andValLabel:(NSString*)label andPrompt:(NSString*)prompt andValidator:(NumberFieldValidator*)validator; -(void)populateMultiScenFixedValField:(MultiScenarioInputValue*)inputVal andValLabel:(NSString*)label andPrompt:(NSString*)prompt andObjectForDelete:(NSManagedObject*)objForDelete andValidator:(NumberFieldValidator*)validator; -(void)populateCurrencyField:(NSManagedObject*)parentObj andValKey:(NSString*)valKey andLabel:(NSString*)label andPlaceholder:(NSString*)placeholder; -(void)populateCurrencyField:(NSManagedObject*)parentObj andValKey:(NSString*)valKey andLabel:(NSString*)label andPlaceholder:(NSString*)placeholder andSubtitle:(NSString*)subTitle; -(void)populatePercentField:(NSManagedObject*)parentObj andValKey:(NSString*)valKey andLabel:(NSString*)label andPlaceholder:(NSString*)placeholder; -(void)populateMultiScenPercentField:(MultiScenarioInputValue*)inputVal andValLabel:(NSString*)label andPrompt:(NSString*)prompt andAllowGreaterThan100Percent:(BOOL)allowGreaterThan100; -(void)populateMultiScenarioAmount:(MultiScenarioAmount*)theAmount withValueTitle:(NSString*)valueTitle andValueName:(NSString*)valueName; -(void)populateMultiScenarioAmount:(MultiScenarioAmount*)theAmount withValueTitle:(NSString*)valueTitle andValueName:(NSString*)valueName withShowHideCondition:(id -(void)populateMultiScenarioLoanOrigAmount:(MultiScenarioAmount*)theAmount withValueTitle:(NSString*)valueTitle andValueName:(NSString*)valueName; -(void)populateMultiScenarioGrowthRate:(MultiScenarioGrowthRate*)growthRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; -(void)populateMultiScenarioGrowthRate:(MultiScenarioGrowthRate*)growthRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName withShowHideCondition:(id -(void)populateSingleScenarioVariableValue:(VariableValue*)growthRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; - (void)populateMultiScenarioInterestRate:(MultiScenarioGrowthRate*)intRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; - (void)populateMultiScenarioInvestmentReturnRate:(MultiScenarioGrowthRate*)roiRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; - (void)populateMultiScenarioTaxRate:(MultiScenarioGrowthRate*)taxRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; - (void)populateMultiScenarioDividendReturnRate:(MultiScenarioGrowthRate*)dividendRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; - (void)populateMultiScenarioDividendReturnRate:(MultiScenarioGrowthRate*)dividendRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName andShowHideCondition:(id - (void)populateMultiScenarioApprecRate:(MultiScenarioGrowthRate*)apprecRate withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; -(void)populateLoanDownPmtPercent:(LoanInput*)loan withValueLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; -(void)populateLoanDownPmtPercent:(LoanInput*)loan withValueLabel:(NSString*)valueLabel andValueName:(NSString*)valueName andShowHideCondition:(id - (void)populateMultiScenarioDividendReinvestPercent:(MultiScenarioPercent*)multiScenPercent withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName; - (void)populateMultiScenarioDividendReinvestPercent:(MultiScenarioPercent*)multiScenPercent withLabel:(NSString*)valueLabel andValueName:(NSString*)valueName andShowHideCondition:(id -(RepeatFrequencyFieldEditInfo*)populateRepeatFrequency:(MultiScenarioInputValue*)repeatFreq andLabel:(NSString*)label; -(RepeatFrequencyFieldEditInfo*)populateRepeatFrequency:(MultiScenarioInputValue*)repeatFreq andLabel:(NSString*)label andShowHideCondition:(id -(void)populateMultiScenarioDuration:(MultiScenarioInputValue*)duration andLabel:(NSString*)label andPlaceholder:(NSString*)placeholder; -(void)populateMultiScenSimDate:(MultiScenarioSimDate*)multiScenSimDate andLabel:(NSString*)label andTitle:(NSString*)title andTableHeader:(NSString*)tableHeader andTableSubHeader:(NSString*)tableSubHeader; -(void)populateMultiScenSimDate:(MultiScenarioSimDate*)multiScenSimDate andLabel:(NSString*)label andTitle:(NSString*)title andTableHeader:(NSString*)tableHeader andTableSubHeader:(NSString*)tableSubHeader andShowHideCondition:(id -(void)populateMultiScenSimEndDate:(MultiScenarioSimEndDate*)multiScenSimEndDate andLabel:(NSString*)label andTitle:(NSString*)title andTableHeader:(NSString*)tableHeader andTableSubHeader:(NSString*)tableSubHeader andNeverEndFieldTitle:(NSString*)neverEndFieldTitle andNeverEndFieldSubtitle:(NSString*)neverEndFieldSubTitle andNeverEndSectionTitle:(NSString*)neverEndSectionTitle andNeverEndHelpInfo:(NSString*)neverEndHelpFile andRelEndDateSectionTitle:(NSString*)relEndDateSectionTitle andRelEndDateHelpFile:(NSString*)relEndDateHelpFile andRelEndDateFieldLabel:(NSString*)relEndDateFieldLabel; -(void)populateMultiScenSimEndDate:(MultiScenarioSimEndDate*)multiScenSimEndDate andLabel:(NSString*)label andTitle:(NSString*)title andTableHeader:(NSString*)tableHeader andTableSubHeader:(NSString*)tableSubHeader andNeverEndFieldTitle:(NSString*)neverEndFieldTitle andNeverEndFieldSubtitle:(NSString*)neverEndFieldSubTitle andNeverEndSectionTitle:(NSString*)neverEndSectionTitle andNeverEndHelpInfo:(NSString*)neverEndHelpFile andRelEndDateSectionTitle:(NSString*)relEndDateSectionTitle andRelEndDateHelpFile:(NSString*)relEndDateHelpFile andRelEndDateFieldLabel:(NSString*)relEndDateFieldLabel andShowHideCondition:(id -(void)populateLoanDeferPaymentDate:(LoanInput*)loan withFieldLabel:(NSString*)fieldLabel; -(void)populateLoanDeferPaymentDate:(LoanInput*)loan withFieldLabel:(NSString*)fieldLabel withShowHideCondition:(id -(void)populateItemizedTaxForTaxAmtsInfo:(ItemizedTaxAmtsInfo*)itemizedTaxAmtsInfo andTaxAmt:(ItemizedTaxAmt*)itemizedTaxAmt andTaxAmtCreator:(id -(void)populateItemizedTaxSelectionWithFieldLabel:(NSString*)fieldLabel andFormInfoCreator:(id andItemizedTaxAmtsInfo:(NSSet*)itemizedTaxAmts andShowHideCondition:(id -(StaticNavFieldEditInfo*)createItemizedTaxSelectionFieldEditInfoWithFieldLabel:(NSString*)fieldLabel andFormInfoCreator:(id andItemizedTaxAmtsInfo:(NSSet*)itemizedTaxAmts; -(void)populateItemizedTaxSelectionWithFieldLabel:(NSString*)fieldLabel andFormInfoCreator:(id andItemizedTaxAmtsInfo:(NSSet*)itemizedTaxAmts; -(void)populateItemizedTaxSelectionWithFieldLabel:(NSString*)fieldLabel andItemizedTaxAmtsFormInfoCreator:(ItemizedTaxAmtsSelectionFormInfoCreator *)formInfoCreator; -(void)populateAcctWithdrawalOrderField:(Account*)account andFieldCaption:(NSString*)caption andFieldSubtitle:(NSString*)subtitle; -(TableHeaderWithDisclosure*)scenarioListTableHeaderWithFormContext:(FormContext*)formContext; @end
c
24
0.851406
110
45.198068
207
starcoderdata
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace FabricTest { class FabricTestSession; class SecureStoreTestClient { DENY_COPY(SecureStoreTestClient); typedef std::function<bool(Common::StringCollection const &)> CommandHandler; public: // ctors SecureStoreTestClient(FabricTestDispatcher & dispatcher); virtual ~SecureStoreTestClient(); // helpers bool IsSecureStoreClientCommand(std::wstring const & command); bool ExecuteCommand(std::wstring const & command, Common::StringCollection const & params); // API/command handling bool PutSecret(Common::StringCollection const & parameters); bool PutVersionedPlaintextSecret(Common::StringCollection const & parameters); bool GetSecret(Common::StringCollection const & parameters); bool GetVersionedSecretValue(Common::StringCollection const & parameters); bool ListSecretVersions(Common::StringCollection const & parameters); bool ListSecrets(Common::StringCollection const & parameters); bool RemoveSecret(Common::StringCollection const & parameters); bool RemoveSecretVersion(Common::StringCollection const & parameters); bool ClearAllSecrets(Common::StringCollection const & parameters); // parameters static struct SecretCommandParameters { static std::wstring const Name; static std::wstring const Version; static std::wstring const Value; static std::wstring const Kind; static std::wstring const ContentType; static std::wstring const Description; static std::wstring const ExpectedValue; static std::wstring const ExpectedValues; static std::wstring const ExpectedFailure; } SecretCommandParameters; private: // helper methods void SetCommandHandlers(); bool TryParseParameters( Common::StringCollection const & parameters, std::vector expectedParameters, std::map<std::wstring, std::wstring> & parsedParameters, std::wstring & firstError); void InstantiateInnerSecureStoreClient(__in FabricTestFederation & testFederation); void OnSetSecretsComplete(AsyncOperationSPtr operation, Management::CentralSecretService::SecretsDescription & results, bool expectedSynchronousCompletion); void OnGetSecretsComplete(AsyncOperationSPtr operation, Management::CentralSecretService::SecretsDescription & results, bool expectedSynchronousCompletion); void OnRemoveSecretsComplete(AsyncOperationSPtr operation, Management::CentralSecretService::SecretReferencesDescription & results, bool expectedSynchronousCompletion); void OnGetSecretVersionsComplete(AsyncOperationSPtr operation, Management::CentralSecretService::SecretReferencesDescription & results, bool expectedSynchronousCompletion); static std::shared_ptr InstantiateSecretFromParameters(std::map<std::wstring, std::wstring> parameterMap); static std::shared_ptr InstantiateSecretReferenceFromParameters(std::map<std::wstring, std::wstring> parameterMap); // SecureStore API // members // keeping the Dispatcher manageable, we'll track S3 commands in the SecureStore class. std::map<std::wstring, CommandHandler> commandHandlers_; // behavior control bool expectedFailureIsSet_; bool expectedFailure_; bool expectedValuesAreSet_; StringCollection expectedValues_; bool expectedValueIsSet_; std::wstring expectedValue_; // parent reference FabricTestDispatcher & dispatcher_; // proper secure store client instance Api::ISecretStoreClientPtr secureStoreClient_; }; }
c
11
0.691651
180
45.855556
90
starcoderdata
/* Page Content */ var PageContent = (function () { /** * Page Content constructor * @constructor */ function PageContent(viewport) { this.viewport = viewport || false; } return PageContent; })();
javascript
12
0.627907
36
11
18
starcoderdata
const { CLIEngine } = require('eslint'); const config = require('../etc/eslint.config'); /* Sample report { results: [ { filePath: '/something.js', messages: [], errorCount: 0, warningCount: 0, fixableErrorCount: 0, fixableWarningCount: 0 }, fixableWarningCount: 0 } ], errorCount: 0, warningCount: 0, fixableErrorCount: 0, fixableWarningCount: 0, usedDeprecatedRules: [ { ruleId: 'no-negated-in-lhs', replacedBy: [Array] } ] } */ exports.command = 'lint [--fix -f] [dir]'; exports.desc = 'start linting using pre-defined rules set.'; exports.builder = (yargs) => yargs .option('fix', { alias: 'f', type: 'boolean', description: 'automatically fix problems', }) .option('dir', { alias: 'd', type: 'string', description: 'directory to start linting (default: cwd)', }); /** * Execute `eslint` linting with default settings under current `cwd`.. * @param {String} [argv.dir] - directory to perform linting. * @param {Object} argv - `yargs` options. */ exports.handler = (argv) => { const dir = argv.dir || process.cwd(); const fix = argv.fix === true; const eslint = new CLIEngine({ fix, extensions: ['.js', '.jsx'], ...config, }); const report = eslint.executeOnFiles([dir]); const output = eslint.getFormatter('stylish')(report.results); if (output) console.log(output); // eslint-disable-line no-console if (fix) CLIEngine.outputFixes(report); const hasUnfixableError = output.errorCount > output.fixableErrorCount; const hasUnfixableWarning = output.warningCount > output.fixableWarningCount; if (hasUnfixableError || hasUnfixableWarning) { process.exitCode = 1; } };
javascript
13
0.640092
81
26.47619
63
starcoderdata
// Copyright (c) 2004-2022 et al. // // This file is part of TNL - Template Numerical Library (https://tnl-project.org/) // // SPDX-License-Identifier: MIT #pragma once namespace TNL { namespace Meshes { template< typename GridEntity > class GridEntityCenterGetter {}; /*** * 1D grids */ template< typename Real, typename Device, typename Index, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 1, Real, Device, Index >, 1, Config > > { public: using GridType = Meshes::Grid< 1, Real, Device, Index >; using GridEntityType = GridEntity< GridType, 1, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + ( entity.getCoordinates().x() + 0.5 ) * grid.getSpaceSteps().x() ); } }; template< typename Real, typename Device, typename Index, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 1, Real, Device, Index >, 0, Config > > { public: using GridType = Meshes::Grid< 1, Real, Device, Index >; using GridEntityType = GridEntity< GridType, 0, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + ( entity.getCoordinates().x() ) * grid.getSpaceSteps().x() ); } }; /**** * 2D grids */ template< typename Real, typename Device, typename Index, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 2, Real, Device, Index >, 2, Config > > { public: using GridType = Meshes::Grid< 2, Real, Device, Index >; using GridEntityType = GridEntity< GridType, 2, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + ( entity.getCoordinates().x() + 0.5 ) * grid.getSpaceSteps().x(), grid.getOrigin().y() + ( entity.getCoordinates().y() + 0.5 ) * grid.getSpaceSteps().y() ); } }; template< typename Real, typename Device, typename Index, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 2, Real, Device, Index >, 1, Config > > { public: using GridType = Meshes::Grid< 2, Real, Device, Index >; using GridEntityType = GridEntity< GridType, 1, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + ( entity.getCoordinates().x() + 0.5 * entity.getBasis().x() ) * grid.getSpaceSteps().x(), grid.getOrigin().y() + ( entity.getCoordinates().y() + 0.5 * entity.getBasis().y() ) * grid.getSpaceSteps().y() ); } }; template< typename Real, typename Device, typename Index, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 2, Real, Device, Index >, 0, Config > > { public: using GridType = Meshes::Grid< 2, Real, Device, Index >; using GridEntityType = GridEntity< GridType, 0, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + entity.getCoordinates().x() * grid.getSpaceSteps().x(), grid.getOrigin().y() + entity.getCoordinates().y() * grid.getSpaceSteps().y() ); } }; /*** * 3D grid */ template< typename Real, typename Device, typename Index, int EntityDimension, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 3, Real, Device, Index >, EntityDimension, Config > > { public: using GridType = Meshes::Grid< 3, Real, Device, Index >; using GridEntityType = GridEntity< GridType, EntityDimension, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + ( entity.getCoordinates().x() + 0.5 * entity.getBasis().x() ) * grid.getSpaceSteps().x(), grid.getOrigin().y() + ( entity.getCoordinates().y() + 0.5 * entity.getBasis().y() ) * grid.getSpaceSteps().y(), grid.getOrigin().z() + ( entity.getCoordinates().z() + 0.5 * entity.getBasis().z() ) * grid.getSpaceSteps().z() ); } }; template< typename Real, typename Device, typename Index, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 3, Real, Device, Index >, 3, Config > > { public: using GridType = Meshes::Grid< 3, Real, Device, Index >; using GridEntityType = GridEntity< GridType, 3, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + ( entity.getCoordinates().x() + 0.5 ) * grid.getSpaceSteps().x(), grid.getOrigin().y() + ( entity.getCoordinates().y() + 0.5 ) * grid.getSpaceSteps().y(), grid.getOrigin().z() + ( entity.getCoordinates().z() + 0.5 ) * grid.getSpaceSteps().z() ); } }; template< typename Real, typename Device, typename Index, typename Config > class GridEntityCenterGetter< GridEntity< Meshes::Grid< 3, Real, Device, Index >, 0, Config > > { public: using GridType = Meshes::Grid< 3, Real, Device, Index >; using GridEntityType = GridEntity< GridType, 0, Config >; using PointType = typename GridType::PointType; __cuda_callable__ inline static PointType getEntityCenter( const GridEntityType& entity ) { const GridType& grid = entity.getMesh(); return PointType( grid.getOrigin().x() + ( entity.getCoordinates().x() ) * grid.getSpaceSteps().x(), grid.getOrigin().y() + ( entity.getCoordinates().y() ) * grid.getSpaceSteps().y(), grid.getOrigin().z() + ( entity.getCoordinates().z() ) * grid.getSpaceSteps().z() ); } }; } // namespace Meshes } // namespace TNL
c
18
0.65863
123
36.66092
174
starcoderdata
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ReLogic.Content; using Terraria; using Terraria.DataStructures; using Terraria.GameContent; using Terraria.Graphics.Shaders; using Terraria.ID; using Terraria.ModLoader; using TrailEffects.ModPlayers; namespace TrailEffects.Pets.FloatingBonboriPet { public class FloatingBonboriProj : ModProjectile { public override void SetStaticDefaults() { DisplayName.SetDefault("Floating Bonbori"); Main.projFrames[Type] = 1; Main.projPet[Type] = true; ProjectileID.Sets.TrailingMode[Type] = 2; ProjectileID.Sets.TrailCacheLength[Type] = 8; ProjectileID.Sets.LightPet[Type] = true; } public override void SetDefaults() { Projectile.Size = TextureAssets.Projectile[Type]?.Size() ?? Vector2.Zero; Projectile.penetrate = -1; Projectile.netImportant = true; Projectile.friendly = true; Projectile.ignoreWater = true; Projectile.tileCollide = false; Projectile.manualDirectionChange = true; } public override void AI() { const float rotateFactor = 11f; Player player = Main.player[Projectile.owner]; float cos = (float)Math.Cos(Main.GlobalTimeWrappedHourly * 1.16f); Vector2 calcPos = new Vector2(-player.direction * 60, -20 + cos); Vector2 vector = player.MountedCenter + calcPos - Projectile.Center; float distance = Vector2.Distance(Projectile.Center, player.MountedCenter + calcPos); if (!player.active || !player.GetModPlayer Projectile.Kill(); if (distance > 1000) Projectile.Center = player.MountedCenter + calcPos; if (distance < 1f) Projectile.velocity *= 0.25f; if (vector != Vector2.Zero) { if (vector.Length() < 0.004f) Projectile.velocity = vector; else Projectile.velocity = vector * 0.1f; } Projectile.position += new Vector2(0, cos); // Rotation adapted from flying pets if (Projectile.velocity.Length() > 1f) { float value = Projectile.velocity.X * 0.02f + Projectile.velocity.Y * Projectile.spriteDirection * 0.02f; if (Math.Abs(Projectile.rotation - value) >= Math.PI) { if (value < Projectile.rotation) Projectile.rotation -= (float)Math.PI * 2f; else Projectile.rotation += (float)Math.PI * 2f; } Projectile.rotation = (Projectile.rotation * (rotateFactor - 1f) + value) / rotateFactor; } else { if (Projectile.rotation > (float)Math.PI) Projectile.rotation -= (float)Math.PI * 2f; if (Projectile.rotation > -0.004f && Projectile.rotation < 0.004f) Projectile.rotation = 0; else Projectile.rotation *= 0.95f; } Projectile.spriteDirection = Projectile.position.X < player.position.X ? 1 : -1; LightMethod(); if (player.miscCounter % 15 == 0 && Main.rand.NextBool(5)) DustMethod(); } public override void Kill(int timeLeft) { for (int i = 0; i < 3; i++) DustMethod(); } private void LightMethod() { float sine = ((float)Math.Sin(Main.GlobalTimeWrappedHourly * 3.5f) + 1f) / 2.2f; Lighting.AddLight(Projectile.Center, Color.DarkOrange.ToVector3() * 0.75f * (sine + 0.9f)); } private void DustMethod() { Player player = Main.player[Projectile.owner]; Vector2 center = Projectile.position; float rand = 1f + Main.rand.NextFloat() * 0.5f; if (Main.rand.NextBool(2)) rand *= -1f; center += new Vector2(rand * -25f, -8f); Dust dust = Dust.NewDustDirect(center, player.width, player.height, DustID.Firefly, 0, 0, 100); dust.rotation = Main.rand.NextFloat() * ((float)Math.PI * 2f); dust.velocity.X = rand * 0.2f; dust.noGravity = true; dust.customData = Projectile; dust.shader = GameShaders.Armor.GetSecondaryShader(player.cLight, player); } public override bool PreDraw(ref Color lightColor) { Asset texture = ModContent.GetTexture("TrailEffects/Assets/FloatingBonbori_Glow"); float cos = (float)Math.Cos(Main.GlobalTimeWrappedHourly * 3.5f) + 1f; int shader = Main.player[Projectile.owner].cLight; for (int i = 0; i < 4; i++) { Vector2 offsetPosition = new Vector2(0, cos).RotatedBy(MathHelper.PiOver2 * i) * 2; Vector2 drawPos = Projectile.Center + offsetPosition - Main.screenPosition; if (shader > 0) { Main.spriteBatch.End(); Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, Main.spriteBatch.GraphicsDevice.DepthStencilState, Main.spriteBatch.GraphicsDevice.RasterizerState, null, Main.GameViewMatrix.TransformationMatrix); DrawData drawData = new DrawData { position = drawPos, scale = new Vector2(Projectile.scale), texture = texture.Value, rotation = Projectile.rotation }; GameShaders.Armor.ApplySecondary(shader, Projectile, drawData); } Main.spriteBatch.Draw(texture.Value, drawPos, null, Color.White * 0.25882352941f, Projectile.rotation, Projectile.Size / 2f, Projectile.scale, SpriteEffects.None, 0f); } for (int i = 0; i < ProjectileID.Sets.TrailCacheLength[Projectile.type]; i++) { Vector2 position = Projectile.oldPos[i] + Projectile.Size / 2f; float rotation = Projectile.oldRot[i]; Vector2 drawPos = position - Main.screenPosition; if (shader > 0) { Main.spriteBatch.End(); Main.spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, SamplerState.PointClamp, Main.spriteBatch.GraphicsDevice.DepthStencilState, Main.spriteBatch.GraphicsDevice.RasterizerState, null, Main.GameViewMatrix.TransformationMatrix); DrawData drawData = new DrawData { position = drawPos, scale = new Vector2(Projectile.scale), texture = texture.Value, rotation = Projectile.rotation }; GameShaders.Armor.ApplySecondary(shader, Projectile, drawData); } Main.spriteBatch.Draw(texture.Value, drawPos, null, Color.White * 0.1f * (1f / i), rotation, Projectile.Size / 2f, Projectile.scale, SpriteEffects.None, 0f); } Main.spriteBatch.End(); Main.spriteBatch.Begin(shader > 0 ? SpriteSortMode.Immediate : SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, Main.spriteBatch.GraphicsDevice.DepthStencilState, Main.spriteBatch.GraphicsDevice.RasterizerState, null, Main.GameViewMatrix.TransformationMatrix); return true; } public override Color? GetAlpha(Color lightColor) => Color.White; } }
c#
22
0.556556
129
38.344498
209
starcoderdata
class ListNode(): def __init__(self, val, next = None): self.val = val self.next = next def print_list(l1:ListNode): answer = [] head = l1 while head : answer.append(head.val) head = head.next return answer class Solution(): def addTwoNumbers(self,l1:ListNode,l2:ListNode)->ListNode: carry = 0 # 进位 state = 0 temp_node = None while l1 !=None or l2!=None or carry != 0: a = l1.val if l1 else 0 b = l2.val if l2 else 0 sum = a + b + carry p = ListNode(sum%10) carry = sum//10 print('sum', sum,carry) if state == 0: state =1 head = p temp_node = head else: temp_node.next = p temp_node = temp_node.next l1 = l1.next l2 = l2.next return head if __name__ == '__main__': app = Solution() l1 = [2, 4, 3] l2 = [5, 6, 9] p1_head = ListNode(l1[0]) temp_node = p1_head for i in range(1,len(l1)): temp_node.next = ListNode(l1[i]) temp_node = temp_node.next p2_head = ListNode(l2[0]) temp_node = p2_head for i in range(1, len(l2)): temp_node.next = ListNode(l2[i]) temp_node = temp_node.next print(p1_head, type(p1_head), print_list(p1_head)) result = app.addTwoNumbers(p1_head,p2_head) print(result,type(result)) print(print_list(result))
python
13
0.495787
62
20.732394
71
starcoderdata
""" Test python scripted process in lldb """ import os import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from lldbsuite.test import lldbtest class ScriptedProcesTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp(self): TestBase.setUp(self) self.source = "main.c" def tearDown(self): TestBase.tearDown(self) def test_python_plugin_package(self): """Test that the lldb python module has a `plugins.scripted_process` package.""" self.expect('script import lldb.plugins', substrs=["ModuleNotFoundError"], matching=False) self.expect('script dir(lldb.plugins)', substrs=["scripted_process"]) self.expect('script import lldb.plugins.scripted_process', substrs=["ModuleNotFoundError"], matching=False) self.expect('script dir(lldb.plugins.scripted_process)', substrs=["ScriptedProcess"]) self.expect('script from lldb.plugins.scripted_process import ScriptedProcess', substrs=["ImportError"], matching=False) self.expect('script dir(ScriptedProcess)', substrs=["launch"]) def test_launch_scripted_process_sbapi(self): """Test that we can launch an lldb scripted process using the SBAPI, check its process ID and read string from memory.""" self.build() target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) scripted_process_example_relpath = ['..','..','..','..','examples','python','scripted_process','my_scripted_process.py'] os.environ['SKIP_SCRIPTED_PROCESS_LAUNCH'] = '1' self.runCmd("command script import " + os.path.join(self.getSourceDir(), *scripted_process_example_relpath)) launch_info = lldb.SBLaunchInfo(None) launch_info.SetProcessPluginName("ScriptedProcess") launch_info.SetScriptedProcessClassName("my_scripted_process.MyScriptedProcess") error = lldb.SBError() process = target.Launch(launch_info, error) self.assertTrue(process and process.IsValid(), PROCESS_IS_VALID) self.assertEqual(process.GetProcessID(), 42) hello_world = "Hello, world!" memory_read = process.ReadCStringFromMemory(0x50000000000, len(hello_world) + 1, # NULL byte error) self.assertTrue(error.Success(), "Failed to read memory from scripted process.") self.assertEqual(hello_world, memory_read) def test_launch_scripted_process_cli(self): """Test that we can launch an lldb scripted process from the command line, check its process ID and read string from memory.""" self.build() target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) scripted_process_example_relpath = ['..','..','..','..','examples','python','scripted_process','my_scripted_process.py'] self.runCmd("command script import " + os.path.join(self.getSourceDir(), *scripted_process_example_relpath)) process = target.GetProcess() self.assertTrue(process, PROCESS_IS_VALID) self.assertEqual(process.GetProcessID(), 42) error = lldb.SBError() hello_world = "Hello, world!" memory_read = process.ReadCStringFromMemory(0x50000000000, len(hello_world) + 1, # NULL byte error) self.assertTrue(error.Success(), "Failed to read memory from scripted process.") self.assertEqual(hello_world, memory_read)
python
13
0.605112
128
40.14433
97
starcoderdata
from helpers import functions def start(app): # add some filters to jinja, to enable us to use it on our template files app.jinja_env.filters['datetimeformat'] = functions.format_datetime app.jinja_env.filters['gravatar'] = functions.gravatar_url app.jinja_env.filters['url_for'] = functions.url_for # teardown_appcontext closes the database app.teardown_appcontext(functions.close_database) # we're adding the cli command to initialize the database app.cli.command('initdb')(functions.initdb_command)
python
8
0.746114
77
37.6
15
starcoderdata
// Copyright © 2017, EPSITEC SA, CH-1400 Yverdon-les-Bains, Switzerland // Author: Maintainer: namespace ScriptLab { class Program { static void Main(string[] args) { Program.Compile (new Mine ()); Program.Compile (new Locals ()); Program.TimeIt1 (10); Program.TimeIt2 (10); // Throws: // // An unhandled exception of type 'Microsoft.CodeAnalysis.Scripting.CompilationErrorException' // occurred in Microsoft.CodeAnalysis.Scripting.dll // // Additional information: // (1,1): error CS0012: The type 'Decimal' is defined in an assembly that is not referenced. // You must add a reference to assembly 'System.Runtime, Version=4.0.20.0, Culture=neutral, PublicKeyToken= Program.Compile (new Globals ()); } private static void Compile(object globals) { var func = ScriptCompiler.Compile (@"UniversalConstant", globals); System.Console.WriteLine (func ()); } private static void TimeIt1(int count) { System.Console.WriteLine ("Using CSharpScript.Create every time:"); var watch = new System.Diagnostics.Stopwatch (); watch.Start (); for (int i = 0; i < count; i++) { Program.Compile (new Locals ()); } watch.Stop (); System.Console.WriteLine ("Time to compile and run is {0} ms", watch.ElapsedMilliseconds / count); System.Console.ReadLine (); } private static void TimeIt2(int count) { System.Console.WriteLine ("Using CSharpScript.Create once and then only Script.ContineWith:"); var compiler = new StatefulScriptCompiler (); compiler.Setup (new Locals ()); var watch = new System.Diagnostics.Stopwatch (); watch.Start (); for (int i = 0; i < count; i++) { var func = compiler.Compile ("@UniversalConstant", new Locals ()); System.Console.WriteLine (func ()); } watch.Stop (); System.Console.WriteLine ("Time to compile and run is {0} ms", watch.ElapsedMilliseconds / count); System.Console.ReadLine (); } } }
c#
18
0.672147
117
26.875
72
starcoderdata
def save_matches(image_list, check_if_dirty=False): """Save matches and image metadata.""" log("saving matches and image meta data ...") for image in image_list: if check_if_dirty: if not image.matches_clean: image.save_matches() else: image.save_matches()
python
12
0.58642
51
35.111111
9
inline
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/framework/types.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Tensorflow { /// for reflection information generated from tensorflow/core/framework/types.proto public static partial class TypesReflection { #region Descriptor /// descriptor for tensorflow/core/framework/types.proto public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TypesReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( " " " "EA "EAoMRFRfQ09NUExFWDY0EAgSDAoIRFRfSU5UNjQQCRILCgdEVF9CT09MEAoS", "DAoIRFRfUUlOVDgQCxINCglEVF9RVUlOVDgQDBINCglEVF9RSU5UMzIQDRIP", "CgtEVF9CRkxPQVQxNhAOEg0KCURUX1FJTlQxNhAPEg4KCkRUX1FVSU5UMTYQ", "EB " " " " " " " " " " " "VDY0X1JFRhB7QiwKGG9yZy50ZW5zb3JmbG93LmZyYW1ld29ya0ILVHlwZXNQ", "cm90b3NQAfgBAWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Tensorflow.DataType), }, null)); } #endregion } #region Enums /// /// LINT.IfChange /// public enum DataType { /// /// Not a legal value for DataType. Used to indicate a DataType field /// has not been set. /// [pbr::OriginalName("DT_INVALID")] DtInvalid = 0, /// /// Data types that all computation devices are expected to be /// capable to support. /// [pbr::OriginalName("DT_FLOAT")] DtFloat = 1, [pbr::OriginalName("DT_DOUBLE")] DtDouble = 2, [pbr::OriginalName("DT_INT32")] DtInt32 = 3, [pbr::OriginalName("DT_UINT8")] DtUint8 = 4, [pbr::OriginalName("DT_INT16")] DtInt16 = 5, [pbr::OriginalName("DT_INT8")] DtInt8 = 6, [pbr::OriginalName("DT_STRING")] DtString = 7, /// /// Single-precision complex /// [pbr::OriginalName("DT_COMPLEX64")] DtComplex64 = 8, [pbr::OriginalName("DT_INT64")] DtInt64 = 9, [pbr::OriginalName("DT_BOOL")] DtBool = 10, /// /// Quantized int8 /// [pbr::OriginalName("DT_QINT8")] DtQint8 = 11, /// /// Quantized uint8 /// [pbr::OriginalName("DT_QUINT8")] DtQuint8 = 12, /// /// Quantized int32 /// [pbr::OriginalName("DT_QINT32")] DtQint32 = 13, /// /// Float32 truncated to 16 bits. Only for cast ops. /// [pbr::OriginalName("DT_BFLOAT16")] DtBfloat16 = 14, /// /// Quantized int16 /// [pbr::OriginalName("DT_QINT16")] DtQint16 = 15, /// /// Quantized uint16 /// [pbr::OriginalName("DT_QUINT16")] DtQuint16 = 16, [pbr::OriginalName("DT_UINT16")] DtUint16 = 17, /// /// Double-precision complex /// [pbr::OriginalName("DT_COMPLEX128")] DtComplex128 = 18, [pbr::OriginalName("DT_HALF")] DtHalf = 19, [pbr::OriginalName("DT_RESOURCE")] DtResource = 20, /// /// Arbitrary C++ data types /// [pbr::OriginalName("DT_VARIANT")] DtVariant = 21, [pbr::OriginalName("DT_UINT32")] DtUint32 = 22, [pbr::OriginalName("DT_UINT64")] DtUint64 = 23, /// /// Do not use! These are only for parameters. Every enum above /// should have a corresponding value below (verified by types_test). /// [pbr::OriginalName("DT_FLOAT_REF")] DtFloatRef = 101, [pbr::OriginalName("DT_DOUBLE_REF")] DtDoubleRef = 102, [pbr::OriginalName("DT_INT32_REF")] DtInt32Ref = 103, [pbr::OriginalName("DT_UINT8_REF")] DtUint8Ref = 104, [pbr::OriginalName("DT_INT16_REF")] DtInt16Ref = 105, [pbr::OriginalName("DT_INT8_REF")] DtInt8Ref = 106, [pbr::OriginalName("DT_STRING_REF")] DtStringRef = 107, [pbr::OriginalName("DT_COMPLEX64_REF")] DtComplex64Ref = 108, [pbr::OriginalName("DT_INT64_REF")] DtInt64Ref = 109, [pbr::OriginalName("DT_BOOL_REF")] DtBoolRef = 110, [pbr::OriginalName("DT_QINT8_REF")] DtQint8Ref = 111, [pbr::OriginalName("DT_QUINT8_REF")] DtQuint8Ref = 112, [pbr::OriginalName("DT_QINT32_REF")] DtQint32Ref = 113, [pbr::OriginalName("DT_BFLOAT16_REF")] DtBfloat16Ref = 114, [pbr::OriginalName("DT_QINT16_REF")] DtQint16Ref = 115, [pbr::OriginalName("DT_QUINT16_REF")] DtQuint16Ref = 116, [pbr::OriginalName("DT_UINT16_REF")] DtUint16Ref = 117, [pbr::OriginalName("DT_COMPLEX128_REF")] DtComplex128Ref = 118, [pbr::OriginalName("DT_HALF_REF")] DtHalfRef = 119, [pbr::OriginalName("DT_RESOURCE_REF")] DtResourceRef = 120, [pbr::OriginalName("DT_VARIANT_REF")] DtVariantRef = 121, [pbr::OriginalName("DT_UINT32_REF")] DtUint32Ref = 122, [pbr::OriginalName("DT_UINT64_REF")] DtUint64Ref = 123, } #endregion } #endregion Designer generated code
c#
21
0.62563
111
37.086093
151
starcoderdata
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Recipe for Skia Infra. import json import re PYTHON_VERSION_COMPATIBILITY = "PY3" DEPS = [ 'recipe_engine/context', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/step', ] INFRA_GIT_URL = 'https://skia.googlesource.com/buildbot' def retry(api, attempts, *args, **kwargs): exc = None for _ in range(attempts): try: api.step(*args, **kwargs) return except api.step.StepFailure as e: exc = e else: # pragma: nocover raise exc # pylint:disable=raising-bad-type def RunSteps(api): # Hack start_dir to remove the "k" directory which is added by Kitchen. # Otherwise, we can't get to the CIPD packages, caches, and isolates which # were put into the task workdir. if api.path.c.base_paths['start_dir'][-1] == 'k': # pragma: nocover api.path.c.base_paths['start_dir'] = api.path.c.base_paths['start_dir'][:-1] # The 'build' and 'depot_tools directories come from recipe DEPS and aren't # provided by default. We have to set them manually. api.path.c.base_paths['depot_tools'] = ( api.path.c.base_paths['start_dir'] + ('recipe_bundle', 'depot_tools')) gopath = api.path['start_dir'].join('cache', 'gopath') infra_dir = api.path['start_dir'].join('buildbot') go_cache = api.path['start_dir'].join('cache', 'go_cache') go_root = api.path['start_dir'].join('go', 'go') go_bin = go_root.join('bin') # Initialize the Git repo. We receive the code via Isolate, but it doesn't # include the .git dir. with api.context(cwd=infra_dir): api.step('git init', cmd=['git', 'init']) api.step('git add', cmd=['git', 'add', '.']) api.step('git commit', cmd=['git', 'commit', '-m', 'Fake commit to satisfy recipe tests']) # Fetch Go dependencies. env = { 'CHROME_HEADLESS': '1', 'DOCKER_CONFIG': '/home/chrome-bot/.docker', 'GOCACHE': go_cache, 'GOFLAGS': '-mod=readonly', # Prohibit builds from modifying go.mod. 'GOROOT': go_root, 'GOPATH': gopath, 'GIT_USER_AGENT': 'git/1.9.1', # I don't think this version matters. 'PATH': api.path.pathsep.join([ str(go_bin), str(gopath.join('bin')), str(api.path['start_dir'].join('gcloud_linux', 'bin')), str(api.path['start_dir'].join('protoc', 'bin')), str(api.path['start_dir'].join('node', 'node', 'bin')), str(api.path['start_dir'].join('cockroachdb')), '%(PATH)s', ]), } with api.context(cwd=infra_dir, env=env): api.step('which go', cmd=['which', 'go']) # Try up to three times in case of transient network failures. retry(api, 3, 'go mod download', cmd=['go', 'mod', 'download']) install_targets = [ 'github.com/golang/protobuf/protoc-gen-go', 'github.com/kisielk/errcheck', 'golang.org/x/tools/cmd/goimports', 'golang.org/x/tools/cmd/stringer', 'github.com/twitchtv/twirp/protoc-gen-twirp', 'go.larrymyers.com/protoc-gen-twirp_typescript' ] for target in install_targets: api.step('go install %s' % target, cmd=['go', 'install', '-v', target]) # More prerequisites. builder = api.properties['buildername'] run_emulators = infra_dir.join('scripts', 'run_emulators', 'run_emulators') if ('Large' in builder) or ('Race' in builder): with api.context(cwd=infra_dir, env=env): api.step('start the cloud emulators', cmd=[run_emulators, 'start']) env['DATASTORE_EMULATOR_HOST'] = 'localhost:8891' env['BIGTABLE_EMULATOR_HOST'] = 'localhost:8892' env['PUBSUB_EMULATOR_HOST'] = 'localhost:8893' env['FIRESTORE_EMULATOR_HOST'] = 'localhost:8894' env['COCKROACHDB_EMULATOR_HOST'] = 'localhost:8895' # Run tests. env['SKIABOT_TEST_DEPOT_TOOLS'] = api.path['depot_tools'] env['PATH'] = api.path.pathsep.join([ env['PATH'], str(api.path['depot_tools'])]) if 'Build' in builder: with api.context(cwd=infra_dir, env=env): api.step('make all', ['make', 'all']) else: cmd = ['go', 'run', './run_unittests.go'] if 'Race' in builder: cmd.extend(['--race', '--large', '--medium', '--small']) elif 'Large' in builder: cmd.append('--large') elif 'Medium' in builder: cmd.append('--medium') else: cmd.append('--small') try: with api.context(cwd=infra_dir, env=env): api.step('run_unittests', cmd) finally: if ('Large' in builder) or ('Race' in builder): with api.context(cwd=infra_dir, env=env): api.step('stop the cloud emulators', cmd=[run_emulators, 'stop']) # Sanity check; none of the above should have modified the go.mod file. with api.context(cwd=infra_dir): api.step('git diff go.mod', cmd=['git', 'diff', '--no-ext-diff', '--exit-code', 'go.mod']) def GenTests(api): test_revision = 'abc123' yield ( api.test('Infra-PerCommit') + api.properties(buildername='Infra-PerCommit-Small', path_config='kitchen') + api.step_data('go mod download', retcode=1) ) yield ( api.test('Infra-PerCommit_initialcheckout') + api.properties(buildername='Infra-PerCommit-Small', path_config='kitchen') ) yield ( api.test('Infra-PerCommit_try_gerrit') + api.properties(buildername='Infra-PerCommit-Small', revision=test_revision, patch_issue='1234', patch_ref='refs/changes/34/1234/1', patch_repo='https://skia.googlesource.com/buildbot.git', patch_set='1', patch_storage='gerrit', path_config='kitchen', repository='https://skia.googlesource.com/buildbot.git') ) yield ( api.test('Infra-PerCommit-Build') + api.properties(buildername='Infra-PerCommit-Build', path_config='kitchen') ) yield ( api.test('Infra-PerCommit-Large') + api.properties(buildername='Infra-PerCommit-Large', path_config='kitchen') ) yield ( api.test('Infra-PerCommit-Medium') + api.properties(buildername='Infra-PerCommit-Medium', path_config='kitchen') ) yield ( api.test('Infra-PerCommit-Race') + api.properties(buildername='Infra-PerCommit-Race', path_config='kitchen') )
python
19
0.603206
80
33.656085
189
starcoderdata
var http = require('http'); var https = require('https'); const Axios = require('axios') function searchSongByName(userName,songName,callback){ var param = 's='+encodeURIComponent(songName)+'&type=1'; getSong(param).then(function(data){ var code = data.code; if(code==200){ if(data.result.songs){ var song = data.result.songs[0]; var id = song.id; var songname = song.name; var songurl = 'http://music.163.com/song?id='+id; callback(songname); setTimeout(function(){ callback(songurl); },500); }else{ callback('不知道'+songName+'是什么歌哇!'+userName+'唱给我听好不好哇!') } }else{ callback('不知道'+songName+'是什么歌哇!'+userName+'唱给我听好不好哇!') } }) } const getSong = param => new Promise((resolve, reject) => { Axios.post('https://music.163.com/api/search/pc',param, { timeout: 30000, headers: { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36' } }) .then(response => resolve(response.data)) .catch(error => { console.log(error) }) }) module.exports={ searchSongByName }
javascript
21
0.590909
128
24.765957
47
starcoderdata
//>>built require({cache:{"url:dijit/templates/MenuBarItem.html":"<div class=\"dijitReset dijitInline dijitMenuItem dijitMenuItemLabel\" data-dojo-attach-point=\"focusNode\"\n\t \trole=\"menuitem\" tabIndex=\"-1\">\n\t<span data-dojo-attach-point=\"containerNode,textDirNode\"> define("dijit/MenuBarItem",["dojo/_base/declare","./MenuItem","dojo/text!./templates/MenuBarItem.html"],function(_1,_2,_3){ var _4=_1("dijit._MenuBarItemMixin",null,{templateString:_3,_setIconClassAttr:null}); var _5=_1("dijit.MenuBarItem",[_2,_4],{}); _5._MenuBarItemMixin=_4; return _5; });
javascript
12
0.708263
289
73.125
8
starcoderdata
#include "amuse/Studio.hpp" #include #include "amuse/Engine.hpp" namespace amuse { #ifndef NDEBUG bool Studio::_cyclicCheck(const Studio* leaf) const { return std::any_of(m_studiosOut.cbegin(), m_studiosOut.cend(), [leaf](const auto& studio) { return leaf == studio.m_targetStudio.get() || studio.m_targetStudio->_cyclicCheck(leaf); }); } #endif Studio::Studio(Engine& engine, bool mainOut) : m_engine(engine), m_master(engine), m_auxA(engine), m_auxB(engine) { if (mainOut && engine.m_defaultStudioReady) addStudioSend(engine.getDefaultStudio(), 1.f, 1.f, 1.f); } void Studio::addStudioSend(ObjToken studio, float dry, float auxA, float auxB) { m_studiosOut.emplace_back(std::move(studio), dry, auxA, auxB); /* Cyclic check */ assert(!_cyclicCheck(this)); } void Studio::resetOutputSampleRate(double sampleRate) { m_master.resetOutputSampleRate(sampleRate); m_auxA.resetOutputSampleRate(sampleRate); m_auxB.resetOutputSampleRate(sampleRate); } } // namespace amuse
c++
17
0.722549
115
29
34
starcoderdata
def run_cprofile(func: Callable) -> Callable: """Decorate a function with this function to get profiled.""" @functools.wraps(func) def profiled_func(*args, **kwargs) -> Any: """Profile the function and print the results.""" profile = cProfile.Profile() _LOGGER.info('Start profiling function "%s"', func) profile.enable() try: return func(*args, **kwargs) finally: profile.disable() _LOGGER.info('Finished profiling function "%s"', func) pstats.Stats(profile).sort_stats('cumulative').print_stats(30) _LOGGER.info('End of profiling results for "%s"', func) return profiled_func
python
16
0.60485
74
42.875
16
inline
<?php class Model_proses extends CI_Model { // var $table = 'trans_so'; var $column_order = array(null, 'a.nomor_so', 'd.nama', 'b.nama', "DATE_FORMAT(a.created_at,'%d/%m/%Y %H:%i:%s')", 'a.nama_so', 'c.nama_lengkap', ' a.nama_marketing', ' a.status_hm'); var $column_search = array('a.nomor_so', 'd.nama', 'b.nama', "DATE_FORMAT(a.created_at,'%d/%m/%Y %H:%i:%s')", 'a.nama_so', 'c.nama_lengkap', ' a.nama_marketing', ' a.status_hm'); // var $order = array('id' => 'DESC'); public function __construct() { parent::__construct(); $this->load->database(); $this->load->model('model_menu'); } private function _get_datatables_query() { $this->sql_so(); $i = 0; foreach ($this->column_search as $item) { if ($_POST['search']['value']) { if ($i === 0) { $this->db->group_start(); $this->db->like($item, $_POST['search']['value']); } else { $this->db->or_like($item, $_POST['search']['value']); } if (count($this->column_search) - 1 == $i) $this->db->group_end(); } $i++; } if (isset($_POST['order'])) { $this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']); } // else if (isset($this->order)) { // $order = $this->order; // $this->db->order_by(key($order), $order[key($order)]); // } } function sql_so() { $outputs = $this->model_menu->getUser(); $user_id = $outputs['data']['user_id']; $get_cabang = "SELECT id_cabang FROM m_pic WHERE user_id='$user_id'"; $data = $this->db->query($get_cabang)->result(); foreach ($data as $data2) { $cabang[] = $data2->id_cabang; } $this->db->select("a.id,a.id_cabang,a.id_pic, a.nomor_so, b.nama AS asal_data,d.nama as cabang,DATE_FORMAT(a.created_at,'%d/%m/%Y %H:%i:%s') as tanggal, a.nama_so, a.nama_marketing, a.status_das, c.nama_lengkap as nama_debitur", false); $this->db->from('trans_so a'); $this->db->join('view_kode_group4 b', 'b.id=a.id_asal_data', 'left'); $this->db->join('calon_debitur c', 'c.id=a.id_calon_debitur', 'left'); $this->db->join('mk_cabang d', 'd.id=a.id_cabang', 'left'); $this->db->where_in('a.id_cabang', $cabang); $this->db->order_by('a.id', 'desc'); } function get_datatables() { $this->_get_datatables_query(); if ($_POST['length'] != -1) $this->db->limit($_POST['length'], $_POST['start']); $query = $this->db->get(); return $query->result(); } function count_filtered() { $this->_get_datatables_query(); $query = $this->db->get(); return $query->num_rows(); } public function count_all() { $this->sql_so(); return $this->db->count_all_results(); } }
php
19
0.471108
244
32.802198
91
starcoderdata
#include "Clipper.h" #include #include "DataFlow.h" #include "DrawEngine.h" #include "MemoryPool.h" #include "compiler.h" namespace glsp { using glm::vec4; static glm::vec4 sPlanes[Clipper::MAX_PLANES] = { glm::vec4( 0.0f, 0.0f, 1.0f, 1.0f), // PLANE_NEAR glm::vec4( 0.0f, 0.0f, -1.0f, 1.0f), // PLANE_FAR glm::vec4( 1.0f, 0.0f, 0.0f, 1.0f), // PLANE_LEFT glm::vec4(-1.0f, 0.0f, 0.0f, 1.0f), // PLANE_RIGHT glm::vec4( 0.0f, 1.0f, 0.0f, 1.0f), // PLANE_BOTTOM glm::vec4( 0.0f, -1.0f, 0.0f, 1.0f), // PLANE_TOP glm::vec4( 0.0f, 0.0f, 0.0f, 1.0f), // PLANE_ZEROW glm::vec4( 1.0f, 0.0f, 0.0f, 0.0f), // PLANE_GB_LEFT glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f), // PLANE_GB_RIGHT glm::vec4( 0.0f, 1.0f, 0.0f, 0.0f), // PLANE_GB_BOTTOM glm::vec4( 0.0f, -1.0f, 0.0f, 0.0f) // PLANE_GB_TOP }; Clipper::Clipper(): PipeStage("Clipping", DrawEngine::getDrawEngine()) { } void Clipper::emit(void *data) { Batch *bat = static_cast<Batch *>(data); onClipping(bat); getNextStage()->emit(bat); } // Compute Cohen-Sutherland style outcodes against the view frustum void Clipper::ComputeOutcodesFrustum(const Primitive &prim, int outcodes[3]) { float dist[3]; for (int i = PLANE_NEAR; i <= PLANE_ZEROW; ++i) { dist[0] = glm::dot(prim.mVert[0].position(), sPlanes[i]); dist[1] = glm::dot(prim.mVert[1].position(), sPlanes[i]); dist[2] = glm::dot(prim.mVert[2].position(), sPlanes[i]); if (i == PLANE_ZEROW) { // Plane w > 0, use "<=" to get rid of clip space (0, 0, 0, 0), // which is a degenerate triangle and can be thrown way directly if (dist[0] <= 0.0f) outcodes[0] |= (1 << i); if (dist[1] <= 0.0f) outcodes[1] |= (1 << i); if (dist[2] <= 0.0f) outcodes[2] |= (1 << i); } else { if (dist[0] < 0.0f) outcodes[0] |= (1 << i); if (dist[1] < 0.0f) outcodes[1] |= (1 << i); if (dist[2] < 0.0f) outcodes[2] |= (1 << i); } } } // Compute outcodes against the guard band void Clipper::ComputeOutcodesGuardband(const Primitive &prim, int outcodes[3]) { float dist[3]; for (int i = PLANE_GB_LEFT; i <= PLANE_GB_TOP; ++i) { dist[0] = glm::dot(prim.mVert[0].position(), sPlanes[i]); dist[1] = glm::dot(prim.mVert[1].position(), sPlanes[i]); dist[2] = glm::dot(prim.mVert[2].position(), sPlanes[i]); if (dist[0] < 0.0f) outcodes[0] |= (1 << i); if (dist[1] < 0.0f) outcodes[1] |= (1 << i); if (dist[2] < 0.0f) outcodes[2] |= (1 << i); } } /* NOTE: * When guard band is used, need clip against guard band * rather than view frustum. Otherwise, there will be cracks * on the shared edge between two triangles(one is inside * guard band, while another intersects with guard band) * after snapping to subpixel grids. */ void Clipper::ClipAgainstGuardband(Primitive &prim, int outcodes_union, Primlist &out) { /* Two round robin intermediate boxes * One src, one dst. Next loop, reverse! */ vsOutput tmp[6 * 2]; vsOutput *rr[2][6]; int vertNum[2]; float dist[2]; int src = 0, dst = 1; int tmpnr = 0; assert(prim.mType == Primitive::TRIANGLE); rr[src][0] = &(prim.mVert[0]); rr[src][1] = &(prim.mVert[1]); rr[src][2] = &(prim.mVert[2]); vertNum[src] = 3; unsigned long i; while (_BitScanForward(&i, (unsigned long)outcodes_union)) { outcodes_union &= ~(1 << i); if(vertNum[src] > 0) dist[0] = glm::dot(rr[src][0]->position(), sPlanes[i]); vertNum[dst] = 0; for(int j = 0; j < vertNum[src]; j++) { int k = (j + 1) % vertNum[src]; dist[1] = dot(rr[src][k]->position(), sPlanes[i]); // Can not use unified linear interpolation equation. // Otherwise, if clip AB and BA, the results will be different. // Here we solve this by clip an edge in a fixed direction: from inside out if(dist[0] >= 0.0f) { rr[dst][vertNum[dst]++] = rr[src][j]; if(dist[1] < 0.0f) { vsOutput *new_vert = &tmp[tmpnr++]; vertexLerp(*new_vert, *rr[src][j], *rr[src][k], dist[0] / (dist[0] - dist[1])); rr[dst][vertNum[dst]++] = new_vert; } } else if(dist[1] >= 0.0f) { vsOutput *new_vert = &tmp[tmpnr++]; vertexLerp(*new_vert, *rr[src][k], *rr[src][j], dist[1] / (dist[1] - dist[0])); rr[dst][vertNum[dst]++] = new_vert; } dist[0] = dist[1]; } src = (src + 1) & 0x1; dst = (dst + 1) & 0x1; } if(vertNum[src] > 0) { assert(vertNum[src] >= 3 && vertNum[src] <= 6); // Triangulation for (int i = 1; i < vertNum[src] - 1; i++) { Primitive *new_prim = new(MemoryPoolMT::get()) Primitive; new_prim->mType = Primitive::TRIANGLE; new_prim->mVertNum = 3; new_prim->mVert[0] = *rr[src][0]; new_prim->mVert[1] = std::move(*rr[src][i]); /* OPT to avoid copy */ new_prim->mVert[2] = *rr[src][i+1]; out.push_back(new_prim); } } } void Clipper::onClipping(Batch *bat) { Primlist out; Primlist &pl = bat->mPrims; auto it = pl.begin(); while (it != pl.end()) { int outcodes[3] = {0, 0, 0}; Primitive *prim = *it; ComputeOutcodesFrustum(*prim, outcodes); // trivially accepted if ((outcodes[0] | outcodes[1] | outcodes[2]) == 0) { out.push_back(prim); it = pl.erase(it); continue; } auto orig_it = it; ++it; // trivially rejected if (outcodes[0] & outcodes[1] & outcodes[2]) { continue; } /* A bit tricky here: * Consider this particular outcode b1000000: * -w <= x <= w (true) * -w <= y <= w (true) * -w <= z <= w (true) * w > 0 (false) * * This can derive that (x, y, z, w) = (0, 0, 0, 0). * So it's an efficient way to catch this degenerated case. */ if (UNLIKELY(outcodes[0] == (1 << PLANE_ZEROW) || outcodes[1] == (1 << PLANE_ZEROW) || outcodes[2] == (1 << PLANE_ZEROW))) { continue; } ComputeOutcodesGuardband(*prim, outcodes); unsigned outcodes_union = (outcodes[0] | outcodes[1] | outcodes[2]) & kGBClipMask; if (LIKELY(outcodes_union == 0)) { out.push_back(prim); it = pl.erase(orig_it); } else { // need to do clipping ClipAgainstGuardband(*prim, outcodes_union, out); } } pl.swap(out); for (Primitive *prim: out) { prim->~Primitive(); MemoryPoolMT::get().deallocate(prim, sizeof(Primitive)); } } // vertex linear interpolation void Clipper::vertexLerp(vsOutput &new_vert, vsOutput &vert1, vsOutput &vert2, float t) { assert(vert1.getRegsNum() == vert2.getRegsNum()); new_vert.resize(vert1.getRegsNum()); for(size_t i = 0; i < vert1.getRegsNum(); ++i) { new_vert[i] = vert1[i] * (1 - t) + vert2[i] * t; } } void Clipper::ComputeGuardband(float width, float height) { sPlanes[PLANE_GB_LEFT ].w = sPlanes[PLANE_GB_RIGHT ].w = GUARDBAND_WIDTH / width; sPlanes[PLANE_GB_BOTTOM].w = sPlanes[PLANE_GB_TOP ].w = GUARDBAND_HEIGHT / height; } void Clipper::finalize() { } } // namespace glsp
c++
21
0.589144
86
23.192171
281
starcoderdata
def ny(self, val): # type: (int) -> None """Sets the number of rows.""" self.check_destroyed() if val <= 0: raise ValueError('Cannot have non-positive number of rows.') self._ny = val
python
9
0.523404
72
32.714286
7
inline
namespace MtgPairings.Domain { public class Seat { public int Number { get; private set; } public Team Team { get; private set; } public Seat(int number, Team team) { this.Number = number; this.Team = team; } public override bool Equals(object obj) { return this.Equals(obj as Seat); } public bool Equals(Seat other) { if (other == null) { return false; } else if (ReferenceEquals(other, this)) { return true; } else { return this.Number == other.Number && this.Team.Equals(other.Team); } } } }
c#
16
0.429975
53
21.611111
36
starcoderdata
<?php namespace KDuma\SMS\Drivers; interface SMSSenderDriverInterface { /** * @param $to string Recipient phone number * @param $message string Message to send * * @return void */ public function send($to, $message); }
php
7
0.616858
54
19.153846
13
starcoderdata
void RedQueueDisc::UpdateMaxP (double newAve) { NS_LOG_FUNCTION (this << newAve); Time now = Simulator::Now (); double m_part = 0.4 * (m_maxTh - m_minTh); // AIMD rule to keep target Q~1/2(m_minTh + m_maxTh) if (newAve < m_minTh + m_part && m_curMaxP > m_bottom) { // we should increase the average queue size, so decrease m_curMaxP m_curMaxP = m_curMaxP * m_beta; m_lastSet = now; } else if (newAve > m_maxTh - m_part && m_top > m_curMaxP) { // we should decrease the average queue size, so increase m_curMaxP double alpha = m_alpha; if (alpha > 0.25 * m_curMaxP) { alpha = 0.25 * m_curMaxP; } m_curMaxP = m_curMaxP + alpha; m_lastSet = now; } }
c++
12
0.574099
73
27.846154
26
inline
package main //func TestFromString(t *testing.T) { // cases := []struct { // name string // connStr string // pairs []types.Pair // err error // }{ // { // "empty", // "", // nil, // services.ErrConnectionStringInvalid, // }, // { // "simplest", // "tests://", // nil, // nil, // }, // { // "only options", // "tests://?size=200", // []types.Pair{ // pairs.WithSize(200), // }, // nil, // }, // { // "only root dir", // "tests:///", // []types.Pair{ // pairs.WithWorkDir("/"), // }, // nil, // }, // { // "end with ?", // "tests:///?", // []types.Pair{ // pairs.WithWorkDir("/"), // }, // nil, // }, // { // "stupid, but valid (ignored)", // "tests:///?&&&", // []types.Pair{ // pairs.WithWorkDir("/"), // }, // nil, // }, // { // "value can contain all characters except &", // "tests:///?string_pair=a=b:/c?d&size=200", // []types.Pair{ // pairs.WithWorkDir("/"), // WithStringPair("a=b:/c?d"), // pairs.WithSize(200), // }, // nil, // }, // { // "full format", // "tests://abc/tmp/tmp1?size=200&storage_class=sc", // []types.Pair{ // pairs.WithName("abc"), // pairs.WithWorkDir("/tmp/tmp1"), // pairs.WithSize(200), // WithStorageClass("sc"), // }, // nil, // }, // { // "duplicate key, appear in order (finally, first will be picked)", // "tests://abc/tmp/tmp1?size=200&name=def&size=300", // []types.Pair{ // pairs.WithName("abc"), // pairs.WithWorkDir("/tmp/tmp1"), // pairs.WithSize(200), // pairs.WithName("def"), // pairs.WithSize(300), // }, // nil, // }, // { // "not registered pair", // "tests://abc/tmp?not_a_pair=a", // nil, // services.ErrConnectionStringInvalid, // }, // { // "key without value (not registered pair)", // "tests://abc/tmp?not_a_pair&&", // nil, // services.ErrConnectionStringInvalid, // }, // { // "not parsable pair", // "tests://abc/tmp?io_call_back=a", // nil, // services.ErrConnectionStringInvalid, // }, // { // "key with features", // "tests://abc/tmp?enable_loose_pair", // []types.Pair{ // pairs.WithName("abc"), // pairs.WithWorkDir("/tmp"), // WithEnableLoosePair(), // }, // nil, // }, // { // "key with default paris", // "tests://abc/tmp?default_storage_class=STANDARD", // []types.Pair{ // pairs.WithName("abc"), // pairs.WithWorkDir("/tmp"), // WithDefaultStorageClass("STANDARD"), // }, // nil, // }, // } // // for _, tt := range cases { // t.Run(tt.name, func(t *testing.T) { // t.Run("NewServicerFromString", func(t *testing.T) { // servicer, err := services.NewServicerFromString(tt.connStr) // service, ok := servicer.(*Service) // // if tt.err == nil { // assert.Nil(t, err) // assert.True(t, ok) // } else { // assert.True(t, errors.Is(err, tt.err)) // return // } // // assert.Equal(t, service.Pairs, tt.pairs) // }) // t.Run("NewStoragerFromString", func(t *testing.T) { // storager, err := services.NewStoragerFromString(tt.connStr) // storage, ok := storager.(*Storage) // // if tt.err == nil { // assert.Nil(t, err) // assert.True(t, ok) // } else { // assert.True(t, errors.Is(err, tt.err)) // return // } // // assert.Equal(t, storage.Pairs, tt.pairs) // }) // // }) // } //}
go
5
0.516967
70
20.049689
161
starcoderdata
package de.hskl.repominer.repository; import de.hskl.repominer.models.File; import de.hskl.repominer.models.exception.DaoException; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.sql.*; import java.util.ArrayList; import java.util.List; @Service public class FileRepository { private final DataSource ds; public FileRepository(DataSource ds) { this.ds = ds; } public File loadFile(int id) { try { Connection con = DataSourceUtils.getConnection(ds); PreparedStatement pstmt = con.prepareStatement("SELECT * FROM File WHERE id = ? ", Statement.RETURN_GENERATED_KEYS); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { return parseFile(rs); } return null; } catch (SQLException e) { throw new DaoException("Error loading File", e); } } public List loadAllFilesFromProject(int projectId){ List resultList = new ArrayList<>(); try{ Connection con = DataSourceUtils.getConnection(ds); PreparedStatement pstmt = con.prepareStatement("SELECT * FROM File WHERE projectId = ?"); pstmt.setInt(1, projectId); ResultSet rs = pstmt.executeQuery(); while(rs.next()){ File file = parseFile(rs); if(file != null) resultList.add(file); } return resultList; }catch(SQLException ex){ throw new DaoException("Error loading files with projectId"); } } public File addFile(File file) { try { Connection con = DataSourceUtils.getConnection(ds); PreparedStatement pstmt = con.prepareStatement("INSERT INTO File (projectId) VALUES (?)", Statement.RETURN_GENERATED_KEYS); pstmt.setInt(1, file.getProjectId()); pstmt.execute(); ResultSet rs = pstmt.getGeneratedKeys(); if(rs.next()){ file.setId(rs.getInt(1)); return file; } throw new DaoException("Error saving File"); } catch (SQLException e) { throw new DaoException("Error saving File", e); } } public boolean deleteFile(File file) { try { Connection con = DataSourceUtils.getConnection(ds); PreparedStatement pstmt = con.prepareStatement("DELETE FROM File WHERE id = ?", Statement.RETURN_GENERATED_KEYS); pstmt.setInt(1, file.getId()); return pstmt.executeUpdate() != 0; } catch (SQLException e) { throw new DaoException("Error deleting File", e); } } private File parseFile(ResultSet rs) throws SQLException { return new File( rs.getInt("id"), rs.getInt("projectId") ); } }
java
12
0.594021
128
30.744898
98
starcoderdata
#include #include #include #include using namespace std; int main(){ Vec3 a(1,2,3); Vec3 b(4,5,6); cout << a << endl; cout << a+b << endl; Mat3 m; cout << m << endl; for (int i=0; i<9; ++i) m.p[i] = double(i); cout << m << endl; cout << m.T() << endl; return 0; }
c++
8
0.498575
47
14.954545
22
starcoderdata
namespace Perfolizer.Properties { internal static class PerfolizerInfo { public const string PublicKey = " + " + " + " + "d698b246c5022b00b952567954dc01fef3dbe56d2a3efc1e2e5e725d111ffdee804c8744285025" + "7a4f6420f4058f8a474e4353adbac403bf7f9ced867d55132a7f25d63fe8d7d59f888ac61f618d" + "ebf2a7bf25b5d17d80062a2b8b5d5882c252c202da410fba522a52b9548ef64605e31e7b196feb" + "14a144ccbe71fa0515c5a709afc5ae"; } }
c#
15
0.540705
122
53.933333
15
starcoderdata
package com.bng.ddaja.common.config.interceptor; import java.util.Arrays; import javax.security.sasl.AuthenticationException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.bng.ddaja.common.enums.AuthRequiredURLs; import com.bng.ddaja.tokens.service.TokenService; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import lombok.AllArgsConstructor; @Component @AllArgsConstructor public class JWTInterceptor implements HandlerInterceptor { private TokenService tokenService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if(request.getMethod().equals("OPTIONS")) return true; boolean isAuthRequiredURL = Arrays.stream(AuthRequiredURLs.values()).anyMatch(e-> request.getRequestURI().contains(e.getName())); if(!isAuthRequiredURL) return true; String jwt = request.getHeader("Authorization"); if(jwt == null) throw new AuthenticationException("JWT is Required"); return tokenService.isValidatedJWT(jwt); } }
java
14
0.778057
137
35.212121
33
starcoderdata
const { getUserByEmail } = require('../user/service.js'); const {Order} = require('./model.js'); exports.getOrder = async (req, res) =>{ let query = {}; if(req.body.movieId) query.movieId = req.body.movieId; let orders = await Order.find(query); res.json({'orders':orders}); } let getOrderByUserId = async (id) =>{ let orders = await Order.find({userId: id}); return orders; } exports.getOrderUser = async(req, res) =>{ let user = await getUserByEmail(req, res); //console.log("getOrderUSer: ", user); try{ order = await getOrderByUserId(user._id); //console.log("order: ", order); if(order.length) res.json({"msg":"1 order was found", "content":order}); else res.json({"msg":"No order was found", "content":""}); return true; }catch{ console.log("Error happened"); order = ""; res.status(400).json({"error":"Error", "content":order}); return false; } } let userHasOrder = async (req, res) =>{ return !!(await getOrderByUserId(req.body.userId)).length; } exports.addOrder = async (req, res) =>{ if(!(await userHasOrder(req, res))){ let {userId, movieId, daysToRent} = req.body; let createdAt = new Date(); let refundDate = new Date(createdAt); refundDate.setDate(createdAt.getDate() + daysToRent); let newOrder = new Order({userId, movieId, createdAt, refundDate}); await newOrder.save(); res.json({"msg":"Added"}) return true; }else{ res.json({"msg":"Not added: user has another movie already"}) return false; } }
javascript
12
0.60309
80
30.773585
53
starcoderdata
// // GRChartHeaderView.h // GoldRush // // Created by 徐孟林 on 2016/12/26. // Copyright © 2016年 Jack. All rights reserved. // #import @protocol ChartHeaderDelegate @optional - (void)buttonChartTypeAction:(UIButton *)chartType; - (void)buttonChartTypeImageAction; @end @interface GRChartHeaderView : UIView @property (nonatomic,assign) id delegate; @end
c
9
0.759336
70
19.083333
24
starcoderdata
func NewClientCertForHubController( clusterName string, agentName string, clientCertSecretNamespace string, clientCertSecretName string, kubeconfigData []byte, spokeCoreClient corev1client.CoreV1Interface, hubCSRClient csrclient.CertificateSigningRequestInterface, hubCSRInformer certificatesinformers.CertificateSigningRequestInformer, spokeSecretInformer corev1informers.SecretInformer, recorder events.Recorder, controllerName string, ) factory.Controller { clientCertOption := clientcert.ClientCertOption{ SecretNamespace: clientCertSecretNamespace, SecretName: clientCertSecretName, AdditonalSecretData: map[string][]byte{ clientcert.ClusterNameFile: []byte(clusterName), clientcert.AgentNameFile: []byte(agentName), clientcert.KubeconfigFile: kubeconfigData, }, } csrOption := clientcert.CSROption{ ObjectMeta: metav1.ObjectMeta{ GenerateName: fmt.Sprintf("%s-", clusterName), Labels: map[string]string{ // the label is only an hint for cluster name. Anyone could set/modify it. clientcert.ClusterNameLabel: clusterName, }, }, Subject: &pkix.Name{ Organization: []string{ fmt.Sprintf("%s%s", user.SubjectPrefix, clusterName), user.ManagedClustersGroup, }, CommonName: fmt.Sprintf("%s%s:%s", user.SubjectPrefix, clusterName, agentName), }, SignerName: certificates.KubeAPIServerClientSignerName, EventFilterFunc: func(obj interface{}) bool { accessor, err := meta.Accessor(obj) if err != nil { return false } labels := accessor.GetLabels() // only enqueue csr from a specific managed cluster if labels[clientcert.ClusterNameLabel] != clusterName { return false } // only enqueue csr whose name starts with the cluster name return strings.HasPrefix(accessor.GetName(), fmt.Sprintf("%s-", clusterName)) }, } return clientcert.NewClientCertificateController( clientCertOption, csrOption, hubCSRInformer, hubCSRClient, spokeSecretInformer, spokeCoreClient, recorder, controllerName, ) }
go
20
0.758128
82
30.246154
65
inline
/* Copyright(c) Sophist Solutions Inc. 1991-1992. All rights reserved */ #ifndef __Language__ #define __Language__ /* * $Header: /fuji/lewis/RCS/Language.hh,v 1.4 1992/10/10 04:21:25 lewis Exp $ * * Description: * * TODO: * * Changes: * $Log: Language.hh,v $ * Revision 1.4 1992/10/10 04:21:25 lewis * *** empty log message *** * * Revision 1.3 1992/10/10 03:56:51 lewis * Got rid of CollectionSize typedef - use size_t directly instead. * * Revision 1.2 1992/05/23 00:11:34 lewis * Dont include UserCommand.hh since never used, and we've moved down * to the foundation and cannot. * * * */ #include "Config-Foundation.hh" #ifndef qDynamicLanguages #define qDynamicLanguages 0 #endif #if qDynamicLanguages extern Boolean qEnglish; extern Boolean qFrench; extern Boolean qGerman; extern Boolean qItalian; extern Boolean qSpanish; extern Boolean qJapanese; #else /* qDynamicLanguages */ #ifndef qEnglish #define qEnglish 1 #endif #ifndef qFrench #define qFrench 0 #endif #ifndef qGerman #define qGerman 0 #endif #ifndef qItalian #define qItalian 0 #endif #ifndef qSpanish #define qSpanish 0 #endif #ifndef qJapanese #define qJapanese 0 #endif #endif /* qDynamicLanguages */ #endif /* __Language__ */
c++
6
0.703383
77
16.410959
73
starcoderdata
/** * Copyright (C) 2015 DataTorrent, Inc. * * 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 com.datatorrent.stram; import org.junit.Assert; import org.junit.Test; import com.datatorrent.api.StringCodec; import com.datatorrent.stram.engine.GenericOperatorProperty; import com.datatorrent.stram.engine.GenericTestOperator; import com.datatorrent.stram.plan.TestPlanContext; import com.datatorrent.stram.plan.logical.LogicalPlan; import com.datatorrent.stram.plan.logical.LogicalPlan.OperatorMeta; import com.datatorrent.stram.plan.physical.PhysicalPlan; import com.datatorrent.stram.plan.physical.PlanModifier; import com.datatorrent.stram.support.StramTestSupport.MemoryStorageAgent; import java.util.*; public class GenericOperatorPropertyCodecTest { @Test public void testGenericOperatorPropertyCodec() { LogicalPlan dag = new LogicalPlan(); Map Class<? extends StringCodec codecs = new HashMap Class<? extends StringCodec codecs.put(GenericOperatorProperty.class, GenericOperatorProperty.GenericOperatorPropertyStringCodec.class); dag.setAttribute(com.datatorrent.api.Context.DAGContext.STRING_CODECS, codecs); dag.setAttribute(com.datatorrent.api.Context.OperatorContext.STORAGE_AGENT, new MemoryStorageAgent()); GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class); OperatorMeta o1Meta = dag.getMeta(o1); TestPlanContext ctx = new TestPlanContext(); PhysicalPlan plan = new PhysicalPlan(dag, ctx); ctx.deploy.clear(); ctx.undeploy.clear(); PlanModifier pm = new PlanModifier(plan); try { pm.setOperatorProperty(o1Meta.getName(), "genericOperatorProperty", "xyz"); Assert.fail("validation error expected"); // cannot set properties on an operator that is already deployed. } catch (javax.validation.ValidationException e) { Assert.assertTrue(e.getMessage().contains(o1Meta.toString())); } GenericTestOperator newOperator = new GenericTestOperator(); pm.addOperator("newOperator", newOperator); pm.setOperatorProperty("newOperator", "genericOperatorProperty", "xyz"); Assert.assertEquals("", "xyz", newOperator.getGenericOperatorProperty().obtainString()); } }
java
16
0.761388
117
40.283582
67
starcoderdata
using UnityEngine; namespace DeadSilence { public class WeaponPickup : MonoBehaviour { private WeaponManager weaponManager; public int ammoInWeaponCount; public string weaponNameToEquip; private void Start() { weaponManager = FindObjectOfType } public void Pickup() { weaponManager.EquipWeapon(weaponNameToEquip, gameObject); print("Pickup:" + weaponNameToEquip); } } }
c#
13
0.542461
77
20.192308
26
starcoderdata
std::string StripComment(const std::string &line) { char prev_char = '\0'; for (size_t i = 0; i < line.size(); ++i) { const char this_char = line[i]; if (this_char == '#' && prev_char != '\\') { // Strips comment and any trailing whitespace. return std::string(::fst::StripTrailingAsciiWhitespace(line.substr(0, i))); } prev_char = this_char; } return line; }
c++
14
0.589873
81
32
12
inline
import axios from 'axios'; import { loading } from './loading'; const url = `https://amman-api-server.herokuapp.com/categories`; let initialState = { categories: [{ name: 'electronics', displayName: 'Electronics', description: 'electronics' }, { name: 'food', displayName: 'Food', description: 'food' }, { name: 'clothing', displayName: 'Clothing', description: 'clothing' } ], activeCategory: 'clothing', }; export default (state = {categories: []}, action) => { let { type, payload } = action; switch (type) { case 'CHANGE_ACTIVE': return { ...state, activeCategory: payload } case 'GET_CATEGORIES': return { categories: payload, activeCategory: '' }; default: return state; } } export const getCategories = () => { return async dispatch => { dispatch(loading(true)); let response = await axios({ url, method: 'GET' }); dispatch(loading(false)); dispatch({ type: 'GET_CATEGORIES', payload: response.data.results .filter(product => product.name !== 'admin') }) } } export const changeActiveCategory = name => ({ type: 'CHANGE_ACTIVE', payload: name, })
javascript
15
0.507937
64
20.014493
69
starcoderdata
package com.gdut.fundraising.blockchain.Service; import com.gdut.fundraising.blockchain.Block; import com.gdut.fundraising.blockchain.Peer; import com.gdut.fundraising.blockchain.Transaction; import java.util.List; public interface BlockChainService { /** * 创建候选区块 * @param txs * @param preBlock * @return */ Block createCandidateBlock(List txs,Block preBlock); /** * 验证区块 * @param peer * @param block * @return */ boolean verifyBlock(Peer peer,Block block); /** * 添加区块到链上 * @param peer * @param block * @return */ boolean addBlockToChain(Peer peer,Block block); /** * 回滚当前的区块,block区块必须是最后一个区块才可以回滚 * @param peer * @param block */ void rollBackBlock(Peer peer,Block block); }
java
8
0.635036
69
19.55
40
starcoderdata
namespace SimulatedTemperatureSensor { using System; using System.Diagnostics; using System.Linq; using System.Net; internal static class Utilities { internal static void InjectIoTEdgeVariables(string containerName) { var dockerCommand = $"docker exec dev_iot_edge bash -c \"docker exec {containerName} env | grep IOTEDGE_\""; Process p = new Process() { StartInfo = new ProcessStartInfo(dockerCommand) { FileName = "cmd.exe", Arguments = $"/C {dockerCommand}", RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }, }; p.Start(); p.WaitForExit(); var output = p.StandardOutput.ReadToEnd(); var lines = output.Split(new[] { "\n" }, StringSplitOptions.None) .Where(e => e != null && e.Contains("=")); var variables = lines.ToDictionary(e => e.Split("=")[0], e => e.Split("=")[1]); // Overwrite these settigns variables["IOTEDGE_WORKLOADURI"] = "http://127.0.0.1:15581/"; variables["IOTEDGE_GATEWAYHOSTNAME"] = Dns.GetHostName(); foreach (var variable in variables) { Environment.SetEnvironmentVariable(variable.Key, variable.Value); Console.WriteLine($"Injected {variable.Key}={variable.Value}"); } } } }
c#
20
0.523049
104
36
44
starcoderdata
void TNodeletPt::subscribeFrameMessages() { std::string depthImageStream = "camera/depth/image_raw"; std::string colorImageStream = "camera/color/image_raw"; NODELET_INFO_STREAM("Listening on " << depthImageStream); NODELET_INFO_STREAM("Listening on " << colorImageStream); // Subscribe to color, point cloud and depth using synchronization filter mDepthSubscriber = std::shared_ptr<message_filters::Subscriber<sensor_msgs::Image>> (new message_filters::Subscriber<sensor_msgs::Image>(nh, depthImageStream, 1)); mColorSubscriber = std::shared_ptr<message_filters::Subscriber<sensor_msgs::Image>> (new message_filters::Subscriber<sensor_msgs::Image>(nh, colorImageStream, 1)); mTimeSynchronizer = std::shared_ptr<message_filters::TimeSynchronizer<sensor_msgs::Image, sensor_msgs::Image>> (new message_filters::TimeSynchronizer<sensor_msgs::Image, sensor_msgs::Image>(*mDepthSubscriber, *mColorSubscriber, 40)); mTimeSynchronizer->registerCallback(boost::bind(&TNodeletPt::personTrackingCallback, this, _1, _2)); }
c++
15
0.723133
144
63.647059
17
inline
using System.ComponentModel.DataAnnotations; using System.Web; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Santiago.Web.Authorization; namespace Santiago.Web.Attributes.ValidationAttributes.User { public class UniqueUserNameAttribute : ValidationAttribute { private const string DefaultErrorMessage = "Пользователь с таким именем уже существует"; public string UserNameIdPropertyName { get; set; } public UniqueUserNameAttribute(string userNameIdPropertyName = "Id") { UserNameIdPropertyName = userNameIdPropertyName; } public string FormatErrorMessage() { return !string.IsNullOrEmpty(ErrorMessage) ? ErrorMessage : DefaultErrorMessage; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { bool isUserNameUnique; var user = HttpContext.Current.GetOwinContext().GetUserManager if (user == null) { isUserNameUnique = true; } else { var userIdProperty = validationContext.ObjectType.GetProperty(UserNameIdPropertyName); if (userIdProperty == null) { isUserNameUnique = false; } else { isUserNameUnique = user.Id == (string)userIdProperty.GetValue(validationContext.ObjectInstance, null); } } return isUserNameUnique ? ValidationResult.Success : new ValidationResult(FormatErrorMessage()); } } }
c#
19
0.62839
127
33
51
starcoderdata
import React, { Component } from "react"; import { View, Text, KeyboardAvoidingView, Image, } from 'react-native'; import styles from './ChatDetails.style.js'; import getGroupInfo from '../../../store/SendGroupMessage'; export default class ChatDetails extends Component { constructor(props) { super(props); } render() { const {navigate} = this.props.navigation; return ( <KeyboardAvoidingView behavior="padding" enabled> <View style={styles.detailBox}> <Image source={{uri: 'https://i.imgur.com/VhqvEBn.jpg'}} style={styles.groupPicture} /> <Text style={styles.groupHeader}> {this.props.navigation.getParam('room', '').title} <Text style={styles.sidePanel} onPress={navigate.bind(this, 'InviteUsers', {room: this.props.navigation.getParam('room', '').roomID})}> Invite <Text style={styles.sidePanel} onPress={navigate.bind(this, 'MemberList', {room: this.props.navigation.getParam('room', '').roomID})}> Members (#) <Text style={styles.sidePanel} onPress={navigate.bind(this, 'TaskManager', {id: this.props.navigation.getParam('room', '').roomID})}> Tasks (#) <Text style={styles.confirmButton} onPress={navigate.bind(this, 'Home')}> Leave Group ); } }
javascript
22
0.587114
143
30.6875
48
starcoderdata
package com.davidmogar.quizzer; import com.davidmogar.quizzer.loaders.AssessmentLoader; import com.davidmogar.quizzer.serializers.AssessmentSerializer; import spark.ModelAndView; import spark.template.freemarker.FreeMarkerEngine; import java.io.IOException; import java.util.HashMap; import java.util.Map; import static spark.Spark.get; import static spark.Spark.post; import static spark.SparkBase.staticFileLocation; public class Server { /** * Starts the Spark server and define get and post routes. */ public static void startServer() { /* Static files location */ staticFileLocation("public"); /* Get index page */ get("/", (req, res) -> { return new ModelAndView(new HashMap<String, Object>(), "index.ftl"); }, new FreeMarkerEngine()); /* Post questions and answers */ post("/", (req, res) -> { String questionsJson = req.queryParams("questions"); String answersJson = req.queryParams("answers"); String jsonGrades = "Invalid input"; if (questionsJson != null && answersJson != null) { try { Assessment assessment = AssessmentLoader.loadAssessment(questionsJson, answersJson, null); assessment.calculateGrades(); jsonGrades = AssessmentSerializer.serializeGrades(assessment.getGrades(), AssessmentSerializer.Format.JSON); } catch (IOException e) { /* Return default value */ } } Map<String, Object> attributes = new HashMap<>(); attributes.put("grades", jsonGrades); return new ModelAndView(attributes, "grades.ftl"); }, new FreeMarkerEngine()); } }
java
20
0.612234
110
31.122807
57
starcoderdata
using System; namespace BGC.Parameters { public enum ChoiceRenderingModifier { Normal = 0, Controlled } [AttributeUsage(AttributeTargets.Class)] public class PropertyChoiceTitleAttribute : PropertyLabelAttribute { public readonly ChoiceRenderingModifier renderingModifier; public PropertyChoiceTitleAttribute( string title, string serializationString = "", ChoiceRenderingModifier renderingModifier = ChoiceRenderingModifier.Normal) : base(title, serializationString) { this.renderingModifier = renderingModifier; } } }
c#
11
0.664697
87
25.038462
26
starcoderdata
import discord from discord.ext import commands from db.mongodb import checks from datetime import datetime, timedelta import asyncio class On_Ready(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def collect_data(self): while True: currTime = datetime.utcnow() - timedelta(hours=4) for doc in checks.find({"guild":793248462446919772}): if currTime >= doc["expires"] and doc["status"] =="incomplete": checks.update_one({"message":doc["message"]}, {"$set":{"status":"complete"}}) guild = self.client.get_guild(793248462446919772) channel = self.client.get_channel(doc["channel"]) role = discord.utils.get(guild.roles, id=864225432151523338) string = "" arr = [] for user in role.members: if user.id not in doc["reacted"]: string += f"{user.mention}, " arr.append(user) if len(arr) == role.members: await channel.send(f"Everyone has reacted to the activity check!") else: await channel.send(f"{string} has not reacted to activity check #{doc['count']}!") await asyncio.sleep(1) @commands.Cog.listener() async def on_ready(self): print("Ready.") await self.collect_data() self.client.loop.create_task(self.status_change) def setup(client): client.add_cog(On_Ready(client))
python
23
0.527096
106
34.06
50
starcoderdata
class Credits extends Phaser.Scene { constructor() { super("credits"); } preload() { this.load.image('credits1',"assets/sprites/credits/credits1.png"); this.load.image('credits2',"assets/sprites/credits/credits2.png"); this.load.image('credits3',"assets/sprites/credits/credits3.png"); this.load.image('credits4',"assets/sprites/credits/credits4.png"); this.load.image('credits5',"assets/sprites/credits/credits5.png"); this.load.image('credits6',"assets/sprites/credits/credits6.png"); } create() { gamePaused = false; this.skip = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); this.skip2 = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ESC); this.skip3 = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.ENTER); game.input.mouse.releasePointerLock(); this.creditsGroup = this.add.group({runChildUpdate: true}); this.add.sprite(config.width/2, config.height/2, 'creditsBackground'); var credits = new CreditsPanel(this,config.width/2,config.height/2,"credits1",1,false); var credits2 = new CreditsPanel(this,config.width/2,credits.y + config.height,"credits2",2,false); var credits3 = new CreditsPanel(this,config.width/2,credits2.y + config.height,"credits3",3,false); var credits4 = new CreditsPanel(this,config.width/2,credits3.y + config.height,"credits4",4,false); var credits5 = new CreditsPanel(this,config.width/2,credits4.y + config.height,"credits5",5,false); var credits6 = new CreditsPanel(this,config.width/2,credits5.y + config.height,"credits6",6,true); confirmSound = this.sound.add('confirmSound'); if (music.key!== 'titleMusic') { music.stop(); music = this.sound.add('titleMusic'); music.loop = true; music.play(); } } update () { if ((Phaser.Input.Keyboard.JustDown(this.skip)) || (Phaser.Input.Keyboard.JustDown(this.skip2)) || (Phaser.Input.Keyboard.JustDown(this.skip3))) { this.scene.stop('UIScene'); this.scene.start("mainMenu"); } } }
javascript
14
0.694538
148
42.104167
48
starcoderdata
def CorrBasis(psr_locs, lmax): corr = [] for ll in range(0, lmax + 1): mmodes = 2 * ll + 1 # Number of modes for this ll for mm in range(mmodes): corr.append(np.zeros((len(psr_locs), len(psr_locs)))) for aa in range(len(psr_locs)): for bb in range(aa, len(psr_locs)): plus_gamma_ml = [] # this will hold the list of gammas # evaluated at a specific value of phi{1,2}, and theta{1,2}. neg_gamma_ml = [] gamma_ml = [] # Pre-calculate all the gammas so this gets done only once. # Need all the values to execute rotation codes. for mm in range(ll + 1): zeta = calczeta(psr_locs[:, 0][aa], psr_locs[:, 0][bb], psr_locs[:, 1][aa], psr_locs[:, 1][bb]) intg_gamma = arbCompFrame_ORF(mm, ll, zeta) # just (-1)^m Gamma_ml since this is in the computational frame neg_intg_gamma = (-1) ** (mm) * intg_gamma # all of the gammas from Gamma^-m_l --> Gamma ^m_l plus_gamma_ml.append(intg_gamma) # get the neg m values via complex conjugates neg_gamma_ml.append(neg_intg_gamma) neg_gamma_ml = neg_gamma_ml[1:] # this makes sure we don't have 0 twice rev_neg_gamma_ml = neg_gamma_ml[::-1] # reverse direction of list, now runs from -m...0 gamma_ml = rev_neg_gamma_ml + plus_gamma_ml mindex = len(corr) - mmodes for mm in range(mmodes): m = mm - ll corr[mindex + mm][aa, bb] = real_rotated_Gammas( m, ll, psr_locs[:, 0][aa], psr_locs[:, 0][bb], psr_locs[:, 1][aa], psr_locs[:, 1][bb], gamma_ml ) if aa != bb: corr[mindex + mm][bb, aa] = corr[mindex + mm][aa, bb] return corr
python
18
0.478175
119
39.34
50
inline
public void run() { if (isInitialized && isActive) { if (!client.isPaused()) { sExecutor.execute(new UploadDataTask(client)); // schedule the upload for the next interval sendMetricsHandler.postDelayed(this, uploadIntervalMillis); } else { // monitoring is paused and our send loop will terminate on its own } } else { Log.i(ClientLog.TAG_MONITORING_CLIENT, "Configuration was not able to initialize. Not initiating metrics send loop"); } }
java
12
0.650485
122
31.25
16
inline
@ShellMethod(value = "Decrypt an encrypted value", key = {"d", "decrypt"}) String decrypt(final String encodedValue) throws Exception { if (encodedValue.length() <= 0) { throw new RuntimeException("cipherMessageB64 must not be empty!"); } if (this.keyStoreType.equals(KeyStoreType.GCP)) { final GcpEncryptionService gcpSecretsManager = new GcpEncryptionService( gcpProjectId, gcpKeyringLocationId.get(), credentialsProvider ); final EncryptedSecret encryptedSecret = EncryptedSecret.fromEncodedValue(encodedValue); final byte[] plainTextBytes = gcpSecretsManager.decrypt(encryptedSecret); return "PlainText: " + new String(plainTextBytes); } else if (this.keyStoreType.equals(KeyStoreType.JKS)) { // Load Secret0 from Keystore. final KeyStore keyStore = JavaKeystoreLoader.loadFromClasspath(this.jksFileName, jksPassword.toCharArray()); final SecretKey secret0Key = loadSecretKeyFromJavaKeystore(keyStore); final EncryptionService encryptionService = new JksEncryptionService(secret0Key); final EncryptedSecret encryptedSecret = EncryptedSecret.fromEncodedValue(encodedValue); final byte[] utfPlainText = encryptionService.decrypt(encryptedSecret); return "PlainText: " + new String(utfPlainText); } else { throw new RuntimeException("Please select a valid Keystore Platform! Unsupported Platform: " + keyStoreType); } }
java
12
0.742718
115
54.5
26
inline
#!/usr/bin/env node const { JsonRpc } = require('eosjs') const fetch = require('node-fetch') const { generalContractScope, edenContractScope, massiveDB } = require('../config') const HAPI_EOS_API_ENDPOINT = process.env.HAPI_EOS_API_ENDPOINT || 'https://jungle.eosio.cr' const HAPI_RATING_CONTRACT = process.env.HAPI_RATING_CONTRACT || 'rateproducer' const getRatingsStats = async (scope) => { const eos = new JsonRpc(HAPI_EOS_API_ENDPOINT, { fetch }) try { const ratings = await eos.get_table_rows({ json: true, code: HAPI_RATING_CONTRACT, scope: scope, table: 'stats', limit: 1000, reverse: false, show_payer: false }) return ratings } catch (err) { console.log(`Database connection error ${err}`) return [] } } const updateRatingsStats = async () => { console.log('==== Updating ratings stats ====') const generalRatingsStats = await getRatingsStats(generalContractScope) const edenRatingsStats = await getRatingsStats(edenContractScope) generalRatingsStats.rows.forEach(async (rating) => { try { const resultRatingStatsSave = await (await massiveDB).ratings_stats.save(rating) const dbResult = resultRatingStatsSave ? resultRatingStatsSave : await (await massiveDB).ratings_stats.insert(rating) console.log(`General save or insert of ${rating.bp} was ${dbResult ? 'SUCCESSFULL' : 'UNSUCCESSFULL'}`) } catch (err) { console.log(`Error: ${err}`) } }) edenRatingsStats.rows.forEach(async (rating) => { try { const resultRatingStatsSave = await (await massiveDB).eden_ratings_stats.save(rating) const dbResult = resultRatingStatsSave ? resultRatingStatsSave : await (await massiveDB).eden_ratings_stats.insert(rating) console.log(`Eden save or insert of ${rating.bp} was ${dbResult ? 'SUCCESSFULL' : 'UNSUCCESSFULL'}`) } catch (err) { console.log(`Error: ${err}`) } }) } updateRatingsStats()
javascript
21
0.683967
128
33.75
56
starcoderdata
def __init__(self): # (PS) Not sure about any of this... config = yaml.read('/etc/osreporter.yaml') self.username = os.getenv("OS_USERNAME", default=config['credentials']['username']) self.password = os.getenv("OS_PASSWORD", default=config['credentials']['password']) self.tenant = os.getenv("OS_TENANT_NAME", default=config['credentials']['project']) self.url = os.getenv("OS_AUTH_URL", default=config['credentials']['uri'])
python
11
0.636364
91
66.714286
7
inline
func deliverLocal(addrInfo *resolver.AddressInfo, msgID string, header *message.Header) error { // Check the serverSignature if !message.VerifyServerHeader(*header) { logrus.Errorf("message %s destined for %s has failed the server signature check. Seems that this message did not originate from the original mail server. Removing the message.", msgID, header.To.Addr) err := message.RemoveMessage(message.SectionProcessing, msgID) if err != nil { // @TODO: we should notify somebody? logrus.Warnf("cannot remove message %s from the process queue.", msgID) } return nil } // Check the clientSignature if !message.VerifyClientHeader(*header) { logrus.Errorf("message %s destined for %s has failed the client signature check. Seems that this message may have been spoofed. Removing the message.", msgID, header.To.Addr) err := message.RemoveMessage(message.SectionProcessing, msgID) if err != nil { // @TODO: we should notify somebody? logrus.Warnf("cannot remove message %s from the process queue.", msgID) } return nil } // Deliver mail to local user inbox h, err := hash.NewFromHash(addrInfo.Hash) if err != nil { return err } // Add message ar := container.Instance.GetAccountRepo() err = ar.CreateMessage(*h, msgID) if err != nil { return err } // Move to inbox err = ar.AddToBox(*h, account.BoxInbox, msgID) if err != nil { return err } _ = dispatcher.DispatchLocalDelivery(*h, header, msgID) return nil }
go
11
0.716994
202
28.56
50
inline
import get from 'lodash/get'; angular.module('App').controller( 'DomainLockDisableCtrl', class DomainLockDisableCtrl { constructor($scope, $rootScope, $translate, Alerter, Domain) { this.$scope = $scope; this.$rootScope = $rootScope; this.$translate = $translate; this.Alerter = Alerter; this.Domain = Domain; } $onInit() { this.domain = angular.copy(this.$scope.currentActionData); this.$scope.resetSwitchAndAction = () => this.resetSwitchAndAction(); this.$scope.unlockDomain = () => this.unlockDomain(); } resetSwitchAndAction() { this.$rootScope.$broadcast('domain.protection.unlock.cancel'); this.$scope.resetAction(); } unlockDomain() { return this.Domain.changeLockState(this.domain.name, 'unlocked') .then((data) => { this.$rootScope.$broadcast('domain.protection.unlock.done', data); this.Alerter.success( this.$translate.instant( 'domain_configuration_protection_desactivate_success', ), this.$scope.alerts.main, ); }) .catch((err) => { this.$rootScope.$broadcast('domain.protection.unlock.error', err); this.Alerter.alertFromSWS( this.$translate.instant( 'domain_configuration_protection_desactivate_fail', ), get(err, 'data', err), this.$scope.alerts.main, ); }) .finally(() => { this.$scope.resetAction(); }); } }, );
javascript
17
0.591018
100
31.115385
52
starcoderdata
bool VerifyKeyMatchesAssembly(PublicKeyBlob * pAssemblySignaturePublicKey, __in_z LPCWSTR wszKeyContainer, BYTE *pbKeyBlob, ULONG cbKeyBlob, DWORD dwFlags) { _ASSERTE(wszKeyContainer != NULL || pbKeyBlob != NULL); // If we're test signing, then the assembly's public key will not match the private key by design. // Since there's nothing to check, we can quit early. if ((dwFlags & SN_TEST_SIGN) == SN_TEST_SIGN) { return true; } if (SN_IS_NEUTRAL_KEY(pAssemblySignaturePublicKey)) { // If we're ECMA signing an assembly with the ECMA public key, then by definition the key matches. if ((dwFlags & SN_ECMA_SIGN) == SN_ECMA_SIGN) { return true; } // Swap the real public key in for ECMA signing pAssemblySignaturePublicKey = SN_THE_KEY(); } // Otherwise, we need to check that the public key from the key container matches the public key from // the assembly. StrongNameBufferHolder<BYTE> pbSignaturePublicKey = NULL; DWORD cbSignaturePublicKey; if (!StrongNameGetPublicKeyEx(wszKeyContainer, pbKeyBlob, cbKeyBlob, &pbSignaturePublicKey, &cbSignaturePublicKey, GET_UNALIGNED_VAL32(&pAssemblySignaturePublicKey->HashAlgID), 0 /*Should be GET_UNALIGNED_VAL32(&pAssemblySignaturePublicKey->HashAlgID) once we support different signature algorithms*/)) { // We failed to get the public key for the key in the given key container. StrongNameGetPublicKey // has already set the error information, so we can just return false here without resetting it. return false; } _ASSERTE(!pbSignaturePublicKey.IsNull() && pAssemblySignaturePublicKey != NULL); // Do a raw compare on the public key blobs to see if they match if (SN_SIZEOF_KEY(reinterpret_cast<PublicKeyBlob *>(pbSignaturePublicKey.GetValue())) == SN_SIZEOF_KEY(pAssemblySignaturePublicKey) && memcmp(static_cast<void *>(pAssemblySignaturePublicKey), static_cast<void *>(pbSignaturePublicKey.GetValue()), cbSignaturePublicKey) == 0) { return true; } SetStrongNameErrorInfo(SN_E_PUBLICKEY_MISMATCH); return false; }
c++
14
0.695909
306
45.829787
47
inline
// Copyright (c) 2016 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache License, Version 2.0 (the "License"). // You may not use this product except in compliance with the License. // // This product may include a number of subcomponents with separate copyright notices and // license terms. Your use of these subcomponents is subject to the terms and conditions // of the subcomponent's license, as noted in the LICENSE file. package command import ( "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "fmt" "log" "math/big" "net" "net/http" "net/http/httptest" "net/url" "testing" "time" cf "github.com/vmware/photon-controller-cli/photon/configuration" ) //Generates a self signed test root cert for the test server func genTestRootCert() (cert_b, priv_b []byte) { //Generate a short lived cert //valid for 1 day to be used with server hosted ca := &x509.Certificate{ SerialNumber: big.NewInt(1653), Subject: pkix.Name{ Country: []string{"Test"}, Organization: []string{"Test"}, OrganizationalUnit: []string{"Test"}, }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(0, 0, 1), SubjectKeyId: []byte{1, 2, 3, 4, 5}, BasicConstraintsValid: true, IsCA: true, DNSNames: []string{"localhost"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, } priv, _ := rsa.GenerateKey(rand.Reader, 1024) pub := &priv.PublicKey ca_b, err := x509.CreateCertificate(rand.Reader, ca, ca, pub, priv) if err != nil { log.Println("create ca failed", err) return } priv_b = x509.MarshalPKCS1PrivateKey(priv) return ca_b, priv_b } func TestServerTrustUtils(t *testing.T) { //Launch Test Server cert_b, priv_b := genTestRootCert() //Certificate for the TLS connectiona and private key are the args cert, _ := x509.ParseCertificate(cert_b) priv, _ := x509.ParsePKCS1PrivateKey(priv_b) pool := x509.NewCertPool() pool.AddCert(cert) tls_cert := tls.Certificate{ Certificate: [][]byte{cert_b}, PrivateKey: priv, } config := tls.Config{ ClientAuth: tls.NoClientCert, Certificates: []tls.Certificate{tls_cert}, } //Launch a server with TLS end point ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, client") })) defer ts.Close() ts.TLS = &config ts.StartTLS() //At this point the appropriate test root cert doesn't exist //Test the case when we dont have root cert for the server u, err := url.Parse(ts.URL) if err != nil { t.Error("Failed to parse URL") return } bServerTrusted, err := isServerTrusted(u.Host) if err != nil || bServerTrusted == true { fmt.Println(err) t.Error("Failed to check server trust") return } //Get the remote server's root cert and add it to our trust list cert, err = getServerCert(u.Host) if err != nil { t.Error("Failed to get server cert") return } err = cf.AddCertToLocalStore(cert) if err != nil { t.Error("Failed to Add server cert to local store") return } //At this point we should have added the root cert of the remote server //trust should be established already bServerTrusted, err = isServerTrusted(u.Host) if err != nil || bServerTrusted == false { t.Error("Failed to check server trust") } err = cf.RemoveCertFromLocalStore(cert) if err != nil { t.Error("Failed to Add server cert to local store") } }
go
18
0.688638
98
26.263158
133
starcoderdata
public override void Simulate(float timeStep) { int updatedEntityCount; IntPtr updatedEntitiesPtr; int collidersCount; IntPtr collidersPtr; // prevent simulation until we've been initialized if (!m_initialized) return; // update the prim states while we know the physics engine is not busy ProcessTaints(); // Some of the prims operate with special vehicle properties ProcessVehicles(timeStep); ProcessTaints(); // the vehicles might have added taints // step the physical world one interval m_simulationStep++; int numSubSteps = BulletSimAPI.PhysicsStep(m_worldID, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out updatedEntitiesPtr, out collidersCount, out collidersPtr); // Don't have to use the pointers passed back since we know it is the same pinned memory we passed in // Get a value for 'now' so all the collision and update routines don't have to get their own m_simulationNowTime = Util.EnvironmentTickCount(); List<PhysicsActor> _colliders = new List<PhysicsActor>(); // If there were collisions, process them by sending the event to the prim. // Collisions must be processed before updates. if (collidersCount > 0 && !DisableCollisions) { for (int ii = 0; ii < collidersCount; ii++) { uint cA = m_collisionArray[ii].aID; uint cB = m_collisionArray[ii].bID; Vector3 point = m_collisionArray[ii].point; Vector3 normal = m_collisionArray[ii].normal; PhysicsActor c1, c2; SendCollision(cA, cB, point, normal, 0.01f, out c1); SendCollision(cB, cA, point, -normal, 0.01f, out c2); _colliders.Add(c1); _colliders.Add(c2); } //Send out all the collisions now #if (!ISWIN) foreach (PhysicsActor colID in _colliders) { if (colID != null) { colID.SendCollisions(); } } #else foreach (PhysicsActor colID in _colliders.Where(colID => colID != null)) { colID.SendCollisions(); } #endif } if (updatedEntityCount > 0) lock (m_entProperties) m_entProperties.AddRange(m_updateArray); }
c#
16
0.505061
113
42.107692
65
inline
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Sortingtime.ApiModels { public class ReportAndContentApi { public long? RelatedId { get; set; } [Required] [StringLength(400, ErrorMessage = "The {0} field must be a maximum length of {1} characters.")] public string ToEmail { get; set; } [NotMapped] public string FromFullName { get; set; } [NotMapped] public string FromEmail { get; set; } [Required] [StringLength(200, ErrorMessage = "The {0} field must be a maximum length of {1} characters.")] public string EmailSubject { get; set; } [StringLength(4000, ErrorMessage = "The {0} field must be a maximum length of {1} characters.")] public string EmailBody { get; set; } public bool showGroupColl { get; set; } [StringLength(200, ErrorMessage = "The {0} field must be a maximum length of {1} characters.")] public string ReportTitle { get; set; } [StringLength(400, ErrorMessage = "The {0} field must be a maximum length of {1} characters.")] public string ReportSubTitle { get; set; } [StringLength(4000, ErrorMessage = "The {0} field must be a maximum length of {1} characters.")] public string ReportText { get; set; } [Required] public ReportApi Report { get; set; } } }
c#
11
0.632302
104
33.642857
42
starcoderdata
import json import sys import os from collections import OrderedDict from warcio.archiveiterator import ArchiveIterator from warcio.utils import open_or_default # ============================================================================ class Indexer(object): field_names = {} def __init__(self, fields, inputs, output): if isinstance(fields, str): fields = fields.split(',') self.fields = fields self.record_parse = any(field.startswith('http:') for field in self.fields) self.inputs = inputs self.output = output def process_all(self): with open_or_default(self.output, 'wt', sys.stdout) as out: for filename in self.inputs: try: stdin = sys.stdin.buffer except AttributeError: # py2 stdin = sys.stdin with open_or_default(filename, 'rb', stdin) as fh: self.process_one(fh, out, filename) def process_one(self, input_, output, filename): it = self._create_record_iter(input_) self._write_header(output, filename) for record in it: self.process_index_entry(it, record, filename, output) def process_index_entry(self, it, record, filename, output): index = self._new_dict(record) for field in self.fields: value = self.get_field(record, field, it, filename) if value is not None: field = self.field_names.get(field, field) index[field] = value self._write_line(output, index, record, filename) def _create_record_iter(self, input_): return ArchiveIterator(input_, no_record_parse=not self.record_parse, arc2warc=True) def _new_dict(self, record): return OrderedDict() def get_field(self, record, name, it, filename): value = None if name == 'offset': value = str(it.get_record_offset()) elif name == 'length': value = str(it.get_record_length()) elif name == 'filename': value = os.path.basename(filename) elif name == 'http:status': if record.rec_type in ('response', 'revisit') and record.http_headers: value = record.http_headers.get_statuscode() elif name.startswith('http:'): if record.http_headers: value = record.http_headers.get_header(name[5:]) else: value = record.rec_headers.get_header(name) return value def _write_header(self, out, filename): pass def _write_line(self, out, index, record, filename): out.write(json.dumps(index) + '\n')
python
16
0.554955
83
30.896552
87
starcoderdata
import App from "../app"; import { gql, withFilter } from "apollo-server-express"; import { pubsub } from "../helpers/subscriptionManager"; const mutationHelper = require("../helpers/mutationHelper").default; // We define a schema that encompasses all of the types // necessary for the functionality in this file. const schema = gql` type StationSet { id: ID name: String simulator: Simulator crewCount: Int stations: [Station] } type Station { name: String description: String training: String login: Boolean executive: Boolean messageGroups: [String] layout: String widgets: [String] cards(showHidden: Boolean): [Card] } type Card { name: String component: String hidden: Boolean } extend type Simulator { stationSets: [StationSet] stationSet: StationSet } extend type Query { stations: [StationSet] station(simulatorId: ID!, station: String!): Station } extend type Mutation { createStationSet(name: String!, simulatorId: ID!): String removeStationSet(stationSetID: ID!): String renameStationSet(stationSetID: ID!, name: String!): String setStationSetCrewCount(stationSetID: ID!, crewCount: Int!): String addStationToStationSet(stationSetID: ID!, stationName: String!): String removeStationFromStationSet(stationSetID: ID!, stationName: String!): String editStationInStationSet( stationSetID: ID! stationName: String! newStationName: String! ): String addCardToStation( stationSetID: ID! stationName: String! cardName: String! cardComponent: String! cardIcon: String ): String removeCardFromStation( stationSetID: ID! stationName: String! cardName: String! ): String editCardInStationSet( stationSetID: ID! stationName: String! cardName: String! newCardName: String cardComponent: String cardIcon: String ): String setStationLogin( stationSetID: ID! stationName: String! login: Boolean! ): String setStationLayout( stationSetID: ID! stationName: String! layout: String! ): String setStationExecutive( stationSetID: ID! stationName: String! exec: Boolean! ): String toggleStationWidgets( stationSetID: ID! stationName: String! widget: String! state: Boolean! ): String setStationDescription( stationSetID: ID! stationName: String! description: String! ): String setStationTraining( stationSetID: ID! stationName: String! training: String ): String reorderStationWidgets( stationSetId: ID! stationName: String! widget: String! order: Int! ): String } extend type Subscription { stationSetUpdate: [StationSet] } `; const resolver = { StationSet: { simulator(rootValue) { return App.simulators.find(s => s.id === rootValue.simulatorId); } }, Station: { cards(station, { showHidden }) { if (showHidden) return station.cards; return station.cards.filter(c => !c.hidden); } }, Query: { station: (root, { simulatorId, station }) => { const sim = App.simulators.find(s => s.id === simulatorId); if (!sim) return null; const { stations } = sim; if (!stations) return null; return stations.find(s => s.name === station); }, stations() { return App.stationSets; } }, Mutation: mutationHelper(schema), Subscription: { stationSetUpdate: { resolve(rootValue) { return rootValue; }, subscribe: () => pubsub.asyncIterator("stationSetUpdate") } } }; export default { schema, resolver };
javascript
16
0.638118
80
23.888158
152
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Task; use App\Todolist; class TasksController extends Controller { /* ==================================== API functionality goes under here ==================================== */ public function get($id) { $user = \Auth::user(); $task = Task::find($id); $list = Todolist::find($task->list_id); if ($task != null) { if ($user->id != $list->user_id) { return response('Unauthorized', 401); } return response()->json([ 'id' => $task->id, 'list_id'=> $task->list_id, 'description' => $task->description, 'position' => $task->position, 'state' => $task->state, 'comment' => $task->comment, 'color' => $task->color, 'created_at' => $task->created_at, 'updated_at' => $task->updated_at ]); } else { return response('Not found', 404); } } /** * Store the task * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function post(Request $request) { $this->validate($request, Task::$create_validation_rules); $data = $request->only('list_id', 'description', 'position'); $user = \Auth::user(); $list = Todolist::find($data['list_id']); if ($user->id != $list->user_id) { return response('Unauthorized', 401); } $task = Task::create($data); if($task){ return response()->json([ 'id' => $task->id, 'list_id'=> $task->list_id, 'description' => $task->description, 'position' => $task->position, 'state' => $task->state, 'comment' => $task->comment, 'color' => $task->color, 'created_at' => $task->created_at, 'updated_at' => $task->updated_at ]); } return response('Error', 500); } /*Update the task*/ public function update(Request $request) { $task = Task::find($request->id); $data = $request->only('description', 'position', 'state'); $user = \Auth::user(); $list = Todolist::find($task->list_id); if ($task != null) { if ($user->id != $list->user_id) { return response('Unauthorized', 401); } if($data['description'] != ""){ $task->description = $data['description']; } if($data['position'] != ""){ $task->position = $data['position']; } if($data['state'] != ""){ $task->state = $data['state']; } if($task->save()){ return response()->json([ 'id' => $task->id, 'list_id'=> $task->list_id, 'description' => $task->description, 'position' => $task->position, 'state' => $task->state, 'comment' => $task->comment, 'color' => $task->color, 'created_at' => $task->created_at, 'updated_at' => $task->updated_at ]); } else{ return response('Error', 500); } } else { return response('Not found', 404); } } /* ==================================== Web App functionality goes under here ==================================== */ }
php
17
0.487342
67
24.523077
130
starcoderdata
package com.jishukezhan.core.lang; import java.util.HashSet; import java.util.List; import java.util.Set; /** * 布尔 * @author miles.tang */ public class BooleanEvaluator { private final Set trueFactors = new HashSet<>(); private final Set falseFactors = new HashSet<>(); /** * 当比对的对象为空时返回{@code false} */ private boolean nullValue = false; /** * 比对的字符串是否忽略大小写 */ private boolean stringIgnoreCase = true; public BooleanEvaluator(boolean nullValue, boolean stringIgnoreCase, Object[] trueFactors, Object[] falseFactors) { this(nullValue, stringIgnoreCase, CollectionUtil.newArrayList(trueFactors), CollectionUtil.newArrayList(falseFactors)); } public BooleanEvaluator(boolean nullValue, boolean stringIgnoreCase, List trueFactors, List falseFactors) { setNullValue(nullValue); setStringIgnoreCase(stringIgnoreCase); addTrueFactors(trueFactors); addFalseFactors(falseFactors); } public boolean isNullValue() { return nullValue; } public void setNullValue(boolean nullValue) { this.nullValue = nullValue; } public boolean isStringIgnoreCase() { return stringIgnoreCase; } public void setStringIgnoreCase(boolean stringIgnoreCase) { this.stringIgnoreCase = stringIgnoreCase; } public void addTrueFactors(List trueFactors) { if (CollectionUtil.isNotEmpty(trueFactors)) { for (Object object : trueFactors) { addTrueFactor(object); } } } public void addFalseFactors(List falseFactors) { if (CollectionUtil.isNotEmpty(falseFactors)) { for (Object object : falseFactors) { addFalseFactor(object); } } } public void addTrueFactor(Object trueFactor) { if (trueFactor != null) { if (trueFactor instanceof String) { trueFactors.add(stringIgnoreCase ? ((String) trueFactor).toLowerCase() : trueFactor); } trueFactors.add(trueFactor); } } public void addFalseFactor(Object falseFactor) { if (falseFactor != null) { if (falseFactor instanceof String) { falseFactors.add(stringIgnoreCase ? ((String) falseFactor).toLowerCase() : falseFactor); return; } falseFactors.add(falseFactor); } } public void addFactor(Object trueFactor, Object falseFactor) { addTrueFactor(trueFactor); addFalseFactor(falseFactor); } public boolean evalTrue(Object object) { if (object == null) { return nullValue; } if (object instanceof String && stringIgnoreCase) { object = ((String) object).toLowerCase(); } if (trueFactors.contains(object)) { return true; } if (falseFactors.contains(object)) { return false; } return !nullValue; } public boolean evalFalse(Object object) { if (object == null) { return nullValue; } if (object instanceof String && stringIgnoreCase) { object = ((String) object).toLowerCase(); } if (falseFactors.contains(object)) { return true; } if (trueFactors.contains(object)) { return false; } return nullValue; } public static BooleanEvaluator createFalseEvaluator(boolean nullValue, boolean stringIgnoreCase, Object[] falseArray) { return new BooleanEvaluator(nullValue, stringIgnoreCase, null, falseArray); } public static BooleanEvaluator createFalseEvaluator(Object... falseArray) { return new BooleanEvaluator(false, true, null, falseArray); } public static BooleanEvaluator createTrueEvaluator(Object... truthArray) { return new BooleanEvaluator(false, true, truthArray, null); } public static BooleanEvaluator createTrueEvaluator(boolean nullValue, boolean stringIgnoreCase, Object[] truthArray) { return new BooleanEvaluator(nullValue, stringIgnoreCase, truthArray, null); } }
java
16
0.630588
127
28.929577
142
starcoderdata
// // Stop.cpp // transportnyi-spravochnik // // Created by on 02.07.2020. // Copyright © 2020 All rights reserved. // #include "Stop.hpp" namespace guide::route { Stop::Stop(std::string name, const GeoPoint& geoPoint) : name_(std::move(name)) , geoPoint_(geoPoint) , completion_(Stop::Completion::Complete) {} Stop::Stop(std::string name) : name_(std::move(name)) , completion_(Stop::Completion::Nocoord) {} void Stop::SetGeoPoint(const GeoPoint& geoPoint) { this->geoPoint_ = geoPoint; this->completion_ = Stop::Completion::Complete; } bool Stop::AddCrossingRoute(std::weak_ptr route) { crossingRoutes_.push_back(route); return true; } bool Stop::AddNeighborStopsDistance(std::weak_ptr stop, size_t distance) { auto [_, ok] = neighborStopsDistances_.insert({ stop, distance }); return ok; } bool Stop::UpdateNeighborStopsDistance(std::weak_ptr stop, size_t distance) { if (auto stopPtr = neighborStopsDistances_.find(stop); stopPtr != neighborStopsDistances_.end()) { stopPtr->second = distance; return true; } return false; } std::optional Stop::FindNeighborStopDistance(std::shared_ptr stop) const { if (auto stopPtr = neighborStopsDistances_.find(stop); stopPtr != neighborStopsDistances_.end()) { return stopPtr->second; } return std::nullopt; } const std::string& Stop::GetName() const { return name_; } std::optional Stop::GetGeoPoint() const { return geoPoint_; } const std::vector Stop::GetCrossingRoutes() const { return crossingRoutes_; } const std::map size_t, Stop::WeakComparator>& Stop::GetNeighborStopsDistances() const { return neighborStopsDistances_; } bool Stop::IsComplete() const { return this->completion_ == Stop::Completion::Complete; } bool Stop::operator==(const Stop& rhs) const { return this->name_ == rhs.GetName(); } bool Stop::operator<(const Stop& rhs) const { return std::lexicographical_compare( this->GetName().cbegin(), this->GetName().cend(), rhs.GetName().cbegin(), rhs.GetName().cend()); } std::ostream& operator<<(std::ostream& os, const Stop& stop) { os << std::string{ "`Stop`(" } << stop.GetName(); if (auto geoPointOpt = stop.GetGeoPoint(); geoPointOpt.has_value()) { os << std::string{ ", " } << std::to_string(geoPointOpt.value().GetLatitude()); os << std::string{ ", " } << std::to_string(geoPointOpt.value().GetLongitude()); } os << std::string{ ")" }; return os; } }
c++
15
0.65219
106
22.863636
110
starcoderdata
@Test public void testScheduledRemovalOfEmbargoAndCheckAccessibilityWithDifferentUsers() throws Exception { //testing creating a document with the editor user. final Node editorFolderNode = editor.getNode(TestConstants.CONTENT_DOCUMENTS_EMBARGODEMO_PATH); final FolderWorkflow editorFolderWorkflow = (FolderWorkflow) getWorkflow(editorFolderNode, "internal"); final String editorDocumentLocation = editorFolderWorkflow.add("new-document", "embargotest:document", TestConstants.TEST_DOCUMENT_NAME); assertTrue(editor.itemExists(editorDocumentLocation)); final EmbargoWorkflow embargoEditorsEmbargoWorkflow = (EmbargoWorkflow) getWorkflow(embargoEditor.getNode(editorDocumentLocation), "embargo"); final String subjectId = editor.getNode(editorDocumentLocation).getIdentifier(); embargoEditorsEmbargoWorkflow.addEmbargo(embargoEditor.getUserID(), subjectId,null); assertTrue(embargoEditor.itemExists(editorDocumentLocation)); assertFalse(editor.itemExists(editorDocumentLocation)); //creating a calendar object which removes embargo 10 seconds in the future final Calendar scheduledTime = Calendar.getInstance(); scheduledTime.add(Calendar.SECOND, 2); embargoEditorsEmbargoWorkflow.scheduleRemoveEmbargo(subjectId, scheduledTime); assertFalse(editor.itemExists(editorDocumentLocation)); //wait 3 seconds just to be sure Thread.sleep(3000); assertTrue(embargoEditor.itemExists(editorDocumentLocation)); assertTrue(editor.itemExists(editorDocumentLocation)); }
java
10
0.763838
150
49.84375
32
inline
using Microsoft.CodeAnalysis.FindSymbols; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis { public static class INamedTypeSymbolExtensions { public static async Task DetermineMethodNameUsedToNotifyThatPropertyWasChanged(this INamedTypeSymbol typeSymbol, Solution solution) { String result = "OnPropertyChanged"; var typesInInheritanceHierarchy = new List var currentType = typeSymbol; while ((currentType != null) && (!currentType.ContainingNamespace?.ToString().StartsWith("System.") == true)) { typesInInheritanceHierarchy.Add(currentType); currentType = currentType.BaseType; } foreach (INamedTypeSymbol type in typesInInheritanceHierarchy) { var methodSymbols = type.GetMembers().Where(x => !x.IsImplicitlyDeclared).OfType => x.MethodKind == MethodKind.Ordinary); foreach (ISymbol methodSymbol in methodSymbols) { foreach (var syntaxReference in methodSymbol.DeclaringSyntaxReferences) { var methodNode = await syntaxReference.GetSyntaxAsync().ConfigureAwait(false) as MethodDeclarationSyntax; var invocations = methodNode.DescendantNodes().OfType foreach (InvocationExpressionSyntax invocation in invocations) { if (invocation.Expression is IdentifierNameSyntax idSyntaxt) { if (idSyntaxt.Identifier.ValueText == "PropertyChanged") { result = methodSymbol.Name; return result; } } } } } } /* Old slower implementation foreach (INamedTypeSymbol interfaceSymbol in typeSymbol.AllInterfaces) { if (interfaceSymbol.Name == "INotifyPropertyChanged" && String.Equals(interfaceSymbol?.ContainingNamespace?.ToString(), "System.ComponentModel")) { ISymbol propertyChangedEventSymbol = interfaceSymbol.GetMembers("PropertyChanged").First(); foreach (Location location in type.Locations) { if (location.SourceTree != null) { var document = solution.GetDocument(location.SourceTree); var setOfDocuments = ImmutableHashSet.Create( document); IEnumerable callers = await SymbolFinder.FindCallersAsync(propertyChangedEventSymbol, solution, setOfDocuments).ConfigureAwait(false); foreach (SymbolCallerInfo caller in callers) { if ((caller.CallingSymbol is IMethodSymbol methodSymbol) && (methodSymbol.MethodKind == MethodKind.Ordinary)) { result = caller.CallingSymbol.Name; } } } } } } */ return result; } public static char? DetermineBackingFiledPrefix(this INamedTypeSymbol typeSymbol) { char? result = null; IEnumerable backingFileds = typeSymbol.GetMembers().Where(x => x.Kind == SymbolKind.Field).Where(x => x.IsImplicitlyDeclared == false); if (backingFileds.Any()) { if (backingFileds.First().Name?.HasPrefix() == true) { char candidateForPrefix = backingFileds.First().Name[0]; if (backingFileds.All(x => x.Name[0] == candidateForPrefix)) { result = candidateForPrefix; } } } return result; } } }
c#
23
0.505665
186
45.72549
102
starcoderdata
# _*_ coding:utf-8 _*_ import asyncio import discord import logging import os import random import time from cleverbot import Cleverbot logging.basicConfig(level=logging.INFO) client = discord.Client() cb = Cleverbot() @client.async_event def on_message(message): if message.content.startswith('#GO'): yield from client.change_status(discord.Game(name=random.choice(["dibou","rtichau","Broutter","la claire fontaine","bricot","rien"]))) return if message.author == client.user: return if not message.author.id == ' return yield from client.send_typing(message.channel) O = cb.ask(message.content) time.sleep(2) print (O) yield from client.send_message(message.channel,O.format(message)) print ('CleverBot2 Pret!!') client.run('mail','mdp')
python
17
0.616468
150
24.371429
35
starcoderdata
using System; namespace Codestellation.Pulsar.FluentApi { /// /// Contains few extension methods and properties to support fluent api /// public static class Repeat { /// /// Timespan that equals to a minute /// public static readonly TimeSpan Minutely = TimeSpan.FromMinutes(1); /// /// Timespan that equals to a hour /// public static readonly TimeSpan Hour = TimeSpan.FromHours(1); /// /// Timespan that equals to a day /// public static readonly TimeSpan Daily = TimeSpan.FromDays(1); /// /// Timespan that equals to a second /// public static readonly TimeSpan EverySecond = TimeSpan.FromSeconds(1); /// /// /// /// <param name="timeSpan"> /// public static TimeSpan Every(TimeSpan timeSpan) { if (timeSpan <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException(nameof(timeSpan), "Should be greater than TimeSpan.Zero"); } return timeSpan; } } }
c#
16
0.569185
112
28.733333
45
starcoderdata
import os import pandas from nonbonded.library.models.authors import Author from nonbonded.library.models.datasets import DataSet from nonbonded.library.utilities.environments import ChemicalEnvironment from openff.evaluator.datasets.curation.components import ( conversion, filtering, selection, thermoml, ) from openff.evaluator.datasets.curation.components.selection import State, TargetState from openff.evaluator.datasets.curation.workflow import ( CurationWorkflow, CurationWorkflowSchema, ) AUTHORS = [ Author( name=" email=" institute="University of Colorado Boulder", ), ] N_PROCESSES = 4 def main(): if os.path.isfile("thermoml.csv"): thermoml_data_frame = pandas.read_csv("thermoml.csv") else: thermoml_data_frame = thermoml.ImportThermoMLData.apply( pandas.DataFrame(), thermoml.ImportThermoMLDataSchema(), N_PROCESSES ) thermoml_data_frame.to_csv("thermoml.csv", index=False) curation_schema = CurationWorkflowSchema( component_schemas=[ # Filter out any measurements made for systems with more than # two components filtering.FilterByNComponentsSchema(n_components=[1, 2]), # Remove any duplicate data. filtering.FilterDuplicatesSchema( temperature_precision=1, pressure_precision=0 ), # Filter out data points measured away from ambient conditions. filtering.FilterByTemperatureSchema( minimum_temperature=298.0, maximum_temperature=320.0 ), filtering.FilterByPressureSchema( minimum_pressure=100.0, maximum_pressure=101.4 ), # Retain only density and enthalpy of mixing data points which # have been measured for the same systems. filtering.FilterByPropertyTypesSchema( property_types=[ "Density", "EnthalpyOfMixing", ], n_components={ "Density": [1, 2], "EnthalpyOfMixing": [2], }, strict=True, ), # Convert density data to excess molar volume where possible. conversion.ConvertExcessDensityDataSchema(), filtering.FilterDuplicatesSchema(), # Apply the property filter again to retain only those systems # which have data points for all the properties of interest. filtering.FilterByPropertyTypesSchema( property_types=[ "Density", "EnthalpyOfMixing", "ExcessMolarVolume", ], n_components={ "Density": [2], "EnthalpyOfMixing": [2], "ExcessMolarVolume": [2], }, strict=True, ), # Remove any substances measured for systems with undefined # stereochemistry filtering.FilterByStereochemistrySchema(), # Remove any measurements made for systems where any of the components # are charged. filtering.FilterByChargedSchema(), # Remove measurements made for ionic liquids filtering.FilterByIonicLiquidSchema(), # Remove any molecules containing elements other than C, O, N and H filtering.FilterByElementsSchema(allowed_elements=["C", "O", "N", "H"]), # Retain only measurements made for substances which contain environments # of interest. filtering.FilterByEnvironmentsSchema( environments=[ ChemicalEnvironment.Alcohol, ChemicalEnvironment.CarboxylicAcidEster, ChemicalEnvironment.CarboxylicAcid, ChemicalEnvironment.Amine, ChemicalEnvironment.CarboxylicAcidAmide, ChemicalEnvironment.Ether, ChemicalEnvironment.Nitrile, ChemicalEnvironment.Ketone, ChemicalEnvironment.Aldehyde, ] ), # # Attempt to select a reasonable number of diverse substances selection.SelectSubstancesSchema( target_environments=[ ChemicalEnvironment.Alcohol, ChemicalEnvironment.CarboxylicAcidEster, ChemicalEnvironment.CarboxylicAcid, ChemicalEnvironment.Amine, ChemicalEnvironment.CarboxylicAcidAmide, ChemicalEnvironment.Ether, ChemicalEnvironment.Nitrile, ChemicalEnvironment.Ketone, ChemicalEnvironment.Aldehyde, ], n_per_environment=5, per_property=False, ), # Select the data points for different compositions. selection.SelectDataPointsSchema( target_states=[ TargetState( property_types=[("Density", 1)], states=[ State( temperature=298.15, pressure=101.325, mole_fractions=(1.0,), ) ], ), TargetState( property_types=[ ("Density", 2), ("EnthalpyOfMixing", 2), ("ExcessMolarVolume", 2), ], states=[ State( temperature=298.15, pressure=101.325, mole_fractions=(0.25, 0.75), ), State( temperature=298.15, pressure=101.325, mole_fractions=(0.5, 0.5), ), State( temperature=298.15, pressure=101.325, mole_fractions=(0.75, 0.25), ), ], ), ] ), ] ) # Apply the curation schema to yield the test set. test_set_frame = CurationWorkflow.apply( thermoml_data_frame, curation_schema, N_PROCESSES ) test_set = DataSet.from_pandas( data_frame=test_set_frame, identifier="eval-bench-full", description="A data set composed of enthalpy of mixing, density, and " "excess molar volume data points designed with the aim of having a diverse " "data set which can be estimated using a minimum number of simulations." "\n\n" "In practice, this was attempted by selecting only data points for the " "same set of substance and measured at, where possible, the same set of " "state points. These factors combined should in principle lead to a data " "set where many of the contained data points can be estimated using the " "same simulation outputs." "\n\n" "Note in this data set, all temperatures (K) have been rounded to one " "decimal place, and all pressures (kPa) to zero decimal places." "\n\n" "This data set was originally curated as for the benchmarking component of " "the `openff-evaluator` project", authors=AUTHORS, ) test_set = test_set.upload() os.makedirs("../../schemas/data-sets", exist_ok=True) test_set.to_pandas().to_csv( os.path.join("../../schemas/data-sets", f"{test_set.id}.csv"), index=False ) test_set.to_file( os.path.join("../../schemas/data-sets", f"{test_set.id}.json") ) if __name__ == "__main__": main()
python
21
0.5251
86
38.552885
208
starcoderdata
import createRender from 'found/lib/createRender'; import getFarceResult from 'found/lib/server/getFarceResult'; import { graphql } from 'react-relay'; import { Resolver } from '../../src'; import { createEnvironment, createFakeFetch } from './helpers'; describe('refetch behavior', () => { let fetchSpy; let environment; beforeEach(() => { fetchSpy = jest.fn(createFakeFetch()); environment = createEnvironment(fetchSpy); }); it('should support redirecting based on query data', async () => { const routeConfig = [ { path: '/', query: graphql` query refetch_parent_Query { widget { name } } `, render: () => null, children: [ { path: ':name', query: graphql` query refetch_child_Query($name: String!) { widgetByArg(name: $name) { name } } `, render: () => null, }, ], }, ]; const resolver = new Resolver(environment); const render = createRender({}); expect(fetchSpy.mock.calls).toHaveLength(0); await getFarceResult({ url: '/foo', routeConfig, resolver, render }); expect(fetchSpy.mock.calls).toHaveLength(2); await getFarceResult({ url: '/bar', routeConfig, resolver, render }); expect(fetchSpy.mock.calls).toHaveLength(3); }); });
javascript
21
0.542662
73
24.258621
58
starcoderdata
/* * Copyright (c) 2010, Kajtar Zsolt <[email protected]>. * All rights reserved. * * 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 of the Institute 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 INSTITUTE 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 INSTITUTE 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. * * This file is part of the Contiki operating system. * * Author: Kajtar Zsolt <[email protected]> * */ #include <string.h> #include "cfs/cfs.h" #include "http-strings.h" #define ISO_number 0x23 #define ISO_percent 0x25 #define ISO_period 0x2e #define ISO_slash 0x2f #define ISO_question 0x3f static char wwwroot[40]; static unsigned char wwwrootlen; void urlconv_init(void) { int fd = cfs_open("wwwroot.cfg", CFS_READ); int rd = cfs_read(fd, wwwroot, sizeof(wwwroot)); cfs_close(fd); if(rd != -1) wwwrootlen = rd; } /*---------------------------------------------------------------------------*/ /* URL to filename conversion * * prepends wwwroot prefix * normalizes path by removing "/./" * interprets "/../" and calculates path accordingly * resulting path is always absolute * replaces "%AB" notation with characters * strips "#fragment" and "?query" from end * replaces multiple slashes with a single one * rejects non-ASCII characters * * MAXLEN is including trailing zero! * input and output is ASCII */ void urlconv_tofilename(char *dest, char *source, unsigned char maxlen) { static unsigned char len; static unsigned char c, hex1; static unsigned char *from, *to; *dest = ISO_slash; strncpy(dest + 1, wwwroot, wwwrootlen); len = 0; from = (unsigned char *)source; to = (unsigned char *)dest + wwwrootlen; maxlen -= 2 + wwwrootlen; do { c = *(from++); switch(c) { case ISO_number: case ISO_question: c = 0; break; case ISO_percent: c = 0; hex1 = (*(from++) | 0x20) ^ 0x30; // ascii only! if(hex1 > 0x50 && hex1 < 0x57) hex1 -= 0x47; else if(hex1 > 9) break; // invalid hex c = (*(from++) | 0x20) ^ 0x30; // ascii only! if(c > 0x50 && c < 0x57) c -= 0x47; else if(c > 9) break; // invalid hex c |= hex1 << 4; } if(c < 0x20 || c > 0x7e) c = 0; // non ascii?! if(len >= maxlen) c = 0; // too long? if(c == ISO_slash || !c) { switch(*to) { case ISO_slash: continue; // no repeated slash case ISO_period: switch(to[-1]) { case ISO_slash: // handle "./" --to; --len; continue; case ISO_period: if(to[-2] == ISO_slash) { to -= 2; len -= 2; if(len) { do { --to; --len; } while(*to != ISO_slash); } continue; } } } } if(c) { ++to; ++len; *to = c; } } while(c); if(*to == ISO_slash && (len + sizeof(http_index_htm) - 3) < maxlen) { strcpy((char *)to, http_index_htm); // add index.htm } else { ++to; *to = 0; } } /*---------------------------------------------------------------------------*/
c
21
0.597166
79
29.040541
148
research_code
package com.wanxp.dao; import com.wanxp.model.Tmeta; /** * Meta数据库操作类 * * @author John * */ public interface MetaDaoI extends BaseDaoI { }
java
6
0.706731
51
13.857143
14
starcoderdata
#region COPYRIGHT© 2009-2012 All rights reserved. // For licensing information see License.txt (MIT style licensing). #endregion using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using FlitBit.Core; namespace FlitBit.Data.Meta { public struct SyntheticID : IEquatable { const int AsciiOffsetToDigitZero = 48; const int OffsetToLowerCaseA = 49; const int OffsetToLowerCaseG = 56; const int OffsetToUpperCaseA = 17; const int OffsetToUpperCaseG = 24; /// /// Empty synthetic ID. /// public static readonly SyntheticID Empty = new SyntheticID(); static readonly int CHashCodeSeed = typeof(SyntheticID).AssemblyQualifiedName.GetHashCode(); static readonly char[] HexDigits = "0123456789ABCDEF".ToCharArray(); readonly int _hashcode; readonly char[] _value; /// /// Creates a new instance. /// /// <param name="value">Value of the ID public SyntheticID(string value) { Contract.Requires != null); Contract.Requires > 0); _value = value.ToCharArray(); _hashcode = _value.CalculateCombinedHashcode(CHashCodeSeed); } /// /// Creates a new instance. /// /// <param name="value">Value of the ID public SyntheticID(char[] value) { Contract.Requires != null); Contract.Requires > 0); _value = new char[value.Length]; Array.Copy(value, _value, value.Length); _hashcode = _value.CalculateCombinedHashcode(CHashCodeSeed); } /// /// Indicates whether the ID is empty. /// public bool IsEmpty { get { return _hashcode == 0; } } /// /// Indicates whether the ID is valid. /// public bool IsValid { get { return IsValidID(_value); } } /// /// Determins if the ID is equal to another. /// /// <param name="obj">the other ID /// /// if this and the other are equal; otherwise /// public override bool Equals(object obj) { return obj is SyntheticID && Equals((SyntheticID) obj); } /// /// Gets the ID's hashcode. /// /// ID's hashcode public override int GetHashCode() { return _hashcode; } /// /// Gets the string representation of the ID. /// /// representation of the ID public override string ToString() { return (IsEmpty) ? String.Empty : new String(_value); } /// /// Compares two syntetic IDs for equality. /// /// <param name="lhs">left-hand operand /// <param name="rhs">right-hand operand /// if equal; otherwise public static bool operator ==(SyntheticID lhs, SyntheticID rhs) { return lhs.Equals(rhs); } /// /// Compares two syntetic IDs for inequality. /// /// <param name="lhs">left-hand operand /// <param name="rhs">right-hand operand /// if unequal; otherwise public static bool operator !=(SyntheticID lhs, SyntheticID rhs) { return !lhs.Equals(rhs); } #region IEquatable Members /// /// Determins if the ID is equal to another. /// /// <param name="other">the other ID /// /// if this and the other are equal; otherwise /// public bool Equals(SyntheticID other) { return _hashcode == other._hashcode && _value.EqualsOrItemsEqual(other._value); } #endregion /// /// Calculates a check digit for a string of hexidecimal characters. /// /// <param name="value">hex digits over which a check digit will be calculated /// check digit for the given value public static char CalculateCheckDigit(string value) { Contract.Requires != null); Contract.Requires > 0); return CalculateCheckDigit(value.ToCharArray()); } /// /// Calculates a check digit for an array of hexidecimal characters. /// /// <param name="value">hex digits over which a check digit will be calculated /// check digit for the given value public static char CalculateCheckDigit(char[] value) { Contract.Requires != null); Contract.Requires > 0); // Modified Luhn algorithm for base 16 check digit. -Pdc var len = value.Length - 1; var sum = 0; for (var i = 0; i <= len; i++) { var digit = (value[len - i] - AsciiOffsetToDigitZero); if (digit < 0) { throw new ArgumentException(); } if (digit < 10) { sum += (i % 2 == 0) ? (digit << 1) % 0xf : digit; } else if ((digit >= OffsetToUpperCaseA && digit < OffsetToUpperCaseG) || (digit >= OffsetToLowerCaseA && digit < OffsetToLowerCaseG)) { digit = 9 + (0x0F & digit); sum += (i % 2 == 0) ? (digit << 1) % 0xf : digit; } else { throw new ArgumentException(); } } return HexDigits[0xF - (sum % 0xF)]; } /// /// Determines if a value is a valid identity. /// /// <param name="value">the value /// /// if the value is formatted as a valid identity; otherwise /// public static bool IsValidID(string value) { return !string.IsNullOrEmpty(value) && IsValidID(value.ToCharArray()); } /// /// Determines if a value is a valid identity. /// /// <param name="value">the value /// /// if the value is formatted as a valid identity; otherwise /// public static bool IsValidID(char[] value) { if (value != null && value.Length != 0) { // Modified Luhn algorithm for base 16 check digit. -Pdc var len = value.Length - 1; var sum = 0; for (var i = 0; i <= len; i++) { var digit = (value[len - i] - AsciiOffsetToDigitZero); if (digit < 0) { return false; } if (digit < 10) { sum += (i % 2 == 1) ? (digit << 1) % 0xf : digit; } else if ((digit >= OffsetToUpperCaseA && digit < OffsetToUpperCaseG) || (digit >= OffsetToLowerCaseA && digit < OffsetToLowerCaseG)) { digit = 9 + (0x0F & digit); sum += (i % 2 == 1) ? (digit << 1) % 0xf : digit; } else { return false; // input contains a non-digit character } } return (sum % 0xF == 0); } return false; } } }
c#
18
0.633833
94
27.885714
245
starcoderdata
package com.fernandocejas.android10.sample.presentation.view; import com.fernandocejas.android10.sample.presentation.model.PhotoFolderModel; import java.util.List; /** * Created by an.tran on 8/16/2017. */ public interface PhotoFoldersView extends LoadDataView { void renderPhotoFolderList(List photoFolderList); }
java
8
0.8
78
22
15
starcoderdata
void OpenScenarioXmlExporter::FillLaneOffsetActionDynamicsNode(std::shared_ptr<tinyxml2::XMLDocument> document, tinyxml2::XMLNode* elementNode, std::shared_ptr<ILaneOffsetActionDynamicsWriter> laneOffsetActionDynamicsWriter) { // Add Attributes (Parameters) const auto kDynamicsShape = laneOffsetActionDynamicsWriter->GetDynamicsShape(); if (laneOffsetActionDynamicsWriter->IsDynamicsShapeParameterized()) { elementNode->ToElement()->SetAttribute(OSC_CONSTANTS::ATTRIBUTE__DYNAMICS_SHAPE.c_str(), laneOffsetActionDynamicsWriter->GetParameterFromDynamicsShape().c_str()); } else { elementNode->ToElement()->SetAttribute(OSC_CONSTANTS::ATTRIBUTE__DYNAMICS_SHAPE.c_str(), kDynamicsShape.GetLiteral().c_str()); } const auto kMaxLateralAcc = laneOffsetActionDynamicsWriter->GetMaxLateralAcc(); if (!( kMaxLateralAcc == 0)) { elementNode->ToElement()->SetAttribute(OSC_CONSTANTS::ATTRIBUTE__MAX_LATERAL_ACC.c_str(), XmlExportHelper::ToXmlStringFromDouble( kMaxLateralAcc).c_str()); } else if (laneOffsetActionDynamicsWriter->IsMaxLateralAccParameterized()) { elementNode->ToElement()->SetAttribute(OSC_CONSTANTS::ATTRIBUTE__MAX_LATERAL_ACC.c_str(), laneOffsetActionDynamicsWriter->GetParameterFromMaxLateralAcc().c_str()); } // Add Children (Normal, Wrapped, Unwrapped, simpleContent); }
c++
14
0.66817
224
66.521739
23
inline
public void testSingleValuedFieldDefaultSigma() throws Exception { // Same as previous test, but uses a default value for sigma SearchResponse searchResponse = client().prepareSearch("idx") .setQuery(matchAllQuery()) .addAggregation(extendedStats("stats").field("value")) .execute().actionGet(); assertHitCount(searchResponse, 10); ExtendedStats stats = searchResponse.getAggregations().get("stats"); assertThat(stats, notNullValue()); assertThat(stats.getName(), equalTo("stats")); assertThat(stats.getAvg(), equalTo((double) (1+2+3+4+5+6+7+8+9+10) / 10)); assertThat(stats.getMin(), equalTo(1.0)); assertThat(stats.getMax(), equalTo(10.0)); assertThat(stats.getSum(), equalTo((double) 1+2+3+4+5+6+7+8+9+10)); assertThat(stats.getCount(), equalTo(10L)); assertThat(stats.getSumOfSquares(), equalTo((double) 1+4+9+16+25+36+49+64+81+100)); assertThat(stats.getVariance(), equalTo(variance(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); assertThat(stats.getStdDeviation(), equalTo(stdDev(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))); checkUpperLowerBounds(stats, 2); }
java
20
0.624178
92
51.913043
23
inline
package com.baeldung.arrays; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class JavaArraysToStringUnitTest { @Test public void givenInstanceOfArray_whenTryingToConvertToString_thenNameOfClassIsShown() { Object[] arrayOfObjects = { "John", 2, true }; assertTrue(arrayOfObjects.toString().startsWith("[Ljava.lang.Object;")); } @Test public void givenInstanceOfArray_whenUsingArraysToStringToConvert_thenValueOfObjectsAreShown() { Object[] arrayOfObjects = { "John", 2, true }; assertEquals(Arrays.toString(arrayOfObjects), "[John, 2, true]"); } @Test public void givenInstanceOfDeepArray_whenUsingArraysDeepToStringToConvert_thenValueOfInnerObjectsAreShown() { Object[] innerArray = { "We", "Are", "Inside" }; Object[] arrayOfObjects = { "John", 2, innerArray }; assertEquals(Arrays.deepToString(arrayOfObjects), "[John, 2, [We, Are, Inside]]"); } @Test public void givenInstanceOfDeepArray_whenUsingStreamsToConvert_thenValueOfObjectsAreShown() { Object[] arrayOfObjects = { "John", 2, true }; List listOfString = Stream.of(arrayOfObjects) .map(Object::toString) .collect(Collectors.toList()); assertEquals(listOfString.toString(), "[John, 2, true]"); } }
java
11
0.700131
113
34.44186
43
starcoderdata
/* * index.js: Built-in plugins for forever-monitor. * * (C) 2010 & the Contributors * MIT LICENCE * */ exports.logger = require('./logger'); exports.watch = require('./watch');
javascript
3
0.641148
50
18.090909
11
starcoderdata
<?php namespace App; interface ForecastDataParser { public function getNumDiasPrevisao(); public function populateDadosPrevisao(); }
php
5
0.789855
41
12.9
10
starcoderdata
static PaError CloseStream( PaStream* s ) { PaError result = paNoError; PaSkeletonStream *stream = (PaSkeletonStream*)s; /* IMPLEMENT ME: - additional stream closing + cleanup */ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor ); PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); PaUtil_FreeMemory( stream ); return result; }
c
8
0.683698
74
24.75
16
inline
#include <cstdio> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <climits> #include <map> using namespace std; int main(void) { long long n,m; cin >>n >>m; map<long long, long long> mp; for(int i = 0; i < n; i++){ long long tmp; cin >>tmp; map<long long, long long>::iterator it = mp.find(tmp); if(it == mp.end()){ mp[tmp] = 0; } mp[tmp]++; } for(int i = 0; i < m; i++){ long long b,c; cin >>b >>c; map<long long , long long>::iterator it = mp.find(c); if(it == mp.end()){ mp[c] = 0; } mp[c] += b; } long long ans = 0; for(map<long long,long long>::reverse_iterator rit = mp.rbegin(); rit != mp.rend(); rit++){ if((*rit).second > n){ ans += (*rit).first * n; break; }else{ ans += (*rit).first * (*rit).second; n -= (*rit).second; if(n <= 0){ break; } } } printf("%lld\n", ans); return 0; }
c++
14
0.437163
95
20.037736
53
codenet
/*************************************************************************** lib/ibCmd.c ------------------- copyright : (C) 2001,2002,2003 by email : ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #include "ib_internal.h" #include #include #include #include #include int ibcmd(int ud, const void *cmd_buffer, long cnt) { ibConf_t *conf; ssize_t count; conf = enter_library( ud ); if( conf == NULL ) return exit_library( ud, 1 ); // check that ud is an interface board if( conf->is_interface == 0 ) { setIberr( EARG ); return exit_library( ud, 1 ); } count = my_ibcmd( conf, cmd_buffer, cnt); if(count < 0) { // report no listeners error XXX return exit_library( ud, 1); } if(count != cnt) { return exit_library( ud, 1 ); } return exit_library( ud, 0 ); } int ibcmda( int ud, const void *cmd_buffer, long cnt ) { ibConf_t *conf; ibBoard_t *board; int retval; conf = general_enter_library( ud, 1, 0 ); if( conf == NULL ) return general_exit_library( ud, 1, 0, 0, 0, 0, 1 ); // check that ud is an interface board if( conf->is_interface == 0 ) { setIberr( EARG ); return general_exit_library( ud, 1, 0, 0, 0, 0, 1 ); } board = interfaceBoard( conf ); if( is_cic( board ) == 0 ) { setIberr( ECIC ); return general_exit_library( ud, 1, 0, 0, 0, 0, 1 ); } retval = gpib_aio_launch( ud, conf, GPIB_AIO_COMMAND, (void*)cmd_buffer, cnt ); if( retval < 0 ) return general_exit_library( ud, 1, 0, 0, 0, 0, 1 ); return general_exit_library( ud, 0, 0, 0, 0, 0, 1 ); } ssize_t my_ibcmd( ibConf_t *conf, const uint8_t *buffer, size_t count) { read_write_ioctl_t cmd; int retval; ibBoard_t *board; board = interfaceBoard( conf ); if( is_cic( board ) == 0 ) { setIberr( ECIC ); return -1; } assert(sizeof(buffer) <= sizeof(cmd.buffer_ptr)); cmd.buffer_ptr = (uintptr_t)buffer; cmd.requested_transfer_count = count; cmd.completed_transfer_count = 0; cmd.handle = conf->handle; cmd.end = 0; set_timeout( board, conf->settings.usec_timeout); retval = ioctl( board->fileno, IBCMD, &cmd ); if( retval < 0 ) { switch( errno ) { case ETIMEDOUT: setIberr( EBUS ); conf->timed_out = 1; break; case EINTR: setIberr( EABO ); break; default: setIberr( EDVR ); setIbcnt( errno ); break; } return -1; } return cmd.completed_transfer_count; } unsigned int create_send_setup( const ibBoard_t *board, const Addr4882_t addressList[], uint8_t *cmdString ) { unsigned int i, j; unsigned int board_pad; int board_sad; if( addressList == NULL ) { fprintf(stderr, "libgpib: bug! addressList NULL in create_send_setup()\n"); return 0; } if( addressListIsValid( addressList ) == 0 ) { fprintf(stderr, "libgpib: bug! bad address list\n"); return 0; } i = 0; /* controller's talk address */ if(query_pad(board, &board_pad) < 0) return 0; cmdString[i++] = MTA(board_pad); if(query_sad(board, &board_sad) < 0) return 0; if(board_sad >= 0 ) cmdString[i++] = MSA(board_sad); cmdString[ i++ ] = UNL; for( j = 0; j < numAddresses( addressList ); j++ ) { unsigned int pad; int sad; pad = extractPAD( addressList[ j ] ); sad = extractSAD( addressList[ j ] ); cmdString[ i++ ] = MLA( pad ); if( sad >= 0) cmdString[ i++ ] = MSA( sad ); } return i; } unsigned int send_setup_string( const ibConf_t *conf, uint8_t *cmdString ) { ibBoard_t *board; Addr4882_t addressList[ 2 ]; board = interfaceBoard( conf ); addressList[ 0 ] = packAddress( conf->settings.pad, conf->settings.sad ); addressList[ 1 ] = NOADDR; return create_send_setup( board, addressList, cmdString ); } int send_setup( ibConf_t *conf ) { uint8_t cmdString[8]; int retval; retval = send_setup_string( conf, cmdString ); if( my_ibcmd( conf, cmdString, retval ) < 0 ) return -1; return 0; } int InternalSendSetup( ibConf_t *conf, const Addr4882_t addressList[] ) { int i; ibBoard_t *board; uint8_t *cmd; int count; if( addressListIsValid( addressList ) == 0 || numAddresses( addressList ) == 0 ) { setIberr( EARG ); return -1; } if( conf->is_interface == 0 ) { setIberr( EDVR ); return -1; } board = interfaceBoard( conf ); if( is_cic( board ) == 0 ) { setIberr( ECIC ); return -1; } cmd = malloc( 16 + 2 * numAddresses( addressList ) ); if( cmd == NULL ) { setIberr( EDVR ); setIbcnt( ENOMEM ); return -1; } i = create_send_setup( board, addressList, cmd ); //XXX detect no listeners (EBUS) error count = my_ibcmd( conf, cmd, i ); free( cmd ); cmd = NULL; if(count != i) { return -1; } return 0; } void SendSetup( int boardID, const Addr4882_t addressList[] ) { int retval; ibConf_t *conf; conf = enter_library( boardID ); if( conf == NULL ) { exit_library( boardID, 1 ); return; } retval = InternalSendSetup( conf, addressList ); if( retval < 0 ) { exit_library( boardID, 1 ); return; } exit_library( boardID, 0 ); } void SendCmds( int boardID, const void *buffer, long count ) { ibcmd( boardID, buffer, count ); }
c
11
0.56188
77
19.892857
280
starcoderdata
using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace Cpnucleo.GRPC.Services; public static class TokenService { public static string GenerateToken(string id, string key, string issuer, int expires) { SecurityTokenDescriptor tokenDescriptor = new() { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.PrimarySid, id) }), NotBefore = DateTime.UtcNow, Expires = DateTime.UtcNow.AddSeconds(Convert.ToInt32(expires)), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key)), SecurityAlgorithms.HmacSha256Signature), Issuer = issuer, }; JwtSecurityTokenHandler tokenHandler = new(); SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token); } }
c#
22
0.685769
152
33.9
30
starcoderdata
using System.Collections; using System.Runtime.InteropServices; using LibMMD.Reader; using LibMMD.Unity3D; using LibMMD.Unity3D.BonePose; using UnityEngine; using UnityEngine.UI; namespace LibMmdDemo { public class BonePoseGeneratorDemoController : MonoBehaviour { public Text StatusText; public string ModelPath; public string MotionPath; public string BonePoseFileOutputPath; protected void Start() { var model = new PmxReader().Read(ModelPath, new ModelReadConfig {GlobalToonPath = ""}); Debug.Log("model load finished"); var motion = new VmdReader().Read(MotionPath); Debug.Log("motion load finished" + motion.Length + " frames"); var bonePoseFileGenerator = BonePoseFileGenerator.GenerateAsync(model, motion, BonePoseFileOutputPath); StartCoroutine(CheckGenerateStatus(bonePoseFileGenerator)); } private IEnumerator CheckGenerateStatus(BonePoseFileGenerator generator) { while (true) { var generatorStatus = generator.Status; var statusStr = generatorStatus.ToString(); if (generatorStatus == BonePoseFileGenerator.GenerateStatus.CalculatingFrames) { statusStr = statusStr + " " + generator.CalculatedFrames + "/" + generator.TotalFrames; } StatusText.text = statusStr; if (generatorStatus == BonePoseFileGenerator.GenerateStatus.Failed) { break; } if (generatorStatus == BonePoseFileGenerator.GenerateStatus.Finished) { StartPlay(); break; } yield return null; } } private void StartPlay() { var mmdObj = MmdGameObject.CreateGameObject("MmdGameObject"); var mmdGameObject = mmdObj.GetComponent mmdGameObject.LoadModel(ModelPath); mmdGameObject.LoadBonePoseFile(BonePoseFileOutputPath); mmdGameObject.Playing = true; } } }
c#
18
0.593183
107
32.731343
67
starcoderdata
func (c *Chip) getHandleRequest(offsets []int, lro lineReqOptions) (uintptr, error) { hr := uapi.HandleRequest{ Lines: uint32(len(offsets)), Flags: lro.defCfg.toHandleFlags(), } copy(hr.Consumer[:len(hr.Consumer)-1], lro.consumer) // copy(hr.Offsets[:], offsets) - with cast for i, o := range offsets { hr.Offsets[i] = uint32(o) } for idx, offset := range lro.offsets { hr.DefaultValues[idx] = uint8(lro.values[offset]) } err := uapi.GetLineHandle(c.f.Fd(), &hr) if err != nil { return 0, err } return uintptr(hr.Fd), nil }
go
13
0.662385
85
27.736842
19
inline
package silencebeat.onlineradio.Presenter; import android.app.Activity; import android.content.Context; import android.content.Intent; import silencebeat.onlineradio.View.View.PlayerActivity; /** * Created by on 30/09/2017. */ public class PlayerWireframe { private PlayerWireframe(){ } private static class SingleTonHelper{ private static final PlayerWireframe INSTANCE = new PlayerWireframe(); } public static PlayerWireframe getInstance() { return SingleTonHelper.INSTANCE; } public void toView(Context context){ Intent intent = new Intent(context, PlayerActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); ((Activity) context).finish(); } }
java
10
0.718714
88
25.393939
33
starcoderdata
<?php /** * @see https://github.com/laminas-api-tools/api-tools-api-problem for the canonical source repository * @copyright https://github.com/laminas-api-tools/api-tools-api-problem/blob/master/COPYRIGHT.md * @license https://github.com/laminas-api-tools/api-tools-api-problem/blob/master/LICENSE.md New BSD License */ namespace Laminas\ApiTools\ApiProblem\Listener; use Exception; use Laminas\ApiTools\ApiProblem\ApiProblem; use Laminas\ApiTools\ApiProblem\ApiProblemResponse; use Laminas\ApiTools\ApiProblem\View\ApiProblemModel; use Laminas\EventManager\AbstractListenerAggregate; use Laminas\EventManager\EventManagerInterface; use Laminas\Http\Header\Accept as AcceptHeader; use Laminas\Http\Request as HttpRequest; use Laminas\Mvc\MvcEvent; use Laminas\View\Model\ModelInterface; use Throwable; /** * ApiProblemListener. * * Provides a listener on the render event, at high priority. * * If the MvcEvent represents an error, then its view model and result are * replaced with a RestfulJsonModel containing an API-Problem payload. */ class ApiProblemListener extends AbstractListenerAggregate { /** * Default types to match in Accept header. * * @var array */ protected $acceptFilters = [ 'application/json', 'application/*+json', ]; /** * Constructor. * * Set the accept filter, if one is passed * * @param string|array $filters */ public function __construct($filters = null) { if (! empty($filters)) { if (is_string($filters)) { $this->acceptFilters = [$filters]; } if (is_array($filters)) { $this->acceptFilters = $filters; } } } /** * {@inheritDoc} */ public function attach(EventManagerInterface $events, $priority = 1) { $this->listeners[] = $events->attach(MvcEvent::EVENT_RENDER, [$this, 'onRender'], 1000); $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, [$this, 'onDispatchError'], 100); $sharedEvents = $events->getSharedManager(); $sharedEvents->attach( 'Laminas\Stdlib\DispatchableInterface', MvcEvent::EVENT_DISPATCH, [$this, 'onDispatch'], 100 ); } /** * Listen to the render event. * * @param MvcEvent $e */ public function onRender(MvcEvent $e) { if (! $this->validateErrorEvent($e)) { return; } // Next, do we have a view model in the result? // If not, nothing more to do. $model = $e->getResult(); if (! $model instanceof ModelInterface || $model instanceof ApiProblemModel) { return; } // Marshal the information we need for the API-Problem response $status = $e->getResponse()->getStatusCode(); $exception = $model->getVariable('exception'); if ($exception instanceof Throwable || $exception instanceof Exception) { $apiProblem = new ApiProblem($status, $exception); } else { $apiProblem = new ApiProblem($status, $model->getVariable('message')); } // Create a new model with the API-Problem payload, and reset // the result and view model in the event using it. $model = new ApiProblemModel($apiProblem); $e->setResult($model); $e->setViewModel($model); } /** * Handle dispatch. * * It checks if the controller is in our list * * @param MvcEvent $e */ public function onDispatch(MvcEvent $e) { $app = $e->getApplication(); $services = $app->getServiceManager(); $config = $services->get('config'); if (! isset($config['api-tools-api-problem']['render_error_controllers'])) { return; } $controller = $e->getRouteMatch()->getParam('controller'); $controllers = $config['api-tools-api-problem']['render_error_controllers']; if (! in_array($controller, $controllers)) { // The current controller is not in our list of controllers to handle return; } // Attach the ApiProblem render.error listener $events = $app->getEventManager(); $services->get('Laminas\ApiTools\ApiProblem\RenderErrorListener')->attach($events); } /** * Handle render errors. * * If the event represents an error, and has an exception composed, marshals an ApiProblem * based on the exception, stops event propagation, and returns an ApiProblemResponse. * * @param MvcEvent $e * * @return ApiProblemResponse */ public function onDispatchError(MvcEvent $e) { if (! $this->validateErrorEvent($e)) { return; } // Marshall an ApiProblem and view model based on the exception $exception = $e->getParam('exception'); if (! ($exception instanceof Throwable || $exception instanceof Exception)) { // If it's not an exception, do not know what to do. return; } $e->stopPropagation(); $response = new ApiProblemResponse(new ApiProblem($exception->getCode(), $exception)); $e->setResponse($response); return $response; } /** * Determine if we have a valid error event. * * @param MvcEvent $e * * @return bool */ protected function validateErrorEvent(MvcEvent $e) { // only worried about error pages if (! $e->isError()) { return false; } // and then, only if we have an Accept header... $request = $e->getRequest(); if (! $request instanceof HttpRequest) { return false; } $headers = $request->getHeaders(); if (! $headers->has('Accept')) { return false; } // ... that matches certain criteria $accept = $headers->get('Accept'); if (! $this->matchAcceptCriteria($accept)) { return false; } return true; } /** * Attempt to match the accept criteria. * * If it matches, but on "*\/*", return false. * * Otherwise, return based on whether or not one or more criteria match. * * @param AcceptHeader $accept * * @return bool */ protected function matchAcceptCriteria(AcceptHeader $accept) { foreach ($this->acceptFilters as $type) { $match = $accept->match($type); if ($match && $match->getTypeString() != '*/*') { return true; } } return false; } }
php
17
0.588227
111
28.415584
231
starcoderdata
/******************************************************************* Module: Counterexample-Guided Inductive Synthesis Author: \*******************************************************************/ #ifndef CEGIS_CONCRETE_FITNESS_SOURCE_PROVIDER_H_ #define CEGIS_CONCRETE_FITNESS_SOURCE_PROVIDER_H_ #include #include /** * @brief * * @details */ template<class progt, class configt> class concrete_fitness_source_providert { const progt &prog; configt learn_config; const std::function max_size; const std::string execute_func_name; std::string source; public: /** * @brief * * @details * * @param prog * @param max_size * @param execute_func_name */ concrete_fitness_source_providert(const progt &prog, std::function max_size, const std::string &execute_func_name); /** * @brief * * @details */ ~concrete_fitness_source_providert(); /** * @brief * * @details * * @return */ std::string operator()(); }; /** * @brief * * @details * * @param result * @param st * @param gf * @param num_ce_vars * @param num_vars * @param num_consts * @param max_prog_size * @param exec_func_name */ std::string &post_process_fitness_source(std::string &result, const symbol_tablet &st, const goto_functionst &gf, size_t num_ce_vars, size_t num_vars, size_t num_consts, size_t max_prog_size, const std::string &exec_func_name); #include "concrete_fitness_source_provider.inc" #endif /* CEGIS_CONCRETE_FITNESS_SOURCE_PROVIDER_H_ */
c
11
0.5939
75
19.390244
82
starcoderdata
@Test public void test01() throws SQLException { DruidDataSource dataSource = new DruidDataSource(); // dataSource.setDriverClassName("oracle.jdbc.OracleDriver"); // dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:49161:XE"); // dataSource.setUsername("mytest"); // dataSource.setPassword("m121212"); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true"); dataSource.setUsername("root"); dataSource.setPassword("121212"); dataSource.setInitialSize(1); dataSource.setMinIdle(1); dataSource.setMaxActive(2); dataSource.setMaxWait(60000); dataSource.setTimeBetweenEvictionRunsMillis(60000); dataSource.setMinEvictableIdleTimeMillis(300000); dataSource.init(); Connection conn = dataSource.getConnection(); conn.setAutoCommit(false); PreparedStatement pstmt = conn .prepareStatement("insert into user (id,name,role_id,c_time,test1,test2) values (?,?,?,?,?,?)"); java.util.Date now = new java.util.Date(); for (int i = 1; i <= 10000; i++) { pstmt.clearParameters(); pstmt.setLong(1, (long) i); pstmt.setString(2, "test_" + i); pstmt.setLong(3, (long) i % 4 + 1); pstmt.setDate(4, new java.sql.Date(now.getTime())); pstmt.setString(5, null); pstmt.setBytes(6, null); pstmt.execute(); if (i % 5000 == 0) { conn.commit(); } } conn.commit(); pstmt.close(); // Statement stmt = conn.createStatement(); // ResultSet rs = stmt.executeQuery("select * from user t where 1=2"); // // ResultSetMetaData rsm = rs.getMetaData(); // int cnt = rsm.getColumnCount(); // for (int i = 1; i <= cnt; i++) { // System.out.println(rsm.getColumnName(i) + " " + rsm.getColumnType(i)); // } // rs.close(); // stmt.close(); // PreparedStatement pstmt = conn // .prepareStatement("insert into tb_user (id,name,role_id,c_time,test1,test2) // values (?,?,?,?,?,?)"); // pstmt.setBigDecimal(1, new BigDecimal("5")); // pstmt.setString(2, "test"); // pstmt.setBigDecimal(3, new BigDecimal("1")); // pstmt.setDate(4, new Date(new java.util.Date().getTime())); // byte[] a = { (byte) 1, (byte) 2 }; // pstmt.setBytes(5, a); // pstmt.setBytes(6, a); // pstmt.execute(); // // pstmt.close(); conn.close(); dataSource.close(); }
java
12
0.552206
108
34.802632
76
inline
def _retrieve_l10n_ch_postal(self, iban): """Reads a swiss postal account number from a an IBAN and returns it as a string. Returns None if no valid postal account number was found, or the given iban was not from Swiss Postfinance. CH09 0900 0000 1000 8060 7 -> 10-8060-7 """ if self._is_postfinance_iban(iban): # the IBAN corresponds to a swiss account return self._pretty_postal_num(iban[-9:]) return None
python
11
0.631148
79
43.454545
11
inline
// 2021 #pragma once #include "CoreMinimal.h" #include "Located.generated.h" /** * Struct representing actor/projectile that have a position in the world. */ USTRUCT(BlueprintType, Category = "Basic") struct APPARATISTRUNTIME_API FLocated { GENERATED_BODY() public: /* Location of the object. */ UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "Data") FVector Location = FVector::ZeroVector; /* Default constructor. */ FLocated() {} /* Constructor with all arguments. */ FORCEINLINE FLocated(const FTransform& InTransform) : Location(InTransform.GetLocation()) {} /* Construct the trait by 2D-location. */ FORCEINLINE FLocated(const FVector& InLocation) : Location(InLocation) {} /* Simple get Location pure function. */ FORCEINLINE const FVector& GetLocation() const { return Location; } /* Simple set Location pure function. */ FORCEINLINE void SetLocation(const FVector& InLocation) { Location = InLocation; } };
c
9
0.717791
74
18.56
50
starcoderdata
connect("weblogic","weblogic", "t3://localhost:7001") try: cd('JDBCSystemResources/${dsJndiName}') except Exception, e: edit() dsname="${dsJndiName}" server="examplesServer" cd("Servers/"+server) target=cmo cd("../..") startEdit() jdbcSR = create(dsname,"JDBCSystemResource") theJDBCResource = jdbcSR.getJDBCResource() theJDBCResource.setName("${dsJndiName}") connectionPoolParams = theJDBCResource.getJDBCConnectionPoolParams() connectionPoolParams.setTestTableName("SQL SELECT 1") dsParams = theJDBCResource.getJDBCDataSourceParams() dsParams.addJNDIName("${dsJndiName}") driverParams = theJDBCResource.getJDBCDriverParams() driverParams.setUrl("${dsUrl}") driverParams.setDriverName("org.postgresql.Driver") driverParams.setPassword("${ driverProperties = driverParams.getProperties() proper = driverProperties.createProperty("user") proper.setValue("${dsUser}") jdbcSR.addTarget(target) save() activate(block="true") else: print "Datasource ${dsJndiName} already exists"
python
9
0.703704
72
26
41
starcoderdata
package gui; import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; public class VentanaPrincipal extends JFrame { private JTabbedPane JTabbedPane = null; private static VentanaPrincipal instance = null; public static VentanaPrincipal getInstance() { if (instance == null) { instance = new VentanaPrincipal(); } return instance; } /** * */ public VentanaPrincipal() { super("Gestión de ventas de coches"); this.setBounds(0, 0, 600, 400); this.setJMenuBar(new MenuBar()); this.setLayout(new BorderLayout()); this.add(getPanelPrincipal(), BorderLayout.CENTER); } /** * * @return */ public JTabbedPane getPanelPrincipal() { JTabbedPane = new JTabbedPane(); JTabbedPane.add("Fabricantes", new PanelFabricantes()); JTabbedPane.add("Coches", new PanelCoches()); JTabbedPane.add("Clientes", new PanelCliente()); JTabbedPane.add("Concesionario", new PanelConcesionario()); JTabbedPane.add("Ventas", new PanelVenta()); return JTabbedPane; } public static void main(String[] args) { VentanaPrincipal.getInstance().setVisible(true); } /** * * @return to JTabbedPane */ public JTabbedPane getJTabbedPane() { return JTabbedPane; } }
java
11
0.704957
61
17.705882
68
starcoderdata
/** * Copyright 2014 Modeliosoft * * 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 org.modelio.juniper.wrapper.keyvaluestore; import java.net.UnknownHostException; import java.util.logging.Logger; import mpi.MPI; import org.modelio.juniper.CommunicationToolkit; import org.modelio.juniper.platform.JuniperProgram; import org.modelio.juniper.wrapper.WrapperHelper; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; public class MongoDB extends JuniperProgram { private MongoClient mongoClient; private DB db; private DBCollection dbc; public MongoDB() { try { mongoClient = new MongoClient("localhost", 27017); db = mongoClient.getDB("db"); dbc = db.getCollection("col"); } catch (UnknownHostException e) { e.printStackTrace(); System.exit(-1); } } public IKeyValueStore iKeyValueStoreImpl = new IKeyValueStore { public void put(Object key, Object value) { DBObject kdoc = BasicDBObjectBuilder.start().add("_id", key).get(); if (dbc.find(kdoc).hasNext()) { DBObject vdoc = BasicDBObjectBuilder .start() .add("$set", BasicDBObjectBuilder.start() .add("value", value).get()).get(); dbc.update(kdoc, vdoc); } else { DBObject doc = BasicDBObjectBuilder.start().add("_id", key) .add("value", value).get(); dbc.insert(doc); } } public Object find(Object key) { DBObject doc = BasicDBObjectBuilder.start().add( "_id" , key ).get(); DBCursor cursor = dbc.find(doc); Object value = null; if (cursor.hasNext()) { value = cursor.next().get("value"); } return value; } }; public static final Logger log = Logger.getLogger(MongoDB.class.getName()); public static void main(final String[] args) throws java.lang.Exception { MongoDB mongodb = new MongoDB(); WrapperHelper.initialize(mongodb.communicationToolkit, mongodb.iKeyValueStoreImpl, args); MPI.Init(new String[0]); mongodb.communicationToolkit.initProgramCommunication(); mongodb.initProvidedInterfaces(); while (true) { Thread.yield(); mongodb.communicationToolkit.processReceivedMessages(); } } public void initProvidedInterfaces() throws Exception { if (juniperPlatform != null) { WrapperHelper.initialize(communicationToolkit,iKeyValueStoreImpl, juniperPlatform); } } }
java
20
0.688262
99
30.816327
98
starcoderdata
package com.sunsharing.eos.clientexample.sys; import com.sunsharing.eos.client.EosClient; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; import java.util.Properties; /** * color="blue">SysInit * * * JDK版本:JDK1.5.0 * * @author */ public class SysInit extends HttpServlet { private static final long serialVersionUID = 1L; /** * 记录日志 */ private static Logger logger = Logger.getLogger(SysInit.class); private static Properties pro; public void init() { ServletContext sc = this.getServletContext(); logger.info("系统开始初始化..."); ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc); ServiceLocator.init(ctx); logger.info("系统初始化上下文结束..."); logger.info("初始化其它参数..."); //初始化配置文件信息和数据库全局参数信息 String sysPath = this.getClass().getClassLoader().getResource("/").getPath(); SysParam.setSysPath(sysPath); SysParam.init(); EosClient.start(); logger.info("初始化其它参数结束..."); } @Override public void destroy() { super.destroy(); try { } catch (Exception e) { e.printStackTrace(); } } }
java
12
0.648667
97
22.809524
63
starcoderdata
private void QueueLivePreviewUpdate() { try { _livePrevTokenSource?.Cancel(); } catch (Exception) { // For some reason this calls Process.Kill which might throw access is denied? } _livePrevTokenSource = new CancellationTokenSource(); UpdateStatus(String.Empty, StatusType.Neutral); // Assert live preview is on if (_livePreviewChecked) { _livePrevTimer.Change(_delayMs, Timeout.Infinite); } }
c#
11
0.503311
94
27.809524
21
inline
<?php declare(strict_types=1); namespace Shopware\Core\Content\Test\Sitemap\Service; use League\Flysystem\FilesystemInterface; use PHPUnit\Framework\TestCase; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; use Shopware\Core\Content\Sitemap\Exception\AlreadyLockedException; use Shopware\Core\Content\Sitemap\Service\SitemapExporter; use Shopware\Core\Content\Sitemap\Service\SitemapHandleFactoryInterface; use Shopware\Core\Defaults; use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface; use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter; use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\NotFilter; use Shopware\Core\Framework\Test\Seo\StorefrontSalesChannelTestHelper; use Shopware\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour; use Shopware\Core\Framework\Uuid\Uuid; use Shopware\Core\System\SalesChannel\Aggregate\SalesChannelDomain\SalesChannelDomainEntity; use Shopware\Core\System\SalesChannel\Context\SalesChannelContextFactory; use Shopware\Core\System\SalesChannel\Context\SalesChannelContextService; use Shopware\Core\System\SalesChannel\SalesChannelContext; use Shopware\Core\System\SalesChannel\SalesChannelEntity; use Symfony\Component\Cache\CacheItem; use Symfony\Component\EventDispatcher\EventDispatcher; /** * @internal */ class SitemapExporterTest extends TestCase { use IntegrationTestBehaviour; use StorefrontSalesChannelTestHelper; private SalesChannelContext $context; private EntityRepositoryInterface $salesChannelRepository; protected function setUp(): void { parent::setUp(); $this->context = $this->createStorefrontSalesChannelContext(Uuid::randomHex(), 'sitemap-exporter-test'); $this->salesChannelRepository = $this->getContainer()->get('sales_channel.repository'); } public function testNotLocked(): void { $cache = $this->createMock(CacheItemPoolInterface::class); $cache->method('getItem')->willReturn($this->createCacheItem('', true, false)); $exporter = new SitemapExporter( [], $cache, 10, $this->createMock(FilesystemInterface::class), $this->createMock(SitemapHandleFactoryInterface::class), $this->createMock(EventDispatcher::class) ); $result = $exporter->generate($this->context, false, null, null); static::assertTrue($result->isFinish()); } public function testExpectAlreadyLockedException(): void { $cache = $this->createMock(CacheItemPoolInterface::class); $cache->method('getItem')->willReturn($this->createCacheItem('', true, true)); $exporter = new SitemapExporter( [], $cache, 10, $this->createMock(FilesystemInterface::class), $this->createMock(SitemapHandleFactoryInterface::class), $this->createMock(EventDispatcher::class) ); $this->expectException(AlreadyLockedException::class); $exporter->generate($this->context, false, null, null); } public function testForce(): void { $cache = $this->createMock(CacheItemPoolInterface::class); $cache->method('getItem')->willReturn($this->createCacheItem('', true, true)); $exporter = new SitemapExporter( [], $cache, 10, $this->createMock(FilesystemInterface::class), $this->createMock(SitemapHandleFactoryInterface::class), $this->createMock(EventDispatcher::class) ); $result = $exporter->generate($this->context, true, null, null); static::assertTrue($result->isFinish()); } public function testLocksAndUnlocks(): void { $cache = $this->createMock(CacheItemPoolInterface::class); /** * @var CacheItemInterface $cacheItem */ $cacheItem = null; $cache->method('getItem')->willReturnCallback(function (string $k) use (&$cacheItem) { if ($cacheItem === null) { $cacheItem = $this->createCacheItem($k, null, false); } return $cacheItem; }); $cache->method('save')->willReturnCallback(function (CacheItemInterface $i) use (&$cacheItem): void { static::assertSame($cacheItem->getKey(), $i->getKey()); $cacheItem = $this->createCacheItem($i->getKey(), $i->get(), true); }); $cache->method('deleteItem')->willReturnCallback(function (string $k) use (&$cacheItem): void { static::assertNotNull($cacheItem, 'Was not locked'); static::assertSame($cacheItem->getKey(), $k); static::assertTrue($cacheItem->isHit(), 'Was not locked'); }); $exporter = new SitemapExporter( [], $cache, 10, $this->createMock(FilesystemInterface::class), $this->createMock(SitemapHandleFactoryInterface::class), $this->createMock(EventDispatcher::class) ); $result = $exporter->generate($this->context, false, null, null); static::assertTrue($result->isFinish()); } /** * NEXT-21735 * * @group not-deterministic */ public function testWriteWithMulitpleSchemesAndSameLanguage(): void { $salesChannel = $this->salesChannelRepository->search( $this->storefontSalesChannelCriteria([$this->context->getSalesChannelId()]), $this->context->getContext() )->first(); $domain = $salesChannel->getDomains()->first(); $this->salesChannelRepository->update([ [ 'id' => $this->context->getSalesChannelId(), 'domains' => [ [ 'id' => Uuid::randomHex(), 'languageId' => $domain->getLanguageId(), 'url' => str_replace('http://', 'https://', $domain->getUrl()), 'currencyId' => Defaults::CURRENCY, 'snippetSetId' => $domain->getSnippetSetId(), ], ], ], ], $this->context->getContext()); /** @var SalesChannelEntity $salesChannel */ $salesChannel = $this->salesChannelRepository->search($this->storefontSalesChannelCriteria([$this->context->getSalesChannelId()]), $this->context->getContext())->first(); $languageIds = $salesChannel->getDomains()->map(function (SalesChannelDomainEntity $salesChannelDomain) { return $salesChannelDomain->getLanguageId(); }); $languageIds = array_unique($languageIds); foreach ($languageIds as $languageId) { $salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create('', $salesChannel->getId(), [SalesChannelContextService::LANGUAGE_ID => $languageId]); $this->generateSitemap($salesChannelContext, false); $files = $this->getFilesystem('shopware.filesystem.sitemap')->listContents('sitemap/salesChannel-' . $salesChannel->getId() . '-' . $salesChannelContext->getLanguageId()); static::assertCount(1, $files); } static::assertTrue(true); } private function createCacheItem($key, $value, $isHit): CacheItemInterface { $class = new \ReflectionClass(CacheItem::class); $keyProp = $class->getProperty('key'); $keyProp->setAccessible(true); $valueProp = $class->getProperty('value'); $valueProp->setAccessible(true); $isHitProp = $class->getProperty('isHit'); $isHitProp->setAccessible(true); $item = new CacheItem(); $keyProp->setValue($item, $key); $valueProp->setValue($item, $value); $isHitProp->setValue($item, $isHit); return $item; } private function storefontSalesChannelCriteria(array $ids): Criteria { $criteria = new Criteria($ids); $criteria->addAssociation('domains'); $criteria->addFilter(new NotFilter( NotFilter::CONNECTION_AND, [new EqualsFilter('domains.id', null)] )); $criteria->addAssociation('type'); $criteria->addFilter(new EqualsFilter('type.id', Defaults::SALES_CHANNEL_TYPE_STOREFRONT)); return $criteria; } private function generateSitemap(SalesChannelContext $salesChannelContext, bool $force, ?string $lastProvider = null, ?int $offset = null): void { $result = $this->getContainer()->get(SitemapExporter::class)->generate($salesChannelContext, $force, $lastProvider, $offset); if ($result->isFinish() === false) { $this->generateSitemap($salesChannelContext, $force, $result->getProvider(), $result->getOffset()); } } }
php
22
0.638496
191
37.14346
237
starcoderdata
public List<AbstractFile> findFiles(Content dataSource, String fileName) throws TskCoreException { if (dataSource.getParent() != null) { final String msg = MessageFormat.format(bundle.getString("SleuthkitCase.isFileFromSource.exception.msg1.text"), dataSource); logger.log(Level.SEVERE, msg); throw new IllegalArgumentException(msg); } List<AbstractFile> files = new ArrayList<AbstractFile>(); CaseDbConnection connection = connections.getConnection(); acquireSharedLock(); ResultSet rs = null; try { PreparedStatement statement = connection.getPreparedStatement(CaseDbConnection.PREPARED_STATEMENT.SELECT_FILES_BY_FILE_SYSTEM_AND_NAME); statement.clearParameters(); if (dataSource instanceof Image) { for (FileSystem fileSystem : getFileSystems((Image) dataSource)) { statement.setString(1, fileName.toLowerCase()); statement.setLong(2, fileSystem.getId()); rs = connection.executeQuery(statement); files.addAll(resultSetToAbstractFiles(rs)); } } else if (dataSource instanceof VirtualDirectory) { //fs_obj_id is special for non-fs files (denotes data source) statement.setString(1, fileName.toLowerCase()); statement.setLong(2, dataSource.getId()); rs = connection.executeQuery(statement); files = resultSetToAbstractFiles(rs); } else { final String msg = MessageFormat.format(bundle.getString("SleuthkitCase.findFiles.exception.msg2.text"), dataSource); logger.log(Level.SEVERE, msg); throw new IllegalArgumentException(msg); } } catch (SQLException e) { throw new TskCoreException(bundle.getString("SleuthkitCase.findFiles.exception.msg3.text"), e); } finally { closeResultSet(rs); releaseSharedLock(); } return files; }
java
15
0.740826
139
42.625
40
inline