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
using Gameplay.Characters; using System.ComponentModel; using UnityEngine; namespace Gameplay { public enum ScoreType { [Description("Eaten pommes")] EatenPommes, [Description("Action executed")] ActionExecuted, [Description("Second of life")] SecondOfLife, [Description("Death avoided")] DeathAvoided } public class ScoreHandler : MonoBehaviour { public int Score { get; private set; } private ICharacter character; private float timer = 0.0f; private float OneSecond = 1.0f; private void Start() { character = GetComponent Score = 0; } private void Update() { timer += Time.deltaTime; if (timer >= OneSecond) { // Update the score Score += character.GetScore(ScoreType.SecondOfLife); // Reset the timer timer = 0.0f; } } public void OnEaterStateChange(EaterState eaterState) { // eaterState holds the new state. // If the current state is Eating then the previous one must've been Starving. if (eaterState == EaterState.Eating) { Score += character.GetScore(ScoreType.DeathAvoided); } } public void OnPommesEaten() { Score += character.GetScore(ScoreType.EatenPommes); } public void OnActionExecuted() { Score += character.GetScore(ScoreType.ActionExecuted); } } }
c#
15
0.540203
90
24.439394
66
starcoderdata
package com.megvii.zhimasdk.b.a.i.b; import com.megvii.zhimasdk.b.a.b.e.h; import com.megvii.zhimasdk.b.a.b.e.i; import com.megvii.zhimasdk.b.a.n.d; import com.megvii.zhimasdk.b.a.n.j; import com.megvii.zhimasdk.b.a.n.l; import com.megvii.zhimasdk.b.a.n.m; import com.megvii.zhimasdk.b.a.v; import java.nio.charset.Charset; @Deprecated public class k extends a { public k() { super(null, null); } public k(com.megvii.zhimasdk.b.a.e.b paramb, com.megvii.zhimasdk.b.a.l.e parame) { super(paramb, parame); } public static void a(com.megvii.zhimasdk.b.a.l.e parame) { com.megvii.zhimasdk.b.a.l.f.a(parame, v.c); com.megvii.zhimasdk.b.a.l.f.a(parame, d.a.name()); com.megvii.zhimasdk.b.a.l.c.a(parame, true); com.megvii.zhimasdk.b.a.l.c.b(parame, 8192); com.megvii.zhimasdk.b.a.l.f.b(parame, s.a); } protected com.megvii.zhimasdk.b.a.l.e a() { com.megvii.zhimasdk.b.a.l.g localg = new com.megvii.zhimasdk.b.a.l.g(); a(localg); return localg; } protected com.megvii.zhimasdk.b.a.n.b b() { com.megvii.zhimasdk.b.a.n.b localb = new com.megvii.zhimasdk.b.a.n.b(); localb.b(new com.megvii.zhimasdk.b.a.b.e.f()); localb.b(new j()); localb.b(new l()); localb.b(new com.megvii.zhimasdk.b.a.b.e.e()); localb.b(new m()); localb.b(new com.megvii.zhimasdk.b.a.n.k()); localb.b(new com.megvii.zhimasdk.b.a.b.e.b()); localb.b(new i()); localb.b(new com.megvii.zhimasdk.b.a.b.e.c()); localb.b(new h()); localb.b(new com.megvii.zhimasdk.b.a.b.e.g()); return localb; } } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/megvii/zhimasdk/b/a/i/b/k.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
java
16
0.638622
111
26.6875
64
starcoderdata
package com.monet.seeyou.tool; /** * Created by Monet on 2015/6/16. */ import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.net.DhcpInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import java.text.DecimalFormat; import java.util.Calendar; /** * 存放一些工具函数 * */ public class Util { // RSSI的粗略评定标准 private static final int RARE = -80; private static final int MEDIUM_RARE = -60; private static final int MEDIUM_WELL = -40; private static final int WELL_DONE = -20; // 与RSSI相对应的距离 private static final String DIST_1 = " 0- 5m"; private static final String DIST_2 = " 5-10m"; private static final String DIST_3 = "10-15m"; private static final String DIST_4 = "15-20m"; private static final String DIST_5 = "20-25m"; //生成圆角图片 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) { try { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int left = 0, top = 0, right = width, bottom = height; float roundPx = height/2; if (width > height) { left = (width - height)/2; top = 0; right = left + height; bottom = height; } else if (height > width) { left = 0; top = (height - width)/2; right = width; bottom = top + width; roundPx = width/2; } //ZLog.i(TAG, "ps:"+ left +", "+ top +", "+ right +", "+ bottom); Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); int color = 0xff424242; Paint paint = new Paint(); Rect rect = new Rect(left, top, right, bottom); RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } catch (Exception e) { return bitmap; } } public static String getDate() { Calendar c = Calendar.getInstance(); DecimalFormat df = new DecimalFormat("00"); String year = String.valueOf(c.get(Calendar.YEAR)); String month = String.valueOf(c.get(Calendar.MONTH)); String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1); String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY)); String mins = df.format(c.get(Calendar.MINUTE)); StringBuffer sbBuffer = new StringBuffer(); sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":" + mins); return sbBuffer.toString(); } /** * 获取Wifi环境下的一些参数 */ public static String getSSID(Context context) { //获取WifiManager WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); //检查wifi是否开启 if (wifiManager.isWifiEnabled()) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); // wifiInfo.getSSID得到的SSID会带双引号 return (wifiInfo == null) ? null : wifiInfo.getSSID().substring(1, wifiInfo.getSSID().length()-1); } return null; } public static String getBSSID(Context context) { //获取WifiManager WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); //检查wifi是否开启 if (wifiManager.isWifiEnabled()) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); // wifiInfo.getSSID得到的SSID会带双引号 return (wifiInfo == null) ? null : wifiInfo.getBSSID(); } return null; } // 获取所连接的AP的接收信号强度,即RSSI public static int getRSSI(Context context) { //获取WifiManager WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); //检查wifi是否开启 if (wifiManager.isWifiEnabled()) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); return (wifiInfo == null) ? -255 : wifiInfo.getRssi(); } // 获取不了接收信号强度,则返回-255,因RSSI为负值 return -255; } public static String getServerAddress(Context context) { //获取WifiManager WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); //检查wifi是否开启 if (wifiManager.isWifiEnabled()) { // 没开启wifi时,ip地址为0.0.0.0 // 获取的是DHCP服务器的IP地址 DhcpInfo dhcpinfo = wifiManager.getDhcpInfo(); return (dhcpinfo == null) ? null : Util.formatIpAddress(dhcpinfo.serverAddress); } return null; } // 将int格式的IP地址转换为字符串格式 public static String formatIpAddress(int ip) { return (ip & 0xFF)+ "." + ((ip >> 8 ) & 0xFF) + "." + ((ip >> 16 ) & 0xFF) +"."+((ip >> 24 ) & 0xFF); } // 将RSSI转换为粗略估计的距离 public static String rssi2Distance(int rssi) { if (rssi < RARE) { return DIST_5; } else if (RARE <= rssi && rssi< MEDIUM_RARE) { return DIST_4; } else if (MEDIUM_RARE <= rssi && rssi< MEDIUM_WELL) { return DIST_3; } else if (MEDIUM_WELL <= rssi && rssi< WELL_DONE) { return DIST_2; } else { return DIST_1; } } }
java
17
0.585412
110
34.195122
164
starcoderdata
// [2021y-03m-10d][13:28:40] #include //================================================================================= //================================================================================= #ifdef TEST_TOOLS_FEATURE_CSTDINT #define dTEST_COMPONENT tools, features #define dTEST_METHOD test_HAS_CSTDINT #define dTEST_TAG tdd #include #ifdef dHAS_CSTDINT dMESSAGE("[test] tools: enabled -> dHAS_CSTDINT") #include #else dMESSAGE("[test] tools: disabled -> dHAS_CSTDINT") #endif //============================================================================== //============================================================================== namespace { #ifdef dHAS_CSTDINT static_assert( sizeof(::std::uint8_t) == 1, "ERROR_INVALID_SIZE_MUST_BE_8BIT" ); static_assert( sizeof(::std::uint16_t) == 2, "ERROR_INVALID_SIZE_MUST_BE_16BIT" ); static_assert( sizeof(::std::uint32_t) == 4, "ERROR_INVALID_SIZE_MUST_BE_32BIT" ); static_assert( sizeof(::std::int64_t) == 8, "ERROR_INVALID_SIZE_MUST_BE_64BIT" ); #endif }//namespace //============================================================================== //============================================================================== #endif // ! TEST_TOOLS_FEATURE_CSTDINT
c++
11
0.397107
83
28.25
52
starcoderdata
#include "Resolver.h" #include "../Config.h" #include "../Interfaces.h" #include "../Memory.h" #include "../Netvars.h" #include "Misc.h" #include "../SDK/ConVar.h" #include "../SDK/Surface.h" #include "../SDK/GlobalVars.h" #include "../SDK/NetworkChannel.h" #include "../SDK/WeaponData.h" #include "EnginePrediction.h" #include "../SDK/LocalPlayer.h" #include "../SDK/Entity.h" #include "../SDK/UserCmd.h" #include "../SDK/GameEvent.h" #include "../SDK/FrameStage.h" #include "../SDK/Client.h" #include "../SDK/ItemSchema.h" #include "../SDK/WeaponSystem.h" #include "../SDK/WeaponData.h" #include "../SDK/Vector.h" #include "../GUI.h" #include "../Helpers.h" #include "../SDK/ModelInfo.h" #include "Backtrack.h" #include "../SDK/AnimState.h" #include "../SDK/LocalPlayer.h" #include const int MAX_RECORDS = 128; std::vector Resolver::PlayerRecords(65); Resolver::Record Resolver::invalid_record; void Resolver::Update() { if (!localPlayer || !localPlayer->isAlive()) { return; } for (int i = 0; i < PlayerRecords.size(); i++) { auto record = &PlayerRecords.at(i); if (!record) continue; auto entity = interfaces->entityList->getEntity(i); if (!entity || entity->isDormant() || !entity->isAlive()) { if (record->FiredUpon || record->wasTargeted) { record->lastworkingshot = record->missedshots; } record->invalid = true; continue; } if (record->invalid == true) { record->missedshots = config->debug.animstatedebug.resolver.missedoffset; record->prevhealth = entity->health(); } record->invalid = false; if (!record->FiredUpon) continue; else if (record->prevhealth == entity->health() || (config->debug.animstatedebug.resolver.goforkill)) { record->lastworkingshot = -1; record->missedshots = (record->missedshots >= 12 ? 0 : ++(record->missedshots)); record->wasUpdated = false; } record->prevhealth = entity->health(); } } void Resolver::BasicResolver(Entity* entity, int missed_shots) { // config->debug.indicators.resolver = false; if (!localPlayer || !localPlayer->isAlive() || !entity || entity->isDormant() || !entity->isAlive()) return; if (PlayerRecords.empty()) return; auto record = &PlayerRecords.at(entity->index()); if (!record || record->invalid) return; if (entity->getVelocity().length2D() > 3.0f) { record->PreviousEyeAngle = entity->eyeAngles().y; return; } /* const auto Brecord = &Backtrack::records[entity->index()]; if (!(Brecord && Vrecord->size() && Backtrack::valid(Vrecord->front().simulationTime))) return; */ /* auto Animstate = entity->getAnimstate(); if (!Animstate) return; int currAct = 1; if (entity->getVelocity().length2D() > 1.0f) return; for (int b = 0; b < entity->getAnimationLayerCount(); b++) { auto AnimLayer = entity->getAnimationLayer(b); currAct = entity->getSequenceActivity(AnimLayer->sequence); //if (currAct == ACT_CSGO_FIRE_PRIMARY && (AnimLayer->weight > (0.0f)) && (AnimLayer->cycle < .8f)) // return;, if ((currAct == ACT_CSGO_IDLE_TURN_BALANCEADJUST) || (currAct == ACT_CSGO_IDLE_ADJUST_STOPPEDMOVING)) { break; } }; float DesyncAng = Animstate->m_flGoalFeetYaw; //float eyeAnglesY = entity->eyeAngles().y; //record->front().prevAngles = entity->eyeAngles().y; if ((record->size() > 1) && Backtrack::valid(record->at(1).simulationTime)) { if (record->at(1).wasUpdated) { entity->eyeAngles().y = record->front().resolvedaddition; Animstate->m_flGoalFeetYaw = record->front().resolvedaddition; entity->UpdateState(Animstate, entity->eyeAngles()); return; } } if (!currAct) return; if ((currAct != ACT_CSGO_IDLE_TURN_BALANCEADJUST) && (currAct != ACT_CSGO_IDLE_ADJUST_STOPPEDMOVING) && !(config->debug.animstatedebug.resolver.overRide)) { return; } if ( ( !(record->front().PreviousAct == ACT_CSGO_IDLE_TURN_BALANCEADJUST) && !(record->front().PreviousAct == ACT_CSGO_IDLE_ADJUST_STOPPEDMOVING) ) && !(config->debug.animstatedebug.resolver.overRide)) { return; } //if ((record->front().PreviousAct == 0) || (!record->front().wasTargeted)) // return; //record->front().PreviousAct = 0; */ float DesyncAng = 0; auto Animstate = entity->getAnimstate(); if (!Animstate) return; if (!record->FiredUpon || !record->wasTargeted) { entity->UpdateState(Animstate, entity->eyeAngles()); if ((record->wasUpdated == false) && (entity->eyeAngles().y != record->PreviousEyeAngle)) { //record->PreviousEyeAngle = entity->eyeAngles().y; record->eyeAnglesOnUpdate = entity->eyeAngles().y; record->prevSimTime = entity->simulationTime(); record->PreviousEyeAngle = entity->eyeAngles().y + record->PreviousDesyncAng; record->wasUpdated = true; } if ((record->wasUpdated == true) && (entity->eyeAngles().y != record->PreviousEyeAngle) && (record->prevSimTime != entity->simulationTime())){ //record->PreviousEyeAngle = entity->eyeAngles().y; /* record->eyeAnglesOnUpdate = entity->eyeAngles().y; record->PreviousEyeAngle = entity->eyeAngles().y + record->PreviousDesyncAng; record->prevSimTime = entity->simulationTime(); */ } entity->eyeAngles().y = record->PreviousEyeAngle; entity->UpdateState(Animstate, entity->eyeAngles()); return; } //if (record->wasUpdated == true) // return; entity->UpdateState(Animstate, entity->eyeAngles()); //config->debug.indicators.resolver = true; int missed = record->missedshots; // if (config->debug.animstatedebug.resolver.missed_shots > 0) // missed = config->debug.animstatedebug.resolver.missed_shots; if (record->lastworkingshot != -1) missed = record->lastworkingshot; switch (missed) { case 1: DesyncAng += 25.0f; break; case 2: DesyncAng -= 25.0f; break; case 3: DesyncAng += 58.0f; break; case 4: DesyncAng -= 58.0f; break; case 5: DesyncAng = 70; break; case 6: DesyncAng = -70; break; case 7: DesyncAng = Animstate->m_flGoalFeetYaw; break; case 8: DesyncAng += -116.0f; break; case 9: DesyncAng += +116.0f; break; case 10: DesyncAng = DesyncAng + (entity->getMaxDesyncAngle() * -1); break; case 11: DesyncAng = DesyncAng + entity->getMaxDesyncAngle(); break; case 12: DesyncAng = -15; case 13: DesyncAng = 15; default: DesyncAng = Animstate->m_flGoalFeetYaw; break; } entity->eyeAngles().y += DesyncAng; Animstate->m_flGoalFeetYaw += DesyncAng; entity->UpdateState(Animstate, entity->eyeAngles()); record->PreviousEyeAngle = entity->eyeAngles().y; if (record->PreviousEyeAngle > 180) { record->PreviousEyeAngle -= 180; } else if (record->PreviousEyeAngle < -180) { record->PreviousEyeAngle += 180; } record->PreviousDesyncAng = DesyncAng; record->wasUpdated = true; record->FiredUpon = false; //record->front().resolvedaddition = entity->eyeAngles().y; //Animstate->m_flEyeYaw = Animstate->m_flCurrentFeetYaw; //Animstate->m_flGoalFeetYaw = 0.0f; //entity->eyeAngles().x = Animstate->m_flPitch; return; }
c++
16
0.572427
211
26.829352
293
starcoderdata
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. """High-level helper class to provide a familiar interface to encrypted tables.""" from functools import partial import attr import botocore try: # Python 3.5.0 and 3.5.1 have incompatible typing modules from typing import Any, Callable, Dict, Iterator, Optional # noqa pylint: disable=unused-import except ImportError: # pragma: no cover # We only actually need these imports when running the mypy checks pass from dynamodb_encryption_sdk.internal.utils import ( crypto_config_from_cache, crypto_config_from_kwargs, decrypt_batch_get_item, decrypt_get_item, decrypt_multi_get, encrypt_batch_write_item, encrypt_put_item, TableInfoCache, validate_get_arguments ) from dynamodb_encryption_sdk.internal.validators import callable_validator from dynamodb_encryption_sdk.material_providers import CryptographicMaterialsProvider from dynamodb_encryption_sdk.structures import AttributeActions from .item import decrypt_dynamodb_item, decrypt_python_item, encrypt_dynamodb_item, encrypt_python_item __all__ = ('EncryptedClient', 'EncryptedPaginator') @attr.s(init=False) class EncryptedPaginator(object): """Paginator that decrypts returned items before returning them. :param paginator: Pre-configured boto3 DynamoDB paginator object :type paginator: botocore.paginate.Paginator :param decrypt_method: Item decryptor method from :mod:`dynamodb_encryption_sdk.encrypted.item` :param callable crypto_config_method: Callable that returns a :class:`CryptoConfig` """ _paginator = attr.ib(validator=attr.validators.instance_of(botocore.paginate.Paginator)) _decrypt_method = attr.ib() _crypto_config_method = attr.ib(validator=callable_validator) def __init__( self, paginator, # type: botocore.paginate.Paginator decrypt_method, # type: Callable crypto_config_method # type: Callable ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 self._paginator = paginator self._decrypt_method = decrypt_method self._crypto_config_method = crypto_config_method attr.validate(self) @_decrypt_method.validator def validate_decrypt_method(self, attribute, value): # pylint: disable=unused-argument """Validate that _decrypt_method is one of the item encryptors.""" if self._decrypt_method not in (decrypt_python_item, decrypt_dynamodb_item): raise ValueError( '"{name}" must be an item decryptor from dynamodb_encryption_sdk.encrypted.item'.format( name=attribute.name ) ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object """ return getattr(self._paginator, name) def paginate(self, **kwargs): # type: (**Any) -> Iterator[Dict] # TODO: narrow this down """Create an iterator that will paginate through responses from the underlying paginator, transparently decrypting any returned items. """ validate_get_arguments(kwargs) crypto_config, ddb_kwargs = self._crypto_config_method(**kwargs) for page in self._paginator.paginate(**ddb_kwargs): for pos, value in enumerate(page['Items']): page['Items'][pos] = self._decrypt_method( item=value, crypto_config=crypto_config ) yield page @attr.s(init=False) class EncryptedClient(object): # pylint: disable=too-few-public-methods,too-many-instance-attributes """High-level helper class to provide a familiar interface to encrypted tables. >>> import boto3 >>> from dynamodb_encryption_sdk.encrypted.client import EncryptedClient >>> from dynamodb_encryption_sdk.material_providers.aws_kms import AwsKmsCryptographicMaterialsProvider >>> client = boto3.client('dynamodb') >>> aws_kms_cmp = AwsKmsCryptographicMaterialsProvider('alias/MyKmsAlias') >>> encrypted_client = EncryptedClient( ... client=client, ... materials_provider=aws_kms_cmp ... ) .. note:: This class provides a superset of the boto3 DynamoDB client API, so should work as a drop-in replacement once configured. https://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#client If you want to provide per-request cryptographic details, the ``put_item``, ``get_item``, ``query``, ``scan``, ``batch_write_item``, and ``batch_get_item`` methods will also accept a ``crypto_config`` parameter, defining a custom :class:`CryptoConfig` instance for this request. .. warning:: We do not currently support the ``update_item`` method. :param client: Pre-configured boto3 DynamoDB client object :type client: boto3.resources.base.BaseClient :param CryptographicMaterialsProvider materials_provider: Cryptographic materials provider to use :param AttributeActions attribute_actions: Table-level configuration of how to encrypt/sign attributes :param bool auto_refresh_table_indexes: Should we attempt to refresh information about table indexes? Requires ``dynamodb:DescribeTable`` permissions on each table. (default: True) :param bool expect_standard_dictionaries: Should we expect items to be standard Python dictionaries? This should only be set to True if you are using a client obtained from a service resource or table resource (ex: ``table.meta.client``). (default: False) """ _client = attr.ib(validator=attr.validators.instance_of(botocore.client.BaseClient)) _materials_provider = attr.ib(validator=attr.validators.instance_of(CryptographicMaterialsProvider)) _attribute_actions = attr.ib( validator=attr.validators.instance_of(AttributeActions), default=attr.Factory(AttributeActions) ) _auto_refresh_table_indexes = attr.ib( validator=attr.validators.instance_of(bool), default=True ) _expect_standard_dictionaries = attr.ib( validator=attr.validators.instance_of(bool), default=False ) def __init__( self, client, # type: botocore.client.BaseClient materials_provider, # type: CryptographicMaterialsProvider attribute_actions=None, # type: Optional[AttributeActions] auto_refresh_table_indexes=True, # type: Optional[bool] expect_standard_dictionaries=False # type: Optional[bool] ): # noqa=D107 # type: (...) -> None # Workaround pending resolution of attrs/mypy interaction. # https://github.com/python/mypy/issues/2088 # https://github.com/python-attrs/attrs/issues/215 if attribute_actions is None: attribute_actions = AttributeActions() self._client = client self._materials_provider = materials_provider self._attribute_actions = attribute_actions self._auto_refresh_table_indexes = auto_refresh_table_indexes self._expect_standard_dictionaries = expect_standard_dictionaries attr.validate(self) self.__attrs_post_init__() def __attrs_post_init__(self): """Set up the table info cache and translation methods.""" if self._expect_standard_dictionaries: self._encrypt_item = encrypt_python_item # attrs confuses pylint: disable=attribute-defined-outside-init self._decrypt_item = decrypt_python_item # attrs confuses pylint: disable=attribute-defined-outside-init else: self._encrypt_item = encrypt_dynamodb_item # attrs confuses pylint: disable=attribute-defined-outside-init self._decrypt_item = decrypt_dynamodb_item # attrs confuses pylint: disable=attribute-defined-outside-init self._table_info_cache = TableInfoCache( # attrs confuses pylint: disable=attribute-defined-outside-init client=self._client, auto_refresh_table_indexes=self._auto_refresh_table_indexes ) self._table_crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_cache, self._materials_provider, self._attribute_actions, self._table_info_cache ) self._item_crypto_config = partial( # attrs confuses pylint: disable=attribute-defined-outside-init crypto_config_from_kwargs, self._table_crypto_config ) self.get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_get_item, self._decrypt_item, self._item_crypto_config, self._client.get_item ) self.put_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_put_item, self._encrypt_item, self._item_crypto_config, self._client.put_item ) self.query = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.query ) self.scan = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_multi_get, self._decrypt_item, self._item_crypto_config, self._client.scan ) self.batch_get_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init decrypt_batch_get_item, self._decrypt_item, self._table_crypto_config, self._client.batch_get_item ) self.batch_write_item = partial( # attrs confuses pylint: disable=attribute-defined-outside-init encrypt_batch_write_item, self._encrypt_item, self._table_crypto_config, self._client.batch_write_item ) def __getattr__(self, name): """Catch any method/attribute lookups that are not defined in this class and try to find them on the provided client object. :param str name: Attribute name :returns: Result of asking the provided client object for that attribute name :raises AttributeError: if attribute is not found on provided client object """ return getattr(self._client, name) def update_item(self, **kwargs): """Update item is not yet supported. :raises NotImplementedError: if called """ raise NotImplementedError('"update_item" is not yet implemented') def get_paginator(self, operation_name): """Get a paginator from the underlying client. If the paginator requested is for "scan" or "query", the paginator returned will transparently decrypt the returned items. :param str operation_name: Name of operation for which to get paginator :returns: Paginator for name :rtype: :class:`botocore.paginate.Paginator` or :class:`EncryptedPaginator` """ paginator = self._client.get_paginator(operation_name) if operation_name in ('scan', 'query'): return EncryptedPaginator( paginator=paginator, decrypt_method=self._decrypt_item, crypto_config_method=self._item_crypto_config ) return paginator
python
16
0.66733
119
43.264085
284
starcoderdata
/* * Decompiled with CFR 0_115. */ package cow.milkgod.cheese.module.modules; import com.darkmagician6.eventapi.EventTarget; import cow.milkgod.cheese.events.EventTick; import cow.milkgod.cheese.module.Category; import cow.milkgod.cheese.module.Module; import net.minecraft.client.Minecraft; public class Fastplace extends Module { public Fastplace() { super("FastPlace", 0, Category.PLAYER, 15120384, true, "Lowers the delay between right clicks", new String[]{"fp", "fastright", "fplace"}); } @EventTarget public void onTick(EventTick event) { Minecraft.getMinecraft(); Minecraft.rightClickDelayTimer = 1; } }
java
8
0.725689
147
26.56
25
starcoderdata
class ActionDecorationError extends Error { constructor (action, message) { super() if (!message) { message = `Tried to add action of type ${action.constructor.name}. It is not of Type Action.` } this.message = message } } module.exports.ActionDecorationError = ActionDecorationError
javascript
8
0.714689
99
28.5
12
starcoderdata
var ImageProcessor = require('./dist/image-processor.min.js'); const gm = require('gm').subClass({ imageMagick: true }); var fs = require('fs'); var event = require('./actual-test-event.json'); var image_blob = event['image_blob'], processed_image_blob = image_blob.split(","), options = event['options'], image_type = event['content_type'], image_blob_buffer, processedImage; var smartCrop = require('./smart-crop.min.js'); processed_image_blob = processed_image_blob.length > 1 ? processed_image_blob[1] : processed_image_blob[0]; image_blob_buffer = new Buffer(processed_image_blob, "base64"); gm(image_blob_buffer, options.image_type).write('./og.jpeg', function (err, data) { if (err) console.log("ERROR", err); console.log("DATA", data); }); console.log(options.crop.width, options.crop.height, options.crop.x, options.crop.y, "CROP PARAMS"); gm(image_blob_buffer, options.image_type).crop(options.crop.width, options.crop.height, options.crop.x, options.crop.y).write('./cropped_image.jpeg', function (err, data) { if (err) console.log("ERROR", err); console.log("DATA", data); }); // event['crop_image_json'] smartCrop.smartCrop(image_blob, { width: 1260, height: 756 }).then(function (result) { console.log(result, "RESULT...................."); var crop_params = result.topCrop; gm(image_blob_buffer, options.image_type).crop(crop_params.width, crop_params.height, crop_params.x, crop_params.y).write('./cropped_image.jpeg', function (err, data) { if (err) console.log("ERROR", err); console.log("DATA", data); }); }).catch(function (err) { console.log(err, "?????"); }); var gifImage = fs.readFileSync('./test.gif').toString('base64'); smartCrop.smartCrop(gifImage, { width: 1260, height: 756 }).then((result) => { console.log(result, "GIF RESULT...................."); var crop_params = result.topCrop, crop_image = new Buffer(gifImage, 'base64'); gm(crop_image, options.image_type).crop(crop_params.width, crop_params.height, crop_params.x, crop_params.y).write('./cropped-gif-image.jpeg', function (err, data) { if (err) console.log("ERROR", err); console.log("DATA", data); }); }).catch(function (err) { console.log(err, "?????"); });
javascript
18
0.656787
172
44.666667
51
starcoderdata
using System.Linq; using System.Threading; using System.Threading.Tasks; using CinemaConstructor.Database.Repositories; using CinemaConstructor.Models.TicketControlViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace CinemaConstructor.Controllers { [Authorize] public class TicketControlController : BaseController { private readonly TicketRepository _ticketRepository; private readonly FilmSessionRepository _filmSessionRepository; public TicketControlController(TicketRepository ticketRepository, FilmSessionRepository filmSessionRepository) { _ticketRepository = ticketRepository; _filmSessionRepository = filmSessionRepository; } [HttpGet] public async Task Index(CancellationToken token) { AddBreadcrumb("Ticket control", "/TicketControl"); var viewModel = new TicketControlViewModel { }; return View(viewModel); } [HttpPost] public async Task Index(TicketControlViewModel model, CancellationToken token, string returnUrl = null) { AddBreadcrumb("Ticket control", "/TicketControl"); ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var tickets = (await _ticketRepository.FindByConfirmationCodeAsync(model.ConfirmationCode, token)).ToList(); if (tickets.Count != 0) { model.FilmSession = await _filmSessionRepository.FindByIdAsync(tickets.First().FilmSession.Id, token); model.Tickets = tickets; } model.IsChecked = true; return View(model); } return View(model); } } }
c#
21
0.646485
126
32.033898
59
starcoderdata
import { CHANGE_CANDIDATE } from '../constants'; const changeCandidate = candidate => ({ type: CHANGE_CANDIDATE, candidate, }); export default changeCandidate;
javascript
7
0.716867
48
19.75
8
starcoderdata
package org.stepik.android.view.glide.mapper; import com.bumptech.glide.load.Options; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.load.model.ModelLoader; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.stepic.droid.configuration.Config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.InputStream; public class RelativeLoaderTest { private RelativeUrlLoader relativeUrlLoader; @Mock Config config; @Mock ModelLoader<GlideUrl, InputStream> loaderFactory; @Before public void beforeEachTest() { MockitoAnnotations.initMocks(this); Mockito.when(config.getBaseUrl()).thenReturn("https://stepik.org"); relativeUrlLoader = new RelativeUrlLoader(loaderFactory, config); } @Test public void handlesTest() { assertTrue(relativeUrlLoader.handles("/topsecret/sandwich.svg")); assertTrue(relativeUrlLoader.handles("/some/addr/http/image.png")); assertTrue(relativeUrlLoader.handles("/some/image/wow.png")); assertFalse(relativeUrlLoader.handles("stepik.org/logo.png")); assertFalse(relativeUrlLoader.handles("https://stepik.org/logo.png")); assertFalse(relativeUrlLoader.handles("")); } @Test public void getUrlTest() { assertEquals( config.getBaseUrl() + "/some/image/wow.png", relativeUrlLoader.getUrl("/some/image/wow.png", 100, 100, new Options())); assertEquals(config.getBaseUrl() + "/some/addr/http/image.png", relativeUrlLoader.getUrl("/some/addr/http/image.png", 100, 100, new Options())); assertEquals(config.getBaseUrl() + "/topsecret/sandwich.svg", relativeUrlLoader.getUrl("/topsecret/sandwich.svg", 100, 100, new Options())); } }
java
10
0.711155
92
33.033898
59
starcoderdata
package com.gdn.x.beirut.domain.event.model; public class DomainEventName { public static final String CANDIDATE_NEW_INSERT = "com.gdn.x.beirut.candidate.new.insert"; public static final String POSITION_NEW_INSERT = "com.gdn.x.beirut.position.new.insert"; public static final String CANDIDATE_UPDATE_STATUS = "com.gdn.x.beirut.candidate.update.status"; public static final String CANDIDATE_MARK_FOR_DELETE = "com.gdn.x.beirut.candidate.mark.for.delete"; public static final String POSITION_MARK_FOR_DELETE = "com.gdn.x.beirut.position.mark.for.delete"; public static final String CANDIDATE_APPLY_NEW_POSITION = "com.gdn.x.beirut.candidate.apply.new.position"; public static final String CANDIDATE_UPDATE_INFORMATION = "com.gdn.x.beirut.candidate.update.information"; public static final String POSITION_UPDATE_INFORMATION = "com.gdn.x.beirut.position.update.information"; }
java
8
0.763441
100
53.705882
17
starcoderdata
<?php if(isset($_POST['user'])) { if($_POST['user']==EMAIL_ADDRESS && $_POST['password']==PASSWORD) { $_SESSION['user'] = EMAIL_ADDRESS; } else { $_GET['logout'] = true; } } if(isset($_GET['logout'])) { unset($_SESSION['user']); $_SESSION = array(); session_unset(); session_destroy(); header('Location: ./'); } if(!isset($_SESSION['user']) || is_null($_SESSION['user']) || $_SESSION['user']=='') { ?><!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./style.css"> <form action="./" method="POST"> <label for="user">E-mail <input type="text" name="user" id="user"> <label for="password">Password <input type="password" name="password" id="password"> <input type="submit" value="Login" /> exit; }
php
11
0.547187
86
22.978261
46
starcoderdata
import React from 'react'; import PropTypes from 'prop-types'; import styles from 'styles/containers/write.module.scss'; import { PromiseButtonItem } from 'components/Button'; const MarkdownSubmit = ({ texts, onClicks, promise }) => { return ( <div className={styles.submitContainer}> <button className={styles.submitContainerExit} type="button" onClick={onClicks.no}> {texts.no} {texts.save ? ( promise ? ( <PromiseButtonItem text={texts.save} className={styles.submitContainerSave} onClick={onClicks.save} /> ) : ( <button className={styles.submitContainerSave} type="button" onClick={onClicks.save}> {texts.save} ) ) : ( )} {promise ? ( <PromiseButtonItem text={texts.yes} className={styles.submitContainerSubmit} onClick={onClicks.yes} /> ) : ( <button className={styles.submitContainerSubmit} type="button" onClick={onClicks.yes}> {texts.yes} )} ); }; MarkdownSubmit.propTypes = { texts: PropTypes.object, onClicks: PropTypes.object, promise: PropTypes.bool, }; export default MarkdownSubmit;
javascript
16
0.596762
95
26.734694
49
starcoderdata
<?php namespace App\Services\Forms; use Illuminate\Support\Str; abstract class BaseQuestion { protected $_id = null; public function getId() { if (isset($this->_id)) return $this->_id; $path = explode('\\', get_called_class()); return Str::kebab(end($path)); } /** * BaseQuestion constructor. */ public function __construct($type, $nextQuestion = null) { } }
php
13
0.555056
60
14.892857
28
starcoderdata
package io.proleap.vb6.asg; import static org.junit.Assert.assertNotNull; import java.io.File; import org.junit.Test; import io.proleap.vb6.VbTestBase; import io.proleap.vb6.asg.metamodel.ClazzModule; import io.proleap.vb6.asg.metamodel.Program; import io.proleap.vb6.asg.runner.impl.VbParserRunnerImpl; public class HelloWorldTest extends VbTestBase { @Test public void test() throws Exception { final File inputFile = new File("src/test/resources/io/proleap/vb6/asg/HelloWorld.cls"); final Program program = new VbParserRunnerImpl().analyzeFile(inputFile); final ClazzModule clazzModule = program.getClazzModule("HelloWorld"); assertNotNull(clazzModule); assertNotNull(clazzModule.getVariable("I")); assertNotNull(clazzModule.getVariable("J")); } }
java
9
0.791872
90
30.269231
26
starcoderdata
#include #include #include #include #include #include using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=50100*2; const int maxBit=21; const int inf=2147483647; int n,K,S[maxN]; int Log2[maxN],Appr[maxN]; class SA { public: int Num[maxN]; int A[maxN],B[maxN],CntA[maxN],CntB[maxN]; int SA[maxN],SSA[maxN],Rank[maxN],Height[maxBit][maxN]; void GetSA(){ for (int i=1;i<=n;i++) CntA[Num[i]]++; for (int i=1;i<maxN;i++) CntA[i]+=CntA[i-1]; for (int i=n;i>=1;i--) SA[CntA[Num[i]]--]=i; Rank[SA[1]]=1; for (int i=2;i<=n;i++){ Rank[SA[i]]=Rank[SA[i-1]]; if (Num[SA[i]]!=Num[SA[i-1]]) Rank[SA[i]]++; } for (int i=1;Rank[SA[n]]!=n;i<<=1){ mem(CntA,0);mem(CntB,0); for (int j=1;j<=n;j++){ CntA[A[j]=Rank[j]]++; CntB[B[j]=((i+j<=n)?(Rank[i+j]):(0))]++; } for (int j=1;j<maxN;j++) CntA[j]+=CntA[j-1],CntB[j]+=CntB[j-1]; for (int j=n;j>=1;j--) SSA[CntB[B[j]]--]=j; for (int j=n;j>=1;j--) SA[CntA[A[SSA[j]]]--]=SSA[j]; Rank[SA[1]]=1; for (int j=2;j<=n;j++){ Rank[SA[j]]=Rank[SA[j-1]]; if ((A[SA[j]]!=A[SA[j-1]])||(B[SA[j]]!=B[SA[j-1]])) Rank[SA[j]]++; } } for (int i=1,j=0;i<=n;i++){ while (Num[i+j]==Num[SA[Rank[i]-1]+j]) j++; Height[0][Rank[i]]=j; if (j) j--; } for (int i=1;i<maxBit;i++) for (int j=1;j+(1<<(i-1))<=n;j++) Height[i][j]=min(Height[i-1][j],Height[i-1][j+(1<<(i-1))]); //for (int i=1;i<=n;i++) cout<<Num[i]<<" ";cout<<endl; //for (int i=1;i<=n;i++) cout<<Rank[i]<<" ";cout<<endl; //for (int i=1;i<=n;i++) cout<<SA[i]<<" ";cout<<endl; //for (int i=1;i<=n;i++) cout<<Height[0][i]<<" ";cout<<endl<<endl; return; } int LCP(int p1,int p2){ if ((p1 return 0; //cout<<"GetLCP:"<<p1<<" "<<p2<<endl; p1=Rank[p1];p2=Rank[p2]; if (p1>p2) swap(p1,p2); //cout<<p1<<" "<<p2<<endl; int lg=Log2[p2-p1]; return min(Height[lg][p1+1],Height[lg][p2-(1<<lg)+1]); } }; SA A,B; int main() { for (int i=1;i<maxN;i++) Log2[i]=log2(i); scanf("%d%d",&n,&K); for (int i=1;i<=n;i++) scanf("%d",&S[i]); for (int i=1;i<n;i++) S[i]=S[i+1]-S[i]; n--; for (int i=1;i<=n;i++) Appr[i]=S[i]; sort(&Appr[1],&Appr[n+1]);int numcnt=unique(&Appr[1],&Appr[n+1])-Appr-1; for (int i=1;i<=n;i++) S[i]=lower_bound(&Appr[1],&Appr[numcnt+1],S[i])-Appr; for (int i=1;i<=n;i++) A.Num[i]=S[i],B.Num[n-i+1]=S[i]; A.GetSA();B.GetSA(); ll Ans=0; for (int len=1;len<=n;len++) for (int i=len;i<=n;i+=len){ int j=i+len+K; if (j>n) continue; int a=A.LCP(i,j),b=B.LCP(n-i+2,n-j+2); //cout<<len<<" ("<<i<<","<<j<<") "<<a<<" "<<b<<" - "; a=min(a,len);b=min(b,len-1); Ans=Ans+max(0,a+b-len+1);//cout<<a+b-len+1<<endl; } printf("%lld\n",Ans); return 0; } /* 12 4 1 2 3 4 8 9 1 2 3 4 8 9 //*/
c++
20
0.514737
77
23.782609
115
starcoderdata
/** * dateToString */ import { __includes } from '../compare/__includes.js'; import { _objectKeys } from '../object/objectKeys.js'; import { _SortFunc } from '../array/_SortFunc.js'; import { __loop } from '../syntax/__loop.js'; import { _replaceAllArray } from '../string/_replaceAllArray.js'; import { isOdd } from '../number/number.js'; import { _includeCount } from '../string/_includeCount.js'; import { __dateToStringRule } from './__dateToStringRule.js'; import { _map } from '../array/_map.js'; export const _dateToString = ( date, format, timezoneOffset, rule = __dateToStringRule.Default(), ) => { const existSingleQuote = __includes(format, "'"); const existDoubleQuote = __includes(format, '"'); if (existSingleQuote && existDoubleQuote) { throw new Error( `__dateToString args(format:${format}) exists both singleQuote and doubleQuote`, ); } const keys = _objectKeys(rule); keys.sort( _SortFunc([ [_SortFunc.order.normal.descending, v => v.length], ]), ); const replaceArray = _map(keys, key => [key, rule[key].func(date, timezoneOffset)], ); let quoteChar; if ((existSingleQuote === false) && (existDoubleQuote === false)) { return _replaceAllArray(format, replaceArray); } else if (existSingleQuote === false) { quoteChar = '"'; } else if (existDoubleQuote === false) { quoteChar = "'"; } if (isOdd(_includeCount(format, quoteChar))) { throw new Error( `__dateToString args(format:${format}) exists odd Quotes`, ); } const formatStrs = format.split(quoteChar); for (let i = 0, l = formatStrs.length; i < l; i += 2) { formatStrs[i] = _replaceAllArray(formatStrs[i], replaceArray); } return formatStrs.join(''); }; _dateToString.rule = __dateToStringRule; export default { _dateToString };
javascript
16
0.641364
86
29.3
60
starcoderdata
<?php namespace App\Handlers\Events\NotificationEventHandlers; use App\Models\UserDevice; use MobileNotification; use Settings; class NewAppointmentNotificationEventHandler { public function handle($event) { if(!config('notifications.enabled')) { return true; } $appointment = $event->appointment; $attendees = $appointment->attendees->pluck('id')->toArray(); //check appointment user if (($user = $appointment->user)) { $attendees[] = $user->id; } if (isset($event->previousData) && !empty($event->previousData)) { $previousData = $event->previousData; $previousAttendees = $previousData['previous_attendees']; $previousAttendees[] = $previousData['previous_user_id']; $attendees = array_diff($attendees, $previousAttendees); } $device = UserDevice::whereIn('user_id', $attendees) ->whereNotNull('device_token') ->count(); if (!$device) { return; } $title = 'New Appointment'; if ($appointment->customer) { $info = 'You have a new appointment with ' . $appointment->customer->full_name_mobile; } else { $info = $appointment->title; } $type = 'new_appointment'; $data = [ 'company_id' => $appointment->company_id, ]; foreach (array_unique($attendees) as $userId) { $timezone = Settings::forUser($userId)->get('TIME_ZONE'); $dateTime = convertTimezone($appointment->start_date_time, $timezone); $message = $info . ' at ' . $dateTime->format('h:ia') . ' on ' . $dateTime->format('m-d-Y'); MobileNotification::send($userId, $title, $type, $message, $data); } } }
php
16
0.56946
104
29.233333
60
starcoderdata
"""Tests for spiketools.plts.trials""" import numpy as np from spiketools.tests.tutils import plot_test from spiketools.tests.tsettings import TEST_PLOTS_PATH from spiketools.plts.trials import * ################################################################################################### ################################################################################################### @plot_test def test_plot_rasters(): data0 = [-500, -250, 250, 100] data1 = [[-750, -300, 125, 250, 750], [-500, -400, -50, 100, 125, 500, 800], [-850, -500, -250, 100, 400, 750, 950]] data2 = [data1, [[-400, 150, 500], [-500, 250, 800]]] plot_rasters(data0, file_path=TEST_PLOTS_PATH, file_name='tplot_rasters0.png') plot_rasters(data1, file_path=TEST_PLOTS_PATH, file_name='tplot_rasters1.png') plot_rasters(data2, colors=['blue', 'red'], file_path=TEST_PLOTS_PATH, file_name='tplot_rasters2.png') @plot_test def test_plot_firing_rates(): x_vals = np.array([1, 2, 3, 4, 5]) y_vals1 = np.array([[2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [4, 4, 4, 4, 4]]) y_vals2 = np.array([[3, 3, 3, 3, 3], [4, 4, 4, 4, 4], [5, 5, 5, 5, 5]]) plot_firing_rates(x_vals, np.mean(y_vals1, 0), file_path=TEST_PLOTS_PATH, file_name='tplot_firing_rates1.png') plot_firing_rates(x_vals, [y_vals1, y_vals2], average='median', shade='sem', labels=['A', 'B'], stats=[0.5, 0.01, 0.5, 0.01, 0.5], file_path=TEST_PLOTS_PATH, file_name='tplot_firing_rates2.png')
python
10
0.503783
99
38.65
40
starcoderdata
public Collection buscarValidacionesCruzadas(Long idVac) { final List listadoAlertas = new ArrayList(); CatalogoVaciados catalogo = new CatalogoVaciadosImpl(); Encabezado enc = catalogo.buscarEncabezado(idVac); if (enc != null) { if (enc.isBalanceDescuadrado()) { listadoAlertas.add(createAlertaInvalidante(MSG_BALANCE_DESCUADRADO)); } if (enc.isUtilidadDescuadrada()) { listadoAlertas.add(createAlertaInvalidante(MSG_UTILIDAD_DESCUADRADA)); } } /* me ahorro toda esta parafernalia sin sentido: * boolean esVaciadoAjustado = vac.getAjustadoFlg().equals(ConstantesSEFE.FLAG_VACIADO_AJUSTADO) || ConstantesSEFE.CLASIF_ID_NO_APLICA.equals(vac.getIdTipoBalance()); if (log.isDebugEnabled()) { log.debug("Realizando la busqueda de validaciones cruzadas"); } // Se realiza la busqueda del listado de Validaciones correspondientes a ese vaciado y el plan de cuentas. GestorAlertas gestorAlert = new GestorAlertasImpl(); ArrayList listValidaciones = (ArrayList) gestorAlert.buscarValidacionesCruzadas(idVac, vac.getIdNombrePlanCtas()); GestorPlanCuentasImpl gestorPlan = new GestorPlanCuentasImpl(); ArrayList listadoAlertas = new ArrayList(); if (log.isDebugEnabled()) { log.debug("Iterando las Validaciones Cruzadas Obtenidas"); } // Se realiza la iteracion de las validaciones obtenidas. Iterator iterador = listValidaciones.iterator(); while (iterador.hasNext()) { ValidacionCruzada validacion = (ValidacionCruzada) iterador.next(); if (log.isDebugEnabled()) { log.debug("Consultando el valor de la cuenta:" + validacion.getIdCuenta()); } // Por cada validacion se realiza la consulta del valor de la Cuenta. Long idCuenta = validacion.getIdCuenta(); Cuenta cuenta = gestorPlan.consultarValorCuentaVaciado(idVac, idCuenta); // Por cada validacion se realiza la consulta del valor de la Cuenta Par. Long idCuentaPar = validacion.getIdCuentaPar(); if (log.isDebugEnabled()) { log.debug("Consultando el valor de la cuenta par:" + idCuentaPar); } Cuenta cuentaPar = gestorPlan.consultarValorCuentaVaciado(idVac, idCuentaPar); // Se realiza la evaluacion de la condicion de dicha validacion con los valores obtenidos. if (!evaluarCondicion(validacion.getCondicion(), cuenta, cuentaPar, esVaciadoAjustado)) { if (log.isDebugEnabled()) { if (cuenta == null || cuentaPar == null) { log.debug("No se cumplio la condicion, ya que una de las cuentas es null."); } else { log.debug("No se cumplio la condicion:" + cuenta.getMonto() + validacion.getCondicion() + cuentaPar.getMonto()); } } // Si la condicion no se cumple, se instancia la alerta Alerta alert = new Alerta(); alert.setMensaje(validacion.getMensaje()); alert.setNivel(ConstantesSEFE.ALERT_INVALIDANTE); // Dicha alerta se agrega al listado de retorno. listadoAlertas.add(alert); } } */ // Se realiza la busqueda del vaciado. GestorVaciados gestorVac = new GestorVaciadosImpl(); Vaciado vac = gestorVac.buscarVaciado(idVac); //Se corrige defecto que no validaba el balance descuadrado de un vaciado consolidado antes de cambiar de estado // Se agrega de ser necesario la alerta en caso que el vaciado anterior no se encuentre vigente aun. Alerta alertaVacAnterior = evaluarAlertaPoseeVaciadoAnterior(vac); if (alertaVacAnterior != null) { listadoAlertas.add(alertaVacAnterior); } Alerta alertaTotalActivos = evaluarAlertaTotalActivos(vac); if (alertaTotalActivos != null) { listadoAlertas.add(alertaTotalActivos); } Alerta alertaTotalPasivos = evaluarAlertaTotalPasivos(vac); if (alertaTotalPasivos != null) { listadoAlertas.add(alertaTotalPasivos); } return listadoAlertas; }
java
12
0.716387
165
36.386139
101
inline
var assert = require('assert'); var assign = require('../../../cartridges/lodash/assign'); var assignIn = require('../../../cartridges/lodash/assignIn'); var constant = require('../../../cartridges/lodash/constant'); var each = require('../../../cartridges/lodash/each'); var { stubOne, noop, stubNaN } = require('../helpers/stubs'); var defineProperty = Object.defineProperty; describe('assign and assignIn', function () { each(['assign', 'assignIn'], function (methodName) { var func = (function () { switch (methodName) { case 'assign': return assign; case 'assignIn': return assignIn; default: return null; } }()); it('`_.' + methodName + '` should assign source properties to `object`', function () { assert.deepStrictEqual(func({ 'a': 1 }, { 'b': 2 }), { 'a': 1, 'b': 2 }); }); it('`_.' + methodName + '` should accept multiple sources', function () { var expected = { 'a': 1, 'b': 2, 'c': 3 }; assert.deepStrictEqual(func({ 'a': 1 }, { 'b': 2 }, { 'c': 3 }), expected); assert.deepStrictEqual(func({ 'a': 1 }, { 'b': 2, 'c': 2 }, { 'c': 3 }), expected); }); it('`_.' + methodName + '` should overwrite destination properties', function () { var expected = { 'a': 3, 'b': 2, 'c': 1 }; assert.deepStrictEqual(func({ 'a': 1, 'b': 2 }, expected), expected); }); it('`_.' + methodName + '` should assign source properties with nullish values', function () { var expected = { 'a': null, 'b': undefined, 'c': null }; assert.deepStrictEqual(func({ 'a': 1, 'b': 2 }, expected), expected); }); it('`_.' + methodName + '` should skip assignments if values are the same', function () { var object = {}; var descriptor = { 'configurable': true, 'enumerable': true, 'set': function () { throw new Error(); } }; var source = { 'a': 1, 'b': undefined, 'c': NaN, 'd': undefined, 'constructor': Object, 'toString': constant('source') }; defineProperty(object, 'a', assign({}, descriptor, { 'get': stubOne })); defineProperty(object, 'b', assign({}, descriptor, { 'get': noop })); defineProperty(object, 'c', assign({}, descriptor, { 'get': stubNaN })); defineProperty(object, 'constructor', assign({}, descriptor, { 'get': constant(Object) })); try { var actual = func(object, source); } catch (e) { // DO NOTHING } assert.deepStrictEqual(actual, source); }); it('`_.' + methodName + '` should treat sparse array sources as dense', function () { var array = [1]; array[2] = 3; assert.deepStrictEqual(func({}, array), { '0': 1, '1': undefined, '2': 3 }); }); it('`_.' + methodName + '` should assign values of prototype objects', function () { function Foo() {} Foo.prototype.a = 1; assert.deepStrictEqual(func({}, Foo.prototype), { 'a': 1 }); }); it('`_.' + methodName + '` should coerce string sources to objects', function () { assert.deepStrictEqual(func({}, 'a'), { '0': 'a' }); }); }); });
javascript
21
0.471246
102
34.970588
102
starcoderdata
import _ from 'lodash'; // simple 'hacky' method to plurarize words export function pluralize(word, count) { let pluralized = word; if (count !== 1) { pluralized = word.endsWith('y') ? word.slice(0, -1).concat('ies') : word.concat('s'); } return `${count} ${pluralized}`; } // parse an array of tags from an input string export function parseTags(inputString) { const matches = inputString.match(/#\w+/g) || []; return matches.map(match => match.replace(/^#/, '')); } // summarize and count an array of tags with provided pathname export function summarizeTags(values) { const tagsMap = values.reduce((tagsCount, value) => { if (!tagsCount[value]) { tagsCount[value] = 0; } tagsCount[value] += 1; return tagsCount; }, {}); const tags = Object.keys(tagsMap).map(value => ({ count: tagsMap[value], value, })); return _.orderBy(tags, ['count', 'value'], ['desc', 'asc']); }
javascript
19
0.62487
62
26.571429
35
starcoderdata
/* ======================================================================== * Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using OMP.Connector.Infrastructure.OpcUa.ComplexTypes.Types; using Opc.Ua; namespace OMP.Connector.Infrastructure.OpcUa.ComplexTypes.TypeBuilder { /// /// Build an assembly with custom enum types and /// complex types based on the BaseComplexType class /// using System.Reflection.Emit. /// public class ComplexTypeBuilder : IComplexTypeBuilder { #region Constructors /// /// Initializes the object with default values. /// public ComplexTypeBuilder( AssemblyModule moduleFactory, string targetNamespace, int targetNamespaceIndex, string moduleName = null) { this.m_targetNamespace = targetNamespace; this.m_targetNamespaceIndex = targetNamespaceIndex; this.m_moduleName = this.FindModuleName(moduleName, targetNamespace, targetNamespaceIndex); this.m_moduleBuilder = moduleFactory.GetModuleBuilder(); } #endregion #region Public Members public string TargetNamespace => this.m_targetNamespace; public int TargetNamespaceIndex => this.m_targetNamespaceIndex; /// /// Create an enum type from a binary schema definition. /// Available before OPC UA V1.04. /// public Type AddEnumType(Opc.Ua.Schema.Binary.EnumeratedType enumeratedType) { if (enumeratedType == null) { throw new ArgumentNullException(nameof(enumeratedType)); } var enumBuilder = this.m_moduleBuilder.DefineEnum( this.GetFullQualifiedTypeName(enumeratedType.Name), TypeAttributes.Public, typeof(int)); enumBuilder.DataContractAttribute(this.m_targetNamespace); foreach (var enumValue in enumeratedType.EnumeratedValue) { var newEnum = enumBuilder.DefineLiteral(enumValue.Name, enumValue.Value); newEnum.EnumMemberAttribute(enumValue.Name, enumValue.Value); } return enumBuilder.CreateTypeInfo(); } /// /// Create an enum type from an EnumDefinition in an ExtensionObject. /// Available since OPC UA V1.04 in the DataTypeDefinition attribute. /// public Type AddEnumType(QualifiedName typeName, ExtensionObject typeDefinition) { var enumDefinition = typeDefinition.Body as EnumDefinition; if (enumDefinition == null) { throw new ArgumentNullException(nameof(typeDefinition)); } var enumBuilder = this.m_moduleBuilder.DefineEnum( this.GetFullQualifiedTypeName(typeName), TypeAttributes.Public, typeof(int)); enumBuilder.DataContractAttribute(this.m_targetNamespace); foreach (var enumValue in enumDefinition.Fields) { var newEnum = enumBuilder.DefineLiteral(enumValue.Name, (int)enumValue.Value); newEnum.EnumMemberAttribute(enumValue.Name, (int)enumValue.Value); } return enumBuilder.CreateTypeInfo(); } /// /// Create an enum type from an EnumValue property of a DataType node. /// Available before OPC UA V1.04. /// public Type AddEnumType(QualifiedName typeName, ExtensionObject[] enumDefinition) { if (enumDefinition == null) { throw new ArgumentNullException(nameof(enumDefinition)); } var enumBuilder = this.m_moduleBuilder.DefineEnum( this.GetFullQualifiedTypeName(typeName), TypeAttributes.Public, typeof(int)); enumBuilder.DataContractAttribute(this.m_targetNamespace); foreach (var extensionObject in enumDefinition) { var enumValue = extensionObject.Body as EnumValueType; var name = enumValue.DisplayName.Text; var newEnum = enumBuilder.DefineLiteral(name, (int)enumValue.Value); newEnum.EnumMemberAttribute(name, (int)enumValue.Value); } return enumBuilder.CreateTypeInfo(); } /// /// Create an enum type from the EnumString array of a DataType node. /// Available before OPC UA V1.04. /// public Type AddEnumType(QualifiedName typeName, LocalizedText[] enumDefinition) { if (enumDefinition == null) { throw new ArgumentNullException(nameof(enumDefinition)); } var enumBuilder = this.m_moduleBuilder.DefineEnum( this.GetFullQualifiedTypeName(typeName), TypeAttributes.Public, typeof(int)); enumBuilder.DataContractAttribute(this.m_targetNamespace); int value = 0; foreach (var enumValue in enumDefinition) { var name = enumValue.Text; var newEnum = enumBuilder.DefineLiteral(name, value); newEnum.EnumMemberAttribute(name, value); value++; } return enumBuilder.CreateTypeInfo(); } /// /// Create a complex type from a StructureDefinition. /// Available since OPC UA V1.04 in the DataTypeDefinition attribute. /// public IComplexTypeFieldBuilder AddStructuredType( QualifiedName name, StructureDefinition structureDefinition) { if (structureDefinition == null) { throw new ArgumentNullException(nameof(structureDefinition)); } Type baseType; switch (structureDefinition.StructureType) { case StructureType.StructureWithOptionalFields: baseType = typeof(OptionalFieldsComplexType); break; case StructureType.Union: baseType = typeof(UnionComplexType); break; case StructureType.Structure: default: baseType = typeof(BaseComplexType); break; } var structureBuilder = this.m_moduleBuilder.DefineType( this.GetFullQualifiedTypeName(name), TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable, baseType); structureBuilder.DataContractAttribute(this.m_targetNamespace); structureBuilder.StructureDefinitonAttribute(structureDefinition); return new ComplexTypeFieldBuilder(structureBuilder, structureDefinition.StructureType); } #endregion #region Private Members /// /// Create a unique namespace module name for the type. /// private string FindModuleName(string moduleName, string targetNamespace, int targetNamespaceIndex) { if (String.IsNullOrWhiteSpace(moduleName)) { Uri uri = new Uri(targetNamespace, UriKind.RelativeOrAbsolute); var tempName = uri.IsAbsoluteUri ? uri.AbsolutePath : uri.ToString(); tempName = tempName.Replace("/", ""); var splitName = tempName.Split(':'); moduleName = splitName.Last(); } return moduleName; } /// /// Creates a unique full qualified type name for the assembly. /// /// <param name="browseName">The browse name of the type. private string GetFullQualifiedTypeName(QualifiedName browseName) { var result = "Opc.Ua.ComplexTypes." + this.m_moduleName + "."; if (browseName.NamespaceIndex > 1) { result += browseName.NamespaceIndex + "."; } return result + this.ReplaceInvalidCSharpSymbolChars(browseName.Name); } private string ReplaceInvalidCSharpSymbolChars(string browseName) { var newChar = "_"; return browseName .Replace(" ", newChar) .Replace("-", newChar) .Replace(".", newChar) .Replace("\"", string.Empty); } #endregion #region Private Fields private ModuleBuilder m_moduleBuilder; private string m_targetNamespace; private string m_moduleName; private int m_targetNamespaceIndex; #endregion } }
c#
18
0.609144
116
39.960159
251
starcoderdata
/* * Copyright 2015 * * 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.killbill.billing.plugin.simpletax.resolving.fixtures; import java.math.BigDecimal; import org.killbill.billing.invoice.api.InvoiceItem; import org.killbill.billing.plugin.simpletax.TaxComputationContext; import org.killbill.billing.plugin.simpletax.internal.TaxCode; import org.killbill.billing.plugin.simpletax.resolving.NullTaxResolver; import org.killbill.billing.plugin.simpletax.resolving.TaxResolver; import org.killbill.billing.test.helpers.TaxCodeBuilder; /** * @author */ @SuppressWarnings("javadoc") public abstract class AbstractTaxResolver implements TaxResolver { protected static final TaxCode TAX_CODE = new TaxCodeBuilder().withRate(new BigDecimal("0.0314")).build(); public AbstractTaxResolver(TaxComputationContext ctx) { } /** * We return a non-zero tax rate here in order to differentiate the tax * resolvers of this hierarchy from the {@link NullTaxResolver}. */ @Override public TaxCode applicableCodeForItem(Iterable taxCodes, InvoiceItem item) { return TAX_CODE; } }
java
11
0.759398
110
35.041667
48
starcoderdata
from tensorflow.keras import layers from tensorflow.keras import Model from tensorflow.keras import regularizers import tensorflow as tf from convRFF.models.convRFF import ConvRFF from convRFF.models.RFF import RFF from functools import partial DefaultConv2D = partial(layers.Conv2D, kernel_size=3, activation='relu', padding="same") DefaultPooling = partial(layers.MaxPool2D, pool_size=2) DefaultConvRFF = partial(ConvRFF, kernel_size=3, padding="SAME", kernel_regularizer = regularizers.l2(1e-4), trainable_scale=True, trainable_W=True, ) DefaultTranspConv = partial(layers.Conv2DTranspose, kernel_size=3, strides=2, padding='same', use_bias=False, activation='relu') def kernel_initializer(seed): return tf.keras.initializers.GlorotUniform(seed=seed) def get_model(input_shape=(128,128,3),name='FCNConvRFF', kernel_regularizer=regularizers.l2(1e-4), normalization=False,phi_units=2,out_channels=1, type_layer='cRFF',padding='SAME',kernel_size=3, trainable_scale=True, trainable_W=True,**kwargs): # Encoder input = layers.Input(shape=(128,128,3)) x = layers.BatchNormalization()(input) x = DefaultConv2D(32,kernel_initializer=kernel_initializer(34),name='Conv10')(x) x = DefaultConv2D(32,kernel_initializer=kernel_initializer(4),name='Conv11')(x) x = layers.BatchNormalization(name='Batch10')(x) x = DefaultPooling()(x) # 128x128 -> 64x64 x = DefaultConv2D(32,kernel_initializer=kernel_initializer(56),name='Conv20')(x) x = DefaultConv2D(32,kernel_initializer=kernel_initializer(28),name='Conv21')(x) x = layers.BatchNormalization(name='Batch20')(x) x = DefaultPooling()(x) # 64x64 -> 32x32 x = DefaultConv2D(64,kernel_initializer=kernel_initializer(332),name='Conv30')(x) x = DefaultConv2D(64,kernel_initializer=kernel_initializer(2),name='Conv31')(x) x = layers.BatchNormalization(name='Batch30')(x) x = level_1 = DefaultPooling()(x) # 32x32 -> 16x16 x = DefaultConv2D(128,kernel_initializer=kernel_initializer(67),name='Conv40')(x) x = DefaultConv2D(128,kernel_initializer=kernel_initializer(89),name='Conv41')(x) x = layers.BatchNormalization(name='Batch40')(x) x = level_2 = DefaultPooling()(x) # 16x16 -> 8x8 x = DefaultConv2D(256,kernel_initializer=kernel_initializer(7),name='Conv50')(x) x = DefaultConv2D(256,kernel_initializer=kernel_initializer(23),name='Conv51')(x) x = layers.BatchNormalization(name='Batch50')(x) x = DefaultPooling()(x) # 8x8 -> 4x4 scale = 32 if type_layer == 'cRFF': x = DefaultConvRFF(phi_units, trainable_scale=trainable_scale, normalization=normalization, kernel_regularizer=kernel_regularizer, kernel_size=kernel_size, padding=padding, trainable_W=trainable_W, name='RFF', seed=42)(x) elif type_layer=='RFF': x = RFF(x,input_shape[0],input_shape[1],phi_units,scale,trainable=trainable_scale,name='RFF',seed=42) else: x = layers.Lambda(lambda x: x,name='RFF')(x) x = layers.Reshape((int(input_shape[0]/scale),int(input_shape[1]/scale),-1),name='Reshape')(x) x = level_3 = DefaultTranspConv(out_channels,kernel_size=4,use_bias=False, kernel_initializer=kernel_initializer(98),name='Trans60')(x) x = DefaultConv2D(out_channels,kernel_size=1,activation=None,kernel_initializer=kernel_initializer(75),name='Conv60')(level_2) x = layers.Add()([x,level_3]) x = level_4 = DefaultTranspConv(out_channels,kernel_size=4,use_bias=False,kernel_initializer=kernel_initializer(87),name='Trans70')(x) x = DefaultConv2D(out_channels,kernel_size=1,activation=None,kernel_initializer=kernel_initializer(54),name='Conv70')(level_1) x = layers.Add()([x,level_4]) x = DefaultTranspConv(1,kernel_size=16,strides=8,activation='sigmoid',use_bias=True,kernel_initializer=kernel_initializer(32),name='Trans80')(x) model = Model(input,x,name=name) return model if __name__ == '__main__': model = get_model(type_layer='cRFF') model.summary()
python
13
0.632359
148
40.072727
110
starcoderdata
package com.cloud.server.client.controller.auth; import com.alibaba.fastjson.JSON; import com.cloud.server.client.common.back.auth.personal.AuthPerson; import com.cloud.server.client.common.back.auth.personal.AuthResultPerson; import com.cloud.server.client.common.config.ApiConstant; import com.cloud.server.client.common.config.AuthStatusEntEnum; import com.cloud.server.client.common.config.AuthStatusPersonEnum; import com.cloud.server.client.common.request.auth.AuthPersonEntity; import com.cloud.server.client.entity.CloudAuthRecordInfo; import com.cloud.service.common.annotation.ValidatedParam; import com.cloud.service.common.enums.AuthEnum; import com.cloud.service.common.exception.BusinessException; import com.cloud.service.common.response.ApiResult; import com.cloud.service.common.response.CommonCodeEnum; import com.cloud.service.common.utils.BeanUtil; import com.cloud.service.common.utils.PrimaryKeyUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; /** * 实名鉴权接口 * @author wentao.qiao * @date 2020/04/30. */ @RestController @RequestMapping(value = "/api/v1.0") @Slf4j public class AuthPersonController extends BaseAuthController { private static final String API_DESC = "个人实名鉴权接口"; private static final String RSP_CODE = CommonCodeEnum.COMMON_USE.code(); @ValidatedParam(methodDesc = API_DESC) @RequestMapping(value = "/auth/person", method = {RequestMethod.POST}) public ApiResult authPerson(@RequestBody AuthPersonEntity authPersonEntity){ log.info("{}开始", API_DESC); if(log.isDebugEnabled()){ log.debug("{}请求参数:{}", API_DESC, authPersonEntity); } String primaryKey = PrimaryKeyUtils.getPrimaryKey(); String authCode = authPersonEntity.getAuthCode(); try{ // 用户相关校验 String checkRequestNo = checkRequestNo(authPersonEntity.getRequestNo()); if(checkRequestNo != null){ log.error("{}流水号重复", API_DESC); return ApiResult.buildApiResult(false,RSP_CODE,checkRequestNo); } }catch (Exception e){ log.error("{}校验用户服务异常:{}", API_DESC, e.getMessage()); return ApiResult.buildApiResult(CommonCodeEnum.ERROR); } try{ //初始化鉴权详情表和鉴权记录表 authService.initAuthInfoTable(primaryKey , JSON.toJSONString(authPersonEntity), authCode, authPersonEntity.getRequestNo(),authPersonEntity.getCustomerNo(),AuthEnum.PERSON); //鉴权开始 AuthResult authPersonal = authPersonal(authPersonEntity,authCode, primaryKey); if(!authPersonal.isFlag()){ return ApiResult.buildApiResult(false,RSP_CODE,authPersonal.getErrorMsg()); }else{ Map<String, Object> body = new HashMap<> (2); body.put("requestNo", authPersonEntity.getRequestNo()); return ApiResult.buildApiResult(CommonCodeEnum.SUCCESS.success(),CommonCodeEnum.SUCCESS.code(), "鉴权通过",body); } }catch (BusinessException e){ log.error("{}鉴权失败BusinessException:{}", API_DESC, e.getMessage()); return ApiResult.buildApiResult(false,RSP_CODE,e.getMessage()); }catch (Exception e){ log.error("{}鉴权失败,Exception错误信息:{}", API_DESC, e.getMessage()); return ApiResult.buildApiResult(CommonCodeEnum.ERROR); } } /** * 个人信息鉴权 * @param primaryKey 记录表主键 * @param entity 请求实体 * @param code 鉴权类型 * @return AuthResult 鉴权信息 */ private AuthResult authPersonal(AuthPersonEntity entity,String code,String primaryKey) throws BusinessException { boolean flag = false; AuthResult authResult; authResult = new AuthResult(); AuthPerson personal = new AuthPerson(); if(StringUtils.equals(AuthEnum.LIMIT2.val(), code) || StringUtils.equals(AuthEnum.LIMIT.val(), code) || StringUtils.equals(AuthEnum.LIMIT3.val(), code)){ personal.setCardHolder(entity.getCardHolder()); personal.setCredNum(entity.getCredNum()); } if(StringUtils.equals(AuthEnum.LIMIT3.val(), code) || StringUtils.equals(AuthEnum.LIMIT.val(), code)){ if(!StringUtils.isEmpty(entity.getCardNo())){ personal.setCardNo(entity.getCardNo()); }else{ authResult.setFlag(false); authResult.setErrorMsg("银行卡号不能为空"); return authResult; } } if(StringUtils.equals(AuthEnum.LIMIT.val(), code)){ if(!StringUtils.isEmpty(entity.getMobile())){ personal.setMobile(entity.getMobile()); }else{ authResult.setFlag(false); authResult.setErrorMsg("预留手机号不能为空"); return authResult; } } personal.setRequestNo(primaryKey); personal.setBank(entity.getBank()); personal.setAuthMode(code); //进行个人用户信息鉴定开始 AuthResultPerson authResultPersonal = authService.authPerson(personal); if(authResultPersonal == null){ authResult.setFlag(false); authResult.setErrorMsg("服务开小差了,请联系技术支持人员!"); return authResult; } BeanUtil.copyEntity(authResultPersonal, authResult); //0-调本地黑库 1-调鉴权通道 int useChannel = authResultPersonal.getUseChannel(); //构建鉴权记录实体 CloudAuthRecordInfo cloudAuthRecord = new CloudAuthRecordInfo(); cloudAuthRecord.setId(primaryKey); cloudAuthRecord.setResponseTime(authResultPersonal.getResponseTime()); if(useChannel == ApiConstant.UN_USE_CHANNEL){ //调用本地库验证通过 cloudAuthRecord.setUseChannel(ApiConstant.UN_USE_CHANNEL); cloudAuthRecord.setStatus(AuthStatusPersonEnum.SUCCESS.getKey()); log.info("在本地库鉴权通过:<---身份证号码为:" + entity.getCredNum()); flag = true; }else if(useChannel == ApiConstant.USE_CHANNEL){ int status = authResultPersonal.getStatus(); cloudAuthRecord.setUseChannel(ApiConstant.USE_CHANNEL); if(status == 0){ cloudAuthRecord.setStatus(AuthStatusEntEnum.SUCCESS.getKey()); log.info("使用鉴权通道通过:<---身份证号码为:" + entity.getCredNum()); flag = true; }else{ cloudAuthRecord.setStatus(AuthStatusEntEnum.FAILURE.getKey()); log.error("鉴权不通过:<---身份证号码为:{},错误信息:{}", entity.getCredNum(), authResultPersonal.getErrorMessage()); authResult.setErrorMsg(authResultPersonal.getErrorMessage()); flag = false; } } //更新鉴权记录表 int flag1 = authService.updateAuthUserRecord(cloudAuthRecord); if(flag1 != 1){ log.error("鉴权记录更新失败"); throw new BusinessException("鉴权失败---鉴权记录更新失败"); } authResult.setFlag(flag); return authResult; } }
java
16
0.645655
116
43.173653
167
starcoderdata
package com.fire.sdk.model.response; import com.fire.sdk.model.Account; import com.fire.sdk.model.Response; public class MandateResponse extends Account implements Response { }
java
4
0.798354
83
21.090909
11
starcoderdata
@Override public MethodVisitor visitMethod( int access, String name, String descriptor, String signature, String[] exceptions) { if (coreLibrarySupport.preserveOriginalMethod(access, internalName, name, descriptor)) { if (BitFlags.isSynthetic(access)) { // Idempotency: this is the preserved override, which we mark synthetic for simplicity. return cv != null ? cv.visitMethod(access, name, descriptor, signature, exceptions) : null; } else { PreservedMethod preserve = PreservedMethod.create(access, name, descriptor, signature, exceptions); preserveOriginals.put(name + ":" + descriptor, preserve); } } return super.visitMethod(access, name, descriptor, signature, exceptions); }
java
13
0.696732
99
50.066667
15
inline
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using Analyzer.Utilities; using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.CopyAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis; using Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.ValueContentAnalysis; #pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis { using CopyAnalysisResult = DataFlowAnalysisResult<CopyBlockAnalysisResult, CopyAbstractValue>; using ValueContentAnalysisResult = DataFlowAnalysisResult<ValueContentBlockAnalysisResult, ValueContentAbstractValue>; using DisposeAnalysisData = DictionaryAnalysisData<AbstractLocation, DisposeAbstractValue>; using InterproceduralDisposeAnalysisData = InterproceduralAnalysisData<DictionaryAnalysisData<AbstractLocation, DisposeAbstractValue>, DisposeAnalysisContext, DisposeAbstractValue>; /// /// Analysis context for execution of <see cref="DisposeAnalysis"/> on a control flow graph. /// public sealed class DisposeAnalysisContext : AbstractDataFlowAnalysisContext<DisposeAnalysisData, DisposeAnalysisContext, DisposeAnalysisResult, DisposeAbstractValue> { private DisposeAnalysisContext( AbstractValueDomain valueDomain, WellKnownTypeProvider wellKnownTypeProvider, ControlFlowGraph controlFlowGraph, ISymbol owningSymbol, InterproceduralAnalysisConfiguration interproceduralAnalysisConfig, bool pessimisticAnalysis, bool exceptionPathsAnalysis, PointsToAnalysisResult pointsToAnalysisResultOpt, Func<DisposeAnalysisContext, DisposeAnalysisResult> tryGetOrComputeAnalysisResult, ImmutableHashSet disposeOwnershipTransferLikelyTypes, bool disposeOwnershipTransferAtConstructor, bool disposeOwnershipTransferAtMethodCall, bool trackInstanceFields, ControlFlowGraph parentControlFlowGraphOpt, InterproceduralDisposeAnalysisData interproceduralAnalysisDataOpt, InterproceduralAnalysisPredicate interproceduralAnalysisPredicateOpt) : base(valueDomain, wellKnownTypeProvider, controlFlowGraph, owningSymbol, interproceduralAnalysisConfig, pessimisticAnalysis, predicateAnalysis: false, exceptionPathsAnalysis, copyAnalysisResultOpt: null, pointsToAnalysisResultOpt, valueContentAnalysisResultOpt: null, tryGetOrComputeAnalysisResult, parentControlFlowGraphOpt, interproceduralAnalysisDataOpt, interproceduralAnalysisPredicateOpt) { DisposeOwnershipTransferLikelyTypes = disposeOwnershipTransferLikelyTypes; DisposeOwnershipTransferAtConstructor = disposeOwnershipTransferAtConstructor; DisposeOwnershipTransferAtMethodCall = disposeOwnershipTransferAtMethodCall; TrackInstanceFields = trackInstanceFields; } internal static DisposeAnalysisContext Create( AbstractValueDomain valueDomain, WellKnownTypeProvider wellKnownTypeProvider, ControlFlowGraph controlFlowGraph, ISymbol owningSymbol, InterproceduralAnalysisConfiguration interproceduralAnalysisConfig, InterproceduralAnalysisPredicate interproceduralAnalysisPredicateOpt, bool pessimisticAnalysis, bool exceptionPathsAnalysis, PointsToAnalysisResult pointsToAnalysisResultOpt, Func<DisposeAnalysisContext, DisposeAnalysisResult> tryGetOrComputeAnalysisResult, ImmutableHashSet disposeOwnershipTransferLikelyTypes, bool disposeOwnershipTransferAtConstructor, bool disposeOwnershipTransferAtMethodCall, bool trackInstanceFields) { return new DisposeAnalysisContext( valueDomain, wellKnownTypeProvider, controlFlowGraph, owningSymbol, interproceduralAnalysisConfig, pessimisticAnalysis, exceptionPathsAnalysis, pointsToAnalysisResultOpt, tryGetOrComputeAnalysisResult, disposeOwnershipTransferLikelyTypes, disposeOwnershipTransferAtConstructor, disposeOwnershipTransferAtMethodCall, trackInstanceFields, parentControlFlowGraphOpt: null, interproceduralAnalysisDataOpt: null, interproceduralAnalysisPredicateOpt); } public override DisposeAnalysisContext ForkForInterproceduralAnalysis( IMethodSymbol invokedMethod, ControlFlowGraph invokedControlFlowGraph, IOperation operation, PointsToAnalysisResult pointsToAnalysisResultOpt, CopyAnalysisResult copyAnalysisResultOpt, ValueContentAnalysisResult valueContentAnalysisResultOpt, InterproceduralDisposeAnalysisData interproceduralAnalysisData) { Debug.Assert(pointsToAnalysisResultOpt != null); Debug.Assert(copyAnalysisResultOpt == null); Debug.Assert(valueContentAnalysisResultOpt == null); return new DisposeAnalysisContext(ValueDomain, WellKnownTypeProvider, invokedControlFlowGraph, invokedMethod, InterproceduralAnalysisConfiguration, PessimisticAnalysis, ExceptionPathsAnalysis, pointsToAnalysisResultOpt, TryGetOrComputeAnalysisResult, DisposeOwnershipTransferLikelyTypes, DisposeOwnershipTransferAtConstructor, DisposeOwnershipTransferAtMethodCall, TrackInstanceFields, ControlFlowGraph, interproceduralAnalysisData, InterproceduralAnalysisPredicateOpt); } internal ImmutableHashSet DisposeOwnershipTransferLikelyTypes { get; } internal bool DisposeOwnershipTransferAtConstructor { get; } internal bool DisposeOwnershipTransferAtMethodCall { get; } internal bool TrackInstanceFields { get; } protected override void ComputeHashCodePartsSpecific(ArrayBuilder builder) { builder.Add(TrackInstanceFields.GetHashCode()); builder.Add(DisposeOwnershipTransferAtConstructor.GetHashCode()); builder.Add(DisposeOwnershipTransferAtMethodCall.GetHashCode()); builder.Add(HashUtilities.Combine(DisposeOwnershipTransferLikelyTypes)); } } }
c#
14
0.752591
185
57.881356
118
starcoderdata
package com.aftershock.mantis.scene.animation; import com.aftershock.mantis.MCallback; import com.aftershock.mantis.scene.MAnimation; /* * Copyright 2016-2017 * * 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. */ public class MCallbackAnim implements MAnimation { public float elapsed = 0.0f, length; public MCallback callback; public MCallbackAnim(float len, MCallback cb) { length = len; callback = cb; } @Override public boolean tick(float delta) { elapsed += delta; return elapsed > length; } @Override public void reverse() { } @Override public boolean doesLoop() { return false; } @Override public void callCallback() { if (callback != null) callback.call(); } }
java
9
0.72958
76
21.927273
55
starcoderdata
#include #include #include #include using namespace std; // Employee info class Employee { public: // It's the unique ID of each node. // unique id of this employee int id; // the importance value of this employee int importance; // the id of direct subordinates vector subordinates; }; class Solution { public: unordered_map dict; queue q; vector val; void build_graph(vector employees){ for(int i=0;i<employees.size();i++){ vector tmp; tmp = employees[i]->subordinates; val[employees[i]->id] = employees[i]->importance; for(int j=0;j<tmp.size();j++){ dict[employees[i]->id].push_back(tmp[j]); } } } int getImportance(vector employees, int id) { //build build_graph(employees); int im_val = val[id]; for(int i=0;i<dict[id].size();i++){ im_val += val[dict[id][i]]; } return im_val; } }; int main(){ }
c++
17
0.563866
76
23.306122
49
starcoderdata
using System; using System.Xml.Serialization; namespace Model { [XmlRoot(ElementName = "appSettings")] public class AppSettings { public int screen = -1; // screen number to open window on start public int fullscreen = 0; // fullscreen: 0-no, 1-yes public int maximize = 0; // expand window: 0-no, 1-yes public int autoplay = 1; // auto start all sources: 0-no, 1-auto play [XmlIgnore] public int autoplay_now = -1; // runtime(can be set by command line) public int priority = -1; // application base priority: 0-Idle, 1-BelowNormal, 2-Normal, 3-AboveNormal, 4-High public int unmute = 0; // do not mute audio: 0-silent, 1-enable sounds [XmlIgnore] public int unmute_now = -1; // runtime(can be set by command line) public int controlPanelWidth = 250; // width of control panel public int camListView = 1; // cameras list type of view (1-4:largeIcon/smallIcon/largeList/smallList) public int camListSort = 3; // cameras list sort type (1-3:asc/desc/none) public Matrix matrix = new Matrix(); // matrix parameters (rows and columns count) public NameView nameView = new NameView(); // camera name show global option public Alert alert = new Alert(); // alert messages [XmlArrayItem(ElementName = "cam", Type = typeof(Camera))] public Camera[] cams; [XmlIgnore] public Hint hint; } public class Matrix { public int cntX = 2; public int cntY = 2; public void SaveTo(Matrix m) { m.cntX = cntX; m.cntY = cntY; m.joins = new MatrixJoin[joins.Length]; Array.Copy(joins, m.joins, joins.Length); } public bool Equals(Matrix m) { if ((m.cntX == cntX) && (m.cntY == cntY) && ( m.joins == joins || joins != null && m.joins != null && joins.Length == m.joins.Length )) { int i = joins.Length - 1; for (; i >= 0; i--) if (!joins[i].Equals(m.joins[i])) break; if (i < 0) return true; } return false; } [XmlArrayItem(ElementName = "join", Type = typeof(MatrixJoin))] public MatrixJoin[] joins = { }; } public class MatrixJoin { public int x; public int y; public int w; public int h; public MatrixJoin() { } public MatrixJoin(int X, int Y, int W, int H) { x = X; y = Y; w = W; h = H; } public void SaveTo(MatrixJoin j) { j.x = x; j.y = y; j.w = w; j.h = h; } public bool Equals(MatrixJoin j) { return (j.x == x) && (j.y == y) && (j.w == w) && (j.h == h); } } }
c#
18
0.517312
118
32.873563
87
starcoderdata
function Apu() { // other devices this.cpu = null; // set by .setCpu() // this.audio = null; // set by .setAudio() // APU units, CPU memory address mapped registers this.pulse1 = new ApuPulse(true); // 0x4000 - 0x4003 this.pulse2 = new ApuPulse(false); // 0x4004 - 0x4007 this.triangle = new ApuTriangle(); // 0x4008 - 0x400B this.noise = new ApuNoise(); // 0x400C - 0x400F this.dmc = new ApuDmc(this); // 0x4010 - 0x4013 this.status = new ApuStatusRegister(); // 0x4015 this.frame = new ApuFrameRegister(); // 0x4017 // this.cycle = 0; this.step = 0; this.samplePeriod = 0; // set by .setAudio() // this.frameIrqActive = false; this.dmcIrqActive = false; }
javascript
7
0.617284
56
22.548387
31
inline
def rgparse_xml(self): """Take the RG XML file and get relevant information, store it in class structures""" self.root = self.parse() for resourcename_elt in self.root.findall('./ResourceGroup/Resources/Resource' '/Name'): resourcename = resourcename_elt.text # Check that resource is active activepath = './ResourceGroup/Resources/Resource/' \ '[Name="{0}"]/Active'.format(resourcename) if not ast.literal_eval(self.root.find(activepath).text): continue # Skip if resource is disabled disablepath = './ResourceGroup/Resources/Resource/' \ '[Name="{0}"]/Disable'.format(resourcename) if ast.literal_eval(self.root.find(disablepath).text): continue if resourcename not in self.resourcedict: resource_grouppath = './ResourceGroup/Resources/Resource/' \ '[Name="{0}"]/../..'.format(resourcename) self.resourcedict[resourcename] = \ self.get_resource_information(resource_grouppath, resourcename) return
python
13
0.526074
86
47.333333
27
inline
import numpy as np import paddle.fluid as fluid from . import BaseActor class SiamFCActor(BaseActor): """ Actor for training the IoU-Net in ATOM""" def __init__(self, net, objective, batch_size, shape, radius, stride): super().__init__(net, objective) self.label_mask, self.label_weights = self._creat_gt_mask( batch_size, shape, radius, stride) def _creat_gt_mask(self, batch_size, shape, radius, stride): h, w = shape y = np.arange(h, dtype=np.float32) - (h - 1) / 2. x = np.arange(w, dtype=np.float32) - (w - 1) / 2. y, x = np.meshgrid(y, x) dist = np.sqrt(x**2 + y**2) mask = np.zeros((h, w)) mask[dist <= radius / stride] = 1 mask = mask[np.newaxis, :, :] weights = np.ones_like(mask) weights[mask == 1] = 0.5 / np.sum(mask == 1) weights[mask == 0] = 0.5 / np.sum(mask == 0) mask = np.repeat(mask, batch_size, axis=0)[:, np.newaxis, :, :] weights = np.repeat(weights, batch_size, axis=0)[:, np.newaxis, :, :] weights = fluid.dygraph.to_variable(weights.astype(np.float32)) mask = fluid.dygraph.to_variable(mask.astype(np.float32)) return mask, weights def __call__(self, data): # Run network to obtain IoU prediction for each proposal in 'test_proposals' target_estimations = self.net(data['train_images'], data['test_images']) # weighted loss loss_mat = fluid.layers.sigmoid_cross_entropy_with_logits( target_estimations, self.label_mask, normalize=False) loss = fluid.layers.elementwise_mul(loss_mat, self.label_weights) loss = fluid.layers.reduce_sum(loss) / loss.shape[0] # Return training stats stats = {'Loss/total': loss.numpy(), 'Loss/center': loss.numpy()} return loss, stats
python
12
0.59407
84
39.326087
46
starcoderdata
#ifndef _SAFE_MEMCLEAR_H_ #define _SAFE_MEMCLEAR_H_ #include "first.h" void safe_memclear(void *s, size_t n); #endif
c
7
0.697479
38
16
7
starcoderdata
/// <reference types="cypress" /> import { getBlogs, visitBlogsPage, getAssetCacheHash, addAssetCacheHash } from '../utils' describe('Blogs', function () { let blogs = [] before(() => { getBlogs().then((list) => { blogs = list }) }) beforeEach(visitBlogsPage) it('displays large blog imgs', () => { let urls = [] cy.get('.media-large .media img') .should('have.length.gt', 10) .each(($img, i) => { const assetHash = getAssetCacheHash($img) const imgSrc = assetHash.length ? addAssetCacheHash(blogs.large[i].img, assetHash) : blogs.large[i].img expect($img).to.have.attr('src', imgSrc) const url = Cypress.config('baseUrl') + imgSrc urls.push(url) }) .task('checkUrls', urls) }) })
javascript
26
0.58801
89
22.757576
33
starcoderdata
def _get_expected(self, timestamps, filter_field=None, start_date=None, end_date=None): if start_date is not None: timestamps = ((timestamps - start_date) // 86400).astype(np.int32) else: if filter_field is not None: timestamps =\ ((timestamps - timestamps[np.argmax(filter_field)]) // 86400)\ .astype(np.int32) # timestamps = np.where(filter_field != 0, timestamps, 0) else: timestamps = ((timestamps - timestamps.min()) // 86400).astype(np.int32) return timestamps
python
19
0.550489
88
50.25
12
inline
private void copyResources(JSONArray resourcesList) { resourcesList.forEach(conf -> { JSONObject object = (JSONObject) conf; try (InputStream stream = MockRestFileStructure.class.getClassLoader() .getResourceAsStream(object.getString(RESOURCE_TO_COPY_FILE))) { if (object.getString(RESOURCE_TO_COPY_DEST) != null || !object.getString(RESOURCE_TO_COPY_DEST).isEmpty()) { //file to written in mockrest output folder structure. final File outputFile = new File( this.rootDirectory + File.separatorChar + object.getString(RESOURCE_TO_COPY_DEST) ); //writing file if does'nt exist if (!outputFile.exists()) { FileUtils.copyInputStreamToFile(stream, outputFile); if (object.getBoolean(RESOURCE_TO_COPY_EXECUTABLE)) { outputFile.setExecutable(true); } } } } catch (IOException e) { logger.error( String.format( "Unable to copy resource %s destination %s ", object.getString(RESOURCE_TO_COPY_FILE), object.getString(RESOURCE_TO_COPY_DEST)), e); } }); }
java
19
0.492527
109
51.607143
28
inline
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Proveedor extends Model { use HasFactory; protected $fillable = [ 'id', 'nombre_proveedor', 'telefono_proveedor', 'correo_proveedor', 'rtn_proveedor', 'identidad_proveedor', 'genero_cliente', 'direccion_proveedor', 'descripcion_proveedor', 'created_at', 'update_at', ]; protected $table ='proveedors'; //relacion uno a muchos public function productos(){ return $this->hasmany('App\models\producto','id'); } //relacion uno a muchos public function compras(){ return $this->hasmany('App\Models\Compra', 'id'); } }
php
10
0.631514
58
20.210526
38
starcoderdata
#include "MqttSubscription.hpp" bool SmartyMqttSubscription::isValidTopic(const char *topic) { // Code from http://git.eclipse.org/c/mosquitto/org.eclipse.mosquitto.git/tree/lib/util_mosq.c char c = '\0'; while (topic && topic[0]) { if (topic[0] == '+') { if ((c != '\0' && c != '/') || (topic[1] != '\0' && topic[1] != '/')) { return false; } } else if (topic[0] == '#') { if ((c != '\0' && c != '/') || topic[1] != '\0') { return false; } } c = topic[0]; topic = &topic[1]; } return true; } SmartyMqttSubscription::SmartyMqttSubscription(const char* topic) { if (!SmartyMqttSubscription::isValidTopic(topic)) { Serial << "ERROR: Invalid MQTT subscription topic!" << endl; abort(); } _topic = strcpy(new char[strlen(topic) + 1], topic); } SmartyMqttSubscription::~SmartyMqttSubscription() { delete _topic; } const char* SmartyMqttSubscription::getTopic() { return _topic; } void SmartyMqttSubscription::setCallback(SMARTY_MQTT_SUBSCRIPTION_CALLBACK_TYPE callback) { _callback = callback; } bool SmartyMqttSubscription::canHandle(const char *topic) { // Code from http://git.eclipse.org/c/mosquitto/org.eclipse.mosquitto.git/tree/lib/util_mosq.c const char* sub = _topic; if (!sub || !topic) { return false; } int subLength = strlen(sub); int topicLength = strlen(topic); int subPosition = 0; int topicPosition = 0; while (subPosition < subLength && topicPosition < topicLength) { if (sub[subPosition] == topic[topicPosition]) { if (topicPosition == topicLength-1) { if (subPosition == subLength-3 && sub[subPosition+1] == '/' && sub[subPosition+2] == '#') { return true; } } subPosition++; topicPosition++; if (topicPosition == topicLength && subPosition == subLength) { return true; } if (topicPosition == topicLength && subPosition == subLength-1 && sub[subPosition] == '+') { return true; } } else { if (sub[subPosition] == '+') { subPosition++; while (topicPosition < topicLength && topic[topicPosition] != '/') { topicPosition++; } if (topicPosition == topicLength && subPosition == subLength) { return true; } } else if (sub[subPosition] == '#') { return subPosition == subLength - 1; } else { return false; } } } return !(topicPosition < topicLength || subPosition < subLength); } void SmartyMqttSubscription::handle(const char *topic, const char* message) { if (_callback != nullptr) { _callback(topic, message); } }
c++
17
0.598859
99
27.27957
93
starcoderdata
package pizzaPlanet; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class coupons { private final String[] coupons = new String[]{"Small Salami - 10$", "Big Hawai - 15$", "Coca-Cola - 3$", "Chips - 7$", "Big Meal Pizza + Coca-Cola - 20$"}; private final boolean[] isTaken = new boolean[coupons.length]; Scanner scan = new Scanner(System.in); StringBuilder strBuilder = new StringBuilder(); public void drawCoupons() { System.out.println("------AVAILABLE COUPONS------"); for (int i = 0; i < coupons.length; i++) { if(!isTaken[i]) System.out.println(i + 1 + ". " + coupons[i]); } System.out.println(coupons.length + 1 + ". Go back"); } public boolean pickCoupons() { System.out.println("Choice: "); int couponChoice = scan.nextInt(); if(couponChoice == coupons.length + 1) return true; if(isTaken[couponChoice - 1]) { System.out.println("Coupon number " + couponChoice + " was already picked by you."); } else { isTaken[couponChoice - 1] = true; System.out.println("You have taken: " + coupons[couponChoice - 1]); System.out.println("Thank you for picking coupon!"); strBuilder.append(coupons[couponChoice - 1] + "\n"); } return false; } public boolean couponsReady() { System.out.println("Do you want to pick any more coupons? [Y/N]"); String needMore = scan.next(); if(needMore.equals("y")) { return true; } else { System.out.println("Maybe next time :/"); return false; } } public void saveCoupons() { try(PrintWriter out = new PrintWriter("coupons.txt")) { out.println(strBuilder.toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
java
14
0.573232
159
32
60
starcoderdata
func (p *connectedPlayer) canForwardPluginMessage(protocol proto.Protocol, message *plugin.Message) bool { var minecraftOrFmlMessage bool // By default, all internal Minecraft and Forge channels are forwarded from the server. if int(protocol) <= int(version.Minecraft_1_12_2.Protocol) { channel := message.Channel minecraftOrFmlMessage = strings.HasPrefix(channel, "MC|") || strings.HasPrefix(channel, forge.LegacyHandshakeChannel) || plugin.LegacyRegister(message) || plugin.LegacyUnregister(message) } else { minecraftOrFmlMessage = strings.HasPrefix(message.Channel, "minecraft:") } // Otherwise, we need to see if the player already knows this channel or it's known by the proxy. return minecraftOrFmlMessage || p.knownChannels().Has(message.Channel) }
go
13
0.770914
106
47.625
16
inline
package SwordRefersOffer; /* 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点), 返回结果为复制后复杂链表的head。 (注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空) */ public class Solution25 { public static class RandomListNode { int label; RandomListNode next = null; RandomListNode random = null; RandomListNode(int label) { this.label = label; } } public static RandomListNode Clone(RandomListNode pHead) { RandomListNode res = new RandomListNode(0); RandomListNode cur = pHead, res_next = res, next; while(cur != null){ res_next.next = new RandomListNode(cur.label); res_next = res_next.next; res_next.random = cur.random; cur = cur.next; } cur = pHead; res_next = res.next; while(cur != null){ next = cur.next; cur.next = res_next; res_next = res_next.next; cur = next; } res_next = res.next; while(res_next != null){ if (res_next.random != null){ res_next.random = res_next.random.next; } res_next = res_next.next; } return res.next; } public static void main(String[] args){ RandomListNode a = new RandomListNode(1); RandomListNode b = new RandomListNode(2); RandomListNode c = new RandomListNode(3); RandomListNode d = new RandomListNode(4); RandomListNode e = new RandomListNode(5); a.next = b; b.next = c; c.next = d; d.next = e; e.next = null; a.random = c; b.random = e; c.random = null; d.random = b; e.random = null; Clone(a); } }
java
13
0.548966
62
26.029412
68
starcoderdata
def querySessionTime(self, request): """Return sessions given a conference object, time and type""" # get conference object from Datastore conf = self._getDataStoreObject(request.websafeConferenceKey) # query sessions using ancestor conf Key, order sessions by start time sessions = Session.query(ancestor=conf.key).order(Session.startTime) # filter sessions by time (before/after/equal certain time) if (request.operator and request.time): node = ndb.query.FilterNode( 'startTime', OPERATORS[request.operator], datetime(1970, 01, 01, request.time, 00)) sessions = sessions.filter(node) else: raise endpoints.BadRequestException("You need to define both " "operator and time") # only return session types that are not equal to what the user provided return SessionForms( items=[self._copySessionToForm(x) for x in sessions if x.sessionType != request.sessionType] )
python
12
0.570593
80
48.916667
24
inline
package co.com.practicaJava.ejercicio15; import java.util.Scanner; public class Menu { Scanner entrada = new Scanner(System.in); public void menu(){ System.out.println("**************GESTIÓN CINEMATOGRÁFICA***************" + "\n 1-NUEVO ACTOR" + "\n 2-BUSCAR ACTOR" + "\n 3-ELIMINAR ACTOR" + "\n 4-MODIFICAR ACTOR" + "\n 5-VER TODOS LOS ACTORES" + "\n 6-VER PELICULAS DE LOS ACTORES" + "\n 7-VER CATEGORIA DE LAS PELICULAS DE LOS ACTORES" + "\n 8-SALIR"); } public void mostrarMenu(int opcion){ while (opcion != 8){ switch (opcion){ case 1: case 2: case 3: case 4: case 5: case 6: case 7: menu(); break; default: System.out.println("----------Opción incorrecta-----------"); menu(); break; } opcion = nuevaOpcion(); } System.exit(0); } public int nuevaOpcion(){ System.out.println("Ingresa una opción del menú: "); return entrada.nextInt(); } }
java
17
0.42165
83
25.959184
49
starcoderdata
# -*- coding: utf-8 -*- """ Created on Wed Dec 30 13:30:43 2020 @author: javi- """ import numpy as np import sklearn.linear_model from . import penalties as pn from . import binary_parser as bp # ============================================================================= # MPA ALPHA FORWARDS # ============================================================================= def mpa_aggregation(logits, agg1, agg2, alpha, keepdims=False): n_2 = len(logits) n_1, samples, clases = logits[0].shape res = np.zeros((n_2, samples, clases)) for ix, logit in enumerate(logits): res[ix, :, :] = agg1(logit, axis=0, keepdims=False, alpha=alpha[ix]) return agg2(res, axis=0, keepdims=keepdims, alpha=alpha[-1]) def logistic_alpha_forward(X, cost_convex, clf): ''' X shape: (bandas, samples, clases) out shape: (samples, clases) ''' reformed_X = np.swapaxes(X, 0, 1) reformed_X = reformed_X.reshape((reformed_X.shape[0], reformed_X.shape[1]*reformed_X.shape[2])) alphas = clf.predict(reformed_X) result = np.zeros((X.shape[1], X.shape[2])) for sample in range(X.shape[1]): alpha_cost = lambda real, yhat, axis: cost_convex(real, yhat, axis, alphas[sample]) result[sample] = pn.penalty_aggregation(X[:, sample, :], [bp.parse(x) for x in bp.classic_aggs], axis=0, keepdims=False, cost=alpha_cost) return result def multimodal_alpha_forward(X, cost, cost2, alpha, agg_set=bp.classic_aggs): ''' X shape: list of n arrays (bandas, samples, clases) clfs: list of alphas. out shape: (samples, clases) ''' david_played_and_it_pleased_the_lord = [bp.parse(x) for x in agg_set] agg_phase_1 = lambda X0, alpha, keepdims=False, axis=0: pn.penalty_aggregation(X0, david_played_and_it_pleased_the_lord, axis=axis, keepdims=keepdims, cost=lambda real, yhat, axis: cost(real, yhat, axis, alpha=alpha)) agg_phase_2 = lambda X0, alpha, keepdims=False, axis=0: pn.penalty_aggregation(X0, david_played_and_it_pleased_the_lord, axis=axis, keepdims=keepdims, cost=lambda real, yhat, axis: cost2(real, yhat, axis, alpha=alpha)) return mpa_aggregation(X, agg_phase_1, agg_phase_2, alpha, keepdims=False) # ============================================================================= # LEARN ALPHA - VARIABILITY MAX ALGORITHM UNI-MODAL # ============================================================================= def generate_real_alpha(X, y, aggs, cost, opt=1): a = None b = None for alpha in np.arange(0.01, 1.01, 0.1): alpha_cost = lambda X, yhat, axis: cost(X, yhat, axis, alpha) pagg = pn.penalty_aggregation(X, [bp.parse(x) for x in aggs], axis=0, keepdims=False, cost=alpha_cost) if np.argmax(pagg) == y: if a is None: a = alpha else: b = alpha if a is None: a = 0.5 if b is None: b = 0.5 d1 = np.abs(a - 0.5) d2 = np.abs(b - 0.5) if opt == 1: if d1 <= d2: return a else: return b elif opt == 2: return (a + b) / 2 def generate_train_data_alpha(logits, labels, aggs=bp.classic_aggs, cost=pn.cost_functions[0], opt=1): ''' Generates and return the alpha targets for a series of data and their labels, using the specified aggregations and cost functions in a MPA. ''' bands, samples, classes = logits.shape y = np.zeros((samples,)) for sample in range(samples): y[sample] = generate_real_alpha(logits[:,sample,:], labels[sample], aggs, cost, opt=opt) return y def learn_model(X, y, cost, aggs=bp.classic_aggs, opt=1): ''' X shape: list of n arrays (bandas, samples, clases) out shape: (samples, clases) Parameters ---------- X : TYPE DESCRIPTION. Returns ------- None. ''' X_reshaped = np.swapaxes(X, 0, 1) X_reshaped = X_reshaped.reshape((X_reshaped.shape[0], X_reshaped.shape[1]*X_reshaped.shape[2])) y_alpha = generate_train_data_alpha(X, y, aggs=aggs, cost=cost, opt=opt) clf = sklearn.linear_model.LinearRegression().fit(X_reshaped, y_alpha) return clf # ============================================================================= # MULTIMODAL ALPHA OPTIMIZATION - LEAST SQAURES VARAIBLITY + ACC ALGORITHM # ============================================================================= def eval_alpha(alpha_v, y_hat, y): ''' Returns ------- None. ''' alpha_score = np.mean(np.minimum(alpha_v, 1 - alpha_v)) acc_score = np.mean(np.equal(y_hat, y)) return (alpha_score + acc_score) / 2 def eval_conf(X, alpha, y, agg1, agg2): ''' Computes the mpa agg for X, and returns the optimization score. Parameters ---------- X : TYPE DESCRIPTION. alpha : TYPE DESCRIPTION. y : TYPE DESCRIPTION. agg1 : TYPE DESCRIPTION. agg2 : TYPE DESCRIPTION. Returns ------- TYPE DESCRIPTION. ''' y_hat = np.argmax(mpa_aggregation(X, agg1, agg2, alpha), axis=1) return eval_alpha(alpha, y_hat, y) def gen_all_good_alpha_mff(X, y, costs, aggs=bp.choquet_family + bp.sugeno_family + bp.overlap, opt=1, four_class=False): ''' Learn the logistic regression for the whole set of datasets. ''' from scipy.optimize import least_squares agg_phases = [lambda X0, alpha, keepdims=False, axis=0: pn.penalty_aggregation(X0, aggs, axis=axis, keepdims=keepdims, cost=lambda real, yhat, axis: costs[ix](real, yhat, axis, alpha=alpha)) for ix in range(costs)] optimize_lambda = lambda alpha: -eval_conf(X, alpha, y, agg_phases) #Remember we are minimizng x0_alpha = np.array([0.5] * len(X) + [0.5]) #WIP: chek the size of each phase. res_1 = least_squares(optimize_lambda, x0_alpha, bounds=[0.0001, 0.9999]) return res_1.x
python
14
0.568519
222
30.208333
192
starcoderdata
package com.zhw.core.map; public class FyPoint { public double lat; // 纬度 public double lon; // 经度 public FyPoint(double lon, double lat){ this.lat = lat; this.lon = lon; } }
java
8
0.668478
40
17.4
10
starcoderdata
uint mp_import_stat(const char *path) { jstring jpath = JNUPY_CALL(NewStringUTF, path); // [!:JNUPY_NESTED_CALL] lead to nested call jobject jresult; JNUPY_ASSIGN_WITH_NESTED_CALL(jresult, CallObjectMethod, JNUPY_PY_JSTATE, JMETHOD(PythonNativeState, readStat), jpath); JNUPY_CALL(ReleaseStringUTFChars, jpath, NULL); jint result = JNUPY_CALL(CallIntMethod, jresult, JMETHOD(PythonImportStat, ordinal)); switch (result) { case MP_IMPORT_STAT_DIR: case MP_IMPORT_STAT_FILE: case MP_IMPORT_STAT_NO_EXIST: return result; default: return MP_IMPORT_STAT_NO_EXIST; } }
c
9
0.675466
120
32.947368
19
inline
def main(): sx = 10.0 # [m] sy = 10.0 # [m] gx = 50.0 # [m] gy = 50.0 # [m] robot_radius = 2.0 grid_resolution = 1.0 ox, oy = get_env() # pathx, pathy = astar_planning(sx, sy, gx, gy, ox, oy, grid_resolution, robot_radius) plt.plot(ox, oy, 'sk') # plt.plot(pathx, pathy, '-r') # plt.plot(sx, sy, 'sg') # plt.plot(gx, gy, 'sb') # plt.axis("equal") plt.show()
python
7
0.491647
89
22.333333
18
inline
package FamilyTree; import java.util.*; public class Main { static Scanner scan = new Scanner(System.in); public static void main(String[] args) { String input = scan.nextLine(); List personList = new ArrayList<>(); ArrayDeque lines = new ArrayDeque<>(); Person inputPerson = new Person(input); String command = scan.nextLine(); while (!"End".equals(command)) { if (command.contains("-")) { lines.offer(command); } else { if (command.contains(input)) { input = command; inputPerson = new Person(command); } personList.add(command); } command = scan.nextLine(); } while (!lines.isEmpty()) { setParentAndChild(lines.pop(), inputPerson,input, personList); } System.out.println(inputPerson); } private static void setParentAndChild(String command, Person inputPerson, String input, List personList) { String parent = command.split(" - ")[0]; String child = command.split(" - ")[1]; for (String s : personList) { if (s.contains(parent)) { parent = s; continue; } if (s.contains(child)) { child = s; } } if (input.contains(parent)) { inputPerson.setChildren(child); } if (input.contains(child)) { inputPerson.setParents(parent); } } }
java
15
0.495187
118
28.777778
54
starcoderdata
################################################################################################## # SCRIPT TO ANIMATE ELBOWS - LEFT AND RIGHT # Created, Invented and Made Alive By : # Date : 08-April-2008 ################################################################################################## ################################################################################################## # This function Animates the Elbows # # Armature_Object - The Bone Armature from which it selects the Elbow Bone to animate # direction - The final direction where the Bone has to be moved() # endFrame - The final frame at which the Bone has to be moved in the specified direction ################################################################################################## from Blender import * import Blender # Left Elbow def LEFTELBOW(Armature_Object, direction, endFrame): #Defining all possible positions for the Left Elbow # first attribute - i am still guessing(nothing happens if changed from 1.0) # second attribute - it moves the head move up and down # third attribute - it is making the bone to rotate on axis (0.5 corresponds to 90 degree rotation) # fourth attribute - it is making the bone move left and right Positions = {} Positions["LESS_BEND"] = [2.5,0.5,0.0,-1.0] Positions["BEND"] = [1.0,0.5,0.0,-1.0] Positions["FULL_BEND"] = [0.25,0.5,0.0,-1.0] Positions["DEFAULT"] = [1.0,0.0,0.0,0.0] #Get the Head Bone from the Armature Object pose_bones = Armature_Object.getPose() all_bones = pose_bones.bones.values() LElbow = [bone for bone in all_bones if bone.name == "Bone.002_R.002"][0] #Set the frame in which the Position will be reached x = Positions[direction][0] y = Positions[direction][1] z = Positions[direction][2] r = Positions[direction][3] LElbow.quat[:] = x,y,z,r LElbow.insertKey(Armature_Object,endFrame,Object.Pose.ROT) return endFrame # Right Elbow def RIGHTELBOW(Armature_Object, direction, endFrame): #Defining all possible positions for the Right Elbow # first attribute - i am still guessing(nothing happens if changed from 1.0) # second attribute - it moves the head move up and down # third attribute - it is making the bone to rotate on axis (0.5 corresponds to 90 degree rotation) # fourth attribute - it is making the bone move left and right Positions = {} Positions["LESS_BEND"] = [2.5,0.5,0.0,1.0] Positions["BEND"] = [1.0,0.5,0.0,1.0] Positions["FULL_BEND"] = [0.25,0.5,0.0,1.0] Positions["DEFAULT"] = [1.0,0.0,0.0,0.0] #Get the Head Bone from the Armature Object pose_bones = Armature_Object.getPose() all_bones = pose_bones.bones.values() RElbow = [bone for bone in all_bones if bone.name == "Bone.002_L.002"][0] #Set the frame in which the Position will be reached x = Positions[direction][0] y = Positions[direction][1] z = Positions[direction][2] r = Positions[direction][3] RElbow.quat[:] = x,y,z,r RElbow.insertKey(Armature_Object,endFrame,Object.Pose.ROT) return endFrame
python
10
0.620632
100
40.178082
73
starcoderdata
void OTWDriverClass::CleanupSplashScreen(void) { // Release the original image data glReleaseMemory((char*)originalImage); glReleaseMemory((char*)originalPalette); originalImage = NULL; originalPalette = NULL; }
c++
9
0.732759
46
24.888889
9
inline
""" Some utility files. :Authors: """ import math import os def which(program): """ Check if the executable given in program exists or if it exists in the operating system PATH variable. Code taken from: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028 @param program: Either a path to a program or the name of a program on the system PATH @return: The path to the program. If the program does not exist, return None. """ def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, _ = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None def one_loop_stats(iterable, num_func, prefix=""): """ Calcualte the mean, standard deviation, count, sum, max, and min in one loop. Parameters ---------- iterable: iterable An object that can be iterated through such as a list or an open file. name_func: function A function that when given an input line from iterable will return a number. This allows this function to be more generic. prefix: str A string prefix to add to each statistic. Returns ------- dict A dictionary of the statistics. """ s = 0.0 s_2 = 0.0 n = 0 mx = -float("inf") mn = float("inf") for line in iterable: ai = num_func(line) if ai > mx: mx = ai if ai < mn: mn = ai s += ai s_2 += ai * ai n += 1 try: mean = s / n var = s_2 / n - mean * mean except ZeroDivisionError: mean = float('inf') var = float('inf') return { prefix + "mean": mean, prefix + "std": math.sqrt(var), prefix + "count": n, prefix + "sum": s, prefix + "max": mx, prefix + "min": mn } def faidx_length(line): """ Get the base length for a contig from a fai file. Parameters ---------- line: str A fai file line. Returns ------- int The number of bases in the contig. """ return float(line.split('\t')[1])
python
13
0.550854
95
22.409524
105
starcoderdata
''' Created on 30/10/2014 @author: Aluno ''' import pygame from pygame.constants import QUIT, KEYDOWN, K_RIGHT, K_LEFT, K_UP, K_DOWN, KEYUP from pygame.rect import Rect def drawTabuleiro (surface, colunas, linhas, width, height): for l in range(linhas): for c in range(colunas): x = c * width y = l * height pygame.draw.rect(surface, (0, 0, 0), Rect( (x, y), (width, height) ), 1) pygame.init() screen = pygame.display.set_mode( (640, 480), 0, 32) x = 50 y = 50 while (True): screen.fill( (255, 255, 255) ) drawTabuleiro( screen, 8, 8, 32, 32 ) pygame.display.update() for e in pygame.event.get(): if (e.type == QUIT): exit()
python
13
0.581486
84
19.72973
37
starcoderdata
// TaskGraph.cs // This class is the highest level of each instantiated visual graph. It holds references to UI elements and the ticks // MB: using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; namespace TaskSim { public class TaskGraph : MonoBehaviour { public List ticks; public Transform ticksParent; public TMP_Text graphTitle; public Image zeroRelease; } }
c#
9
0.727451
118
24.55
20
starcoderdata
import React, { useEffect } from 'react'; import { useState } from 'react'; import {Link} from 'react-router-dom'; import '../../global.css'; import api from '../../services/api'; export default function Catalog() { const [endereco, setEndereco] = useState([]); useEffect(() => { api.get('user').then(response => { setEndereco(response.data); }) }) return ( <div className="main"> <div className="escanteio"> <h1 className="catalog-titulo">Endereço cadastradas <Link to="/catalog"> <button className="logout-btn" type="button"> Back {endereco.map(endereco => ( <li key={endereco.matricula}> <label className="card-matricula">Matricula: {endereco.matricula} <label className="card-name">Cidade: {endereco.cidade} <label className="card-matricula">Estado: {endereco.estado} <label className="card-email">Rua: {endereco.rua} <label className="card-bairro">Bairro: {endereco.bairro} ))} ); }
javascript
18
0.583466
93
28.27907
43
starcoderdata
#pragma once #include "execution_model/execution_model.h" #include "intersectable_scene/intersector.h" #include "render/detail/integrate_image/inputs.h" #include "render/detail/integrate_image/streaming/state.h" #include "render/streaming_settings.h" namespace render { namespace detail { namespace integrate_image { namespace streaming { template <ExecutionModel exec> struct Run { template Items, intersectable_scene::BulkIntersector I> requires std::same_as<typename Items::InfoType, typename I::InfoType> static Output run(Inputs inp, I &intersector, State<exec, Items::C::max_num_light_samples(), typename Items::R> &state, const StreamingSettings &settings, ExecVector<exec, BGRA32> &bgra_32, ExecVector<exec, FloatRGB> &float_rgb, HostVector<ExecVector<exec, FloatRGB>> &output_per_step_rgb); }; } // namespace streaming } // namespace integrate_image } // namespace detail } // namespace render
c
17
0.750476
79
36.5
28
starcoderdata
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use Illuminate\Http\Response; use App\module\company\Company; use Carbon\Carbon; use DB; use Illuminate\Session\TokenMismatchException; use App\Http\Controllers\Controller; class CompanyController extends Controller { public function index(){//Lấy thông tin từ database show ra cho admin xem $data = Company::select(['ID_COM','COM_NAME','SHORT_NAME','EMAIL','TEL','FAX','WEBSITE','ADDRESS'])->get()->first(); return view('backend.admin.company.index',['company'=>$data]); } public function showinfo(){ //return view('backend.admin.company.update');//Show form để update thông tin $data = Company::select(['ID_COM','COM_NAME','SHORT_NAME','EMAIL','TEL','FAX','WEBSITE','ADDRESS'])->get()->first(); return view('backend.admin.company.update',['company'=>$data]); } public function updateAction(Request $request){ $data = $request->except('_token','ac');//Loại bỏ token trong form Company::updateCompany($data); echo '<script language=javascript>window.close();window.opener.location.reload(); } public function viewupdateinfo(){ return view('backend.admin.company.viewupdateinfo'); } }
php
15
0.677394
125
37.606061
33
starcoderdata
TEST (JavaUtilArrays, Equals) { /// Give valid array boolean to test equals Array<boolean> arrayBoolean = { false, false, false, false, true }; Array<boolean> arrayCompareBoolean = { false, false, false, false, true }; assertTrue(Arrays::equals(arrayBoolean, arrayCompareBoolean)); /// Give valid array long to test equals - this test case wrapped <int>, <short>, <char> also Array<long> arrayLong = { 12, 66, 16, 35, 87 }; Array<long> arrayCompareLong = { 12, 66, 16, 35, 87 }; assertTrue(Arrays::equals(arrayLong, arrayCompareLong)); }
c++
8
0.704174
94
41.461538
13
inline
private void CreateItemAtIndex( int index ) { RecycledListItem item; if( pooledItems.Count > 0 ) { item = pooledItems.Pop(); item.gameObject.SetActive( true ); } else { item = adapter.CreateItem( contentTransform ); item.SetAdapter( adapter ); } // Reposition the item ( (RectTransform) item.transform ).anchoredPosition = new Vector2( 0f, -index * itemHeight ); // To access this item easily in the future, add it to the dictionary items[index] = item; }
c#
11
0.656863
96
24.55
20
inline
#!/usr/bin/env yamtbx.python """ (c) RIKEN 2015. All rights reserved. Author: This software is released under the new BSD License; see LICENSE. """ from yamtbx.dataproc.xds import xscale from yamtbx.dataproc.xds.command_line import xscale_simple master_params_str = """\ use_tmpdir_if_available = False .type = bool .help = "Use RAM disk or temporary directory to run xscale" cbf_to_dat = True .type = bool .help = "Convert .cbf files (scale values) to a few .dat files" aniso_analysis = True .type = bool .help = "Do anisotropy analysis" """ import os import sys import iotbx.phil from yamtbx import util def inp_file_analysis(inp): import numpy from yamtbx.util.xtal import format_unit_cell cells = [] for l in open(inp): ll = l[:l.index("!")] if "!" in l else l if "INPUT_FILE=" in ll: # and len(l) > 132: # one line is limited to 131 characters! filename = ll[ll.index("=")+1:].strip() if "*" in filename: filename = filename[filename.index("*")+1:].strip() print ll.strip() info = xscale_simple.get_xac_info(filename, get_nframes=False) print " FRIEDEL'S_LAW=", info.get("friedels_law") print " RESOLUTION_RANGE=", info.get("resol_range") print " SPACE_GROUP_NUMBER=", info.get("spgr_num") print " UNIT_CELL_CONSTANTS=", info.get("cell") cells.append(map(float, info["cell"].split())) print print cells = numpy.array(cells) print "Averaged cell =", format_unit_cell(cells.mean(axis=0)) print " (std dev) =", format_unit_cell(cells.std(axis=0)) print " Median cell =", format_unit_cell(numpy.median(cells, axis=0)) def run(params, inp): try: inp_file_analysis(inp) finally: print print "Starting XSCALE" print xscale.run_xscale(inp, cbf_to_dat=params.cbf_to_dat, aniso_analysis=params.aniso_analysis, use_tmpdir_if_available=params.use_tmpdir_if_available) # run() def show_help(): print """\ This script runs xscale program. No limitation in INPUT_FILE= length. Usage: yamtbx.run_xscale XSCALE.INP [use_tmpdir_if_available=true] Parameters:""" iotbx.phil.parse(master_params_str).show(prefix=" ", attributes_level=1) # show_help() def run_from_args(args): if "-h" in args or "--help" in args: show_help() return cmdline = iotbx.phil.process_command_line(args=args, master_string=master_params_str) params = cmdline.work.extract() if len(cmdline.remaining_args) == 0: xscale_inp = "XSCALE.INP" else: xscale_inp = cmdline.remaining_args[0] if not os.path.isfile(xscale_inp): print "Cannot find %s" % xscale_inp show_help() return run(params, xscale_inp) # run_from_args() if __name__ == "__main__": run_from_args(sys.argv[1:])
python
19
0.604388
93
28.782178
101
starcoderdata
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 14, 2021 at 2:26:29 PM Mountain Standard Time * Operating System: Version 14.4 (Build 18K802) * Image Source: /System/Library/PrivateFrameworks/PassKitCore.framework/PassKitCore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Updated by */ #import @class PKPaymentPass, PKPaymentApplication, PKWrappedPayment, NSData, NSString; @interface PKPaymentRewrapRequestBase : PKPaymentWebServiceRequest { PKPaymentPass* _pass; PKPaymentApplication* _paymentApplication; PKWrappedPayment* _wrappedPayment; NSData* _applicationData; long long _cryptogramType; } @property (nonatomic,readonly) NSString * endpointName; @property (nonatomic,retain) PKPaymentPass * pass; //@synthesize pass=_pass - In the implementation block @property (nonatomic,retain) PKPaymentApplication * paymentApplication; //@synthesize paymentApplication=_paymentApplication - In the implementation block @property (nonatomic,retain) PKWrappedPayment * wrappedPayment; //@synthesize wrappedPayment=_wrappedPayment - In the implementation block @property (nonatomic,copy) NSData * applicationData; //@synthesize applicationData=_applicationData - In the implementation block @property (assign,nonatomic) long long cryptogramType; //@synthesize cryptogramType=_cryptogramType - In the implementation block -(id)bodyDictionary; -(NSData *)applicationData; -(void)setApplicationData:(NSData *)arg1 ; -(PKPaymentPass *)pass; -(void)setPass:(PKPaymentPass *)arg1 ; -(PKPaymentApplication *)paymentApplication; -(void)setPaymentApplication:(PKPaymentApplication *)arg1 ; -(long long)cryptogramType; -(PKWrappedPayment *)wrappedPayment; -(void)setWrappedPayment:(PKWrappedPayment *)arg1 ; -(void)setCryptogramType:(long long)arg1 ; -(NSString *)endpointName; -(id)_urlRequestWithServiceURL:(id)arg1 deviceIdentifier:(id)arg2 rewrapData:(id)arg3 appleAccountInformation:(id)arg4 ; @end
c
7
0.712416
167
52.818182
44
starcoderdata
def _fit_with_t0(self, data: Sequence[int], t0: int, message: Text, enable_tensorboard: bool = False, tensorboard_logdir: Optional[Text] = None ) -> Tuple[ Covid19DeathPredictModel, infection_model.TensorType]: """Returns the death toll model after training with a given t0. Args: data: training data (number of daily new death tolls) in a 1d array. t0: specifies the number of days between the occurrence of the first infected case (patient zero) and the first observed case. message: optionally pass a prefix string in the filenames of training weights (in the format of hdf5 file). We will generate a lot of such files in the training process. enable_tensorboard: whether or not use tensorboard to monitor training. tensorboard_logdir: xxx. Returns: model: the best model after training with t0. loss: the loss of the best model after training with t0. """ model = Covid19DeathPredictModel( n_weights=2 * len(self._knots) + 1 - sum(self._knots_connect), t0=t0, len_inputs=len(data) + t0, max_latency=self._estimator_args.get( "max_latency", infection_model.DEFAULT_MAX_LATENCY), max_intervention=self._estimator_args.get( "max_intervention", DEFAULT_MAX_INTERVENTION), **self._model_args) x = self._get_trainable_x(len(data), t0) # Pad t0 elements at front to be 0. y = np.pad(data, [t0, 0]).astype(np.float64) # Define the loss function for each t0 value. Compare the square-root # difference. def custom_loss(y_actual, y_pred): return self._estimator_args.get( "loss_function", tf.keras.losses.MSE)( # tf.math.sqrt(y_actual[t0:]), tf.math.sqrt(y_pred[t0:])) (y_actual[t0:]), (y_pred[t0:])) optimizer_option = self._estimator_args.get( "optimizer", tf.keras.optimizers.Adam) optimizer = optimizer_option( learning_rate=self._estimator_args.get("learning_rate", 0.01), clipnorm=1.0) model.compile(optimizer, custom_loss) callbacks, min_loss_filepath = Covid19DeathEstimator._setup_callbacks( message, t0, enable_tensorboard, tensorboard_logdir) model.fit( x, y, epochs=self._estimator_args.get("epochs", 100), batch_size=len(data) + t0, shuffle=False, verbose=self._estimator_args.get("verbose", 0), callbacks=callbacks) model.load_weights(min_loss_filepath) loss = custom_loss(y, model(x)) return model, loss
python
14
0.635635
77
41.983607
61
inline
package ca.blarg.gdx.assets.textureatlas; import ca.blarg.gdx.graphics.atlas.TextureAtlas; import com.badlogic.gdx.assets.AssetDescriptor; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.utils.Array; @SuppressWarnings("unchecked") public class TextureAtlasLoader extends AsynchronousAssetLoader<TextureAtlas, TextureAtlasLoader.TextureAtlasParameter> { public TextureAtlasLoader(FileHandleResolver resolver) { super(resolver); } JsonTextureAtlas definition; TextureAtlas atlas; @Override public Array getDependencies(String fileName, FileHandle file, TextureAtlasParameter parameter) { definition = TextureAtlasJsonLoader.load(file); Array deps = new Array deps.add(new AssetDescriptor(definition.texture, Texture.class)); return deps; } @Override public void loadAsync(AssetManager manager, String fileName, FileHandle file, TextureAtlasParameter parameter) { atlas = TextureAtlasJsonLoader.create(file, definition, manager); } @Override public TextureAtlas loadSync(AssetManager manager, String fileName, FileHandle file, TextureAtlasParameter parameter) { return atlas; } public static class TextureAtlasParameter extends AssetLoaderParameters { } }
java
11
0.822612
121
35.642857
42
starcoderdata
def networkx2tensor(nx_graph, idtype, edge_id_attr_name=None): """Function to convert a networkx graph to edge tensors. Parameters ---------- nx_graph : nx.Graph NetworkX graph. idtype : int32, int64, optional Integer ID type. Must be int32 or int64. edge_id_attr_name : str, optional Key name for edge ids in the NetworkX graph. If not found, we will consider the graph not to have pre-specified edge ids. (Default: None) Returns ------- (Tensor, Tensor) Edge tensors. """ if not nx_graph.is_directed(): nx_graph = nx_graph.to_directed() # Relabel nodes using consecutive integers nx_graph = nx.convert_node_labels_to_integers(nx_graph, ordering='sorted') has_edge_id = edge_id_attr_name is not None if has_edge_id: num_edges = nx_graph.number_of_edges() src = [0] * num_edges dst = [0] * num_edges for u, v, attr in nx_graph.edges(data=True): eid = int(attr[edge_id_attr_name]) if eid < 0 or eid >= nx_graph.number_of_edges(): raise DGLError('Expect edge IDs to be a non-negative integer smaller than {:d}, ' 'got {:d}'.format(num_edges, eid)) src[eid] = u dst[eid] = v else: src = [] dst = [] for e in nx_graph.edges: src.append(e[0]) dst.append(e[1]) src = F.tensor(src, idtype) dst = F.tensor(dst, idtype) return src, dst
python
16
0.563767
97
33
45
inline
/* Defines a spellcheck module for CodeMirror that relies on the system spellchecker */ import BBPromise from 'util/bbpromise.js' import CodeMirror from 'codemirror' var checkHandle = 0; var checkResults = []; var focusedCM = null; /* Spell check text. Returns a promise where on success is an array of text ranges that are misspelled. [{ start: ..., end: ... }] */ function checkText(text) { return new BBPromise((resolve, reject) => { if (window.spellcheck) { var handle = ++checkHandle; checkResults[handle] = resolve; window.spellcheck.postMessage({text, handle}); } else { reject(new Error("System spellcheck unavailable")); } }); } window.spellcheckResults = function(data) { var handle = data.handle; var resolve = checkResults[handle]; delete checkResults[handle]; resolve(data.results); }; window.spellcheckFixer = function(token, replacement) { var myCM = focusedCM; if (!myCM) { return; } myCM.replaceRange(replacement, token.start, token.end, "+input"); }; function CheckState(cm, options) { this.marked = []; this.options = options; this.timeout = null; this.waitingFor = 0 } function parseOptions(_cm, options) { if (options instanceof Function) return options(); if (!options || options === true) options = {}; return options; } function clearMarks(cm) { var state = cm.state.systemSpellcheck; for (var i = 0; i < state.marked.length; ++i) state.marked[i].clear(); if (state.pendingMark) { state.pendingMark.clear(); delete state.pendingMark; } state.marked.length = 0; } function textInViewport(cm, viewport) { var start = { line: viewport.from, ch: 0 }; var endl = viewport.to; if (endl > cm.lastLine()) endl = cm.lastLine(); var ll = cm.getLine(endl); var end = { line: endl, ch: ll.length }; if (start.line == end.line && start.ch == end.ch) return ""; return cm.getRange(start, end); } function startChecking(cm) { var state = cm.state.systemSpellcheck, options = state.options; var text = cm.getValue(); checkText(text).then((results) => { var newText = cm.getValue(); if (text != newText) { return; } clearMarks(cm); results.forEach((range) => { var mode = cm.getModeAt(range.start); var tt = cm.getTokenTypeAt(range.start); var cursor = cm.getCursor(); var inCursor = cursor.line == range.start.line && range.start.ch <= cursor.ch && range.end.ch >= cursor.ch; // Only show misspellings in markdown mode, and ignore `backticks` ```triple-ticks``` and links. if (mode.name === 'markdown' && (!tt || (tt.indexOf('comment') == -1 && tt.indexOf('link') == -1))) { if (inCursor) { state.pendingMark = cm.markText(range.start, range.end, {}); } else { state.marked.push(cm.markText(range.start, range.end, {className:'misspelling'})); } } }); }).catch((error) => { console.log("Unable to spellcheck", error); clearMarks(cm); }); } function scheduleCheck(cm) { var state = cm.state.systemSpellcheck; if (!state) return; clearTimeout(state.timeout); state.timeout = setTimeout(function(){startChecking(cm);}, state.options.delay || 50); } function onChange(cm) { scheduleCheck(cm); } function onCursor(cm) { var state = cm.state.systemSpellcheck; if (!state) return; if (state.pendingMark) { var markRange = state.pendingMark.find(); if (!markRange || !markRange.from) return; var wordRange = cm.findWordAt(markRange.from); wordRange = {from: wordRange.anchor, to:wordRange.head}; var cursor = cm.getCursor(); function inCursor(range) { return cursor.line == range.from.line && range.from.ch <= cursor.ch && range.to.ch >= cursor.ch; } if (!inCursor(wordRange)) { state.pendingMark.clear(); delete state.pendingMark; var markIsWord = markRange.from.ch == wordRange.from.ch && markRange.to.ch == wordRange.to.ch; if (markIsWord) { state.marked.push(cm.markText(markRange.from, markRange.to, {className:'misspelling'})); } } } } function onContextMenu(cm, event) { if (!window.spellcheck) { return false; } var el = event.target; var targetIsMisspelling = (' ' + el.className + ' ').indexOf(' misspelling ') > -1; if (targetIsMisspelling) { // find the range of the targeted element var bb = el.getBoundingClientRect(); var leftPt = { left: bb.left, top: bb.top + (bb.height / 2) }; var rightPt = { left: bb.right, top: bb.top + (bb.height / 2) }; var left = cm.coordsChar(leftPt, "window"); var right = cm.coordsChar(rightPt, "window"); var text = cm.getRange(left, right); var token = { start: left, end: right, text: text }; focusedCM = cm; window.spellcheck.postMessage({contextMenu: true, target: token}); } return false; } function onFocus(cm) { focusedCM = cm; } function onBlur(cm) { focusedCM = null; } CodeMirror.defineOption("systemSpellcheck", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { clearMarks(cm); cm.off("change", onChange); cm.off("cursorActivity", onCursor); cm.off("contextmenu", onContextMenu); cm.off("focus", onFocus); cm.off("blur", onBlur); clearTimeout(cm.state.systemSpellcheck.timeout); delete cm.state.systemSpellcheck; } if (val) { var state = cm.state.systemSpellcheck = new CheckState(cm, parseOptions(cm, val)); cm.on("change", onChange); cm.on("cursorActivity", onCursor); cm.on("contextmenu", onContextMenu); cm.on("focus", onFocus); cm.on("blur", onBlur); startChecking(cm); } });
javascript
28
0.633391
113
26.511962
209
starcoderdata
// Copyright 2018 Google LLC // // 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. // Displays the overlay loading dialog. function showLoadingDialog() { $('.loading-dialog').show(); } // Hides the overlay loading dialog. function hideLoadingDialog() { $('.loading-dialog').hide(); } // Shows an error with a title and a JSON object that is pretty printed. function showJsonError(title, json) { showError(title, JSON.stringify(json, null, 2)); } // Shows an error with a title and text. Scrolls the screen to show the error. function showError(title, text) { // Hide the loading dialog, just in case it is still being displayed. hideLoadingDialog(); $('#errorTitle').text(title); $('#errorMessage').text(text); $('#error').show(); // Scroll to show the error message on screen. $('html,body').animate({scrollTop: $('#error').offset().top}, 300); } // Hides the error message. function hideError() { $('#error').hide(); } // Handles errors returned from the backend. // Intended to be used as the error handler for ajax request to the backend. // For authentication issues, the user is redirected to the log out screen. // Otherwise, the error is shown to the user (and prettyprinted if possible). function handleError(title, data) { console.log('Error: ' + JSON.stringify(data)); if((data[0] != null) && (data[0].statusCode == 401)) { // Authentication error. Redirect back to the log in screen. window.location = '/logout'; } else if((data.error != null) && (data.error.code == 401)){ // Authentication error. Redirect back to the log in screen. window.location = '/logout'; } else if ((data.status != null) && (data.status == 0)) { // Server could not be reached from the request. // It could be blocked, unavailable or unresponsive. showError(title, 'Server could not be reached. Please try again.'); } else if (data.responseJSON) { // JSON error that can be formatted. showJsonError(title, data.responseJSON); } else { // Otherwise, display the data returned by the request. showError(title, data); } hideLoadingDialog(); } function displayRemainingAPICalls() { $.ajax({ type: 'GET', url: '/getRemainingCalls', dataType: 'json', success: (data) => { if (data[0] != null) { $("#remaining-plantnet-ids").append(data[0]); } else { $("#remaining-plantnet-ids").append('-'); } }, error: (data) => { handleError('Error trying to get remaining calls: ', data.message); } }); }
javascript
19
0.668523
78
31.83871
93
starcoderdata
package pokedex.Data; import java.util.*; public class Sorting { // Specific searches public static Pokemon searchPokemon(String search) { String name = search.trim().substring(0, 1).toUpperCase() + search.substring(1); for (Pokemon o : DataBank.Pokedex) { if (Objects.equals(name, o.getName())) { return o; } } System.err.println("Could not find that pokemon: " + name); return null; } public static Pokemon searchPokemonID(Integer ID) { int id = Math.abs(ID); for (Pokemon o : DataBank.Pokedex) { if (id == o.getId()) { return o; } } System.err.println("Could not find that pokemon id: " + id); return null; } } // Number compares class totalPoints implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o1.getTotalPoints(), o2.getTotalPoints()); } } class healthPoints implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o1.getHealthPoints(), o2.getHealthPoints()); } } class Attack implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o1.getAttack(), o2.getAttack()); } } class Defense implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o1.getDefense(), o2.getDefense()); } } class specialAttack implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o1.getSpecialAttack(), o2.getSpecialAttack()); } } class specialDefense implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o1.getSpecialDefense(), o2.getSpecialDefense()); } } class speed implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o1.getSpeed(), o2.getSpeed()); } } class Generation implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o2.getGeneration(), o1.getGeneration()); } } class Level implements Comparator { public int compare(Pokemon o1, Pokemon o2) { return Double.compare(o2.getLevel(), o1.getLevel()); } }
java
13
0.583181
88
27.419355
93
starcoderdata
func (f *DepthFrame) PushEvent(e DepthEvent) { select { case <-f.resetC: f.reset() default: } f.snapshotMutex.Lock() snapshot := f.snapshotDepth f.snapshotMutex.Unlock() // before the snapshot is loaded, we need to buffer the events until we loaded the snapshot. if snapshot == nil { // buffer the events until we loaded the snapshot f.bufferEvent(e) go f.once.Do(func() { if err := f.loadDepthSnapshot(); err != nil { log.WithError(err).Errorf("%s depth snapshot load failed, resetting..", f.Symbol) f.emitReset() } }) return } // drop old events if e.FinalUpdateID <= snapshot.FinalUpdateID { log.Infof("DROP %s depth update event, updateID %d ~ %d (len %d)", f.Symbol, e.FirstUpdateID, e.FinalUpdateID, e.FinalUpdateID-e.FirstUpdateID) return } if e.FirstUpdateID > snapshot.FinalUpdateID+1 { log.Infof("MISSING %s depth update event, resetting, updateID %d ~ %d (len %d)", f.Symbol, e.FirstUpdateID, e.FinalUpdateID, e.FinalUpdateID-e.FirstUpdateID) f.emitReset() return } f.snapshotMutex.Lock() f.snapshotDepth.FinalUpdateID = e.FinalUpdateID f.snapshotMutex.Unlock() f.EmitPush(e) }
go
17
0.69191
93
23.744681
47
inline
@SuppressWarnings("unchecked") @Override public void run() { try { watchService = FileSystems.getDefault().newWatchService(); } catch (IOException e) { throw new RuntimeException("Exception while creating watch service", e); } watchKeyToDirectory = new HashMap<>(); for (Path dir : dirPaths) { try { // register the given directory, and all its sub-directories registerDirectory(dir); } catch (IOException e) { log.error("Not watching '{}'", dir, e); } } while (running) { if (Thread.interrupted()) { log.info("Directory watcher thread interrupted"); break; } WatchKey key; try { key = watchService.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); continue; } Path dir = watchKeyToDirectory.get(key); if (dir == null) { log.warn("Watch key not recognized"); continue; } // http://stackoverflow.com/a/25221600 try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore ?! } for (WatchEvent<?> event : key.pollEvents()) { if (event.kind().equals(OVERFLOW)) { break; } WatchEvent<Path> pathEvent = (WatchEvent<Path>) event; WatchEvent.Kind<Path> kind = pathEvent.kind(); Path path = dir.resolve(pathEvent.context()); // if directory is created, and watching recursively, then register it and its sub-directories if (kind == ENTRY_CREATE) { try { if (Files.isDirectory(path, NOFOLLOW_LINKS)) { registerDirectory(dir); } } catch (IOException e) { // ignore } } if (running && EVENT_MAP.containsKey(kind)) { listener.onEvent(EVENT_MAP.get(kind), dir, pathEvent.context()); } } // reset key and remove from set if directory no longer accessible boolean valid = key.reset(); if (!valid) { watchKeyToDirectory.remove(key); // log.warn("'{}' is inaccessible, stopping watch", dir); if (watchKeyToDirectory.isEmpty()) { break; } } } }
java
16
0.454971
110
32.059524
84
inline
/* Copyright (c) 2012-2014 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * (Boundless) - initial implementation */ package org.locationtech.geogig.api; import org.opengis.feature.type.FeatureType; import org.opengis.feature.type.Name; import org.opengis.feature.type.PropertyDescriptor; import com.google.common.collect.ImmutableList; public interface RevFeatureType extends RevObject { public abstract FeatureType type(); /** * @return the sorted {@link PropertyDescriptor}s of the feature type */ public abstract ImmutableList sortedDescriptors(); /** * @return the name of the feature type */ public abstract Name getName(); }
java
6
0.753595
80
30.636364
33
starcoderdata
// .result=COMPILE_OUTPUT // .options=XstructuredPrint public class Test { public static void main(String[] args) { Object f = b -> b ? ((i, j) -> i + j) : (x -> x + 5); } }
java
10
0.612903
55
23.111111
9
starcoderdata
#pragma once #include class Audio { public: Audio(std::string filename); void release(); void play(); void pause(); void resume(); private: Mix_Music* music = NULL; };
c
8
0.610577
32
12.933333
15
starcoderdata
var input = File.ReadAllLines("input.txt"); var numbers = input[0].Split(",").Select(int.Parse).ToArray(); var part1 = ReadBoards().Play(numbers).First(); var part2 = ReadBoards().Play(numbers).Last(); Console.WriteLine((part1, part2)); IEnumerable ReadBoards() => input.Skip(2).GetBoards().ToArray(); class Board { int[,] _numbers; public Board(int[,] numbers) { _numbers = numbers; } public bool Apply(int number) { foreach (var c in Coordinates().Where(c => this[c] == number)) this[c] = -1; return Won; } public bool Won { get { for (var row = 0; row < 5; row++) if (Range(0, 5).All(col => this[(row, col)] == -1)) return true; for (var col = 0; col < 5; col++) if (Range(0, 5).All(row => this[(row, col)] == -1)) return true; return false; } } int this[(int row, int col) p] { get => _numbers[p.row, p.col]; set => _numbers[p.row, p.col] = value; } public int Sum() => Coordinates().Select(c => this[c]).Where(i => i != -1).Sum(); static IEnumerable<(int row, int col)> Coordinates() { for (int row = 0; row < 5; row++) for (int col = 0; col < 5; col++) yield return (row, col); } } static class Extensions { public static IEnumerable Play(this IEnumerable boards, IEnumerable numbers) => from draw in numbers from board in boards where !board.Won // required for part 2 let win = board.Apply(draw) where win select (draw * board.Sum()); public static IEnumerable GetBoards(this IEnumerable input) => from chunk in input.Chunk(6) select CreateBoard(chunk.Take(5)); static Board CreateBoard(IEnumerable chunk) { var board = new int[5, 5]; var row = 0; foreach (var line in chunk) { var span = line.AsSpan(); for (var col = 0; col < 5; col++) { board[row, col] = int.Parse(span.Slice(col * 3, 2)); } row++; } return new Board(board); } }
c#
19
0.523029
108
29.12
75
starcoderdata
private IEnumerator sceneTransition(float time) { yield return new WaitForSeconds(time); currentScene.UnloadDecors(); // Supprime les décors de la scene actuelle. currentScene = _scenes.Dequeue(); // Change la scene actuelle currentScene.LoadDecors(); // Génère les décors de la scene actuelle. currentScene.OnStart(); }
c#
8
0.593381
90
37.545455
11
inline
import ItemSet, ItemDto, Event import eventFunction, itemSetFunction, applicationFunction print('MenuEvent library imported') class MenuEvent(Event.Event): def update(self): self.updateStatus(eventFunction.Status.RESOLVED) def __init__(self,object,itemsPathTree,onLeftClick,onMenuResolve, name = None, itemSize = None, type = eventFunction.Type.MENU_EVENT, inherited = False ): Event.Event.__init__(self,object, name = name, type = type, inherited = True ) self.inherited = inherited self.itemsPathTree = itemsPathTree self.itemNames = list(self.itemsPathTree.keys()) self.itemSize = itemSize self.itemsDto = [] for index in range(len(self.itemNames)) : self.itemsDto.append(ItemDto.ItemDto( self.itemNames[index], text = self.itemNames[index], onLeftClick = onLeftClick, onMenuResolve = onMenuResolve )) self.execute() def buildItems(self,itemsDirection): itemSetName = f'{itemSetFunction.Attribute.NAME}' itemSetFather = self.object ItemSet.ItemSet(itemSetName,itemSetFather, itemsDto = self.itemsDto, itemsDirection = itemsDirection, itemsPriority = applicationFunction.Priority.HIGHT, itemSize = self.itemSize, noImage = True, )
python
15
0.611075
69
29.7
50
starcoderdata
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class MailController extends Controller { public function send(Request $request){ $from = $request->name; $from_email = $request->email; $message = $request->message; $captcha = $request->input('g-recaptcha-response'); if(!isset($captcha)){ return 'fail'; } $name_app = config("app.name"); $emails_group = array(' $title = 'Ey contacto Heavydeveloper'; Mail::send('vendor.mail.new.template', [ 'from'=>$from , 'message_to' => $message, 'from_email' => $from_email ], function ($m) use ( $name_app, $emails_group, $title) { $m->from(' $name_app); $m->to($emails_group)->subject($title); }); /*---REPLAY-----*/ Mail::send('vendor.mail.new.replay', [ 'from'=>$from , 'message_to' => $message, 'from_email' => $from_email ], function ($m) use ( $name_app, $emails_group, $from_email, $title) { $m->from(' $name_app); $m->to($from_email)->subject($title); }); return 'success'; } }
php
17
0.460417
59
25.181818
55
starcoderdata
def __init__(self) -> None: # here, we look for any methods whose name start with 'test' self._functuplst = ll = [] for funcname in dir(self): if funcname.startswith('test'): func = getattr(self, funcname) if callable(func): ll.append((funcname, func))
python
13
0.520588
68
41.625
8
inline
"""this script continuously polls for temperature and saves it as data.csv""" import serial import time import serial.tools.list_ports import os def listPorts(): for item in serial.tools.list_ports.comports(): print(item) def getFreq(ser): while True: try: freq=ser.readline().decode('utf-8').strip() if freq.startswith("F="): freq=freq[2:] return int(freq) except: print("frequency reading failed!") def getTemp(ser): while True: try: ser.write('r'.encode('ascii')) temp=ser.readline().decode('utf-8').strip() #print("TEMP:",temp) temp=float(temp) return temp except: print("temperature reading failed!") def logLine(line,fname="data.csv",firstLine=False): if type(line) == list: line=[str(x) for x in line] line=",".join(line) if firstLine: with open(fname,'w') as f: f.write("# "+line) with open(fname,'a') as f: f.write(line+"\n") if __name__=="__main__": logLine(["time","freq","temp"],firstLine=True) serTemp=serial.Serial('COM51', 4800, timeout=2) serFreq=serial.Serial('COM52', 4800, timeout=2) nReads=0 while True: try: freq=getFreq(serFreq) temp=getTemp(serTemp) tnow="%.02f"%time.time() logLine([tnow,freq,temp]) nReads+=1 print([nReads,tnow,freq,temp]) time.sleep(.5) if nReads==60*10: # 10 minute mark print("HEATER ON") serTemp.write('o'.encode('ascii')) if temp>=100 or nReads==60*70: # 10 minutes + 1 hour of heating print("HEATER OFF") serTemp.write('f'.encode('ascii')) except: print("EXCEPTION!") break print("disconnecting...") serTemp.close() serFreq.close() print("DONE")
python
15
0.510608
77
26.302632
76
starcoderdata
from unittest import TestCase import os from file_readers.excel.excel_reader import ExcelReader from file_readers.excel.simple_excel_data_collector import SimpleExcelDataCollector from file_readers.excel.tests.simple_cell import SimpleCell from openpyxl.cell import Cell base_path = os.path.dirname(__file__) class TestSimpleExcelDataCollector(TestCase): def test_collect_data_with_header(self): data_source = [] row = (SimpleCell("A1", "Name"), SimpleCell("B1", "Age"), SimpleCell("C1", "Title")) data_source.append(row) row = (SimpleCell("A2", "John"), SimpleCell("B2", 24), SimpleCell("C2", "Developer")) data_source.append(row) collector = SimpleExcelDataCollector(use_header=True) for row in data_source: collector.collect_data(row) result_row = collector.data[0] self.assertEqual(result_row['Name'], 'John') self.assertEqual(result_row['Age'], 24) self.assertEqual(result_row['Title'], "Developer") def test_collect_data_without_header(self): data_source = [] row = (SimpleCell("A1", "Name"), SimpleCell("B1", "Age"), SimpleCell("C1", "Title")) data_source.append(row) row = (SimpleCell("A2", "John"), SimpleCell("B2", 24), SimpleCell("C2", "Developer")) data_source.append(row) collector = SimpleExcelDataCollector(use_header=False) for row in data_source: collector.collect_data(row) result_row = collector.data[0] self.assertEqual("Name", result_row[0]) self.assertEqual("Age", result_row[1]) self.assertEqual("Title", result_row[2]) result_row = collector.data[1] self.assertEqual("John", result_row[0]) self.assertEqual(24, result_row[1]) self.assertEqual("Developer", result_row[2]) def test_with_reader_using_headers(self): test_file = base_path + "/data/test.xlsx" collector = SimpleExcelDataCollector(use_header=True) reader = ExcelReader(data_collector=collector) reader.set_sheet_to_read("Personnel") reader.read_file(test_file) result_row = collector.data[0] self.assertEqual(result_row['Name'], 'John') self.assertEqual(result_row['Age'], 24) self.assertEqual(result_row['Title'], "Developer") def test_with_reader_not_using_headers(self): test_file = base_path + "/data/test.xlsx" collector = SimpleExcelDataCollector(use_header=False) reader = ExcelReader(data_collector=collector) reader.set_sheet_to_read("Personnel") reader.read_file(test_file) result_row = collector.data[0] self.assertEqual("Name", result_row[0]) self.assertEqual("Age", result_row[1]) self.assertEqual("Title", result_row[2]) result_row = collector.data[1] self.assertEqual("John", result_row[0]) self.assertEqual(24, result_row[1]) self.assertEqual("Developer", result_row[2])
python
11
0.623094
83
36.360465
86
starcoderdata
<?php namespace extpoint\yii2\gii\models; class MigrationClass extends BaseClass { }
php
3
0.77551
38
11.375
8
starcoderdata
'use strict'; import { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLList, GraphQLNonNull } from 'graphql'; import { characterType, filterByIds as findCharacters } from './characters'; import { specieType, filterByIds as findSpecies } from './species'; import { starshipType, filterByIds as findStarships } from './starships'; import { vehicleType, filterByIds as filterVehicles } from './vehicles'; import { planetType, filterByIds as findPlanets } from './planets'; export const filmType = new GraphQLObjectType({ name: 'Film', description: `Information about a film`, fields: () => { return { title: { type: GraphQLString, description: `The title of this film` }, id: { type: GraphQLInt, description: `Episode number` }, opening_crawl: { type: GraphQLString, description: `The opening paragraphs at the beginning of this film` }, characters: { type: new GraphQLNonNull(new GraphQLList(characterType)), description: 'An array of characters that are in this film', resolve({ characters }, _, ctx) { return findCharacters(characters, ctx); } }, species: { type: new GraphQLNonNull(new GraphQLList(specieType)), description: 'List of characters that are in this film', resolve: ({ species }, _, ctx) => findSpecies(species, ctx) }, planets: { type: new GraphQLNonNull(new GraphQLList(planetType)), description: `List of planets that are in this film.`, resolve: ({ planets }, _, ctx) => findPlanets(planets, ctx) }, starships: { type: new GraphQLNonNull(new GraphQLList(starshipType)), description: `List of starships that in this film.`, resolve: ({ starships }, _, ctx) => findStarships(starships, ctx) }, vehicles: { type: new GraphQLNonNull(new GraphQLList(vehicleType)), description: `List of vehicles that in this film.`, resolve: ({ vehicles }, _, ctx) => filterVehicles(vehicles, ctx) }, director: { type: GraphQLString, description: `The name of the director of this film` }, producers: { type: new GraphQLNonNull(new GraphQLList(GraphQLString)), description: `The name(s) of the producer(s) of this film.` }, release_date: { type: GraphQLString, description: `The ISO 8601 date format of film release at original creator country.` } }; } }); export const filmsQuery = { type: new GraphQLNonNull(new GraphQLList(filmType)), resolve: (_parentValue, _args, { filmsDB }) => filmsDB.all() }; export const filmByIdQuery = { type: filmType, description: 'Return the film with the given id or null it there\'s no film for the episode', args: { id: { type: new GraphQLNonNull(GraphQLString) }, }, resolve: (context, { id }, { filmsDB }) => filmsDB.getById(id) }; export const filmsByTitleQuery = { type: new GraphQLNonNull(new GraphQLList(filmType)), description: 'Returns films which has a given words or expression in is title (empty if no film matchs)', args: { title: { type: new GraphQLNonNull(GraphQLString), description: 'If title="The", will return all films wiht the in the title (search is not case senstive)' }, }, resolve: (context, { title }, { filmsDB }) => { if (title.length > 2048) { throw new Error("Invalid id value"); } return filmsDB.filterByTitle(title); } }; export const filterByIds = (ids, { filmsDB }) => filmsDB.filterByIds(ids);
javascript
14
0.682997
107
30.834862
109
starcoderdata
#ifndef COMBO_H #define COMBO_H #include #include #include "ComboTitle.h" #include "objects/Digit.h" class Combo { public: Combo(u8 playerId); void setValue(int value); inline u32 getValue() { return value; } void show(); void hide(); void relocate(); void tick(); inline ComboTitle* getTitle() { return title.get(); } inline std::vector getDigits() { return &digits; } ~Combo(); private: u32 value = 0; std::unique_ptr title; std::vector digits; u8 playerId; }; #endif // COMBO_H
c
9
0.675074
77
17.722222
36
starcoderdata
/* A stack is a data structure that holds a list of elements. A stack works based on the LIFO principle meaning that the most recently added element is the first one to remove. It has two main operations that occur only at the top of the stack: push and pop. The push operation places an element at the top of stack whereas the pop operation removes an element from the top of the stack. */ function Stack () { this.count = 0; this.obj = {}; } // Adding a value at the top of the stack. And the key of the object will be the current value of count. And the new value that I am pushing will be the value of that key-value pair. Stack.prototype.push = function(value) { this.obj[this.count] = value; this.count++; } // remove, or pop out the top-most value from the stack Stack.prototype.pop = function() { if (this.count === 0 ) { return undefined; } this.count--; let result = this.obj[this.count]; // Hook-up to the key of the object that I will remove delete this.obj[this.count]; return result; } // return the length of the stack, which is the size or how many items were inserted Stack.prototype.size = function () { return this.count; }
javascript
9
0.700499
213
36.59375
32
starcoderdata
// // Created by dominik on 2/24/21. // #include "Core.h" void Netherite::Core::Init() { _module_ctl.Init(); } void Netherite::Core::Exec() { } Netherite::Core::Core() :Module() {} Netherite::Core::~Core() = default;;
c++
6
0.603524
36
12.411765
17
starcoderdata
const os = require('os'); const expect = require('chai').expect; const TRUSTED_PROXY_URL = os.hostname() + ':3004'; const TRANSPARENT_PROXY_URL = os.hostname() + ':3005'; const ERROR_PROXY_URL = 'ERROR'; describe('Using external proxy server', function () { it('Should open page via proxy server', function () { return runTests('testcafe-fixtures/index.test.js', null, { useProxy: TRANSPARENT_PROXY_URL }); }); it('Should open restricted page via trusted proxy server', function () { return runTests('testcafe-fixtures/restricted-page.test.js', null, { useProxy: TRUSTED_PROXY_URL }); }); }); describe('Using proxy-bypass', function () { it('Should bypass using proxy by one rule', function () { return runTests('testcafe-fixtures/index.test.js', null, { useProxy: ERROR_PROXY_URL, proxyBypass: 'localhost:3000' }); }); it('Should bypass using proxy by comma-separated string of rules', function () { return runTests('testcafe-fixtures/index.test.js', null, { useProxy: ERROR_PROXY_URL, proxyBypass: 'dummy,localhost:3000' }); }); it('Should bypass using proxy by array of rules', function () { return runTests('testcafe-fixtures/index.test.js', null, { useProxy: ERROR_PROXY_URL, proxyBypass: ['dummy', 'localhost:3000'] }); }); it('Should bypass using proxy by array of comma-separated strings', function () { return runTests('testcafe-fixtures/index.test.js', null, { useProxy: ERROR_PROXY_URL, proxyBypass: ['dummy,localhost:3000', 'dummy,localhost:3000'] }); }); it('Should fail using proxy-bypass which is set by incorrect argument', function () { return runTests('testcafe-fixtures/index.test.js', null, { useProxy: ERROR_PROXY_URL, proxyBypass: /dummy/, shouldFail: true }) .catch(function (err) { expect(err.message).contains('The "proxyBypass" argument (object) is not of expected type (string or an array)'); }); }); it('Should open page without proxy but get resource with proxy', function () { const http = require('http'); const server = http.createServer(function (req, res) { res.write('document.getElementById(\'result\').innerHTML = \'proxy\''); res.end(); }).listen(3006); return runTests('testcafe-fixtures/bypass-page-proxy-request.test.js', null, { useProxy: 'localhost:3006', proxyBypass: 'localhost:3000' }) .then(() => { server.close(); }); }); });
javascript
19
0.636858
159
44.122807
57
starcoderdata
def data_outlier_remove(data): "remove outlier values based on difference in immediate sample values" CONST_DATA_DIFF = 3 # CONST_DATA_DIMENSION = 12 # Number of ECG leads if(data > CONST_DATA_DIFF).any() or (data < -CONST_DATA_DIFF).any(): for ii in range(CONST_DATA_DIMENSION): # STEP 1: indexes where the difference between immediate samples is greater than +/- CONST_DATA_DIFF idx1 = np.argwhere(np.diff(data[ii]) > CONST_DATA_DIFF) idx2 = np.argwhere(np.diff(data[ii]) < -CONST_DATA_DIFF) idx = np.unique(np.concatenate((idx1,idx2))) del idx1, idx2 # STEP 2: replace above indexes ('idx') with values from previous sample if idx.shape[0] > 0: for jj in idx: data[ii][jj+1] = data[ii][jj] return data
python
15
0.596266
112
39.857143
21
inline
#ifndef __APP_H__ #define __APP_H__ #include "m1Module.h" #include "p2PerfTimer.h" #include "p2Timer.h" #include "PugiXml\src\pugixml.hpp" #include #include "p2Random.h" // Modules class m1Window; class m1Input; class m1Render; class m1Textures; class m1Audio; class m1Map; class m1Scene; class m1GUI; class m1Fonts; class m1MainMenu; class m1EntityManager; class m1PathFinding; class m1FadeToBlack; class m1Collision; class m1EasingSplines; class m1DialogSystem; class m1CutScene; class m1ParticleManager; class m1VideoPlayer; class m1MenuManager; struct GlobalGameAdvances { bool CutSceneTutorialGirlEscapingPlayed = false; bool CutSceneFinalRoomTutorialPlayed = false; bool CutSceneMiddleRoomTutorialPlayed = false; bool CutSceneAfterBossTutorialPlayed = false; bool CutSceneLobbyExplain = false; bool CutSceneLobbyQuest2Finish = false; bool CutSceneLobbyCredits = false; bool Tutorial_first_time = true; bool ability1_gained = false; bool ability2_gained = false; bool ability3_gained = false; bool helmet_bought = false; bool ring_bought = false; bool shop_gone = false; bool CutSceneHomeToSleepQuest2 = false; bool drake_killed = false; bool quest2_rocks_cave_destroyed = false; bool CutSceneQueenQuest2 = false; bool CutSceneFinalRoomQuest2 = false; bool treasure_quest2_opened = false; bool ice_queen_killed = false; bool treasure_boss_opened = false; bool treasure_quest3_opened = false; bool CutSceneHomeToSleeQuest3 = false; bool sleep2 = false; bool CutsceneFinalGame = false; bool CutsceneFinalFinalGame = false; bool CutsceneBegin = false; bool CutsceneLittleDrake = false; bool CutsceneDrake3 = false; bool Ability3PanelShowed = false; std::string player_name; void Reset() { ice_queen_killed = false; sleep2 = false; CutSceneHomeToSleepQuest2 = false; CutSceneLobbyQuest2Finish = false; treasure_quest2_opened = false; treasure_boss_opened = false; treasure_quest3_opened = false; CutSceneTutorialGirlEscapingPlayed = false; CutSceneFinalRoomTutorialPlayed = false; CutSceneMiddleRoomTutorialPlayed = false; CutSceneAfterBossTutorialPlayed = false; CutSceneLobbyExplain = false; CutSceneHomeToSleeQuest3 = false; Tutorial_first_time = true; ability1_gained = false; ability2_gained = false; ability3_gained = false; helmet_bought = false; ring_bought = false; drake_killed = false; shop_gone = false; quest2_rocks_cave_destroyed = false; CutSceneQueenQuest2 = false; CutSceneFinalRoomQuest2 = false; CutsceneFinalGame = false; CutsceneFinalFinalGame = false; CutSceneLobbyCredits = false; CutsceneBegin = false; CutsceneLittleDrake = false; CutsceneDrake3 = false; Ability3PanelShowed = false; } }; class Application { public: // Constructor Application(int argc, char* args[]); // Destructor virtual ~Application(); // Called before render is available bool Awake(); // Called before the first frame bool Start(); // Called each loop iteration bool Update(); // Called before quitting bool CleanUp(); // Add a DBG_NEW module to handle void AddModule(m1Module* module); // Exposing some properties for reading int GetArgc() const; const char* GetArgv(int index) const; const char* GetTitle() const; const char* GetOrganization() const; const char* GetVersion() const; void LoadGame(const char* file); void SaveGame(const char* file) const; inline bool LookForFileExistence(const std::string& name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } //Exit void QuitGame(); inline bool ClosingGame() { return quit_game; } bool GetPause(); bool ChangePause(); uint32 GetFps(); float GetDeltaTime(); bool GetInventory(); bool ChangeInventory(); pugi::xml_node LoadConfig(pugi::xml_document&, std::string name) const; bool capactivated = true; bool fast_start = false; bool debug = false; private: // Load config file // Call modules before each loop iteration void PrepareUpdate(); // Call modules before each loop iteration void FinishUpdate(); // Call modules before each loop iteration bool PreUpdate(); // Call modules on each loop iteration bool DoUpdate(); // Call modules after each loop iteration bool PostUpdate(); // Load / Save bool LoadGameNow(); bool SavegameNow() const; public: // Modules m1Window * win = nullptr; m1Input* input = nullptr; m1Render* render = nullptr; m1Textures* tex = nullptr; m1Audio* audio = nullptr; m1Map* map = nullptr; m1Scene* scene = nullptr; m1Fonts* fonts = nullptr; m1GUI* gui = nullptr; m1MainMenu* main_menu = nullptr; m1EntityManager* entity_manager = nullptr; m1PathFinding* pathfinding = nullptr; m1FadeToBlack* fade_to_black = nullptr; m1Collision* collision = nullptr; m1EasingSplines* easing_splines = nullptr; m1DialogSystem* dialog = nullptr; m1CutScene* cutscene_manager = nullptr; m1ParticleManager* particles = nullptr; m1MenuManager* menu_manager = nullptr; m1VideoPlayer* video_player = nullptr; GlobalGameAdvances globals; Random random; private: std::list modules; int argc; char** args = nullptr; std::string title; std::string organization; std::string version; mutable bool want_to_save = false; bool want_to_load = false; std::string load_game; mutable std::string save_game; bool quit_game = false; bool is_paused = false; bool is_inventory = false; pugi::xml_document config_file; pugi::xml_node config; std::string config_name; p2PerfTimer ptimer; uint64 frame_count = 0u; p2Timer startup_time; p2Timer frame_time; p2Timer last_sec_frame_time; uint32 last_sec_frame_count = 0u; uint32 prev_last_sec_frame_count = 0u; uint16_t framerate_cap = 0u; float avg_fps = 0.0f; uint32 frames_on_last_update = 0u; float dt = 0.f; }; extern Application* App; #endif
c
13
0.723889
72
22.768924
251
starcoderdata
#include #include int main(int argc, char** argv) { int i = 0; const char *p_str = ""; config_t config; config_init(&config); if(config_read_file(&config, "example.conf") != CONFIG_TRUE) { printf("Failed to read conf file: %d %s\n", config_error_line(&config), config_error_text(&config)); return -1; } config_lookup_string(&config, "server", &p_str); printf("Hello World '%s'\n", p_str); config_destroy(&config); return 0; }
c
11
0.645098
63
17.888889
27
starcoderdata
package com.study.util.sort.offer; import java.util.Iterator; import java.util.Stack; public class EvaluateExpression2 { public static void main(String[] args) { char[] chars = "7 + 3 + 6 / 2 - 6 / 3 + 1 + 2 * 1".replaceAll("\\s", "").toCharArray(); System.out.println(computeStr(chars)); System.out.println(computeStr(chars) == 14); chars = "7 + 3 + 6 / 2 * 6 / 3 + 1 + 2 * 1".replaceAll("\\s", "").toCharArray(); System.out.println(computeStr(chars)); System.out.println(computeStr(chars) == 19); chars = "7 + 3 + 6 - 2 - 6 + 3 + 1 + 2 + 1".replaceAll("\\s", "").toCharArray(); System.out.println(computeStr(chars)); System.out.println(computeStr(chars) == 15); chars = "6 / 3 * 6 / 2 / 6 * 3 * 2 * 2 / 2".replaceAll("\\s", "").toCharArray(); System.out.println(computeStr(chars)); System.out.println(computeStr(chars) == 6); } private static int computeStr(char[] chars) { Stack numStack = new Stack<>();//存放操作数 Stack opStack = new Stack<>();//存放操作符 boolean flag = true; for (int i = 0; i < chars.length; i++) { if (chars[i] >= '0' && chars[i] <= '9') { numStack.push(Integer.valueOf(chars[i] + "")); flag = true; while (opStack.size() > 1 && flag) { char currentOp = opStack.pop(); char frontOp = opStack.peek(); if (judgeOp(currentOp, frontOp)) { int nextNum = numStack.pop(); int frontNum = numStack.pop(); numStack.push(compute(frontNum, nextNum, currentOp)); } else { opStack.push(currentOp); flag = false; } } } else { opStack.push(chars[i]); } } int result = 0; Iterator opIter = opStack.iterator(); Iterator numIter = numStack.iterator(); int front = numIter.next(); while (opIter.hasNext()) { result = compute(front, numIter.next(), opIter.next()); front = result; } return result; } //判断运算符优先级,c1 > c2则返回true private static boolean judgeOp(char c1, char c2) { int num1 = 0, num2 = 0; num1 = switchOpOrder(c1); num2 = switchOpOrder(c2); if (num1 > num2) { return true; } return false; } private static int switchOpOrder(char op) { switch (op) { case '#': return 0; case '+': case '-': return 1; case '*': case '/': return 2; case '(': case ')': return 3; } return -1; } //根据运算符对操作数求值 private static int compute(int t1, int t2, char c) { if (c == '+') { return t1 + t2; } else if (c == '-') { return t1 - t2; } else if (c == '*') { return t1 * t2; } else { return t1 / t2; } } }
java
18
0.455873
95
24.679688
128
starcoderdata
using System; namespace SFA.Business.Models { public class SchedulingPassenger : Entity { public Guid PassengerId { get; set; } public Passenger Passenger { get; set; } public Guid SchedulingId { get; set; } public Scheduling Scheduling { get; set; } } }
c#
8
0.666667
51
24.285714
14
starcoderdata
<?php /* All model from sarung database will follow this class , so that we just change change here to impact to another class */ class Sarung_Model_Root extends Eloquent{ protected $connection = 'fusarung'; /*If you decided to use raw query , use below*/ public static function get_db(){ return Config::get('database.main_db'); //return "fusarung"; } public static function get_db_name(){ return Config::get('database.connections.fusarung.database'); //return "mgscom_ngoos"; } /** * will check and return valid value * return -1 if null , id number otherwise **/ protected function check_and_get_id($obj){ if( $obj->first()){ return $obj->first()->id; } return -1; } }
php
11
0.684211
81
26.038462
26
starcoderdata
import React from 'react'; import Layout from '../components/layout'; import { HelmetDatoCms } from 'gatsby-source-datocms'; import { navigate } from 'gatsby-link'; import { graphql } from 'gatsby'; const encode = (data) => { return Object.keys(data) .map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])) .join('&'); }; const Contact = ({ data }) => { const [state, setState] = React.useState({}); const handleChange = (e) => { setState({ ...state, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { e.preventDefault(); const form = e.target; fetch('/', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: encode({ 'form-name': form.getAttribute('name'), ...state, }), }) .then(() => navigate(form.getAttribute('action'))) .catch((error) => alert(error)); }; return ( <article className='contact'> <HelmetDatoCms seo={data.contact.seoMetaTags} /> <div className='contact__inner'> <h1 className='contact__title'>Contact Me <p className='contact__content'> Hello! You can contact me by messaging me on Facebook, Instragram or sending me an email. Links are below (click on icons). If you are interested in commisioning art work from me, please fill out the form below. I can't wait to hear your ideas! <p className='contact__social'> {data.allDatoCmsSocialProfile.edges.map(({ node: profile }) => ( <a key={profile.profileType} href={profile.url} target='blank' className={`social social--${profile.profileType.toLowerCase()}`} > {' '} ))} <h2 className='contact__formTitle'>Request A Commission <form className='contact__form' name='commision-request' method='post' data-netlify='true' data-netlify-honeypot='bot-field' action='/thank-you/' onSubmit={handleSubmit} > <input type='hidden' name='form-name' value='commision-request' /> <input type='hidden' name='bot-field' onChange={handleChange} /> <input type='text' name='name' placeholder='NAME' onChange={handleChange} /> <input type='email' name='email' placeholder='EMAIL' onChange={handleChange} /> <textarea name='message' placeholder='Describe what you would like me to create.' onChange={handleChange} /> <button type='submit'>Send Request ); }; export default Contact; export const query = graphql` query ContactQuery { contact: datoCmsContactPage { seoMetaTags { ...GatsbyDatoCmsSeoMetaTags } } allDatoCmsSocialProfile(sort: { fields: [position], order: ASC }) { edges { node { profileType url } } } } `;
javascript
21
0.499586
81
27.984
125
starcoderdata
def grad_logreg(X, y, W, reg = 0.0): ''' Return the gradient of W for logistic regression. ''' # YOUR CODE BELOW grad = X.T @ (sigmoid(X @ W) - y) + reg * W return grad
python
12
0.596591
51
21.125
8
inline
<?php return [ 'name' => 'Contract Name', 'status' => 'Status', 'action' => 'Action', 'noContracts' => 'There are currently no contracts available.', 'signed' => 'Signed', 'pendingSignature' => 'Pending Signature', 'sign' => 'Sign Contract', 'download' => 'Download Contract', ];
php
5
0.581994
67
27.363636
11
starcoderdata
import Axios from "axios"; /** * 系统认证接口 */ export default { /** * 系统登陆 */ loginIn: function ({ loginName, password }) { var param = { mobile: loginName, password: password }; return Axios.post('/napi/homeApi/login', param); }, /** * 退出登陆 */ loginOut: function () { return Axios.post('/api/shiro-api/loginout'); }, /** * 记录登陆日志 */ loginLog: function ({ip,city,type}) { var param={ ip:ip, city:city, type:type }; return Axios.post('/api/loginlog-api/save', param); }, /** * 还原数据 */ rollBackTables: function () { return Axios.post('/api/loginlog-api/rollBackTables'); } }
javascript
10
0.473214
62
18.6
40
starcoderdata
NTSTATUS GetRegistryCallbacks(OUT CALLBACK_INFO* CallbackArray, OUT ULONG* CallbackCount) { // Check if supported for this version of Windows. WINDOWS_INDEX WindowsIndex = GetWindowsIndex(); if (WindowsIndex == WINDOWS_INDEX::Unsupported) return STATUS_NOT_SUPPORTED; // Get search query. CALLBACK_SEARCH_QUERY Query = RegistryCallbackQueries[(ULONG)WindowsIndex]; // Resolve function addresses to get the start and end of the search space. PUCHAR StartAddress = (PUCHAR)MmGetSystemRoutineAddress(&Query.StartFunction); PUCHAR EndAddress = (PUCHAR)MmGetSystemRoutineAddress(&Query.EndFunction); // Search for an offset to the CallbackListHeadOrCmpCallBackVector linked-list head. PUCHAR CallbackListHeadOrCmpCallBackVector = nullptr; NTSTATUS Status = MemorySearch(StartAddress, EndAddress, Query.PatternBuffer, Query.PatternSize, &CallbackListHeadOrCmpCallBackVector); if (!NT_SUCCESS(Status)) return STATUS_NOT_FOUND; // Resolve the offset to get the address of CallbackListHeadOrCmpCallBackVector. CallbackListHeadOrCmpCallBackVector += Query.PatternOffset; CallbackListHeadOrCmpCallBackVector += *(PLONG)(CallbackListHeadOrCmpCallBackVector); CallbackListHeadOrCmpCallBackVector += sizeof(LONG); // Iterate through the linked list to populate the provided array. int i = 0; PLIST_ENTRY ListEntry = (PLIST_ENTRY)CallbackListHeadOrCmpCallBackVector; while (1) { PVOID CallbackFunction = *(PVOID*)((ULONG64)ListEntry + 0x28); CallbackArray[i].Type = CALLBACK_TYPE::CmRegistry; CallbackArray[i++].Address = CallbackFunction; ListEntry = ListEntry->Flink; // Break when back to first entry or array limit reached. if (((PVOID)ListEntry == (PVOID)CallbackListHeadOrCmpCallBackVector) || (i == MAX_CALLBACKS_REGISTRY)) { *CallbackCount = i; break; } }; return STATUS_SUCCESS; }
c++
13
0.76226
136
38.826087
46
inline