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
// Copyright 2014 BitPay Inc. // Copyright 2015 Bitcoin Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef __UNIVALUE_H__ #define __UNIVALUE_H__ #include #include #include #include #include #include // .get_int64() #include // std::pair class UniValue { public: enum VType { VNULL, VOBJ, VARR, VSTR, VNUM, VBOOL, }; UniValue() { typ = VNULL; } UniValue(UniValue::VType initialType, const std::string& initialStr = "") { typ = initialType; val = initialStr; } UniValue(uint64_t val_) { setInt(val_); } UniValue(int64_t val_) { setInt(val_); } UniValue(bool val_) { setBool(val_); } UniValue(int val_) { setInt(val_); } UniValue(double val_) { setFloat(val_); } UniValue(const std::string& val_) { setStr(val_); } UniValue(const char *val_) { std::string s(val_); setStr(s); } ~UniValue() {} void clear(); bool setNull(); bool setBool(bool val); bool setNumStr(const std::string& val); bool setInt(uint64_t val); bool setInt(int64_t val); bool setInt(int val_) { return setInt((int64_t)val_); } bool setFloat(double val); bool setStr(const std::string& val); bool setArray(); bool setObject(); enum VType getType() const { return typ; } const std::string& getValStr() const { return val; } bool empty() const { return (values.size() == 0); } size_t size() const { return values.size(); } bool getBool() const { return isTrue(); } bool checkObject(const std::map memberTypes); const UniValue& operator[](const std::string& key) const; const UniValue& operator[](size_t index) const; bool exists(const std::string& key) const { size_t i; return findKey(key, i); } bool isNull() const { return (typ == VNULL); } bool isTrue() const { return (typ == VBOOL) && (val == "1"); } bool isFalse() const { return (typ == VBOOL) && (val != "1"); } bool isBool() const { return (typ == VBOOL); } bool isStr() const { return (typ == VSTR); } bool isNum() const { return (typ == VNUM); } bool isArray() const { return (typ == VARR); } bool isObject() const { return (typ == VOBJ); } bool push_back(const UniValue& val); bool push_back(const std::string& val_) { UniValue tmpVal(VSTR, val_); return push_back(tmpVal); } bool push_back(const char *val_) { std::string s(val_); return push_back(s); } bool push_back(uint64_t val_) { UniValue tmpVal(val_); return push_back(tmpVal); } bool push_back(int64_t val_) { UniValue tmpVal(val_); return push_back(tmpVal); } bool push_back(int val_) { UniValue tmpVal(val_); return push_back(tmpVal); } bool push_backV(const std::vector vec); bool pushKV(const std::string& key, const UniValue& val); bool pushKV(const std::string& key, const std::string& val_) { UniValue tmpVal(VSTR, val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, const char *val_) { std::string _val(val_); return pushKV(key, _val); } bool pushKV(const std::string& key, int64_t val_) { UniValue tmpVal(val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, uint64_t val_) { UniValue tmpVal(val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, int val_) { UniValue tmpVal((int64_t)val_); return pushKV(key, tmpVal); } bool pushKV(const std::string& key, double val_) { UniValue tmpVal(val_); return pushKV(key, tmpVal); } bool pushKVs(const UniValue& obj); std::string write(unsigned int prettyIndent = 0, unsigned int indentLevel = 0) const; bool read(const char *raw, size_t len); bool read(const char *raw); bool read(const std::string& rawStr) { return read(rawStr.data(), rawStr.size()); } private: UniValue::VType typ; std::string val; // numbers are stored as C++ strings std::vector keys; std::vector values; bool findKey(const std::string& key, size_t& retIdx) const; void writeArray(unsigned int prettyIndent, unsigned int indentLevel, std::string& s) const; void writeObject(unsigned int prettyIndent, unsigned int indentLevel, std::string& s) const; public: // Strict type-specific getters, these throw std::runtime_error if the // value is of unexpected type const std::vector getKeys() const; const std::vector getValues() const; bool get_bool() const; const std::string& get_str() const; int get_int() const; int64_t get_int64() const; double get_real() const; const UniValue& get_obj() const; const UniValue& get_array() const; enum VType type() const { return getType(); } bool push_back(std::pair pear) { return pushKV(pear.first, pear.second); } friend const UniValue& find_value( const UniValue& obj, const std::string& name); }; // // The following were added for compatibility with json_spirit. // Most duplicate other methods, and should be removed. // static inline std::pair Pair(const char *cKey, const char *cVal) { std::string key(cKey); UniValue uVal(cVal); return std::make_pair(key, uVal); } static inline std::pair Pair(const char *cKey, std::string strVal) { std::string key(cKey); UniValue uVal(strVal); return std::make_pair(key, uVal); } static inline std::pair Pair(const char *cKey, uint64_t u64Val) { std::string key(cKey); UniValue uVal(u64Val); return std::make_pair(key, uVal); } static inline std::pair Pair(const char *cKey, int64_t i64Val) { std::string key(cKey); UniValue uVal(i64Val); return std::make_pair(key, uVal); } static inline std::pair Pair(const char *cKey, bool iVal) { std::string key(cKey); UniValue uVal(iVal); return std::make_pair(key, uVal); } static inline std::pair Pair(const char *cKey, int iVal) { std::string key(cKey); UniValue uVal(iVal); return std::make_pair(key, uVal); } static inline std::pair Pair(const char *cKey, double dVal) { std::string key(cKey); UniValue uVal(dVal); return std::make_pair(key, uVal); } static inline std::pair Pair(const char *cKey, const UniValue& uVal) { std::string key(cKey); return std::make_pair(key, uVal); } static inline std::pair Pair(std::string key, const UniValue& uVal) { return std::make_pair(key, uVal); } enum jtokentype { JTOK_ERR = -1, JTOK_NONE = 0, // eof JTOK_OBJ_OPEN, JTOK_OBJ_CLOSE, JTOK_ARR_OPEN, JTOK_ARR_CLOSE, JTOK_COLON, JTOK_SWINGBICOIN, JTOK_KW_NULL, JTOK_KW_TRUE, JTOK_KW_FALSE, JTOK_NUMBER, JTOK_STRING, }; extern enum jtokentype getJsonToken(std::string& tokenVal, unsigned int& consumed, const char *raw, const char *end); extern const char *uvTypeName(UniValue::VType t); static inline bool jsonTokenIsValue(enum jtokentype jtt) { switch (jtt) { case JTOK_KW_NULL: case JTOK_KW_TRUE: case JTOK_KW_FALSE: case JTOK_NUMBER: case JTOK_STRING: return true; default: return false; } // not reached } static inline bool json_isspace(int ch) { switch (ch) { case 0x20: case 0x09: case 0x0a: case 0x0d: return true; default: return false; } // not reached } extern const UniValue NullUniValue; const UniValue& find_value( const UniValue& obj, const std::string& name); #endif // __UNIVALUE_H__
c
16
0.617188
96
26.855219
297
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Core_ESP8266.Model; using Core_ESP8266.Model.Message; using HidWizards.IOWrapper.DataTransferObjects; namespace Core_ESP8266.Managers { public class DescriptorManager { private UdpManager _udpManager; private readonly Dictionary<string, SubscribedDevice> _subscribedDevices; public DescriptorManager(UdpManager udpManager) { _udpManager = udpManager; _subscribedDevices = new Dictionary<string, SubscribedDevice>(); } public void WriteOutput(OutputSubscriptionRequest subReq, BindingDescriptor bindingDescriptor, int state) { var subscribedDevice = _subscribedDevices[subReq.DeviceDescriptor.DeviceHandle]; switch (EspUtility.GetBindingCategory(bindingDescriptor)) { case BindingCategory.Momentary: subscribedDevice.DataMessage.SetButton(bindingDescriptor.Index, (short)state); break; case BindingCategory.Event: subscribedDevice.DataMessage.SetEvent(bindingDescriptor.Index, (short)state); break; case BindingCategory.Signed: case BindingCategory.Unsigned: subscribedDevice.DataMessage.SetAxis(bindingDescriptor.Index, (short)state); break; case BindingCategory.Delta: subscribedDevice.DataMessage.SetDelta(bindingDescriptor.Index, (short)state); break; } } public bool StartOutputDevice(DeviceInfo deviceInfo) { var subscribedDevice = new SubscribedDevice(_udpManager) { DeviceInfo = deviceInfo, DataMessage = BuildDescriptor(deviceInfo) }; _subscribedDevices.Add(deviceInfo.DeviceReport.DeviceDescriptor.DeviceHandle, subscribedDevice); subscribedDevice.StartSubscription(); return true; } public bool StopOutputDevice(DeviceInfo deviceInfo) { var deviceHandle = deviceInfo.DeviceReport.DeviceDescriptor.DeviceHandle; _subscribedDevices[deviceHandle].StopSubscription(); return _subscribedDevices.Remove(deviceHandle); } private DataMessage BuildDescriptor(DeviceInfo deviceInfo) { var dataMessage = new DataMessage(); deviceInfo.DescriptorMessage.Buttons.ForEach(io => dataMessage.AddButton(io.Value)); deviceInfo.DescriptorMessage.Axes.ForEach(io => dataMessage.AddAxis(io.Value)); deviceInfo.DescriptorMessage.Deltas.ForEach(io => dataMessage.AddDelta(io.Value)); deviceInfo.DescriptorMessage.Events.ForEach(io => dataMessage.AddEvent(io.Value)); return dataMessage; } } }
c#
17
0.647679
113
36.036585
82
starcoderdata
3/animals.py #!/usr/bin/env python3 from urllib.request import urlopen import sys # Get the animals def fetch_animals(url): """Get a list of lines (animals) from a given URL. Args: url: The URL of a utf-8 text Returns: A list of lines. """ with urlopen(url) as data: animals = [] for animal in data: animals.append(animal.decode('utf-8').rstrip()) return animals # Print the animals given def print_items(animals): """Prints all items from given collection. Args: animals: The collection to print. """ for animal in animals: print(animal) # Main method def main(url): """Prints all lines (animals) from a given URL. Args: url: The URL of a utf-8 text """ animals = fetch_animals(url) print_items(animals) """A list of lines printed from the given URL Args: 1: the URL to a UTF-8 text to print Usage: python3 animals.py """ animalsUrl = 'https://raw.githubusercontent.com/BearWithAFez/Learning-Python/master/Hoofdstuk%202/animals.txt' if __name__ == '__main__': main(sys.argv[1])
python
15
0.624576
110
20.071429
56
starcoderdata
package scheduler import ( "math" corev1 "k8s.io/api/core/v1" "github.com/kubernetes-local-volume/kubernetes-local-volume/pkg/common/types" ) func (lvs *LocalVolumeScheduler) getPodLocalVolumeRequestSize(pod *corev1.Pod) uint64 { var result uint64 for _, volume := range pod.Spec.Volumes { if volume.PersistentVolumeClaim != nil { pvcName := volume.PersistentVolumeClaim.ClaimName // get pvc pvc, err := lvs.pvcLister.PersistentVolumeClaims(pod.Namespace).Get(pvcName) if err != nil { continue } // get storageclass sc, err := lvs.storageClassLister.Get(*pvc.Spec.StorageClassName) if err != nil { continue } if types.DriverName == sc.Provisioner { size, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage] if ok { realSize := uint64(math.Ceil(float64(size.Value()) / 1024 / 1024 / 1024)) result = result + realSize } } } } return result } func (lvs *LocalVolumeScheduler) getPodLocalVolumePVCNames(pod *corev1.Pod) map[string]string { result := make(map[string]string) for _, volume := range pod.Spec.Volumes { if volume.PersistentVolumeClaim != nil { pvcName := volume.PersistentVolumeClaim.ClaimName // get pvc pvc, err := lvs.pvcLister.PersistentVolumeClaims(pod.Namespace).Get(pvcName) if err != nil { continue } // get storageclass sc, err := lvs.storageClassLister.Get(*pvc.Spec.StorageClassName) if err != nil { continue } if sc.Provisioner == types.DriverName { result[types.MakePVCKey(pvc.Namespace, pvc.Name)] = "" } } } return result } func (lvs *LocalVolumeScheduler) getNodeFreeSize(nodeName string) uint64 { lv, err := lvs.localVolumeLister.LocalVolumes(corev1.NamespaceDefault).Get(nodeName) if err != nil { return 0 } var preallocateSize uint64 for key := range lv.Status.PreAllocated { pvcNS, pvcName := types.SplitPVCKey(key) pvc, err := lvs.pvcLister.PersistentVolumeClaims(pvcNS).Get(pvcName) if err != nil { continue } size, ok := pvc.Spec.Resources.Requests[corev1.ResourceStorage] if !ok { continue } realSize := uint64(math.Ceil(float64(size.Value()) / 1024 / 1024 / 1024)) preallocateSize = preallocateSize + realSize } return lv.Status.FreeSize - preallocateSize }
go
24
0.700258
95
24.23913
92
starcoderdata
/*! Copyright (c) 2008, EVS. All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Remarks Name: CritSect.h Author: (JME) (NMA) Summary: The critical section object definition History: V 1.00 ???? ?? ???? JME : First Release V 1.01 June 15 2010 NMA : Refactoring */ #pragma once /*** Include ***********************************************************************************************************************/ #include #include #include #if defined(_WINDOWS) || defined (WIN32) || defined(WIN64) #elif defined(POSIX) || defined (__APPLE__) || defined (__linux__) || defined(__linux__) || defined (__ANDROID__) #include #endif /*** Defines ***********************************************************************************************************************/ BEGIN_BOF_NAMESPACE(); // Define this field if there should // only be one global critical section //#define GLOBAL_CRITICAL_SECTION // Uncomment this define // to profile this class //#define PROFILE_CRITSECT #define CCRITSECT_ENTER(X) if((X) != nullptr) { (X)->Enter(); } #define CCRITSECT_LEAVE(X) if((X) != nullptr) { (X)->Leave(); } /*** Enums *************************************************************************************************************************/ enum { PROFILE_CRITSECT_ENTER, PROFILE_CRITSECT_LEAVE, PROFILE_CRITSECT_MAX_ITEMS }; /*** Structures ********************************************************************************************************************/ /*** Classes ***********************************************************************************************************************/ /*! Summary The class representing a critical section */ class CCriticalSection { public : CCriticalSection (); ~CCriticalSection (); uint32_t Init (); uint32_t Enter (); uint32_t Leave (); bool GetProfilingStats (uint32_t _ItemId_U32, STAT_VARIABLE * _pStats_X); uint64_t GetMemoryUsage (); protected : private : public: BofProfiler * mpProfiler_O; #if defined(POSIX) || defined (__APPLE__) || defined (__linux__) || defined(__linux__) || defined (__ANDROID__) pthread_mutex_t mCriticalSection_X; #else #ifdef GLOBAL_CRITICAL_SECTION static void * mpCriticalSection_h; static U32 mNbInstances_U32; #else void * mpCriticalSection_h; #endif #endif }; END_BOF_NAMESPACE();
c
9
0.479655
133
26.722772
101
starcoderdata
// dependencies var _ = require('lomath') var fs = require('fs') var tinder = require('tinderjs'); var client = new tinder.TinderClient(); // Ingredients you'll need, and because FB is jackass there is currently no way to obtain them programmatically: // 1. your FB id: Yes FB is jackass, even getting your user id is hard // go to this page, and paste in the link to your profile url // http://findmyfbid.com // 2. Tinder access token from fb: // Get the user to sign in to fb, and go to this page: // https://www.facebook.com/dialog/oauth?client_id=464891386855067&redirect_uri=https://www.facebook.com/connect/login_success.html&scope=basic_info,email,public_profile,user_about_me,user_activities,user_birthday,user_education_history,user_friends,user_interests,user_likes,user_location,user_photos,user_relationship_details&response_type=token // Then quicky copy the first redirected link and paste it below // // set env vars var env = require('node-env-file'); env(__dirname + '/env'); // FIELDS var FBUserID = process.env.FBUserID var FBRedirectUrl = process.env.FBRedirectUrl // console.log(FBUserID, FBRedirectUrl) // token extractor for FBRedirectUrl function extractToken(url) { return url.replace(/.*access_token=|&expires_in=.*/g, '') } // Start using from below // For API ref, see https://github.com/alkawryk/tinderjs // Primary method to call // task = client.getHistory or someshit // taskcb = callback from task, as task(taskcb) function DTF(task, taskcb) { client.authorize( extractToken(FBRedirectUrl), FBUserID, // callback function() { task(taskcb); }) } // path to data dump var datapath = __dirname + '/data/dump.json' // A taskcb method: The main parser for a matches-object from result // save all matches(updated) and override the old file function parseAllMatches(matchObj) { // array of matches, saved var data = matchObj.matches; if (data) { // console.log(data) fs.writeFile(datapath, JSON.stringify(data)) } } // main method to scrape your past matches // dumps JSON data to output file function scrapeMatches() { DTF(client.getHistory, function(error, data) { parseAllMatches(data) }) } // main method call scrapeMatches()
javascript
10
0.721276
347
30.369863
73
starcoderdata
#ifndef DO_REPORT #define DO_REPORT #endif #include #include // for sqrt #include "report.h" #ifndef _LOG #define _LOG #endif #include "log.h" // PC: Changed to get it to compile. //FILE * reportFP = stdout; FILE * reportFP = NULL; void Report_DoReport(const char * str,int count,double tot,double totsqr) { double avg,avgsqr; avg = tot/count; avgsqr = totsqr/count; Log_TeeFile(reportFP); Log_Printf("%-20s : avg = %2.1f (sdev = %2.1f), tot = %d\n", str , avg, sqrt(avgsqr - avg*avg), (int)tot ); }
c
10
0.663748
73
16.84375
32
starcoderdata
#!/usr/bin/env python """convert docker images to singularity recipes,\ run python d2s.py --help for more details.""" import argparse import logging import os import subprocess import sys logger = logging.getLogger("d2s.py") handler = logging.StreamHandler() handler.setFormatter( logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s") ) logger.addHandler(handler) logger.setLevel(logging.DEBUG) parser = argparse.ArgumentParser( description="Docker to Singularity Image Conversion tool" ) parser.add_argument( "--list_docker_images", action="store_true", help="show a table of docker images available locally.", ) parser.add_argument( "--convert_docker_images", nargs="+", help="docker images to convert", ) def list_docker_images(): """list docker images on system""" images = subprocess.check_output( ["docker", "images", "--format", '"{{.Repository}}"'] ).split() return [img.decode("utf-8") for img in images] def tabular_images(): """covert docker image list to a dict""" img_list = list_docker_images() return {str(i): v for i, v in enumerate(img_list)} def print_image_table(): """print images with ID and name.""" img_table = tabular_images() print("=" * 30) print("Docker images present locally") print("=" * 30) print("{0:<10s} {1:>s}".format("ID", "NAME")) for k, v in img_table.items(): print("{}: {}".format(k, v)) print("=" * 30) def check_singularity_version(): """check singularity CLI tool version.""" print("checking if singularity is installed") try: s_ver = subprocess.run(["singularity", "version"]) logger.info("singualrity cmd available") except subprocess.CalledProcessError: logger.error("singularity tool is required to convert images using d2s.") sys.exit(1) def get_sing_image_name(docker_image: str) -> str: """convert docker_image string to singularity image format""" sing_image = docker_image.replace(":", "_") sing_image = sing_image.replace("/", "_") return sing_image def convert_to_singularity(docker_image: str): """convert docker images to singularity.""" sing_image = get_sing_image_name(docker_image) logger.info( "Converting docker image %s to singularity image %s" % (docker_image, sing_image) ) cmd = "singularity build {} docker://{}".format(sing_image, docker_image) logger.debug("Running command %s" %cmd) ret = os.system(cmd) # nosec if ret == 0: logger.info( "Converted docker image %s to singularity image format %s succesfully" % (docker_image, sing_image) ) def main(): args = parser.parse_args() if args.list_docker_images: print_image_table() elif args.convert_docker_images: check_singularity_version() image_dict = tabular_images() # Convert each docker image to singularity image for image_id in args.convert_docker_images: try: image_name = image_dict[image_id] except KeyError: logger.error("=" * 30) logger.error( "wrong id :: {}, to see available images run '--list_docker_images'".format( image_id ) ) logger.error("=" * 30) exit(1) convert_to_singularity(image_name) if __name__ == "__main__": main()
python
17
0.612876
96
28.890756
119
starcoderdata
using System; using EntityFramework.SoftDeletable; using Microsoft.AspNet.Identity; namespace EntityFramework.IdentitySoftDeletable { public abstract class IdentitySoftDeletable : UserSoftDeletable where T : IConvertible { public sealed override T GetCurrentUserId() { return System.Web.HttpContext.Current.User.Identity.GetUserId } } }
c#
15
0.770889
95
31.727273
11
starcoderdata
public static void main(String[] args) throws Exception { boolean sanityCheck = Arrays.asList(args).contains("--sanity-check"); if (sanityCheck && GraphicsEnvironment.isHeadless()) { Logger.getGlobal().log(Level.SEVERE, "[Vader] Hello, Luke. Can't do much in headless mode."); Runtime.getRuntime().exit(0); } String lookAndFeelClassName = UIManager.getSystemLookAndFeelClassName(); if (!lookAndFeelClassName.contains("AquaLookAndFeel") && !lookAndFeelClassName.contains("PlasticXPLookAndFeel")) { // may be running on linux platform lookAndFeelClassName = "javax.swing.plaf.metal.MetalLookAndFeel"; } UIManager.setLookAndFeel(lookAndFeelClassName); GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment(); genv.registerFont(FontUtils.createElegantIconFont()); var guiThreadResult = new SynchronousQueue<Boolean>(); javax.swing.SwingUtilities.invokeLater( () -> { try { guiThreadResult.put(createGUI()); // Show the initial dialog. OpenIndexDialogFactory openIndexDialogFactory = OpenIndexDialogFactory.getInstance(); new DialogOpener<>(openIndexDialogFactory) .open( MessageUtils.getLocalizedMessage("openindex.dialog.title"), 600, 420, (factory) -> {}); } catch (Exception e) { throw new RuntimeException(e); } }); if (Boolean.FALSE.equals(guiThreadResult.take())) { Logger.getGlobal().log(Level.SEVERE, "Luke could not start."); Runtime.getRuntime().exit(1); } if (sanityCheck) { // In sanity-check mode on non-headless displays, return success. Logger.getGlobal().log(Level.SEVERE, "[Vader] Hello, Luke. We seem to be fine."); Runtime.getRuntime().exit(0); } }
java
16
0.640063
99
38.142857
49
inline
#pragma once typedef void (*void_ptr)(); class VendingMachine { public: static void (*setup)(); static void (*loop)(); };
c
9
0.616541
27
13.888889
9
starcoderdata
package apmsql // DSNInfo contains information from a database-specific data source name. type DSNInfo struct { // Database is the name of the specific database identified by the DSN. Database string // User is the username that the DSN specifies for authenticating the // database connection. User string } // DSNParserFunc is the type of a function that can be used for parsing a // data source name, and returning the corresponding Info. type DSNParserFunc func(dsn string) DSNInfo func genericDSNParser(string) DSNInfo { return DSNInfo{} }
go
7
0.779487
74
28.25
20
starcoderdata
<?php namespace Hanson\Youzan; use Hanson\Foundation\Foundation; /** * Class Youzan * @package Hanson\Youzan * * @property \Hanson\Youzan\Api $api * @property \Hanson\Youzan\AccessToken $access_token * @property \Hanson\Youzan\Oauth\PreAuth $pre_auth * @property \Hanson\Youzan\Oauth\Oauth $oauth * @property \Hanson\Youzan\App\Sso $sso * @property \Hanson\Youzan\Push $push */ class Youzan extends Foundation { const PERSONAL = 'PERSONAL'; const PLATFORM = 'PLATFORM'; const TOOL = 'TOOL'; protected $providers = [ ServiceProvider::class, Oauth\ServiceProvider::class, App\ServiceProvider::class, ]; /** * @param $kdtId * @return Youzan */ public function setKdtId($kdtId) { $this->access_token->setKdtId($kdtId); return $this; } /** * API请求 * * @param $method * @param array $params * @param string $version * @param array $files * @return array */ public function request($method, $params = [], $files = [], $version = '3.0.0') { return $this->api->request($method, $params, $version, $files); } }
php
12
0.593328
83
19.983333
60
starcoderdata
package com.gittors.apollo.extend.binder.demo.properties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.Map; import java.util.Set; /** * @author zlliu * @date 2020/7/22 20:58 */ @ConfigurationProperties(prefix = "my") @Data public class MyProperties { private Map<String, Set map; }
java
14
0.780769
149
26.368421
19
starcoderdata
def get_user_tweets(app, user_id, **kwargs): """ Fetch all the tweets of a given user """ tweets = [] new_tweets = app.user_timeline(user_id, tweet_mode="extended", **kwargs) while new_tweets: tweets += new_tweets min_id = min(tw.id for tw in new_tweets)-1 new_tweets = app.user_timeline(user_id, max_id=min_id, tweet_mode="extended", **kwargs) return tweets
python
11
0.61165
95
30.769231
13
inline
def cdf(y_dists): ''' returns the cdf of each element in each 1d dist ''' y_dists = _assert_dim_3d(y_dists) arr = np.zeros(y_dists.shape) for dist in np.arange(y_dists.shape[0]): for dim in np.arange(y_dists.shape[-1]): arr[dist,:,dim] = _cdf(y_dists[dist,:,dim]) return arr
python
13
0.575851
55
28.454545
11
inline
package com.optimize.performance.tasks; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.imagepipeline.listener.RequestListener; import com.optimize.performance.launchstarter.task.Task; import com.optimize.performance.net.FrescoTraceListener; import java.util.HashSet; import java.util.Set; public class InitFrescoTask extends Task { @Override public void run() { Set listenerset = new HashSet<>(); listenerset.add(new FrescoTraceListener()); ImagePipelineConfig config = ImagePipelineConfig.newBuilder(mContext).setRequestListeners(listenerset) .build(); Fresco.initialize(mContext,config); } }
java
9
0.769614
110
33.913043
23
starcoderdata
package com.strawberry.engine.rendering; import com.strawberry.engine.component.BaseLight; import com.strawberry.engine.component.PointLight; import com.strawberry.engine.core.Matrix4f; import com.strawberry.engine.core.Transform; public class ForwardPoint extends Shader { private static final ForwardPoint instance = new ForwardPoint(); public static ForwardPoint getInstance() { return instance; } public ForwardPoint() { super(); addVertexShader(Shader.loadShader("forward-point.vs")); addFragmentShader(Shader.loadShader("forward-point.fs")); setAttribLocation("position", 0); setAttribLocation("textCoord", 1); setAttribLocation("normal", 2); compileShader(); addUniform("model"); addUniform("MVP"); addUniform("specularIntensity"); addUniform("specularPower"); addUniform("eyePos"); addUniform("pointLight.base.color"); addUniform("pointLight.base.intensity"); addUniform("pointLight.atten.constant"); addUniform("pointLight.atten.linear"); addUniform("pointLight.atten.exponent"); addUniform("pointLight.position"); addUniform("pointLight.range"); } public void updateUniforms(Transform transform, Material material, RenderingEngine engine) { Matrix4f worldMatrix = transform.getTransformation(); Matrix4f projectedMatrix = engine.getMainCamera().getViewProjection().mul(worldMatrix); material.getTexture("diffuse").bind(); setUniformM("MVP", projectedMatrix); setUniformM("model", worldMatrix); setUniformf("specularIntensity", material.getFloat("specularIntensity")); setUniformf("specularPower", material.getFloat("specularPower")); setUniformV("eyePos", engine.getMainCamera().getTransform().getTransformedPosition()); setUniform("pointLight", (PointLight)engine.getActiveLight()); } public void setUniform(String uniformName, BaseLight baseLight) { setUniformV(uniformName + ".color", baseLight.getColor()); setUniformf(uniformName + ".intensity", baseLight.getIntensity()); } private void setUniform(String uniformName, PointLight pointLight) { setUniform(uniformName + ".base", (BaseLight)pointLight); setUniformf(uniformName + ".atten.constant", pointLight.getConstant()); setUniformf(uniformName + ".atten.linear", pointLight.getLinear()); setUniformf(uniformName + ".atten.exponent", pointLight.getExponent()); setUniformV(uniformName + ".position", pointLight.getTransform().getTransformedPosition()); setUniformf(uniformName + ".range", pointLight.getRange()); } }
java
12
0.75336
93
30.625
80
starcoderdata
void CAI_PassengerBehavior::FinishExitVehicle(void) { if (m_hVehicle == NULL) return; // Destroy the blocker if (m_hBlocker != NULL) { UTIL_Remove(m_hBlocker); m_hBlocker = NULL; } // To do this, we need to be very sure we're in a good spot GetOuter()->SetCondition(COND_PROVOKED); GetOuter()->SetMoveType(MOVETYPE_STEP); GetOuter()->RemoveFlag(FL_FLY); GetOuter()->GetMotor()->SetYawLocked(false); // Re-enable the physical collisions for this NPC IPhysicsObject *pPhysObj = GetOuter()->VPhysicsGetObject(); if (pPhysObj != NULL) { pPhysObj->EnableCollisions(true); } m_hVehicle->NPC_RemovePassenger(GetOuter()); m_hVehicle->NPC_FinishedExitVehicle(GetOuter(), (IsPassengerHostile() == false)); SetPassengerState(PASSENGER_STATE_OUTSIDE); // Stop our custom move sequence GetOuter()->m_iszSceneCustomMoveSeq = NULL_STRING; // If we've not been told to enter immediately, we're done if (m_PassengerIntent == PASSENGER_INTENT_EXIT) { m_PassengerIntent = PASSENGER_INTENT_NONE; Disable(); } }
c++
10
0.71636
82
24.85
40
inline
package com.heeexy.example.dao; import com.heeexy.example.util.model.QuestionOption; import tk.mybatis.mapper.common.Mapper; public interface QuestionOptionMapper extends Mapper { }
java
7
0.834171
70
27.571429
7
starcoderdata
import CanvasRenderingContext2DMock from '@/mocks/CanvasRenderingContext2DMock' import { COLOR_APPLE, COLOR_CORPSE, COLOR_PLAYER, COLOR_SNAKE, COLOR_WALL, COLOR_WATERMELON, Canvas, OBJECT_APPLE, OBJECT_CORPSE, OBJECT_PLAYER, OBJECT_SNAKE, OBJECT_WALL, OBJECT_WATERMELON } from '@/game/Canvas' const DOT_SIZE = 20 const LINE_SIZE = 0 const MAP_WIDTH = 100 const MAP_HEIGHT = 100 const CANVAS_WIDTH = DOT_SIZE * MAP_WIDTH + LINE_SIZE * (MAP_WIDTH + 1) const CANVAS_HEIGHT = DOT_SIZE * MAP_HEIGHT + LINE_SIZE * (MAP_HEIGHT + 1) describe('game canvas', () => { it('canvas constructor works correctly', () => { const contextGame = new CanvasRenderingContext2DMock(CANVAS_WIDTH, CANVAS_HEIGHT) const canvas = new Canvas({ contexts: { contextGame }, grid: { dot: DOT_SIZE, line: LINE_SIZE, width: MAP_WIDTH, height: MAP_HEIGHT, border: 0 }, map: { x: 0, y: 0, width: CANVAS_WIDTH, height: CANVAS_HEIGHT }, divHeight: { style: {} } }) expect(canvas._contextGame).toBe(contextGame) expect(canvas._dot).toBe(DOT_SIZE) }) it('canvas draws snakes to snakes context', () => { const contextGame = new CanvasRenderingContext2DMock(CANVAS_WIDTH, CANVAS_HEIGHT) const canvas = new Canvas({ contexts: { contextGame }, grid: { dot: DOT_SIZE, line: LINE_SIZE, width: MAP_WIDTH, height: MAP_HEIGHT, border: 0 }, map: { x: 0, y: 0, width: CANVAS_WIDTH, height: CANVAS_HEIGHT }, divHeight: { style: {} } }) canvas.draw(OBJECT_SNAKE, [[0, 0]]) expect(contextGame.popCall()).toEqual({ 'args': [0, 0, 20, 20], 'methodName': 'fillRect', 'props': { 'canvas': { 'height': CANVAS_HEIGHT, 'width': CANVAS_WIDTH, 'style': { left: '0px', top: '0px' } }, 'fillStyle': COLOR_SNAKE, 'strokeStyle': '#000' } }) }) it('canvas draws apples to food context', () => { const contextGame = new CanvasRenderingContext2DMock(CANVAS_WIDTH, CANVAS_HEIGHT) const canvas = new Canvas({ contexts: { contextGame }, grid: { dot: DOT_SIZE, line: LINE_SIZE, width: MAP_WIDTH, height: MAP_HEIGHT, border: 0 }, map: { x: 0, y: 0, width: CANVAS_WIDTH, height: CANVAS_HEIGHT }, divHeight: { style: {} } }) canvas.draw(OBJECT_APPLE, [[0, 0]]) expect(contextGame.popCall()).toEqual({ 'args': [0, 0, 20, 20], 'methodName': 'fillRect', 'props': { 'canvas': { 'height': CANVAS_HEIGHT, 'width': CANVAS_WIDTH, 'style': { left: '0px', top: '0px' } }, 'fillStyle': COLOR_APPLE, 'strokeStyle': '#000' } }) }) it('canvas draws corpses to food context', () => { const contextGame = new CanvasRenderingContext2DMock(CANVAS_WIDTH, CANVAS_HEIGHT) const canvas = new Canvas({ contexts: { contextGame }, grid: { dot: DOT_SIZE, line: LINE_SIZE, width: MAP_WIDTH, height: MAP_HEIGHT, border: 0 }, map: { x: 0, y: 0, width: CANVAS_WIDTH, height: CANVAS_HEIGHT }, divHeight: { style: {} } }) canvas.draw(OBJECT_CORPSE, [[0, 0]]) expect(contextGame.popCall()).toEqual({ 'args': [0, 0, 20, 20], 'methodName': 'fillRect', 'props': { 'canvas': { 'height': CANVAS_HEIGHT, 'width': CANVAS_WIDTH, 'style': { left: '0px', top: '0px' } }, 'fillStyle': COLOR_CORPSE, 'strokeStyle': '#000' } }) }) it('canvas draws walls to walls context', () => { const contextGame = new CanvasRenderingContext2DMock(CANVAS_WIDTH, CANVAS_HEIGHT) const canvas = new Canvas({ contexts: { contextGame }, grid: { dot: DOT_SIZE, line: LINE_SIZE, width: MAP_WIDTH, height: MAP_HEIGHT, border: 0 }, map: { x: 0, y: 0, width: CANVAS_WIDTH, height: CANVAS_HEIGHT }, divHeight: { style: {} } }) canvas.draw(OBJECT_WALL, [[0, 0]]) expect(contextGame.popCall()).toEqual({ 'args': [0, 0, 20, 20], 'methodName': 'fillRect', 'props': { 'canvas': { 'height': CANVAS_HEIGHT, 'width': CANVAS_WIDTH, 'style': { left: '0px', top: '0px' } }, 'fillStyle': COLOR_WALL, 'strokeStyle': '#000' } }) }) it('canvas draws player snake to snakes context with special filling color', () => { const contextGame = new CanvasRenderingContext2DMock(CANVAS_WIDTH, CANVAS_HEIGHT) const canvas = new Canvas({ contexts: { contextGame }, grid: { dot: DOT_SIZE, line: LINE_SIZE, width: MAP_WIDTH, height: MAP_HEIGHT, border: 0 }, map: { x: 0, y: 0, width: CANVAS_WIDTH, height: CANVAS_HEIGHT }, divHeight: { style: {} } }) canvas.draw(OBJECT_PLAYER, [[0, 0]]) expect(contextGame.popCall()).toEqual({ 'args': [0, 0, 20, 20], 'methodName': 'fillRect', 'props': { 'canvas': { 'height': CANVAS_HEIGHT, 'width': CANVAS_WIDTH, 'style': { left: '0px', top: '0px' } }, 'fillStyle': COLOR_PLAYER, 'strokeStyle': '#000' } }) }) it('canvas draws walls to walls context', () => { const contextGame = new CanvasRenderingContext2DMock(CANVAS_WIDTH, CANVAS_HEIGHT) const canvas = new Canvas({ contexts: { contextGame }, grid: { dot: DOT_SIZE, line: LINE_SIZE, width: MAP_WIDTH, height: MAP_HEIGHT, border: 0 }, map: { x: 0, y: 0, width: CANVAS_WIDTH, height: CANVAS_HEIGHT }, divHeight: { style: {} } }) canvas.draw(OBJECT_WATERMELON, [[0, 0]]) expect(contextGame.popCall()).toEqual({ 'args': [0, 0, 20, 20], 'methodName': 'fillRect', 'props': { 'canvas': { 'height': CANVAS_HEIGHT, 'width': CANVAS_WIDTH, 'style': { left: '0px', top: '0px' } }, 'fillStyle': COLOR_WATERMELON, 'strokeStyle': '#000' } }) }) })
javascript
23
0.502297
86
22.03413
293
starcoderdata
<?php class Metrodb_Sqlite3 extends Metrodb_Connector { public $resultType = SQLITE3_ASSOC; public $isSelected = false; public $qc = '"'; public $collation = ''; /** * Connect to the DB server * * Uses the classes internal host,user,password, and database variables * @return void */ public function connect($options=array()) { if (! class_exists('SQLite3')) { return false; } if ($this->driverId == 0 ) { $this->driverId = new SQLite3($this->database); if (!$this->driverId) { throw new Exception("Unable to connect to database"); } } if ($this->driverId) { $this->isSelected = true; $this->setOptions($options); } } /* public function setAnsiQuotes() { $this->exec('SET SQL_MODE = \'ANSI_QUOTES\''); $this->qc = '"'; } */ public function setTempStoreMemory() { $this->exec('PRAGMA temp_store = 2'); } /** * Send query to the DB * * Results are stored in $this->resultSet; * @return void * @param string $queryString SQL command to send */ public function query($queryString) { $this->queryString = $queryString; $start = microtime(1); if (! is_object($this->driverId) ) { $this->connect(); } //don't try to do queries if there's no DB if (! $this->isSelected ) { $this->errorMessage = 'no schema selected.'; return FALSE; } //docs say returns false on error, but actually throws Exception try { $resSet = @$this->driverId->query($queryString); } catch (Exception $e) { //echo $e->getMessage()."\n"; //echo $queryString."\n"; return FALSE; } $this->row = 0; if (is_object($resSet) ) { $this->resultSet[] = $resSet; } else { $this->getLastError(); } $this->sqltime = abs(microtime(1)-$start); return is_object($resSet); } /** * return SQLite3Stmnt object * * @param string $statementString SQL statement * @param mixed $bind optional array of values for ? replacement or null * @return SQLite3Stmt */ function _prepareStatement($statementString, $bind=array()) { $last = 0; $last = strrpos($statementString, '?', $last); $stmt = @$this->driverId->prepare($statementString); if (is_array($bind)) { foreach ($bind as $_k => $_v) { if (is_double($_v)) { $stmt->bindValue($_k, $_v, SQLITE_FLOAT); } else if( is_int($val) ) { $stmt->bindValue($_k, $_v, SQLITE_INTEGER); } else { $stmt->bindValue($_k, $_v, SQLITE_BLOB); } } } return $stmt; } /** * Prepare statementString into a SQLite3Stmt and return * result of $stmt->execute() * * @param string $statementString SQL statement * @param mixed $bind optional array of values for ? replacement or null * @return SQLite3Result */ function exec($statementString, $bind=NULL) { if (!is_object($this->driverId)) { $this->connect(); } $stmt = $this->_prepareStatement($statementString, $bind); if (!$stmt) { return FALSE; } return $stmt->execute(); } /** * Close connection * * @return void */ function close() { if ( is_object($this->driverId) ) { $this->driverId->close(); } $this->isSelected = false; $this->resultSet = array(); $this->driverId = 0; } /** * Grab the next record from the resultSet * * Returns true while there are more records, false when the set is empty * Automatically frees result when the result set is emtpy * @return boolean * @param int $resID Specific resultSet, default is last query */ function nextRecord($resId = false) { if (! $resId ) { $resId = count($this->resultSet) -1; } if (! isset($this->resultSet[$resId]) ) { return false; } $resultObj = $this->resultSet[$resId]; $this->record = $resultObj->fetchArray($this->resultType); $this->row += 1; //no more records in the result set? $ret = is_array($this->record); if (! $ret ) { if (is_resource($this->resultSet[$resId]) ) { $this->freeResult($resId); } } return $ret; } /** * Pop the top result off the stack */ function freeResult($resId = FALSE) { if (! $resId ) { $resId = array_pop($this->resultSet); $resId->finalize(); } else { $resObj = $this->resultSet[$resId]; $resObj->finalize(); unset($this->resultSet[$resId]); //reindex the keys $this->resultSet = array_merge($this->resultSet); } } /** * Moves resultSet cursor to beginning * @return void */ function reset($resId = FALSE) { if (! $resId ) { $resId = count($this->resultSet) -1; } $resObj = $this->resultSet[$resId]; $resObj->reset(); $this->row = 0; } /** * Moves resultSet cursor to an aribtrary position * * @param int $row Desired index offset * @return void */ function seek($row) { $this->reset(); for ($x=0; $x < $row; $x++) { $this->nextRecord(); } } /** * Retrieves last error message from the DB * * @return string Error message */ function getLastError() { $this->errorNumber = $this->driverId->lastErrorCode(); $this->errorMessage = $this->driverId->lastErrorMsg(); return $this->errorMessage; } public function rollbackTx() { $this->exec("ROLLBACK"); $this->exec("SET autocommit=1"); } public function startTx() { $this->exec("SET autocommit=0"); $this->exec("START TRANSACTION"); } public function commitTx() { $this->exec("COMMIT TRANSACTION"); $this->exec("SET autocommit=1"); } /** * Return the last identity field to be created * * @return mixed */ public function getInsertID() { return $this->driverId->lastInsertRowID(); } /** * Not implemented for SQLite3 * * @return int number of affected rows */ function getNumRows() { return 0; } public function truncate($tbl) { $qc = $this->qc; return $this->exec("DELETE FROM ".$qc.$tbl.$qc) && $this->exec('DELETE FROM "SQLITE_SEQUENCE" WHERE name='.$qc.$tbl.$qc); } function setType($type='ASSOC') { $this->prevType = $this->RESULT_TYPE; if ($type=='ASSOC') { $this->RESULT_TYPE = SQLITE3_ASSOC; } if ($type=='NUM') { $this->RESULT_TYPE = SQLITE3_NUM; } if ($type=='BOTH') { $this->RESULT_TYPE = SQLITE3_BOTH; } } function quote($val) { return $this->driverId->escapeString($val); } public function escapeCharValue($val) { return "'".str_replace("'", "''", $val)."'"; } }
php
19
0.609548
79
20.299663
297
starcoderdata
func (e *Client) List(ctx context.Context, key string) (*Node, error) { // ensure key has '/' suffix key = e.KeyWithRootPath(key) if !strings.HasSuffix(key, "/") { key += "/" } kv := clientv3.NewKV(e.client) resp, err := kv.Get(ctx, key, clientv3.WithPrefix()) if err != nil { return nil, errors.Trace(err) } root := new(Node) length := len(key) for _, kv := range resp.Kvs { key := string(kv.Key) // ignore bad key. if len(key) <= length { continue } keySuffix := key[length:] leafNode := parseToDirTree(root, keySuffix) leafNode.Value = kv.Value } return root, nil }
go
10
0.621087
71
19.266667
30
inline
//////////////////////////////////////////////////////////////////////////////// // // CopyRight (c) 2013 Blue3k // // Author : // // Description : Thread Synchronize // //////////////////////////////////////////////////////////////////////////////// #pragma once #include #include #include namespace BR { /////////////////////////////////////////////////////////////////////////////// // // Critical Section // class CriticalSection : public MutexBase { public: CriticalSection() { pthread_mutexattr_t mAttr; pthread_mutexattr_settype(&mAttr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&m, &mAttr); } ~CriticalSection() { pthread_mutexattr_destroy(&m_CriticalSection); } virtual void Lock() { pthread_mutex_lock(&m_CriticalSection); } virtual void UnLock() { pthread_mutex_unlock(&m_CriticalSection); } private: pthread_mutex_t m_CriticalSection; }; class Mutex : public MutexBase { public: Mutex() { pthread_mutexattr_t mAttr; pthread_mutexattr_settype(&mAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&m, &mAttr); } ~Mutex() { pthread_mutexattr_destroy(&m_CriticalSection); } virtual void Lock() override { pthread_mutex_lock(&m_CriticalSection); } virtual void UnLock() override { pthread_mutex_unlock(&m_CriticalSection); } private: pthread_mutex_t m_CriticalSection; }; class Event { public: Event(bool isInitialySet = false, bool autoReset = true) :m_AutoReset(autoReset) { sem_init(&m_hEvent, 0, isInitialySet ? 1 : 0); } ~Event() { if (m_hEvent) sem_destroy(&m_hEvent); } void Reset() { timespec waitTime; memset(&waitTime, 0, sizeof(waitTime)); if (clock_gettime(CLOCK_REALTIME, &waitTime) == -1) return; waitTime.tv_nsec += 1; sem_timedwait(&m_hEvent, &waitTime); } void Set() { if (sem_getvalue(&m_hEvent) == 1) return; sem_post(&m_hEvent); } bool WaitEvent(UINT uiWaitTimeMs) { // we need mutex version timespec waitTime; memset(&waitTime, 0, sizeof(waitTime)); if (clock_gettime(CLOCK_REALTIME, &waitTime) == -1) return false; waitTime.tv_sec += uiWaitTimeMs / 1000; waitTime.tv_nsec += 1000000 * (uiWaitTimeMs % 1000); int waitRes = sem_timedwait(&m_hEvent, &waitTime); if (waitRes == ETIMEDOUT) return false; else if (waitRes == EAGAIN) return false; if (!m_AutoReset) sem_post(&m_hEvent); return true; } private: sem_t m_hEvent; bool m_AutoReset; }; }
c++
13
0.548399
80
15.820513
156
starcoderdata
#include <bits/stdc++.h> using namespace std; long solve(vector<long>& arr,vector<vector<long>>& dp,int s,int e){ // if(s>e){ // return INT_MAX; // } if(s==e){ return 0; } if(s+1==e){ return arr[s]+arr[e]; } if(dp[s][e]!=-1){ return dp[s][e]; } dp[s][e] = 10000000000000000; long sum = 0; for(int i=s;i<e;i++){ dp[s][e] = min(dp[s][e],solve(arr,dp,s,i)+solve(arr,dp,i+1,e)); sum+=arr[i]; } return dp[s][e] = dp[s][e]+sum+arr[e]; } int main() { int n; cin>>n; vector<long> arr(n); for(int i=0;i<n;i++){ cin>>arr[i]; } vector<vector<long>> dp(n+1,vector<long>(n+1,-1)); cout<<solve(arr,dp,0,n-1)<<'\n'; return 0; }
c++
13
0.4829
71
19.885714
35
codenet
void PostProsessor::Type_Size_Definer(int i) { if (Scope->Defined[i]->Type != CLASS_NODE) return; if (Scope->Defined[i]->Templates.size() > 0) //template types are constructed elsewhere. return; //update members sizes Scope->Defined[i]->Update_Size(); //update the member stack offsets Scope->Defined[i]->Update_Local_Variable_Mem_Offsets(); //update format Scope->Defined[i]->Update_Format(); //update all member formats as well for (auto& i : Scope->Defined[i]->Defined) i->Update_Format(); }
c++
11
0.672316
89
26.052632
19
inline
<?php /** Plugin Name: Date & Time Picker for Advanced Custom Fields Plugin URI: https://github.com/toszcze/acf-date-time-picker Description: Date & Time Picker field for Advanced Custom Fields 4 and 5 (Pro) Version: 1.1.4 Author: Author URI: http://romanowski.im/ License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Text Domain: acf-date-time-picker Domain Path: /languages/ */ // exit if accessed directly if(!defined('ABSPATH')) exit; if(!defined('ACF_DTP_VERSION')) { define('ACF_DTP_VERSION', '1.1.4'); } if(!defined('ACF_DTP_URL')) { define('ACF_DTP_URL', plugin_dir_url(__FILE__)); } if(!class_exists('acf_plugin_date_time_picker')): class acf_plugin_date_time_picker { /** * Class constructor * * @since 1.0.0 */ public function __construct() { load_plugin_textdomain('acf-date-time-picker', false, plugin_basename(dirname(__FILE__)).'/languages'); add_action('acf/include_field_types', array($this, 'include_field_types')); // ACF5 add_action('acf/register_fields', array($this, 'include_field_types')); // ACF4 } /** * Include the field type class * * @since 1.0.0 * * @param integer $version Major ACF version; defaults to 4 */ public function include_field_types($version = 4) { if(empty($version)) { $version = 4; } include_once('fields/acf-date_time_picker-common.php'); include_once('fields/acf-date_time_picker-v'.$version.'.php'); } } // initialize plugin new acf_plugin_date_time_picker(); endif;
php
18
0.67947
105
23.354839
62
starcoderdata
private Int32 GetTotalSize(Int32 count, Int32 limit) { // Calculate minimum number of required lines. Int32 lines = count / limit; // Add one more line if necessary. if (count % limit != 0) { lines += 1; } // Calculate the total number of required // bytes (including padding) and return it. return lines * limit; }
c#
9
0.54067
58
33.916667
12
inline
@Test public void isOverlapping_boundsTest_success() { ScheduleItem startBeforeEnd = new ScheduleItemStub(REF_TIME.plusMinutes(29), REF_TIME.plusMinutes(59)); ScheduleItem startAtEnd = new ScheduleItemStub(REF_TIME.plusMinutes(30), REF_TIME.plusMinutes(45)); ScheduleItem startAfterEnd = new ScheduleItemStub(REF_TIME.plusMinutes(31), REF_TIME.plusMinutes(45)); assertTrue(REF_SCHEDULE_ITEM.isOverlapping(startBeforeEnd)); // Starts before reference ends assertTrue(startBeforeEnd.isOverlapping(REF_SCHEDULE_ITEM)); // Symmetric test assertFalse(REF_SCHEDULE_ITEM.isOverlapping(startAtEnd)); // Starts when reference ends -> OK assertFalse(startAtEnd.isOverlapping(REF_SCHEDULE_ITEM)); // Symmetric test assertFalse(REF_SCHEDULE_ITEM.isOverlapping(startAfterEnd)); // Starts after reference ends -> OK assertFalse(startAfterEnd.isOverlapping(REF_SCHEDULE_ITEM)); // Symmetric test ScheduleItem endAfterStart = new ScheduleItemStub(REF_TIME.minusMinutes(29), REF_TIME.plusMinutes(1)); ScheduleItem endAtStart = new ScheduleItemStub(REF_TIME.minusMinutes(30), REF_TIME); ScheduleItem endBeforeStart = new ScheduleItemStub(REF_TIME.minusMinutes(31), REF_TIME.minusMinutes(1)); assertTrue(REF_SCHEDULE_ITEM.isOverlapping(endAfterStart)); // Ends after reference starts assertTrue(endAfterStart.isOverlapping(REF_SCHEDULE_ITEM)); // Symmetric test assertFalse(REF_SCHEDULE_ITEM.isOverlapping(endAtStart)); // Ends when reference starts -> OK assertFalse(endAtStart.isOverlapping(REF_SCHEDULE_ITEM)); // Symmetric test assertFalse(REF_SCHEDULE_ITEM.isOverlapping(endBeforeStart)); // Ends before reference starts -> OK assertFalse(endBeforeStart.isOverlapping(REF_SCHEDULE_ITEM)); // Symmetric test }
java
9
0.743645
112
76.083333
24
inline
<!DOCTYPE html> <html lang="en" > <meta charset="UTF-8"> $data->home_team }} vs. {{ $data->away_team }} <link href="{{ asset('resources/assets/css/bootstrap.min.css') }}" rel="stylesheet"> <link href="{{ asset('resources/assets/css/font-awesome.min.css') }}" rel="stylesheet"> <link href="{{ asset('resources/assets/css/game.css') }}" rel="stylesheet"> .team { color: #2786bf !important; } .title-info { color: #00ca6d; font-weight: bold; font-size: 1.4em; } .title-warning { color: #ca780f; font-weight: bold; font-size: 1.4em; } .columns { padding:0px !important; } <?php $home = \App\Boxscore::where('game_id',$data->id) ->where('team',$data->home_team) ->get(); $away = \App\Boxscore::where('game_id',$data->id) ->where('team',$data->away_team) ->get(); ?> <div id="social-platforms"> <h1 class="team">{{ $data->home_team }} <font class="title-info home_score">0 vs. <font class="title-warning away_score">0 {{ $data->away_team }} @foreach($home as $row) <?php $player = \App\Players::find($row->player_id); ?> <a class="btn btn-icon btn-twitter" href="#basketModal" data-player="{{ $player->id }}" data-team="{{ $data->home_team }}" data-toggle="modal"> {{ $player->fname[0] }}. {{ $player->lname }}<br /> $player->position }} | {{ $player->jersey}} src="{{ url('public/upload/profile/'.$player->prof_pic.'?img='.date('YmdHis')) }}" width="80px" class="img-responsive" /> @endforeach <hr /> @foreach($away as $row) <?php $player = \App\Players::find($row->player_id); ?> <a class="btn btn-icon btn-twitter" href="#basketModal" data-player="{{ $player->id }}" data-team="{{ $data->away_team }}" data-toggle="modal"> {{ $player->fname[0] }}. {{ $player->lname }}<br /> $player->position }} | {{ $player->jersey}} src="{{ url('public/upload/profile/'.$player->prof_pic.'?img='.date('YmdHis')) }}" width="80px" class="img-responsive" /> @endforeach <div class="modal fade" role="dialog" id="basketModal"> <div class="modal-dialog modal-sm" role="document"> {{ csrf_field() }} <div class="modal-content"> <div class="modal-body"> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-success action" data-action="fg2m"> <img src="{{ url('public/upload/icons/2pt.png') }}" class="img-responsive" /> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-success action" data-action="fg3m"> <img src="{{ url('public/upload/icons/3pt.png') }}" class="img-responsive" /> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-success action" data-action="ftm"> <img src="{{ url('public/upload/icons/ft.png') }}" class="img-responsive" /> <div class="clearfix"> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-danger action" data-action="fg2a"> <img src="{{ url('public/upload/icons/2pt_x.png') }}" class="img-responsive" /> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-danger action" data-action="fg3a"> <img src="{{ url('public/upload/icons/3pt_x.png') }}" class="img-responsive" /> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-danger action" data-action="fta"> <img src="{{ url('public/upload/icons/ft_x.png') }}" class="img-responsive" /> <div class="clearfix"> <hr /> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-default action" data-action="blk"> <img src="{{ url('public/upload/icons/blk.png') }}" class="img-responsive" /> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-default action" data-action="oreb"> <img src="{{ url('public/upload/icons/oreb.png') }}" class="img-responsive" /> <div class="col-sm-4 columns"> <button type="button" data-dismiss="modal" class="btn btn-default action" data-action="dreb"> <img src="{{ url('public/upload/icons/dreb.png') }}" class="img-responsive" /> <div class="clearfix"> <hr /> <div class="col-sm-3 columns"> <button type="button" data-dismiss="modal" class="btn btn-info action" data-action="stl"> <img src="{{ url('public/upload/icons/stl.png') }}" class="img-responsive" /> <div class="col-sm-3 columns"> <button type="button" data-dismiss="modal" class="btn btn-info action" data-action="ast"> <img src="{{ url('public/upload/icons/ast.png') }}" class="img-responsive" /> <div class="col-sm-3 columns"> <button type="button" data-dismiss="modal" class="btn btn-info action" data-action="turnover"> <img src="{{ url('public/upload/icons/ot.png') }}" class="img-responsive" /> <div class="col-sm-3 columns"> <button type="button" data-dismiss="modal" class="btn btn-danger action" data-action="pf"> <img src="{{ url('public/upload/icons/pf.png') }}" class="img-responsive" /> <div class="clearfix"> /.modal-content --> /.modal-dialog --> /.modal --> <div class="modal fade" role="dialog" id="serverModal"> <div class="modal-dialog modal-sm" role="document"> {{ csrf_field() }} <div class="modal-content"> <div class="modal-body"> <div class="alert alert-warning"> <span class="text-warning"> <i class="fa fa-warning"> Opps! Connection problem! Please pause the game. /.modal-content --> /.modal-dialog --> /.modal --> <script src="{{ asset('resources/assets/js/jquery.min.js') }}"> <script src="{{ asset('resources/assets/js/bootstrap.min.js') }}"> var team = ""; var game_id = "{{ $data->id }}"; var player_id = 0; var action = ''; initialize(); function initialize(){ team = "{{ $data->home_team }}"; getScore(); } function getScore() { var url = "{{ url('game/score') }}"; $.ajax({ url: url+'/'+game_id+'/'+team, type: 'GET', success: function(data){ var tmp = "{{ $data->home_team }}"; if(tmp==team){ $('.home_score').html(data).fadeOut().fadeIn(); team = "{{ $data->away_team }}"; getScore(); }else{ $('.away_score').html(data).fadeOut().fadeIn(); team = ""; } }, error: function(){ $('#serverModal').modal('show'); } }); } $('a[href="#basketModal"]').on('click',function(){ player_id = $(this).data('player'); team = $(this).data('team'); }); $('.action').on('click',function(){ action = $(this).data('action'); sendData(); }); function sendData() { var url = "{{ url('admin/games/boxscore/auto/') }}"; $.ajax({ url: url+'/'+game_id+'/'+player_id+'/'+action+'/'+team, type: 'GET', success: function(data){ var tmp = "{{ $data->home_team }}"; console.log(team); if(tmp===team){ $('.home_score').html(data).fadeOut().fadeIn(); }else{ $('.away_score').html(data).fadeOut().fadeIn(); } }, error: function(){ $('#serverModal').modal('show'); } }); }
php
10
0.468228
168
40.076271
236
starcoderdata
using System; using System.ComponentModel; using System.Text; using Xunit; using Xunit.Abstractions; namespace Swisschain.Extensions.Encryption.Tests { public class AsymmetricEncryptionServiceTests { private readonly ITestOutputHelper _testOutputHelper; private readonly AsymmetricEncryptionService _service; private const string Secret = " public AsymmetricEncryptionServiceTests(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; _service = new AsymmetricEncryptionService(); } [Fact] public void GenerateNewPair() { var pair = _service.GenerateKeyPairPem(); var inlinePublicKey = pair.GetPublicKey().Replace("\r\n", @"\r\n"); var inlinePrivateKey = pair.GetPrivateKey().Replace("\r\n", @"\r\n"); _testOutputHelper.WriteLine("Inline public key:"); _testOutputHelper.WriteLine(inlinePublicKey); _testOutputHelper.WriteLine("Inline private key:"); _testOutputHelper.WriteLine(inlinePrivateKey); _testOutputHelper.WriteLine("Public key:"); _testOutputHelper.WriteLine(pair.GetPublicKey()); _testOutputHelper.WriteLine("Private key:"); _testOutputHelper.WriteLine(pair.GetPrivateKey()); } [Fact] public void Encrypt_And_Decrypt() { // arrange var pair = _service.GenerateKeyPairPem(); var secret = Encoding.UTF8.GetBytes(Secret); var encryptedData = _service.Encrypt(secret, pair.GetPublicKey()); var decryptedData = _service.Decrypt(encryptedData, pair.GetPrivateKey()); // assert var decryptedDataBase64 = Encoding.UTF8.GetString(decryptedData); Assert.Equal(Secret, decryptedDataBase64); } [Fact] public void Encrypt_And_Decrypt_With_External_Keys() { // arrange var secret = Encoding.UTF8.GetBytes(Secret); // act var privateKey = "----- var publicKey = "----- var encryptedData = _service.Encrypt(secret, publicKey); var decryptedData = _service.Decrypt(encryptedData, privateKey); // assert var decryptedDataBase64 = Encoding.UTF8.GetString(decryptedData); Assert.Equal(Secret, decryptedDataBase64); } [Fact] public void Decrypt() { // arrange var privateKey = "----- var encryptedData = " // act var decryptedData = _service.Decrypt(Convert.FromBase64String(encryptedData), privateKey); // assert Assert.Equal("8LZOlheUuPJgX2Jm/H9ueYxK3CS+R/668+D2ijzKVn4=", Convert.ToBase64String(decryptedData)); } [Fact] public void Sign_And_Verify() { // arrange var data = "Test string."; // act var keyPair = _service.GenerateKeyPairPem(); var signature = _service.GenerateSignature(Encoding.UTF8.GetBytes(data), keyPair.GetPrivateKey()); var isValid = _service.VerifySignature(Encoding.UTF8.GetBytes(data), signature, keyPair.GetPublicKey()); // assert Assert.True(isValid); } [Fact] public void Verify_Signature() { // arrange var publicKey = "----- ; var data = " ; var signature = "Kf5iSGE44iSX+UMp7lz3bYaYHE5Rpwav/wztVJHQ2E6pjNYt/muXumL7I/dyzBpWkJIGsvnrkOGMB2LiRf+M30CCWKtlZ8U0upSGz1kvlwEDP8dbpo74wcByKQy9h73dJtCuVeFbxZ/PixVUUg3IfNKfM7uExhSIIlNa4AU38Hg=" ; // act var isValid = _service.VerifySignature(Convert.FromBase64String(data), Convert.FromBase64String(signature), publicKey); // assert Assert.True(isValid); } } }
c#
16
0.57187
194
30.177778
135
starcoderdata
var NAVTREEINDEX6 = { "classgraphlab_1_1semaphore.html":[9,0,0,94], "classgraphlab_1_1semaphore.html#a0a5af8f72dd67f95fb70f373d7736395":[9,0,0,94,4], "classgraphlab_1_1semaphore.html#a5fbdb11238833be0aeba62cede328752":[9,0,0,94,1], "classgraphlab_1_1semaphore.html#a8b323ac89c1aec21f3c8f3abb4e1dd2c":[9,0,0,94,3], "classgraphlab_1_1semaphore.html#ae0e513bc610acd6c67ce9db8db99ba37":[9,0,0,94,0], "classgraphlab_1_1semaphore.html#ae861c1f55c77dcf773ad40578be6fffe":[9,0,0,94,2], "classgraphlab_1_1semaphore.html#afee57c96aa1391a95fc832852ad3955a":[9,0,0,94,5], "classgraphlab_1_1simple__spinlock.html":[7,1,4], "classgraphlab_1_1simple__spinlock.html#a2720cdc9ddcc9118b1dd92b7b58c7d83":[7,1,4,1], "classgraphlab_1_1simple__spinlock.html#a78d664381998db7383bdb99ad6cf9ee4":[7,1,4,6], "classgraphlab_1_1simple__spinlock.html#ab85a6a4fbbc496af30feeae4e38aa42e":[7,1,4,3], "classgraphlab_1_1simple__spinlock.html#ad84bebdf825b49d0d3d149659125a67b":[7,1,4,5], "classgraphlab_1_1simple__spinlock.html#ae0737d3b1b04bf4bb1212024b632c715":[7,1,4,4], "classgraphlab_1_1simple__spinlock.html#ae3673594012d800fee192ac7b62dd3dc":[7,1,4,2], "classgraphlab_1_1simple__spinlock.html#af5eb1e5a685425e20b4c21895b040cb6":[7,1,4,0], "classgraphlab_1_1small__set.html":[9,0,0,97], "classgraphlab_1_1small__set.html#a0d1c91ae156e212ed9f2c5f2d176c6c1":[9,0,0,97,27], "classgraphlab_1_1small__set.html#a0f860e393390eec93de26bfd6f290492":[9,0,0,97,22], "classgraphlab_1_1small__set.html#a19cff3a4a3aa8c7210c9597524bd0768":[9,0,0,97,3], "classgraphlab_1_1small__set.html#a19f0091cb324b6682cb16d56815a73bf":[9,0,0,97,9], "classgraphlab_1_1small__set.html#a1a4715366fc9c71ef0e08198e4740ca5":[9,0,0,97,20], "classgraphlab_1_1small__set.html#a1e5c023c0cf6f75ba56e8409aadd6a6e":[9,0,0,97,34], "classgraphlab_1_1small__set.html#a1f49d1323fe1adcb031bf539b6cbb727":[9,0,0,97,18], "classgraphlab_1_1small__set.html#a2c8d4dd5cc29bdafd823c2d5fa5ddc18":[9,0,0,97,30], "classgraphlab_1_1small__set.html#a3076989c9562191f77d8827a181c2764":[9,0,0,97,24], "classgraphlab_1_1small__set.html#a35cbb5951389dd0987c4e73732a811da":[9,0,0,97,13], "classgraphlab_1_1small__set.html#a40e16c5eb8373d1abe3440d894ed0d29":[9,0,0,97,0], "classgraphlab_1_1small__set.html#a48645b02aeec9e21545de14edf726a4d":[9,0,0,97,28], "classgraphlab_1_1small__set.html#a51cefc809e40325d87dacbb7539c7eb3":[9,0,0,97,2], "classgraphlab_1_1small__set.html#a5cd6b3355fd3f736d52178bf62a13bdf":[9,0,0,97,17], "classgraphlab_1_1small__set.html#a60ce8cb5c5bd23966149bfb1fb5c0247":[9,0,0,97,25], "classgraphlab_1_1small__set.html#a650b4db801284a413e3caacd6fc9fca5":[9,0,0,97,26], "classgraphlab_1_1small__set.html#a6b3ca330bae7873f845ab00a17fa8169":[9,0,0,97,16], "classgraphlab_1_1small__set.html#a6ba4262277adb94a69ac6103f151eaf0":[9,0,0,97,31], "classgraphlab_1_1small__set.html#a74ddb62a1bbd7da586c0f263b9691064":[9,0,0,97,8], "classgraphlab_1_1small__set.html#a78d353ac45b2e4a7258c91284f03f8be":[9,0,0,97,32], "classgraphlab_1_1small__set.html#a7a957b53e0310e972f90892fe03ced8c":[9,0,0,97,4], "classgraphlab_1_1small__set.html#a89f19040e3c814ddfe3529a3d8e51fc8":[9,0,0,97,10], "classgraphlab_1_1small__set.html#a9586faac0cd35603ac1dd91b34e5eb53":[9,0,0,97,23], "classgraphlab_1_1small__set.html#a95986ebac1b41b36d6c6ebd51ebea3ab":[9,0,0,97,7], "classgraphlab_1_1small__set.html#a95986ebac1b41b36d6c6ebd51ebea3aba8d57e7bf1aa4404de45ec4c8eccd5dd6":[9,0,0,97,7,0], "classgraphlab_1_1small__set.html#a991f58fd6315030872df9d8308031f00":[9,0,0,97,33], "classgraphlab_1_1small__set.html#a9dd716143f2cd4341a846a689724fc04":[9,0,0,97,29], "classgraphlab_1_1small__set.html#aadb0f4f47169ffe4a8d22a530e5e30ff":[9,0,0,97,11], "classgraphlab_1_1small__set.html#ab26bd3e7f63d2e8570cf16a483c386b4":[9,0,0,97,1], "classgraphlab_1_1small__set.html#ab553b515ce45086b1238399314050536":[9,0,0,97,21], "classgraphlab_1_1small__set.html#ab9bf863b8ea3add8a429c3a8eaa3d365":[9,0,0,97,15], "classgraphlab_1_1small__set.html#ac0326558b79b5efa3255efabe8fdc7d6":[9,0,0,97,14], "classgraphlab_1_1small__set.html#ac35cc550174fbfe7cefc84ddaf5df2a5":[9,0,0,97,6], "classgraphlab_1_1small__set.html#acbe1116f9132b11eeac0af6d5b10a991":[9,0,0,97,12], "classgraphlab_1_1small__set.html#acc41113fbae6b17ea2c9e3b7a8ed70e0":[9,0,0,97,36], "classgraphlab_1_1small__set.html#adb7946ae67e6da8c9f6f29773c8811c5":[9,0,0,97,19], "classgraphlab_1_1small__set.html#af0bfeb496b2d040bd9128c7bc841928f":[9,0,0,97,35], "classgraphlab_1_1small__set.html#af846a18789ed3900e5aeca11392f8daf":[9,0,0,97,5], "classgraphlab_1_1spinrwlock.html":[9,0,0,98], "classgraphlab_1_1spinrwlock.html#a073bb6850321646ddececc94e9ccfc6a":[9,0,0,98,0], "classgraphlab_1_1spinrwlock.html#a207862229444b6f2508097dc2657b4a6":[9,0,0,98,1], "classgraphlab_1_1spinrwlock.html#a2097bc59b573fbeefab167bdd43ce042":[9,0,0,98,5], "classgraphlab_1_1spinrwlock.html#a2ade9ac51ac23b6b2191e4632e3f84d7":[9,0,0,98,4], "classgraphlab_1_1spinrwlock.html#a406734d85867d48f46ca5e9d8b0a0d7f":[9,0,0,98,3], "classgraphlab_1_1spinrwlock.html#aaa327c959073ba0d5367d76c57da2207":[9,0,0,98,2], "classgraphlab_1_1synchronous__engine.html":[7,0,2], "classgraphlab_1_1synchronous__engine.html#a01472800a89cef585293b074e4aa9925":[7,0,2,7], "classgraphlab_1_1synchronous__engine.html#a1b3fde48e79d248db7b815a313cd92e2":[7,0,2,22], "classgraphlab_1_1synchronous__engine.html#a1ce0830e073c4c9f7bde48aa7add78c6":[7,0,2,2], "classgraphlab_1_1synchronous__engine.html#a23b7178b34cf55f0ff27254df488d0e8":[7,0,2,18], "classgraphlab_1_1synchronous__engine.html#a2445bcd6a03578f62a4b3ca471777da3":[7,0,2,17], "classgraphlab_1_1synchronous__engine.html#a39c802e7271358becf2cf2b2418b943a":[7,0,2,13], "classgraphlab_1_1synchronous__engine.html#a457af918f56deee1cfa4d7388612162b":[7,0,2,8], "classgraphlab_1_1synchronous__engine.html#a46c393517c30de7401ca0dfcacf9f21f":[7,0,2,4], "classgraphlab_1_1synchronous__engine.html#a4ab681ecccc66ad8696f5a4d0103fa23":[7,0,2,32], "classgraphlab_1_1synchronous__engine.html#a4d9e97843604c45c08f71502b3494a7a":[7,0,2,33], "classgraphlab_1_1synchronous__engine.html#a4fae54a2dfc7523fe303c7af9c2dd9c2":[7,0,2,6], "classgraphlab_1_1synchronous__engine.html#a53dc0f312b34a2f9ecf3a6790a95aeab":[7,0,2,30], "classgraphlab_1_1synchronous__engine.html#a58c1cb76d31f21796e8eac2918386a33":[7,0,2,3], "classgraphlab_1_1synchronous__engine.html#a5f0ebbe2a3dae9ed3e7cbe6538e37742":[7,0,2,15], "classgraphlab_1_1synchronous__engine.html#a609d06d25b1e06c17a2d04e00d5b3bbf":[7,0,2,31], "classgraphlab_1_1synchronous__engine.html#a615f2b888415c5a98f58abddefdc1cf7":[7,0,2,34], "classgraphlab_1_1synchronous__engine.html#a630bc97984f82232f90477c281b9566a":[7,0,2,1], "classgraphlab_1_1synchronous__engine.html#a6602b1e06b1b4db6537e6e48774499b9":[7,0,2,16], "classgraphlab_1_1synchronous__engine.html#a6b75dd97ee2b20d3c5483d4f851e40bf":[7,0,2,25], "classgraphlab_1_1synchronous__engine.html#a6d1407b75158fdaef63eec9719da40da":[7,0,2,12], "classgraphlab_1_1synchronous__engine.html#a74c8f04b5e42f52b1dd531baf207da6f":[7,0,2,0], "classgraphlab_1_1synchronous__engine.html#a86a7a9e2b10c0934d4c486c56c649c13":[7,0,2,28], "classgraphlab_1_1synchronous__engine.html#a8da8e299fd9bfc87e308d5ad571f35eb":[7,0,2,21], "classgraphlab_1_1synchronous__engine.html#a8fa376024471b03353f6af154942524d":[7,0,2,19], "classgraphlab_1_1synchronous__engine.html#a9c0afe236029be943f870a77bd2a6b3f":[7,0,2,26], "classgraphlab_1_1synchronous__engine.html#aa401498dc228b778e74dd18abe4affc3":[7,0,2,9], "classgraphlab_1_1synchronous__engine.html#aa43d4539e101c16302d07ba90509882e":[7,0,2,27], "classgraphlab_1_1synchronous__engine.html#aafefe848a350d243f62fefe173d3d287":[7,0,2,14], "classgraphlab_1_1synchronous__engine.html#ab295d6cdb7cdbccfb2dd9748a39065fe":[7,0,2,10], "classgraphlab_1_1synchronous__engine.html#ab945aad4bc982b507efc1ba55dba30d8":[7,0,2,24], "classgraphlab_1_1synchronous__engine.html#abc4dc04bce51af81f928f00653fdb4fe":[7,0,2,20], "classgraphlab_1_1synchronous__engine.html#abcb4ab3893aff7ea922341da156878f7":[7,0,2,5], "classgraphlab_1_1synchronous__engine.html#aceb9b35b199d2e76bc22b2f261e585ba":[7,0,2,29], "classgraphlab_1_1synchronous__engine.html#ad8debef60159f9cd584ed57f6d5bfef4":[7,0,2,23], "classgraphlab_1_1synchronous__engine.html#adf21f70c04f6e9954e5db488cad6bff0":[7,0,2,11], "classgraphlab_1_1thread.html":[7,1,9], "classgraphlab_1_1thread.html#a1e750a357bdc47fe65ecf59213a4cfe8":[7,1,9,3], "classgraphlab_1_1thread.html#a266eda0f158b70d139e5c048d8a3e4c4":[7,1,9,6], "classgraphlab_1_1thread.html#a6cc76c8d6eaf971f300b9a0e206a6c20":[7,1,9,5], "classgraphlab_1_1thread.html#a7d21e03d51c607739c29b1c87f50a70f":[7,1,9,0], "classgraphlab_1_1thread.html#a8334e9dcb09bb7ace8cedbd000e86fbc":[7,1,9,1], "classgraphlab_1_1thread.html#a8444895775f38f22dd42532c0a9152dd":[7,1,9,2], "classgraphlab_1_1thread.html#abed4c897d2b36d10bb9972e7326a2b0c":[7,1,9,4], "classgraphlab_1_1thread_1_1tls__data.html":[7,1,8], "classgraphlab_1_1thread_1_1tls__data.html#a40a1a0d09db11a076eb3b53f4967cb07":[7,1,8,5], "classgraphlab_1_1thread_1_1tls__data.html#a6d099719ecb4a9a94d0bbfde0e2277b1":[7,1,8,2], "classgraphlab_1_1thread_1_1tls__data.html#a8b1452e41d30fd95f43aa38acf16ac4b":[7,1,8,1], "classgraphlab_1_1thread_1_1tls__data.html#a9db6a3b328e551fff32eb40c5e37c215":[7,1,8,0], "classgraphlab_1_1thread_1_1tls__data.html#ab11e2e9f1f443669f1dbbaf666036b48":[7,1,8,3], "classgraphlab_1_1thread_1_1tls__data.html#acaf19aa16cf2d6e807d582d62a86b06e":[7,1,8,4], "classgraphlab_1_1thread__group.html":[7,1,10], "classgraphlab_1_1thread__group.html#a0fddf20aa49376a7e46f4b6d0dac3100":[7,1,10,5], "classgraphlab_1_1thread__group.html#a3b5331667012e789ce4b249f6d4ca406":[7,1,10,4], "classgraphlab_1_1thread__group.html#abf0f2033410aa3d916ea78bc0107de34":[7,1,10,0], "classgraphlab_1_1thread__group.html#ae2df8b1a09c6f6854f9289e2b5841301":[7,1,10,3], "classgraphlab_1_1thread__group.html#af73d193dde4398fc6f2691957abeda61":[7,1,10,1], "classgraphlab_1_1thread__group.html#af991086cab5d4f6943ca7fa60da37a85":[7,1,10,2], "classgraphlab_1_1thread__pool.html":[7,1,11], "classgraphlab_1_1thread__pool.html#a005b254092a226c6c8f835f50dcb7265":[7,1,11,6], "classgraphlab_1_1thread__pool.html#a01f16a7af5c77361755bcfb052ee3c3a":[7,1,11,2], "classgraphlab_1_1thread__pool.html#a5d618208a380bc545c0b11c9c4bea894":[7,1,11,1], "classgraphlab_1_1thread__pool.html#a642f8d4fed6444e9832675f66358897f":[7,1,11,0], "classgraphlab_1_1thread__pool.html#a6e2f749be18793e1ae3e09c715d856fa":[7,1,11,4], "classgraphlab_1_1thread__pool.html#a93e1f976a5d80f0baab2a00aa139426b":[7,1,11,7], "classgraphlab_1_1thread__pool.html#aa32851a914217c3240800e677c00a69b":[7,1,11,5], "classgraphlab_1_1thread__pool.html#ac322d85473900f1dc8fe585efec0c351":[7,1,11,3], "classgraphlab_1_1timer.html":[7,1,17], "classgraphlab_1_1timer.html#a8d3d321b6d4bae872c6dd0745a0a22ea":[7,1,17,2], "classgraphlab_1_1timer.html#a91565fab2bdf8cea35f215540290150b":[7,1,17,3], "classgraphlab_1_1timer.html#aedb4e691d24b53dc2b43c94f63ea44ec":[7,1,17,0], "classgraphlab_1_1timer.html#af473b648b11d5499f08a2e9a56aa276c":[7,1,17,1], "classgraphlab_1_1vertex__set.html":[9,0,0,109], "classgraphlab_1_1vertex__set.html#a0a22fca527e08c772fc904e198950a0c":[9,0,0,109,0], "classgraphlab_1_1vertex__set.html#a0cf99d8f92f6decfc8c17c8889a22e91":[9,0,0,109,20], "classgraphlab_1_1vertex__set.html#a124b9c7853397d26e6238ae8c4693597":[9,0,0,109,9], "classgraphlab_1_1vertex__set.html#a1395841634758f2bdc7b7129947339ee":[9,0,0,109,6], "classgraphlab_1_1vertex__set.html#a2e13cd12106aa43648c17a475301e1e8":[9,0,0,109,8], "classgraphlab_1_1vertex__set.html#a384c8193fb481beaeef848b12eca53a6":[9,0,0,109,15], "classgraphlab_1_1vertex__set.html#a3b11a4429efd726da6070e2cda53c89f":[9,0,0,109,18], "classgraphlab_1_1vertex__set.html#a3f937d884e092805831648eed637a761":[9,0,0,109,5], "classgraphlab_1_1vertex__set.html#a442d80f027b979fb595cfb4b0aabb0bb":[9,0,0,109,3], "classgraphlab_1_1vertex__set.html#a763caffa7049762c9e10d594407608d2":[9,0,0,109,10], "classgraphlab_1_1vertex__set.html#a7ec772e93ec4d7bffda7784caa7e61e6":[9,0,0,109,13], "classgraphlab_1_1vertex__set.html#a8110f76d494833c4c1046ec4725c07af":[9,0,0,109,19], "classgraphlab_1_1vertex__set.html#a850faed4908a38b9684bc5fe8c5f801e":[9,0,0,109,12], "classgraphlab_1_1vertex__set.html#a8a1c6c0573595cdf24994698c2221ba6":[9,0,0,109,11], "classgraphlab_1_1vertex__set.html#a8fdb6684ae89b6880fa761f00d7eb99c":[9,0,0,109,14], "classgraphlab_1_1vertex__set.html#a9e0c9cb0a7fc7955eac58b28904ea1c7":[9,0,0,109,7], "classgraphlab_1_1vertex__set.html#a9f0209ab522a1aef0bd405da3d0454fd":[9,0,0,109,21], "classgraphlab_1_1vertex__set.html#aad30a2972b308844fbb94c7204783303":[9,0,0,109,1], "classgraphlab_1_1vertex__set.html#abba0bd709862e83c89c184ce85b0b398":[9,0,0,109,22], "classgraphlab_1_1vertex__set.html#aca63c98826309bf3867958ef64e0577c":[9,0,0,109,4], "classgraphlab_1_1vertex__set.html#ad679b66b0540478e0d8bf0299abcdac1":[9,0,0,109,2], "classgraphlab_1_1vertex__set.html#ad999b0efbdce9bbeac005b7af163b960":[9,0,0,109,17], "classgraphlab_1_1vertex__set.html#ae3b78afc0e8d5ea8c721eeca5863b669":[9,0,0,109,16], "classgraphlab_1_1warp_1_1warp__engine.html":[7,7,0], "classgraphlab_1_1warp_1_1warp__engine.html#a13705e9d5407a9472a67228b0b95c3a1":[7,7,0,17], "classgraphlab_1_1warp_1_1warp__engine.html#a273663e2f972ed060b73a334b5005ab8":[7,7,0,21], "classgraphlab_1_1warp_1_1warp__engine.html#a36a3ca607b82b8d5a5de1d5c68ad5b96":[7,7,0,18], "classgraphlab_1_1warp_1_1warp__engine.html#a38bc5527f07abea3d96834f7bfb8c82d":[7,7,0,10], "classgraphlab_1_1warp_1_1warp__engine.html#a5204f3ebb46545230eb79873eae75b12":[7,7,0,19], "classgraphlab_1_1warp_1_1warp__engine.html#a7e4c250b06b3317b326ce1b66ae083b4":[7,7,0,4], "classgraphlab_1_1warp_1_1warp__engine.html#a82fe72fd293203845a3cadc2a9afdc2e":[7,7,0,7], "classgraphlab_1_1warp_1_1warp__engine.html#a849c2f88fd77470212062686039a1f4e":[7,7,0,1], "classgraphlab_1_1warp_1_1warp__engine.html#a8d4b5f15cea57d6166d869135711fd1d":[7,7,0,9], "classgraphlab_1_1warp_1_1warp__engine.html#aa3ae27e1a3d43c52043a8cd98908e9d0":[7,7,0,14], "classgraphlab_1_1warp_1_1warp__engine.html#aa74b0b52ac5085c68bbc32706dd83432":[7,7,0,0], "classgraphlab_1_1warp_1_1warp__engine.html#acab3e4370cc0bca7df56bad7a2b5e1a4":[7,7,0,8], "classgraphlab_1_1warp_1_1warp__engine.html#ad103f8855ffa197d832080f20f371971":[7,7,0,16], "classgraphlab_1_1warp_1_1warp__engine.html#ad228fe6ec32d8535812fced2e88d4072":[7,7,0,11], "classgraphlab_1_1warp_1_1warp__engine.html#ad2402741a090c78e9fbe0426fe27f7b8":[7,7,0,12], "classgraphlab_1_1warp_1_1warp__engine.html#ae1c1afc63ada7737e95f019aa13d53dd":[7,7,0,3], "classgraphlab_1_1warp_1_1warp__engine.html#aed832e04e05e8d8a18f3843d451758c7":[7,7,0,20], "classgraphlab_1_1warp_1_1warp__engine.html#aefb60417fd2e352891f62647d9646360":[7,7,0,5], "classgraphlab_1_1warp_1_1warp__engine.html#af24910dfd6b6d99142cc875997a419a2":[7,7,0,13], "classgraphlab_1_1warp_1_1warp__engine.html#af757a9f7fd39f6659d65a94ec8a25d00":[7,7,0,2], "classgraphlab_1_1warp_1_1warp__engine.html#af9da2b52a9e48a7ddf11d84659630db3":[7,7,0,6], "classgraphlab_1_1warp_1_1warp__engine.html#afa40613ea0fa65ab9f21f29efd406d8d":[7,7,0,15], "classgraphlab_1_1zookeeper_1_1key__value.html":[9,0,0,3,0], "classgraphlab_1_1zookeeper_1_1key__value.html#a0bd2871db94793b8e1a3659d70934b05":[9,0,0,3,0,7], "classgraphlab_1_1zookeeper_1_1key__value.html#a4da92ea30ed605445370475a2934ebfb":[9,0,0,3,0,6], "classgraphlab_1_1zookeeper_1_1key__value.html#a727bdf5c0ba38f61e199d91ec6c14284":[9,0,0,3,0,2], "classgraphlab_1_1zookeeper_1_1key__value.html#a88f847b0ff5f6626109d3fcaed096196":[9,0,0,3,0,8], "classgraphlab_1_1zookeeper_1_1key__value.html#aa6c569c68715ad1eb93159b61f3d7138":[9,0,0,3,0,0], "classgraphlab_1_1zookeeper_1_1key__value.html#aaff0dd6dc87e56fdf5b9b569a9016d10":[9,0,0,3,0,3], "classgraphlab_1_1zookeeper_1_1key__value.html#ad3b53bd9ce11cf777d7167fa95160912":[9,0,0,3,0,4], "classgraphlab_1_1zookeeper_1_1key__value.html#ae1a4a45f839a27467f58963f69c485cc":[9,0,0,3,0,1], "classgraphlab_1_1zookeeper_1_1key__value.html#af9093c2ee60a9579b2b16b1428896214":[9,0,0,3,0,5], "classgraphlab_1_1zookeeper_1_1server__list.html":[9,0,0,3,1], "classgraphlab_1_1zookeeper_1_1server__list.html#a04baa9b88a49c34b72cdd37ee5bcd6eb":[9,0,0,3,1,1], "classgraphlab_1_1zookeeper_1_1server__list.html#a06b467f49b1a17916491d614cbc79ce2":[9,0,0,3,1,6], "classgraphlab_1_1zookeeper_1_1server__list.html#a109a8d822c7d84cecca4784f228336c2":[9,0,0,3,1,5], "classgraphlab_1_1zookeeper_1_1server__list.html#a709bb1c82d1d072b033d5650e8fe7b33":[9,0,0,3,1,3], "classgraphlab_1_1zookeeper_1_1server__list.html#a74c43d4e6dfacf97a5a5b62d2d9d74c4":[9,0,0,3,1,4], "classgraphlab_1_1zookeeper_1_1server__list.html#aa4bbb1d6d1c25144bad5a637dfa7c258":[9,0,0,3,1,0], "classgraphlab_1_1zookeeper_1_1server__list.html#aecd6fea09de92fe3e87530751c120935":[9,0,0,3,1,7], "classgraphlab_1_1zookeeper_1_1server__list.html#af2e5f0e1060b5e4350e826fbfd2eec76":[9,0,0,3,1,2], "clustering.html":[6,2], "clustering.html#Options":[6,2,1,0], "clustering.html#clustering_kmeans":[6,2,0], "clustering.html#clustering_kmeans_edge_data":[6,2,0,4], "clustering.html#clustering_kmeans_id":[6,2,0,3], "clustering.html#clustering_kmeans_options":[6,2,0,5], "clustering.html#clustering_kmeans_running":[6,2,0,1], "clustering.html#clustering_kmeans_sparse":[6,2,0,2], "clustering.html#clustering_kmeans_synthetic":[6,2,0,0], "clustering.html#clustering_spectral_clustering":[6,2,1], "collaborative_filtering.html":[6,3], "collaborative_filtering.html#ADPREDICTOR":[6,3,14], "collaborative_filtering.html#ALS":[6,3,5], "collaborative_filtering.html#Acknowledgements":[6,3,16], "collaborative_filtering.html#Algorithms":[6,3,1], "collaborative_filtering.html#BIAS_SGD":[6,3,8], "collaborative_filtering.html#CCD_PLUS_PLUS":[6,3,6], "collaborative_filtering.html#Command":[6,3,13,0], "collaborative_filtering.html#History":[6,3,0], "collaborative_filtering.html#Implicit":[6,3,15], "collaborative_filtering.html#Input":[6,3,2], "collaborative_filtering.html#NMF":[6,3,12], "collaborative_filtering.html#Output":[6,3,4], "collaborative_filtering.html#RATINGS":[6,3,3], "collaborative_filtering.html#SALS":[6,3,11], "collaborative_filtering.html#SGD":[6,3,7], "collaborative_filtering.html#SVD":[6,3,13], "collaborative_filtering.html#SVD0":[6,3,13,1], "collaborative_filtering.html#SVD1":[6,3,13,2], "collaborative_filtering.html#SVD2":[6,3,13,3], "collaborative_filtering.html#SVD3":[6,3,13,4], "collaborative_filtering.html#SVD_PLUS_PLUS":[6,3,9], "collaborative_filtering.html#WALS":[6,3,10], "command__line__options_8cpp_source.html":[10,0,1,5,0], "command__line__options_8hpp_source.html":[10,0,1,5,1], "computer_vision.html":[6,7], "computer_vision.html#computer_vision_options":[6,7,2], "computer_vision.html#image_stitching":[6,7,0], "computer_vision.html#running_stitch":[6,7,1], "conditional__addition__wrapper_8hpp_source.html":[10,0,1,11,0,4], "conditional__combiner__wrapper_8hpp_source.html":[10,0,1,11,0,5], "conditional__serialize_8hpp_source.html":[10,0,1,9,1], "context_8hpp_source.html":[10,0,1,12,0], "counting__sort_8hpp_source.html":[10,0,1,11,0,6], "csr__storage_8hpp_source.html":[10,0,1,11,0,7], "cuckoo__map_8hpp_source.html":[10,0,1,11,11], "cuckoo__map__pow2_8hpp_source.html":[10,0,1,11,12], "cuckoo__set__pow2_8hpp_source.html":[10,0,1,11,13], "dc_8cpp_source.html":[10,0,1,7,7], "dc_8hpp_source.html":[10,0,1,7,8], "dc__buffered__stream__send2_8cpp_source.html":[10,0,1,7,9] };
javascript
6
0.791843
117
75.466403
253
starcoderdata
static Instruction *replaceIntrinsicWith(IntrinsicInst *call, Type *RetTy, ArrayRef<Value*> args) { Intrinsic::ID ID = call->getIntrinsicID(); assert(ID); auto oldfType = call->getFunctionType(); auto nargs = oldfType->getNumParams(); assert(args.size() > nargs); SmallVector<Type*, 8> argTys(nargs); for (unsigned i = 0; i < nargs; i++) argTys[i] = args[i]->getType(); auto newfType = FunctionType::get(RetTy, argTys, oldfType->isVarArg()); // Accumulate an array of overloaded types for the given intrinsic // and compute the new name mangling schema SmallVector<Type*, 4> overloadTys; { SmallVector<Intrinsic::IITDescriptor, 8> Table; getIntrinsicInfoTableEntries(ID, Table); ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; auto res = Intrinsic::matchIntrinsicSignature(newfType, TableRef, overloadTys); assert(res == Intrinsic::MatchIntrinsicTypes_Match); (void)res; bool matchvararg = !Intrinsic::matchIntrinsicVarArg(newfType->isVarArg(), TableRef); assert(matchvararg); (void)matchvararg; } auto newF = Intrinsic::getDeclaration(call->getModule(), ID, overloadTys); assert(newF->getFunctionType() == newfType); newF->setCallingConv(call->getCallingConv()); assert(args.back() == call->getCalledFunction()); auto newCall = CallInst::Create(newF, args.drop_back(), "", call); newCall->setTailCallKind(call->getTailCallKind()); auto old_attrs = call->getAttributes(); newCall->setAttributes(AttributeList::get(call->getContext(), getFnAttrs(old_attrs), getRetAttrs(old_attrs), {})); // drop parameter attributes return newCall; }
c++
11
0.664005
104
46.405405
37
inline
void cIniFile::RemoveBom(AString & a_line) const { // The BOM sequence for UTF-8 is 0xEF, 0xBB, 0xBF static unsigned const char BOM[] = { 0xEF, 0xBB, 0xBF }; // The BOM sequence, if present, is always th e first three characters of the input. const AString ref = a_line.substr(0, 3); // If any of the first three chars do not match, return and do nothing. for (size_t i = 0; i < 3; ++i) { if (static_cast<unsigned char>(ref[i]) != BOM[i]) { return; } } // First three characters match; erase them. a_line.erase(0, 3); }
c++
13
0.652495
85
26.1
20
inline
#ifndef __HTMLDOCUMENT_H__ #define __HTMLDOCUMENT_H__ #include using namespace ATL; /** * IHTMLDocument wrapper */ class HTMLDocument : public IDispEventImpl<1, HTMLDocument, &DIID_HTMLDocumentEvents, &LIBID_MSHTML, 1, 1> { public: HTMLDocument(const CComQIPtr<IWebBrowser2, &IID_IWebBrowser2>& webBrowser2); ~HTMLDocument(); BEGIN_SINK_MAP(HTMLDocument) END_SINK_MAP() // TODO - check document type == html for all Inject functions? HRESULT InjectDocument(const wstringpointer& content); HRESULT InjectScript(const wstringpointer& content); HRESULT InjectScriptTag(const wstring& type, const wstring& src); HRESULT InjectStyle(const wstringpointer& content); HRESULT InjectBody(const wstringpointer& content, BSTR where = HTMLDocument::beforeEnd); HRESULT InjectElementById(const wstring& id, const wstringpointer& content, BSTR where = HTMLDocument::beforeEnd); HRESULT ClickElementById(const wstring& id); private: HRESULT OnConnect(); HRESULT OnDisconnect(); const CComQIPtr<IWebBrowser2, &IID_IWebBrowser2>& m_webBrowser2; CComQIPtr<IHTMLDocument2, &IID_IHTMLDocument2> m_htmlDocument2; CComQIPtr<IHTMLDocument3, &IID_IHTMLDocument3> m_htmlDocument3; public: static const BSTR beforeBegin; static const BSTR afterBegin; static const BSTR beforeEnd; static const BSTR afterEnd; static const BSTR tagHead; static const BSTR tagScript; static const BSTR tagStyle; static const BSTR attrScriptType; static const BSTR attrStyleType; public: typedef shared_ptr pointer; }; #endif /* __HTMLDOCUMENT_H__ */
c
12
0.693402
94
28.842105
57
starcoderdata
// // Created by on 2/24/21. // #include namespace responses { std::string account::getId() const { return data.get } std::string account::getCurrency() const { auto currency = data.get_optional return currency ? currency.value() : ""; } std::string account::getBalance() const { return data.get } std::string account::getAvailable() const { return data.get } std::string account::getHold() const { return data.get } std::string account::getProfileId() const { auto profileId = data.get_optional return profileId ? profileId.value() : ""; } bool account::getTradingEnabled() const { auto tradingEnabled = data.get_optional return tradingEnabled ? tradingEnabled.value() : true; } account::account(const pt::ptree &data) : data(data) {} }
c++
13
0.596154
73
21.431373
51
starcoderdata
#pragma once #include "Voxel/Interface/IVoxelRenderer.h" #include "Voxel/OpenGL/OpenGLVoxelRenderer.h" namespace ExtraLife { namespace OpenGL{ class OpenGLVoxelRenderer : public IVoxelRenderer { public: OpenGLVoxelRenderer(const VoxelResource& voxel_resource, const WorldPositionsInRangeUpdater& world_positions_in_range, IShaderProgram* shader_program); void render(Camera& camera) const override; }; } // namespace OpenGL } // namespace ExtraLife
c
13
0.817094
153
31.555556
18
starcoderdata
#!/usr/bin/env python # -*- coding: utf-8 -*- """COmparing Continuous Optimisers (COCO) post-processing software This package is meant to generate output figures and tables for the benchmarking of continuous optimisers in the case of black-box optimisation. The post-processing tool takes as input data from experiments and generates outputs that will be used in the generation of the LateX- formatted article summarizing the experiments. The main method of this package is `cocopp.main` (currently aliased to `cocopp.rungeneric.main`). This method allows to use the post-processing through a command-line interface. To obtain more information on the use of this package from the python interpreter, type ``help(cocopp.cococommands)``, however remark that this info might not be entirely up-to-date. """ from __future__ import absolute_import import matplotlib # just to make sure the following is actually done first matplotlib.use('Agg') # To avoid window popup and use without X forwarding del matplotlib from numpy.random import seed as set_seed from .cococommands import * # outdated from . import config from . import findfiles from .rungeneric import main as main import pkg_resources __all__ = [# 'main', # import nothing with "from cocopp import *" ] __version__ = pkg_resources.require('cocopp')[0].version _data_archive = findfiles.COCODataArchive() data_archive = _data_archive # this line will go away "depreciated" bbob = findfiles.COCOBBOBDataArchive() bbob_noisy = findfiles.COCOBBOBNoisyDataArchive() bbob_biobj = findfiles.COCOBBOBBiobjDataArchive() del absolute_import, pkg_resources
python
8
0.770031
75
30.442308
52
starcoderdata
<?php /** * Phing Task to call WSDLInterpreter on each service WSDL from a build script. * * PHP version 5 * * Copyright 2011, Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @copyright 2011, Google Inc. All Rights Reserved. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, * Version 2.0 * @author * @author */ require_once 'phing/Task.php'; require_once 'WSDLInterpreter/WSDLInterpreter.php'; /** * A Phing task used to generate an Ads API service from a WSDL URL. */ class Wsdl2PhpTask extends Task { /** * The URL passed in the buildfile for the WSDL. * @var string the URL of the WSDL * @access private */ private $url = NULL; /** * The SOAP client classname of the API. * @var string the SoapClient class extension to extend * @access private */ private $soapClientClassName = NULL; /** * The SOAP client class path of the API. * @var string the path of the SoapClient class extension to extend * @access private */ private $soapClientClassPath = NULL; /** * The output directory for the php file. This can be a relative path * from the current directory from which the task is called, or an * absolute path. * @var string the output directory of the task * @access private */ private $outputDir = NULL; /** * The classmap of 'Wsdl Type => PHP Class' for the WSDL. * @var array the classmap for the WSDL type to PHP class * @access private */ private $classmap = NULL; /** * A classmap of 'Wsdl Type => PHP Class' for the WSDL, to be used * to avoid class name conflicts when namespaces are not enabled. * @var array the classmap for the WSDL type to PHP class * @access private */ private $conflictClassmap = NULL; /** * The WSDL types that shouldn't have their class names checked for * uniqueness. This option will be ignored when namespaces are enabled. * @var array the WSDL types that shouldn't have their class names checked for * uniqueness. * @access private */ private $skipClassNameCheckTypes = NULL; /** * The name of the service being worked on. * @var string the name of the service being worked on * @access private */ private $serviceName = NULL; /** * The version of the service being worked on * @var string the version of the service being worked * @access private */ private $version = NULL; /** * The package name to be included in the file header. * @var string the package name to be included in the file header * @access private */ private $package = NULL; /** * The proxy URL to use when downloading WSDLs. * @var string the proxy URL to use when downloading WSDLs * @access private */ private $proxy = NULL; /** * Whether or not to enable namespaces in the generated class names. * @var boolean whether or not to enable namespaces in the generated * class names * @access private */ private $enableNamespaces = FALSE; /** * The setter for the attribute * @param string $url the URL of the WSDL file */ public function setUrl($url) { $this->url = $url; } /** * The setter for the attribute * @param string $soapClientClassName the soap client classname to extend for * each soap client */ public function setSoapClientClassName($soapClientClassName) { $this->soapClientClassName = $soapClientClassName; } /** * The setter for the attribute * @param string $soapClientClassPath the soap client class path to require * in each service class file */ public function setSoapClientClassPath($soapClientClassPath) { $this->soapClientClassPath = $soapClientClassPath; } /** * The setter for the attribute * @param string $path the output directory where the generated PHP * file will be placed */ public function setOutputDir($outputDir) { $this->outputDir = $outputDir; } /** * The setter for the attribute * @param string $classmap JSON representation of the classmap, as a mapping * from WSDL type to PHP class name */ public function setClassmap($classmap) { $this->classmap = json_decode($classmap, true); if (!isset($this->classmap) && !empty($classmap)) { trigger_error('Unable to parse classmap as JSON.', E_USER_ERROR); die; } } /** * The setter for the attribute * @param string $conflictClassmap JSON representation of a classmap, as a * mapping from WSDL type to PHP class name, to be used to avoid name * conflicts when namespaces aren't enabled */ public function setConflictClassmap($conflictClassmap) { $this->conflictClassmap = json_decode($conflictClassmap, true); if (!isset($this->conflictClassmap) && !empty($conflictClassmap)) { trigger_error('Unable to parse the conflict classmap as JSON.', E_USER_ERROR); die; } } /** * The setter for the attribute * @param string $skipClassNameCheckTypes comma separated list of the type * names */ public function setSkipClassNameCheckTypes($skipClassNameCheckTypes) { if (!empty($skipClassNameCheckTypes)) { $this->skipClassNameCheckTypes = array_map('trim', explode(',', $skipClassNameCheckTypes)); } } /** * The setter for the attribute * @param string $version the version of the API for the generated service */ public function SetVersion($version) { $this->version = $version; } /** * The setter for the attribute * @param string $package the pacakge to be inserted into the file header */ public function SetPackage($package) { $this->package = $package; } /** * The setter for the attribute * @param string $proxy the proxy URL to use when downloading WSDLs */ public function SetProxy($proxy) { $this->proxy = $proxy; } /** * The setter for the attribute * @param boolean $enableNamespaces whether or not to enable * namespaces in the generated class names. */ public function SetEnableNamespaces($enableNamespaces) { $this->enableNamespaces = $enableNamespaces; } /** * The setter of the attribute * @param string $serviceName the name of the generated service */ public function SetServiceName($serviceName) { $this->serviceName = $serviceName; } /** * Nothing to initilize for the task. */ public function init() {} /** * The main entry point method for the task. */ public function main() { $this->log(sprintf("Starting: %s to %s", $this->url, $this->outputDir), Project::MSG_INFO); $wsdlInterpreter = new WSDLInterpreter($this->url, $this->soapClientClassName, $this->classmap, $this->conflictClassmap, $this->serviceName, $this->version, $this->package, $this->soapClientClassPath, $this->proxy, $this->enableNamespaces, $this->skipClassNameCheckTypes); $wsdlInterpreter->savePHP($this->outputDir); $loadedClasses = $wsdlInterpreter->getLoadedClassesCount(); $loadedServices = $wsdlInterpreter->getLoadedServicesCount(); $this->log(sprintf("[objects created: %d][url: %s]", $loadedClasses + $loadedServices, $this->url), Project::MSG_INFO); $this->log(sprintf("Created: [classes: %d][services: %d][functions: %d]", $loadedClasses, $loadedServices, $wsdlInterpreter->getLoadedFunctionsCount()), Project::MSG_VERBOSE); } }
php
16
0.671199
80
30.210332
271
starcoderdata
/* * Copyright 2013-2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.goide.codeInsight.imports; import com.goide.project.GoExcludedPathsSettings; import com.goide.psi.GoFile; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupActionProvider; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementAction; import com.intellij.icons.AllIcons; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.Consumer; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import java.util.List; public class GoExcludePathLookupActionProvider implements LookupActionProvider { @Override public void fillActions(LookupElement element, Lookup lookup, Consumer consumer) { PsiElement psiElement = element.getPsiElement(); PsiFile file = psiElement != null ? psiElement.getContainingFile() : null; String importPath = file instanceof GoFile ? ((GoFile)file).getImportPath() : null; if (importPath != null) { Project project = psiElement.getProject(); for (String path : getPaths(importPath)) { consumer.consume(new ExcludePathAction(project, path)); } consumer.consume(new EditExcludedAction(project)); } } private static List getPaths(String importPath) { List result = ContainerUtil.newArrayList(importPath); int i; while ((i = importPath.lastIndexOf('/')) > 0) { importPath = importPath.substring(0, i); result.add(importPath); } return result; } private static class EditExcludedAction extends LookupElementAction { @NotNull Project myProject; protected EditExcludedAction(@NotNull Project project) { super(AllIcons.Actions.Edit, "Edit auto import settings"); myProject = project; } @Override public Result performLookupAction() { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { final GoAutoImportConfigurable configurable = new GoAutoImportConfigurable(myProject, true); ShowSettingsUtil.getInstance().editConfigurable(myProject, configurable, new Runnable() { @Override public void run() { configurable.focusList(); } }); } }); return Result.HIDE_LOOKUP; } } private static class ExcludePathAction extends LookupElementAction { private Project myProject; private String myImportPath; protected ExcludePathAction(@NotNull Project project, @NotNull String importPath) { super(AllIcons.Actions.Exclude, "Exclude '" + importPath + "'"); myProject = project; myImportPath = importPath; } @Override public Result performLookupAction() { GoExcludedPathsSettings.getInstance(myProject).excludePath(myImportPath); return Result.HIDE_LOOKUP; } } }
java
24
0.723787
105
34.855769
104
starcoderdata
import pygame class Hero() RECT_WIDTH = 60 RECT_HEIGHT = 90 white = [255, 255, 255] black = [0,0,0] def __init__(self):
python
4
0.606299
24
13.111111
9
starcoderdata
let srcOrBuild; if (process.env.NODE_ENV === 'staging' || process.env.NODE_ENV === 'production') { srcOrBuild = 'build'; } else { srcOrBuild = 'src'; } const config = require(`../../../${srcOrBuild}/config`); const utilities = require(`../../../${srcOrBuild}/utilities`); import assert from 'assert'; import request from 'request'; import testConfig from '../../testConfig.json'; if (config.environment === 'testing' || config.environment === 'staging') { describe('Should have association', () => { if (testConfig.testCases[testConfig.testNumber - 1].association.aa === 'hasMany') { console.log('hasMany'); it('user should have todos (hasMany)', done => { let options = utilities.createRequestOptions(`users\/${testConfig.testCases[testConfig.testNumber - 1].userID}`); request.get(options, (error, res) => { console.log('res.body', res.body); let matches = res.body.match(/Todos/g); // console.log(matches); if (matches && matches.length > 0) { matches = true; } else { matches = false; } assert.equal(true, matches); done(); }); }).timeout(0); } else if (testConfig.testCases[testConfig.testNumber - 1].association.aa === 'belongsTo') { // todo it('user should have todos (belongsTo)', done => { done(); }).timeout(0); } }); }
javascript
27
0.581461
121
33.756098
41
starcoderdata
def update(self, contact_folder): """Updates the specified ContactFolder. Args: contact_folder (:class:`ContactFolder<microsoft.msgraph.model.contact_folder.ContactFolder>`): The ContactFolder to update. Returns: :class:`ContactFolder<microsoft.msgraph.model.contact_folder.ContactFolder>`: The updated ContactFolder. """ self.content_type = "application/json" self.method = "PATCH" entity = ContactFolder(json.loads(self.send(contact_folder).content)) self._initialize_collection_properties(entity) return entity
python
12
0.632873
106
39.75
16
inline
// Copyright (C) 2001-2003 // // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include #include #include #include #include #include namespace { const int ITERS = 100; boost::mutex io_mutex; } // namespace template <typename M> class buffer_t { public: typedef typename M::scoped_lock scoped_lock; buffer_t(int n) : p(0), c(0), full(0), buf(n) { } void send(int m) { scoped_lock lk(mutex); while (full == buf.size()) cond.wait(lk); buf[p] = m; p = (p+1) % buf.size(); ++full; cond.notify_one(); } int receive() { scoped_lock lk(mutex); while (full == 0) cond.wait(lk); int i = buf[c]; c = (c+1) % buf.size(); --full; cond.notify_one(); return i; } static buffer_t& get_buffer() { static buffer_t buf(2); return buf; } static void do_sender_thread() { for (int n = 0; n < ITERS; ++n) { { boost::mutex::scoped_lock lock(io_mutex); std::cout << "sending: " << n << std::endl; } get_buffer().send(n); } } static void do_receiver_thread() { for (int x=0; x < (ITERS/2); ++x) { int n = get_buffer().receive(); { boost::mutex::scoped_lock lock(io_mutex); std::cout << "received: " << n << std::endl; } } } private: M mutex; boost::condition cond; unsigned int p, c, full; std::vector buf; }; template <typename M> void do_test(M* dummy=0) { typedef buffer_t buffer_type; buffer_type::get_buffer(); boost::thread thrd1(&buffer_type::do_receiver_thread); boost::thread thrd2(&buffer_type::do_receiver_thread); boost::thread thrd3(&buffer_type::do_sender_thread); thrd1.join(); thrd2.join(); thrd3.join(); } void test_buffer() { do_test do_test } int main() { test_buffer(); return 0; }
c++
14
0.502607
81
20.070796
113
starcoderdata
<?php /* * This file is part of the Tapronto Braspag module. * * (c) 2012 Tapronto * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Tapronto\BraspagBundle\Model; use Tapronto\BraspagBundle\Transaction\Data\BoletoDataRequest; /** * @author */ class BoletoModel extends AbstractModel { public $number; public $instructions; public $expirationDate; public function __construct() { $this->setType(parent::TYPE_CREDITCARD); } public function getPaymentData() { $data = new BoletoDataRequest(); $data->Amount = $this->amount; $data->Currency = $this->currency; $data->PaymentMethod = $this->method; $data->BoletoNumber = $this->number; $data->BoletoInstructions = $this->instructions; $data->BoletoExpirationDate = $this->expirationDate; return $data; } public function getNumber() { return $this->number; } public function setNumber($number) { $this->number = $number; return $this; } public function getInstructions() { return $this->instructions; } public function setInstructions($instructions) { $this->instructions = $instructions; return $this; } public function getExpirationDate() { return $this->expirationDate; } public function setExpirationDate($expirationDate) { $this->expirationDate = $expirationDate; return $this; } }
php
11
0.62819
74
20.115385
78
starcoderdata
w=input() l=[] c=0 for i in w: l.append(i) l.sort() if len(l)<2: print('No') exit() for k in range(len(l)-1): if l[k]==l[k+1]: c+=1 elif c%2==1: c=0 continue else: print('No') exit() print('Yes')
python
10
0.493392
25
11
19
codenet
/**************************************************************************** * ==> PSS_VisualStackedPageDialog -----------------------------------------* **************************************************************************** * Description : Provides a visual stacked page dialog box * * Developer : Processsoft * ****************************************************************************/ #include "StdAfx.h" #include "PSS_VisualStackedPagesDialog.h" //--------------------------------------------------------------------------- // Message map //--------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(PSS_VisualStackedPageDialog, CDialog) //{{AFX_MSG_MAP(PSS_VisualStackedPageDialog) //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- // PSS_VisualStackedPageDialog //--------------------------------------------------------------------------- PSS_VisualStackedPageDialog::PSS_VisualStackedPageDialog(LPCTSTR pTemplateName, CWnd* pParent) : CDialog(pTemplateName, pParent) {} //--------------------------------------------------------------------------- PSS_VisualStackedPageDialog::PSS_VisualStackedPageDialog(UINT templateID, CWnd* pParent) : CDialog(templateID, pParent) {} //--------------------------------------------------------------------------- PSS_VisualStackedPageDialog::~PSS_VisualStackedPageDialog() {} //--------------------------------------------------------------------------- void PSS_VisualStackedPageDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(PSS_VisualStackedPageDialog) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } //--------------------------------------------------------------------------- void PSS_VisualStackedPageDialog::OnSetActive(void) {} //--------------------------------------------------------------------------- void PSS_VisualStackedPageDialog::OnKillActive(void) {} //--------------------------------------------------------------------------- void PSS_VisualStackedPageDialog::OnCreatePage(void) {} //--------------------------------------------------------------------------- void PSS_VisualStackedPageDialog::OnDestroyPage(void) {} //--------------------------------------------------------------------------- void PSS_VisualStackedPageDialog::OnOK() {} //--------------------------------------------------------------------------- void PSS_VisualStackedPageDialog::OnCancel() {} //--------------------------------------------------------------------------- BOOL PSS_VisualStackedPageDialog::OnInitDialog() { CDialog::OnInitDialog(); const DWORD style = GetStyle(); PSS_Assert((style & WS_CHILD) != 0); PSS_Assert((style & WS_BORDER) == 0); PSS_Assert((style & WS_DISABLED) != 0); // return TRUE unless the focus is set to a control. NOTE OCX property pages should return FALSE return TRUE; } //--------------------------------------------------------------------------- // Message map //--------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(PSS_VisualStackedPagesDialog, CDialog) //{{AFX_MSG_MAP(PSS_VisualStackedPagesDialog) ON_WM_DESTROY() //}}AFX_MSG_MAP END_MESSAGE_MAP() //--------------------------------------------------------------------------- // PSS_VisualStackedPagesDialog //--------------------------------------------------------------------------- PSS_VisualStackedPagesDialog::PSS_VisualStackedPagesDialog(UINT placeholder, LPCTSTR pTemplateName, CWnd* pParent) : CDialog(pTemplateName, pParent), m_PlaceHolder(0) { Init(placeholder); } //--------------------------------------------------------------------------- PSS_VisualStackedPagesDialog::PSS_VisualStackedPagesDialog(UINT placeholder, UINT templateID, CWnd* pParent) : CDialog(templateID, pParent), m_PlaceHolder(0) { Init(placeholder); } //--------------------------------------------------------------------------- PSS_VisualStackedPagesDialog::~PSS_VisualStackedPagesDialog() {} //--------------------------------------------------------------------------- PSS_VisualStackedPageInfo* PSS_VisualStackedPagesDialog::AddPage(LPCTSTR pTitle, UINT dlgID, long helpID, DWORD data1, DWORD data2) { std::unique_ptr pPage(new PSS_VisualStackedPageInfo()); pPage->m_Title = pTitle; pPage->m_DialogID = dlgID; pPage->m_pDialog = NULL; pPage->m_HelpID = helpID; pPage->m_Created = FALSE; pPage->m_Data1 = data1; pPage->m_Data2 = data2; m_List.AddTail(pPage.get()); pPage->m_pDialog = CreatePage(pPage->m_Title, pPage->m_DialogID); pPage->m_pDialog->Create(pPage->m_DialogID, this); PSS_Assert(pPage->m_pDialog && ::IsWindow(pPage->m_pDialog->m_hWnd)); CWnd* pWnd = GetDlgItem(m_PlaceHolder); PSS_Assert(pWnd && ::IsWindow(pWnd->m_hWnd)); CRect rect; pWnd->GetWindowRect(&rect); ScreenToClient(&rect); pPage->m_pDialog->SetWindowPos(NULL, rect.left, rect.top, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE); pPage->m_pDialog->EnableWindow(TRUE); pPage->m_pDialog->OnCreatePage(); pPage->m_Created = TRUE; return pPage.release(); } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::DelPage(PSS_VisualStackedPageInfo* pPage) { PSS_Assert(pPage); if (pPage->m_Created) { pPage->m_Created = FALSE; PSS_Assert(pPage->m_pDialog); pPage->m_pDialog->OnKillActive(); pPage->m_pDialog->OnDestroyPage(); pPage->m_pDialog->DestroyWindow(); delete pPage->m_pDialog; pPage->m_pDialog = NULL; } POSITION pPos = m_List.GetHeadPosition(); while (pPos) { PSS_VisualStackedPageInfo* pPtr = (PSS_VisualStackedPageInfo*)m_List.GetAt(pPos); if (pPtr == pPage) { m_List.RemoveAt(pPos); delete pPtr; break; } m_List.GetNext(pPos); } } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::DelAllPages(void) { Flush(); } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::ActivatePage(PSS_VisualStackedPageInfo* pPage) { PSS_Assert(pPage); PSS_Assert(pPage->m_pDialog); PSS_Assert(pPage->m_Created); PSS_VisualStackedPageDialog* pDialog = pPage->m_pDialog; pDialog->ShowWindow(SW_SHOW); pDialog->InvalidateRect(NULL); pDialog->UpdateWindow(); pDialog->OnSetActive(); } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::DeactivatePage(PSS_VisualStackedPageInfo* pPage) { PSS_Assert(pPage); PSS_Assert(pPage->m_pDialog); PSS_Assert(pPage->m_Created); PSS_VisualStackedPageDialog* pDialog = pPage->m_pDialog; pDialog->OnKillActive(); pDialog->ShowWindow(SW_HIDE); } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(PSS_VisualStackedPagesDialog) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP } //--------------------------------------------------------------------------- BOOL PSS_VisualStackedPagesDialog::OnInitDialog() { CDialog::OnInitDialog(); ModifyStyleEx(0, WS_EX_CONTROLPARENT); // return TRUE unless the focus is set to a control. NOTE OCX property pages should return FALSE return TRUE; } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::OnDestroy() { DelAllPages(); CDialog::OnDestroy(); } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::Init(UINT placeholder) { m_PlaceHolder = placeholder; } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialog::Flush() { POSITION pPos = m_List.GetHeadPosition(); while (pPos) { PSS_VisualStackedPageInfo* pPtr = (PSS_VisualStackedPageInfo*)m_List.GetNext(pPos); if (pPtr) DelPage(pPtr); } m_List.RemoveAll(); } //--------------------------------------------------------------------------- // PSS_VisualStackedPagesDialogIterator //--------------------------------------------------------------------------- PSS_VisualStackedPagesDialogIterator::PSS_VisualStackedPagesDialogIterator(const PSS_VisualStackedPagesDialog& owner) : m_Owner(owner), m_pPos(NULL) { Reset(); } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialogIterator::Reset() { m_pPos = m_Owner.m_List.GetHeadPosition(); } //--------------------------------------------------------------------------- void PSS_VisualStackedPagesDialogIterator::Next() { m_Owner.m_List.GetNext(m_pPos); } //--------------------------------------------------------------------------- PSS_VisualStackedPageInfo* PSS_VisualStackedPagesDialogIterator::Current() { return (PSS_VisualStackedPageInfo*)m_Owner.m_List.GetAt(m_pPos); } //--------------------------------------------------------------------------- BOOL PSS_VisualStackedPagesDialogIterator::IsDone() { return !m_pPos; } //---------------------------------------------------------------------------
c++
11
0.456274
119
36.014815
270
starcoderdata
import axios from "axios"; export default { eventPost: function (data) { return axios.post('/api/events', data) }, likeUpdate: function (eventID, data) { console.log(data); return axios.put("/api/events/" + eventID, { "likes": data }) } }
javascript
11
0.58589
69
22.357143
14
starcoderdata
@Test(timeout = 1601) @Theory public void slotInfoMustBeAbleToProduceRandomNumbers(PoolFixture fixture) throws Exception { final AtomicReference<SlotInfo<? extends Poolable>> slotInfoRef = new AtomicReference<SlotInfo<? extends Poolable>>(); config.setExpiration(expire($capture($slotInfo(slotInfoRef), $fresh))); createPool(fixture); pool.claim(longTimeout).release(); // Now we have a SlotInfo reference. SlotInfo<? extends Poolable> slotInfo = slotInfoRef.get(); // A full suite for testing the quality of the PRNG would be excessive here. // We just want a back-of-the-envelope estimate that it's random. int nums = 1000000; int bits = 32 * nums; int ones = 0; for (int i = 0; i < nums; i++) { ones += Integer.bitCount(slotInfo.randomInt()); } // In the random data that we collect, we should see a roughly even split // in the bits between ones and zeros. // So, if we count all the one bits and double that number, we should get // a number that is very close to the total number of random bits generated. double diff = Math.abs(bits - ones * 2); assertThat(diff, lessThan(bits * 0.005)); }
java
12
0.681401
80
45.153846
26
inline
package controller import ( "context" "log" "strings" "sync" "github.com/docker/docker/api/types/mount" ) var ( volumeInitializer sync.Once volumeMappings map[string]string ) func (c *Controller) GetSharedVolumeSource(ctx context.Context, source string) string { log.Printf("Get shared volume source: %q", source) volumeInitializer.Do(func() { c.ensureVolumesAreMapped(ctx) }) return volumeMappings[source] } func (c *Controller) ensureVolumesAreMapped(ctx context.Context) { volumeMappings = map[string]string{} for _, mnt := range c.container.Mounts { if mnt.Type != mount.TypeVolume { continue } norm := c.fetchNormalizedVolumeName(ctx, mnt.Name) if norm != "" { volumeMappings[norm] = mnt.Name } } } func (c *Controller) fetchNormalizedVolumeName(ctx context.Context, name string) string { volume, err := c.engine.InspectVolume(ctx, name) if err != nil { log.Printf("Failed to get volume information for %q", name) return "" } if explicitName, ok := volume.Labels["com.github.datamachines.podlike.volume-ref"]; ok { return explicitName } if swarmNamespace, ok := volume.Labels["com.docker.stack.namespace"]; ok { if strings.HasPrefix(volume.Name, swarmNamespace+"_") { return strings.TrimPrefix(volume.Name, swarmNamespace+"_") } } if composeName, ok := volume.Labels["com.docker.compose.volume"]; ok { return composeName } return "" }
go
13
0.708772
89
21.265625
64
starcoderdata
// -*- c -*- #pragma GCC diagnostic ignored "-Wwrite-strings" typedef unsigned char byte; #include #include #include #include #include "minunit.h" #include "../Lantern/Lantern.h" #include "../Lantern/HeartBeat.ino" int tests_run=0; static char* test_heartbeat_false(void) { heartCount=1; mu_assert("test_heartbeat_false: should be false", !isHeartbeat()); return 0; } static char* test_heartbeat_true(void) { heartCount=1440; mu_assert("test_heartbeat_true: should be true", isHeartbeat()); return 0; } static char* all_tests(void) { mu_run_test(test_heartbeat_false); mu_run_test(test_heartbeat_true); return 0; } int main() { char *result = all_tests(); printf("START TESTS\n"); if (result != 0) { printf("%s\n", result); } else { printf("ALL TESTS PASSED\n"); } printf("Tests run: %d\n", tests_run); return 0; }
c++
10
0.656009
69
18.297872
47
starcoderdata
static HRESULT createMobWeakRefVA(IAAFDictionary* pDict, IAAFHeader* pHeader, IAAFMobSP& spOwnerMob) { IAAFObjectSP spObj; checkResult(spOwnerMob->QueryInterface(IID_IAAFObject, (void**)&spObj)); //Get the property def for Component::VA IAAFClassDefSP spCD_mob; checkResult(pDict->LookupClassDef(AUID_AAFMob, &spCD_mob)); //From Class Def, get the Property Def IAAFPropertyDefSP spPD_mob; checkResult(spCD_mob->LookupPropertyDef(kMobReferencedMobsPropertyID, &spPD_mob)); aafBoolean_t bIsPresent = kAAFTrue; //Verify that optional property is NOT yet present in object checkResult(spObj->IsPropertyPresent(spPD_mob, &bIsPresent)); checkExpression(bIsPresent == kAAFFalse, AAFRESULT_TEST_FAILED); //Now, create a property value ....... //first, get the type def //Lookup the VA type IAAFTypeDefSP spTypeDef; checkResult(pDict->LookupTypeDef(kMobWeakRefVariableArrayTypeID, &spTypeDef)); //Get the VA typedef IAAFTypeDefVariableArraySP spVA; checkResult(spTypeDef->QueryInterface(IID_IAAFTypeDefVariableArray, (void**)&spVA)); //Set the array up: Create an array of strong references to tagged values... IAAFPropertyValueSP spElementPropertyValueArray[kMaxReferencedMobs]; IAAFPropertyValue * pElementPropertyValueArray[kMaxReferencedMobs]; // copies of pointers "owned by" the smartptr array. aafUInt32 i; for (i = 0; i < kMaxReferencedMobs; i++) { IAAFMobSP spMob; checkResult(pHeader->LookupMob (TEST_Referenced_MobIDs[i], &spMob)); IAAFPropertyValueSP spElementPropertyValue; checkResult(createMobWeakRefValue(pDict, spMob, &spElementPropertyValue)); spElementPropertyValueArray[i] = spElementPropertyValue; pElementPropertyValueArray[i] = spElementPropertyValueArray[i]; } IAAFPropertyValueSP spArrayPropertyValue; checkResult( spVA->CreateEmptyValue (&spArrayPropertyValue) ); for (i = 0; i < kMaxReferencedMobs; i++) { checkResult(spVA->AppendElement(spArrayPropertyValue, pElementPropertyValueArray[i])); } //Set the value VA to the Object ***************************************** checkResult(spObj->SetPropertyValue(spPD_mob, spArrayPropertyValue)); //Verify that the optional property is now present in the object checkResult(spObj->IsPropertyPresent(spPD_mob, &bIsPresent)); checkExpression(bIsPresent == kAAFTrue, AAFRESULT_TEST_FAILED); return S_OK; }
c++
12
0.756221
121
34.939394
66
inline
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Righthand.Navigation { /// /// Defines a navigation service. /// /// <typeparam name="TPage">Type of page. public class NavigationService : INavigationService where TPage : IPage { readonly Stack history = new Stack /// /// Occurs after a page has been navigated wither forward or backward. /// public event EventHandler PageNavigated; /// /// Occurs when navigation history or a part of has been manually cleared. /// public event EventHandler NavigationHistoryCleared; HistoryItem current; /// /// Raises <see cref="PageNavigated"/> event. /// /// <param name="e">Event arguments. protected virtual void OnPageNavigated(PageNavigatedEventArgs e) => PageNavigated?.Invoke(this, e); /// /// Raises <see cref="NavigationHistoryCleared"/> event. /// /// <param name="e">Event argumetns. protected virtual void OnNavigationHistoryCleared(NavigationHistoryClearedEventArgs e) => NavigationHistoryCleared?.Invoke(this, e); // /// Current depth of navigation history. Current page not included. /// public int NavigationDepth => history.Count; /// /// Clears navigation history. /// public void ClearHistory() { int count = history.Count; while (history.Count > 0) { var item = history.Pop(); item.Page.Removed(); OnNavigationHistoryCleared(new NavigationHistoryClearedEventArgs(0, count)); } } /// /// Navigates forward. /// /// <typeparam name="TNextPage">Type of <paramref name="to"/>. /// <param name="to">An instance of next page. /// <param name="waitFor">True when call should await for navigation back (results), false otherwise. /// <param name="ct">The cancellation token that will be checked prior to completing the returned task. /// value representing the navigation success (DidNavigate) and a navigation result (Result) when page is awaited. public async ValueTask<(bool DidNavigate, TNextPage Result)> NavigateAsync to, bool waitFor, CancellationToken ct) where TNextPage : TPage { var returnsTo = current; bool didNavigate = await NavigateAsync(to, NavigationDirection.Forward, isAwaited: waitFor); if (!didNavigate) { return (false, default(TNextPage)); } else { if (waitFor) { try { var from = await WaitForBackToAsync(returnsTo.Page, ct); return (true, (TNextPage)from); } catch (OperationCanceledException) { throw; } } else { return (true, default(TNextPage)); } } } Task WaitForBackToAsync page, CancellationToken ct) where TNextPage: TPage { var tcs = new TaskCompletionSource EventHandler handler = null; handler = (s, e) => { if (e.Direction.IsBack() && ReferenceEquals(e.To, page)) { PageNavigated -= handler; tcs.TrySetResult((TNextPage)e.From); } }; ct.Register(() => { PageNavigated -= handler; tcs.SetCanceled(); }); PageNavigated += handler; return tcs.Task; } async ValueTask NavigateAsync(TPage to, NavigationDirection direction, bool isAwaited) { bool canNavigate; if (current == null || direction.IsBack()) { canNavigate = true; } else { canNavigate = await current.Page.CanNavigate(to); } if (canNavigate) { var previousCurrent = current; switch (direction) { case NavigationDirection.Forward: if (current != null) { history.Push(current); } current = new HistoryItem isAwaited); var from = previousCurrent != null ? previousCurrent.Page : default(TPage); OnPageNavigated(new PageNavigatedEventArgs to, NavigationDirection.Forward)); break; default: var historyItem = history.Pop(); OnPageNavigated(new PageNavigatedEventArgs historyItem.Page, direction)); if (!current.IsAwaited) { current.Page.Removed(); } current = historyItem; break; } return true; } else { return false; } } /// /// Navigates back if possible. /// /// <param name="isManual">True when navigation is manually triggered, false otherwise. /// when navigation occurred, false otherwise. public ValueTask GoBackAsync(bool isManual) { if (history.Count > 0) { var previous = history.Peek(); var direction = isManual ? NavigationDirection.ManualBack : NavigationDirection.AutomaticBack; // isAwaited isn't used here - only when navigating forward return NavigateAsync(previous.Page, direction, isAwaited: false); } else { return new ValueTask } } } }
c#
22
0.516987
143
39.215116
172
starcoderdata
#pragma once #include "../../Component/Component.h" class PracticeMenu : public Panel { public: PracticeMenu(); ~PracticeMenu(); ImageContainer * image = NULL; ImageContainer * title = NULL; Label * name = NULL; Label * intro = NULL; Label * level = NULL; Label * exp = NULL; Item * magic = NULL; void updateMagic(); void updateExp(); void updateLevel(); private: virtual void onEvent(); virtual void init(); virtual void freeResource(); };
c
7
0.673597
38
14.516129
31
starcoderdata
package pl.wyhasany; import com.structurizr.io.plantuml.C4PlantUMLWriter; import com.structurizr.io.plantuml.C4PlantUMLWriter.RelationshipModes; import com.structurizr.io.plantuml.PlantUMLWriter; import com.structurizr.model.Element; import com.structurizr.model.Model; import com.structurizr.model.Relationship; import com.structurizr.view.RelationshipView; import com.structurizr.view.View; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static com.structurizr.io.plantuml.C4PlantUMLWriter.C4_LAYOUT_MODE; import static com.structurizr.io.plantuml.C4PlantUMLWriter.RelationshipModes.Lay; class PlantUMLGenerator { public static final Pattern PACKAGE_PATTERN = Pattern.compile("^\\s*package\\s*\"(.*)\"\\s*\\{\\s*$"); private final C4PlantUMLWriter plantUMLWriter; private Organization organization; PlantUMLGenerator(Organization organization) { this.organization = organization; plantUMLWriter = new C4PlantUMLWriter(); new PlantUMLStyling(plantUMLWriter, organization); } void saveDiagramToFile(Diagram diagram, String fileName) throws IOException { try (FileWriter fileWriter = new FileWriter(fileName)) { View view = diagram.getView(organization); plantUMLWriter.write(view, fileWriter); fileWriter.flush(); } removeLayouts(); addLegend(fileName); replacePackageWithSystemBondary(fileName); } private void removeLayouts() { try { removeLayoutsFromModel(); removeLayoutRelationshipsPerElement(); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") private void removeLayoutRelationshipsPerElement() throws NoSuchFieldException, IllegalAccessException { Model model = organization.model(); Set elements = model.getElements(); for (Element element : elements) { for (Relationship relationship : element.getRelationships()) { String layoutMode = relationship.getProperties().get(C4_LAYOUT_MODE); if (Lay.name().equals(layoutMode)) { Class<? extends Element> elementClass = Element.class; Field relationshipsField = elementClass.getDeclaredField("relationships"); relationshipsField.setAccessible(true); Set relationships = (Set relationshipsField.get(element); relationships.remove(relationship); } } } } @SuppressWarnings("unchecked") private void removeLayoutsFromModel() throws NoSuchFieldException, IllegalAccessException { Model model = organization.model(); Class<? extends Model> modelClass = model.getClass(); Field relationshipsByIdField = modelClass.getDeclaredField("relationshipsById"); relationshipsByIdField.setAccessible(true); Map<String, Relationship> relationshipViews = (Map<String, Relationship>)relationshipsByIdField.get(model); List keysOfLayoutsRelations = relationshipViews.entrySet().stream() .filter(entry -> { Relationship value = entry.getValue(); Map<String, String> properties = value.getProperties(); String layout = properties.get(C4_LAYOUT_MODE); return Lay.name().equals(layout); }) .map(Entry::getKey) .collect(Collectors.toList()); keysOfLayoutsRelations.forEach(relationshipViews::remove); } private void addLegend(String fileName) throws IOException { Path path = Paths.get(fileName); List lines = Files.readAllLines(path); lines.set(lines.size() - 1, "LAYOUT_WITH_LEGEND()"); lines.add("@enduml"); Files.write(path, lines); } private void replacePackageWithSystemBondary(String fileName) throws IOException { Path path = Paths.get(fileName); List lines = Files.readAllLines(path); List linesWithoutPackages = lines.stream() .map(this::mapLinesToC4PlantUmlFormat) .collect(Collectors.toList()); Files.write(path, linesWithoutPackages); } private String mapLinesToC4PlantUmlFormat(String line) { Matcher matcher = PACKAGE_PATTERN.matcher(line); if (matcher.matches()) { return String.format("System_Boundary(%s, %s) {", UUID.randomUUID().toString(), matcher.group(1)); } return line; } }
java
6
0.678266
115
38.912698
126
starcoderdata
//##################################################################### // Copyright 2009, // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class VORTICITY_CONFINEMENT //##################################################################### #ifndef __VORTICITY_CONFINEMENT__ #define __VORTICITY_CONFINEMENT__ #include namespace PhysBAM{ template<class T_GRID> class GRID_BASED_COLLISION_GEOMETRY_UNIFORM; template<class T_GRID> class VORTICITY_CONFINEMENT:public INCOMPRESSIBLE_FLUIDS_FORCES { typedef typename T_GRID::VECTOR_T TV;typedef typename TV::SCALAR T; typedef typename GRID_ARRAYS_POLICY T_ARRAYS_SCALAR; typedef typename T_ARRAYS_SCALAR::template REBIND T_ARRAYS_VECTOR;typedef typename GRID_ARRAYS_POLICY T_FACE_ARRAYS_SCALAR; typedef typename T_FACE_ARRAYS_SCALAR::template REBIND T_FACE_ARRAYS_BOOL; public: GRID_BASED_COLLISION_GEOMETRY_UNIFORM collision_body_list; T_FACE_ARRAYS_BOOL* valid_mask; bool use_variable_vorticity_confinement; T vorticity_confinement; T_ARRAYS_SCALAR variable_vorticity_confinement; VORTICITY_CONFINEMENT(GRID_BASED_COLLISION_GEOMETRY_UNIFORM collision_body_list=0,T_FACE_ARRAYS_BOOL* valid_mask=0,const bool use_variable_vorticity_confinement=false,const T vorticity_confinement=.3); virtual ~VORTICITY_CONFINEMENT(); void Set_Vorticity_Confinement(const T vorticity_confinement_input=.3) {vorticity_confinement=vorticity_confinement_input;} //##################################################################### void Apply_Vorticity_Confinement_Force(const T_GRID& grid,T_FACE_ARRAYS_SCALAR& face_velocities,T_ARRAYS_VECTOR& F); virtual void Compute_Vorticity_Confinement_Force(const T_GRID& grid,const T_FACE_ARRAYS_SCALAR& face_velocities_ghost,const T_FACE_ARRAYS_BOOL* valid_mask,T_ARRAYS_VECTOR& F); void Add_Explicit_Forces(const T_GRID& grid,const T_FACE_ARRAYS_SCALAR& face_velocities_ghost,T_FACE_ARRAYS_SCALAR& face_velocities,const T dt,const T time) PHYSBAM_OVERRIDE; void Add_Implicit_Forces_Projection(const T_GRID& grid,T_FACE_ARRAYS_SCALAR& face_velocities_ghost,T_FACE_ARRAYS_SCALAR& face_velocities,const T dt,const T time) PHYSBAM_OVERRIDE; void Initialize_Grids(const T_GRID& grid) PHYSBAM_OVERRIDE; //##################################################################### }; } #endif
c
12
0.673416
214
61.023256
43
starcoderdata
struct image *image_new(int w, int h); struct image *image_from_ppm(char *file_name); void image_set_font(struct image *img, struct image *font); int image_text(struct image *img, int x, int y, char *text); void image_set_pos(struct image *img, int x, int y); void image_set_colour(struct image *img, uint8_t r, uint8_t g, uint8_t b); void image_set_pixel(struct image *img, int x, int y, uint8_t r, uint8_t g, uint8_t b); void image_rectangle(struct image *img, int x, int y, int w, int h); int image_write(struct image *img, char *fname); void image_set_text_align(struct image *img, int h_align, int v_align); void image_free(struct image *img);
c
7
0.713405
87
58
11
starcoderdata
<?php declare(strict_types=1); namespace ExileeD\Inoreader\HttpClient; use ExileeD\Inoreader\Exception\InoreaderException; use GuzzleHttp\Client as GuzzleClient; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; use Psr\Http\Message\ResponseInterface; class GuzzleHttpClient implements HttpClient { /** * @var GuzzleClient */ private $client; /** * @param ClientInterface|null $client * * @return void */ public function __construct(ClientInterface $client = null) { $this->client = $client ?? self::createClient(); } /** * @return ClientInterface */ private static function createClient() { return new GuzzleClient(); } /** * @inheritdoc */ public function request( $endpoint, $params = [], $body = [], $method = 'GET', array $headers = [] ): ResponseInterface { $options = [ 'headers' => $headers, 'json' => $body, 'query' => $params, ]; try { return $this->getClient()->request($method, $endpoint, $options); } catch (GuzzleException $e) { throw new InoreaderException($e->getMessage(), $e->getCode(), $e); } } /** * @return GuzzleClient */ public function getClient(): GuzzleClient { return $this->client; } /** * @param GuzzleClient $client */ public function setClient(GuzzleClient $client): void { $this->client = $client; } /** * @param ResponseInterface $response * * @return array */ private static function getHeaders(ResponseInterface $response) { return [ 'Content-Type' => $response->getHeader('Content-Type'), 'X-Reader-Zone1-Limit' => $response->getHeader('X-Reader-Zone1-Limit'), 'X-Reader-Zone2-Limit' => $response->getHeader('X-Reader-Zone2-Limit'), 'X-Reader-Zone1-Usage' => $response->getHeader('X-Reader-Zone1-Usage'), 'X-Reader-Zone2-Usage' => $response->getHeader('X-Reader-Zone2-Usage'), 'X-Reader-Limits-Reset-After' => $response->getHeader('X-Reader-Limits-Reset-After'), ]; } }
php
15
0.568875
97
23.934783
92
starcoderdata
using System; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Linq.Expressions; using KsWare.Presentation.BusinessFramework; namespace KsWare.Presentation.ViewModelFramework { partial class ObjectVM { /// ALIAS CultureInfo.CreateSpecificCulture("en-US") /// protected static readonly CultureInfo EnUs = CultureInfo.CreateSpecificCulture("en-US"); /// ALIAS for CultureInfo.InvariantCulture /// protected static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture; /// ALIAS for /// /// property does not raise <see cref="INotifyPropertyChanged.PropertyChanged"/>. /// [EditorBrowsable(EditorBrowsableState.Never),Browsable(false)] //[Obsolete("Use Data or Metadata.DataProvider.Data",true)]/*enable this to find data accessor/for debug) [Bindable(BindableSupport.No)] public virtual object MːData {get => Metadata.DataProvider.Data; set => Metadata.DataProvider.Data=value; } /// [EXPERIMENTAL] Gets or sets the data of the underlying business object /// /// for /// property does not raise <see cref="INotifyPropertyChanged.PropertyChanged"/>. /// [Bindable(BindableSupport.No)] public object MːDataːData { get { if (IsInDesignMode) return null; // WORKAROUND because NullReferenceException in designer // return ((IObjectBM)MːData).Metadata.DataProvider.Data; return (MːData as IObjectBM)?.Metadata?.DataProvider?.Data; } set => ((IObjectBM)MːData).Metadata.DataProvider.Data=value; } /// [EXPERIMENTAL] Gets or sets the data of the underlying business object. /// /// /// for /// property does not raise <see cref="INotifyPropertyChanged.PropertyChanged"/>. /// [Bindable(BindableSupport.No)] public object MːBusinessObjectːData { get { if (IsInDesignMode) return null; // WORKAROUND because NullReferenceException in designer // return ((IBusinessObjectVM)Metadata.DataProvider.Data).Metadata.DataProvider.Data; return (Metadata.DataProvider.Data as IBusinessObjectVM)?.Metadata?.DataProvider?.Data; } set => ((IObjectBM)MːData).Metadata.DataProvider.Data=value; } /// Gets or set the underlying business object (if any) /// /// ALIAS for /// property does not raise <see cref="INotifyPropertyChanged.PropertyChanged"/>. /// [Bindable(BindableSupport.No)] public virtual IObjectBM MːBusinessObject { get { if (this is IBusinessObjectVM) return ((IBusinessObjectVM) this).BusinessObject; else return MːData as IObjectBM; } set { if (this is IBusinessObjectVM) ((IBusinessObjectVM) this).BusinessObject = value; else MːData = value; } } protected string NameOf TRet>> memberExpression) { var memberName = MemberNameUtil.GetPropertyName(memberExpression); return memberName; } /// TreeHelper /// public static class TreeHelper { public static T FindAnchor obj) where T:IObjectVM { return FindAnchor typeof(T), findSelf: false); } public static T FindAnchor obj, Type type) where T:IObjectVM { return FindAnchor type, findSelf: false); } public static T FindAnchor obj, Type type, bool findSelf) { IObjectVM p = findSelf?obj:obj.Parent; while (true) { if (p == null) return default(T); if (p.GetType() == type) return (T)p; if (type.IsInstanceOfType(p)) return (T)p; p = p.Parent; } } public static IObjectVM FindAnchor<T1, T2, T3, T4, T5>(IObjectVM obj) { return FindAnchor(obj, new[] {typeof (T1), typeof (T2), typeof (T3), typeof (T4), typeof (T5)}, false); } public static IObjectVM FindAnchor<T1, T2, T3, T4>(IObjectVM obj) { return FindAnchor(obj, new[] {typeof (T1), typeof (T2), typeof (T3), typeof (T4)}, false); } public static IObjectVM FindAnchor<T1, T2, T3>(IObjectVM obj) { return FindAnchor(obj, new[] {typeof (T1), typeof (T2), typeof (T3)}, false); } public static IObjectVM FindAnchor<T1, T2>(IObjectVM obj) { return FindAnchor(obj, new[] {typeof (T1), typeof (T2)}, false); } public static IObjectVM FindAnchor(IObjectVM obj, params Type[] types) { return FindAnchor(obj, types, false); } public static IObjectVM FindAnchor(IObjectVM obj,Type[] types, bool findSelf=false) { IObjectVM p = findSelf?obj:obj.Parent; while (true) { if (p == null) return null; var t = p.GetType(); if (types.Contains(t)) return p; if (types.Any(x => x.IsInstanceOfType(p))) return p; p = p.Parent; } } } } }
c#
19
0.699594
110
37.894737
133
starcoderdata
/* U8glib.h C++ Interface Universal 8bit Graphics Library Copyright (c) 2011, 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. 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. */ #ifndef _CPP_U8GLIB #define _CPP_U8GLIB #include #include "utility/u8g.h" class U8GLIB : public Print { private: u8g_t u8g; u8g_uint_t tx, ty; // current position for the Print base class procedures uint8_t is_begin; void prepare(void) { tx = 0; ty = 0; is_begin = 0; } void cbegin(void) { if ( is_begin == 0 ) { is_begin = 1; u8g_Begin(&u8g); } } uint8_t initSPI(u8g_dev_t *dev, uint8_t sck, uint8_t mosi, uint8_t cs, uint8_t a0, uint8_t reset = U8G_PIN_NONE); uint8_t initHWSPI(u8g_dev_t *dev, uint8_t cs, uint8_t a0, uint8_t reset = U8G_PIN_NONE); uint8_t initI2C(u8g_dev_t *dev, uint8_t options); protected: uint8_t init8BitFixedPort(u8g_dev_t *dev, uint8_t en, uint8_t cs, uint8_t di, uint8_t rw, uint8_t reset); private: uint8_t init8Bit(u8g_dev_t *dev, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, uint8_t en, uint8_t cs1, uint8_t cs2, uint8_t di, uint8_t rw = U8G_PIN_NONE, uint8_t reset = U8G_PIN_NONE); uint8_t initRW8Bit(u8g_dev_t *dev, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, uint8_t cs, uint8_t a0, uint8_t wr, uint8_t rd, uint8_t reset); public: /* constructor */ U8GLIB(void) { } U8GLIB(u8g_dev_t *dev) { prepare(); u8g_Init(&u8g, dev); } U8GLIB(u8g_dev_t *dev, u8g_com_fnptr com_fn) { prepare(); u8g_InitComFn(&u8g, dev, com_fn); } U8GLIB(u8g_dev_t *dev, uint8_t sck, uint8_t mosi, uint8_t cs, uint8_t a0, uint8_t reset) { initSPI(dev, sck, mosi, cs, a0, reset); } U8GLIB(u8g_dev_t *dev, uint8_t cs, uint8_t a0, uint8_t reset) { initHWSPI(dev, cs, a0, reset); } U8GLIB(u8g_dev_t *dev, uint8_t options) { initI2C(dev, options); } U8GLIB(u8g_dev_t *dev, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, uint8_t en, uint8_t cs1, uint8_t cs2, uint8_t di, uint8_t rw, uint8_t reset) { init8Bit(dev, d0, d1, d2, d3, d4, d5, d6, d7, en, cs1, cs2, di, rw, reset); } U8GLIB(u8g_dev_t *dev, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7, uint8_t cs, uint8_t a0, uint8_t wr, uint8_t rd, uint8_t reset) { initRW8Bit(dev, d0, d1, d2, d3, d4, d5, d6, d7, cs, a0, wr, rd, reset); } uint8_t begin(void) { is_begin = 1; return u8g_Begin(&u8g); } void setPrintPos(u8g_uint_t x, u8g_uint_t y) { tx = x; ty = y; } u8g_t *getU8g(void) { return &u8g; } /* implementation of the write interface to the print class */ #if defined(ARDUINO) && ARDUINO >= 100 size_t write(uint8_t c) { tx += u8g_DrawGlyph(&u8g, tx, ty, c); return 1;} #else void write(uint8_t c) { tx += u8g_DrawGlyph(&u8g, tx, ty, c); } #endif /* screen rotation */ void undoRotation(void) { u8g_UndoRotation(&u8g); } void setRot90(void) { u8g_SetRot90(&u8g); } void setRot180(void) { u8g_SetRot180(&u8g); } void setRot270(void) { u8g_SetRot270(&u8g); } /* screen scaling */ void undoScale(void) { u8g_UndoScale(&u8g); } void setScale2x2(void) { u8g_SetScale2x2(&u8g); } /* picture loop */ void firstPage(void) { cbegin(); u8g_FirstPage(&u8g); } uint8_t nextPage(void) { return u8g_NextPage(&u8g); } /* system commands */ uint8_t setContrast(uint8_t contrast) { cbegin(); return u8g_SetContrast(&u8g, contrast); } void sleepOn(void) { u8g_SleepOn(&u8g); } void sleepOff(void) { u8g_SleepOff(&u8g); } /* graphic primitives */ void setColorEntry(uint8_t color_index, uint8_t r, uint8_t g, uint8_t b) { u8g_SetColorEntry(&u8g, color_index, r, g, b); } void setHiColor(uint16_t rgb) { u8g_SetHiColor(&u8g, rgb); } void setHiColorByRGB(uint8_t r, uint8_t g, uint8_t b) { u8g_SetHiColorByRGB(&u8g, r, g, b); } void setRGB(uint8_t r, uint8_t g, uint8_t b) { u8g_SetRGB(&u8g, r, g, b); } void setColorIndex(uint8_t color_index) { u8g_SetColorIndex(&u8g, color_index); } uint8_t getColorIndex(void) { return u8g_GetColorIndex(&u8g); } void setDefaultForegroundColor(void) { u8g_SetDefaultForegroundColor(&u8g); } void setDefaultBackgroundColor(void) { u8g_SetDefaultBackgroundColor(&u8g); } void setDefaultMidColor(void) { u8g_SetDefaultMidColor(&u8g); } u8g_uint_t getWidth(void) { return u8g_GetWidth(&u8g); } u8g_uint_t getHeight(void) { return u8g_GetHeight(&u8g); } uint8_t getMode(void) { return u8g_GetMode(&u8g); } void drawPixel(u8g_uint_t x, u8g_uint_t y) { return u8g_DrawPixel(&u8g, x, y); } void drawHLine(u8g_uint_t x, u8g_uint_t y, u8g_uint_t w) { u8g_DrawHLine(&u8g, x, y, w); } void drawVLine(u8g_uint_t x, u8g_uint_t y, u8g_uint_t h) { u8g_DrawVLine(&u8g, x, y, h); } void drawLine(u8g_uint_t x1, u8g_uint_t y1, u8g_uint_t x2, u8g_uint_t y2) { u8g_DrawLine(&u8g, x1, y1, x2, y2); } void drawFrame(u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h) { u8g_DrawFrame(&u8g, x, y, w, h); } void drawRFrame(u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h, u8g_uint_t r) { u8g_DrawRFrame(&u8g, x, y, w, h,r); } void drawBox(u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h) { u8g_DrawBox(&u8g, x, y, w, h); } void drawRBox(u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h, u8g_uint_t r) { u8g_DrawRBox(&u8g, x, y, w, h,r); } void drawCircle(u8g_uint_t x0, u8g_uint_t y0, u8g_uint_t rad, uint8_t opt = U8G_DRAW_ALL) { u8g_DrawCircle(&u8g, x0, y0, rad, opt); } void drawDisc(u8g_uint_t x0, u8g_uint_t y0, u8g_uint_t rad, uint8_t opt = U8G_DRAW_ALL) { u8g_DrawDisc(&u8g, x0, y0, rad, opt); } void drawEllipse(u8g_uint_t x0, u8g_uint_t y0, u8g_uint_t rx, u8g_uint_t ry, uint8_t opt = U8G_DRAW_ALL) { u8g_DrawEllipse(&u8g, x0, y0, rx, ry, opt); } void drawFilledEllipse(u8g_uint_t x0, u8g_uint_t y0, u8g_uint_t rx, u8g_uint_t ry, uint8_t opt = U8G_DRAW_ALL) { u8g_DrawFilledEllipse(&u8g, x0, y0, rx, ry, opt); } void drawTriangle(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) { u8g_DrawTriangle(&u8g, x0, y0, x1, y1, x2, y2); } /* bitmap handling */ void drawBitmap(u8g_uint_t x, u8g_uint_t y, u8g_uint_t cnt, u8g_uint_t h, const uint8_t *bitmap) { u8g_DrawBitmap(&u8g, x, y, cnt, h, bitmap); } void drawBitmapP(u8g_uint_t x, u8g_uint_t y, u8g_uint_t cnt, u8g_uint_t h, const u8g_pgm_uint8_t *bitmap) { u8g_DrawBitmapP(&u8g, x, y, cnt, h, bitmap); } void drawXBM(u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h, const uint8_t *bitmap) { u8g_DrawXBM(&u8g, x, y, w, h, bitmap); } void drawXBMP(u8g_uint_t x, u8g_uint_t y, u8g_uint_t w, u8g_uint_t h, const u8g_pgm_uint8_t *bitmap) { u8g_DrawXBMP(&u8g, x, y, w, h, bitmap); } /* font handling */ void setFont(const u8g_fntpgm_uint8_t *font) {u8g_SetFont(&u8g, font); } int8_t getFontAscent(void) { return u8g_GetFontAscent(&u8g); } int8_t getFontDescent(void) { return u8g_GetFontDescent(&u8g); } int8_t getFontLineSpacing(void) { return u8g_GetFontLineSpacing(&u8g); } u8g_uint_t drawStr(u8g_uint_t x, u8g_uint_t y, const char *s) { return u8g_DrawStr(&u8g, x, y, s); } u8g_uint_t drawStr90(u8g_uint_t x, u8g_uint_t y, const char *s) { return u8g_DrawStr90(&u8g, x, y, s); } u8g_uint_t drawStr180(u8g_uint_t x, u8g_uint_t y, const char *s) { return u8g_DrawStr180(&u8g, x, y, s); } u8g_uint_t drawStr270(u8g_uint_t x, u8g_uint_t y, const char *s) { return u8g_DrawStr270(&u8g, x, y, s); } u8g_uint_t drawStrP(u8g_uint_t x, u8g_uint_t y, const u8g_pgm_uint8_t *s) { return u8g_DrawStrP(&u8g, x, y, s); } u8g_uint_t drawStr90P(u8g_uint_t x, u8g_uint_t y, const u8g_pgm_uint8_t *s) { return u8g_DrawStr90P(&u8g, x, y, s); } u8g_uint_t drawStr180P(u8g_uint_t x, u8g_uint_t y, const u8g_pgm_uint8_t *s) { return u8g_DrawStr180P(&u8g, x, y, s); } u8g_uint_t drawStr270P(u8g_uint_t x, u8g_uint_t y, const u8g_pgm_uint8_t *s) { return u8g_DrawStr270P(&u8g, x, y, s); } void setFontPosBaseline(void) { u8g_SetFontPosBaseline(&u8g); } void setFontPosBottom(void) { u8g_SetFontPosBottom(&u8g); } void setFontPosCenter(void) { u8g_SetFontPosCenter(&u8g); } void setFontPosTop(void) { u8g_SetFontPosTop(&u8g); } void setFontRefHeightText(void) { u8g_SetFontRefHeightText(&u8g); } void setFontRefHeightExtendedText(void) { u8g_SetFontRefHeightExtendedText(&u8g); } void setFontRefHeightAll(void) { u8g_SetFontRefHeightAll(&u8g); } void setFontLineSpacingFactor(uint8_t factor) { u8g_SetFontLineSpacingFactor(&u8g, factor); } u8g_uint_t getStrPixelWidth(const char *s) { return u8g_GetStrPixelWidth(&u8g, s); } u8g_uint_t getStrPixelWidthP(u8g_pgm_uint8_t *s) { return u8g_GetStrPixelWidthP(&u8g, s); } u8g_uint_t getStrWidth(const char *s) { return u8g_GetStrWidth(&u8g, s); } u8g_uint_t getStrWidthP(u8g_pgm_uint8_t *s) { return u8g_GetStrWidthP(&u8g, s); } void setHardwareBackup(u8g_state_cb backup_cb) { u8g_SetHardwareBackup(&u8g, backup_cb); } #if defined(ARDUINO) && ARDUINO >= 100 // support for the F() macro u8g_uint_t drawStr(u8g_uint_t x, u8g_uint_t y, const __FlashStringHelper *s) { return u8g_DrawStrP(&u8g, x, y, (u8g_pgm_uint8_t *)s); } u8g_uint_t drawStr90(u8g_uint_t x, u8g_uint_t y, const __FlashStringHelper *s) { return u8g_DrawStr90P(&u8g, x, y, (u8g_pgm_uint8_t *)s); } u8g_uint_t drawStr180(u8g_uint_t x, u8g_uint_t y, const __FlashStringHelper *s) { return u8g_DrawStr180P(&u8g, x, y, (u8g_pgm_uint8_t *)s); } u8g_uint_t drawStr270(u8g_uint_t x, u8g_uint_t y, const __FlashStringHelper *s) { return u8g_DrawStr270P(&u8g, x, y, (u8g_pgm_uint8_t *)s); } u8g_uint_t getStrPixelWidth(const __FlashStringHelper *s) { return u8g_GetStrPixelWidthP(&u8g, (u8g_pgm_uint8_t *)s); } u8g_uint_t getStrWidth(const __FlashStringHelper *s) { return u8g_GetStrWidthP(&u8g, (u8g_pgm_uint8_t *)s); } #endif /* cursor handling */ void setCursorFont(const u8g_pgm_uint8_t *cursor_font) { u8g_SetCursorFont(&u8g, cursor_font); } void setCursorStyle(uint8_t encoding) { u8g_SetCursorStyle(&u8g, encoding); } void setCursorPos(u8g_uint_t cursor_x, u8g_uint_t cursor_y) { u8g_SetCursorPos(&u8g, cursor_x, cursor_y); } void setCursorColor(uint8_t fg, uint8_t bg) { u8g_SetCursorColor(&u8g, fg, bg); } void enableCursor(void) { u8g_EnableCursor(&u8g); } void disableCursor(void) { u8g_DisableCursor(&u8g); } void drawCursor(void) { u8g_DrawCursor(&u8g); } /* virtual screen */ void setVirtualScreenDimension(u8g_uint_t width, u8g_uint_t height) { u8g_SetVirtualScreenDimension(&u8g, width, height); } uint8_t addToVirtualScreen(u8g_uint_t x, u8g_uint_t y, U8GLIB &child_u8g) { return u8g_AddToVirtualScreen(&u8g, x, y, &child_u8g.u8g); } }; class U8GLIB_SSD1306_128X64 : public U8GLIB { public: U8GLIB_SSD1306_128X64(uint8_t sck, uint8_t mosi, uint8_t cs, uint8_t a0, uint8_t reset = U8G_PIN_NONE) : U8GLIB(&u8g_dev_ssd1306_128x64_sw_spi, sck, mosi, cs, a0, reset) { } U8GLIB_SSD1306_128X64(uint8_t cs, uint8_t a0, uint8_t reset = U8G_PIN_NONE) : U8GLIB(&u8g_dev_ssd1306_128x64_hw_spi, cs, a0, reset) { } U8GLIB_SSD1306_128X64(uint8_t options = U8G_I2C_OPT_NONE) : U8GLIB(&u8g_dev_ssd1306_128x64_i2c, options) { } }; class U8GLIB_VS : public U8GLIB { public: U8GLIB_VS(void) : U8GLIB(&u8g_dev_vs) { } }; #endif /* _CPP_U8GLIB */
c
13
0.655075
240
50.805556
252
starcoderdata
const fs = require('fs'); module.exports = { name: 'deleteclock', args: true, guildOnly: true, description: 'Turn a voice channel back into a normal voice channel.', execute(client, message, logger, args) { const cronName = `updateTime.${message.guild.id}.${args[0]}` if (fs.existsSync(`./cronjobs/${cronName}.js`)){ fs.unlinkSync(`./cronjobs/${cronName}.js`); return message.reply(`the clock has been smashed.`); } message.reply(`there doesn't seem to be an active clock matching that ID.`); } };
javascript
13
0.644689
78
26.842105
19
starcoderdata
synchronized void setPersistenceDir(File persistenceDir) { persistenceDir = new File(persistenceDir, StringToolkit.encodeFilename(mri.getQualifiedName())); if (!persistenceDir.equals(dir)) { // Directory changed dir = persistenceDir; IOToolkit.closeSilently(currentFileStream); currentFileStream = null; currentFile = null; if (dir.isDirectory()) { ArrayList<PersistenceFile> existingFiles = new ArrayList<>(); File[] listFiles = dir.listFiles(PersistenceFile.FILTER); if (listFiles != null) { for (File f : listFiles) { try { PersistenceFile pfr = new PersistenceFile(f); if (!pfr.isCorrupt()) { existingFiles.add(pfr); } } catch (Exception e) { // Ignore invalid files } } } existingFiles.sort(PersistenceFile.PERSISTENCE_FILE_START_COMPARATOR); if (existingFiles.size() > 0) { currentFile = existingFiles.get(existingFiles.size() - 1).file; currentFileSize = currentFile.length(); } } if (!Boolean.FALSE.equals(isRunning)) { isRunning = null; } } }
java
18
0.659028
98
31.117647
34
inline
@Test public void basic_zk_restart_test() throws Exception { clusterClient = ThriftClientBuilder .newBuilder(LegacyModelMeshService.Iface.class) .withZookeeper(localZkConnStr + "/") .withServiceName(tasRuntimeClusterName) .withTimeout(8000) .buildOnceAvailable(8000); assertTrue(((LitelinksServiceClient) clusterClient).awaitAvailable(8000)); System.out.println("Load models"); List<String> modelIds = loadModels(6); System.out.println("first test"); basic_test(modelIds); System.out.println("stopping zk"); localZk.stop(); // kill the ZK server Thread.sleep(6000); // wait System.out.println("test after stopping zk"); basic_test(modelIds); // wait 3 sec (past zk conn timeout) Thread.sleep(3000); // create new clusterClient System.out.println("test after waiting past conn timeout"); basic_test(modelIds); // wait 4 more sec (now past zk session timeout) Thread.sleep(4000); System.out.println("test after waiting past session timeout"); basic_test(modelIds); // now restart zk System.out.println("restarting zk"); localZk.restart(); Thread.sleep(2000); assertTrue(((LitelinksServiceClient) clusterClient).awaitAvailable(8000)); basic_test(modelIds); // shutdown service }
java
13
0.615957
82
41.285714
35
inline
void readoptions(struct _options *options,int argc,char *argv[]) { int i; for(i=1;i<argc;i++) { if(argv[i][0]=='-') { switch(argv[i][1]) { case 'f': options->prog_type = PROG_TYPE_FP; break; case 'v': options->prog_type = PROG_TYPE_VP; break; case 'e': options->entry = argv[++i]; break; case 'a': options->gen_asm = true; break; case 'd': options->dump_asm = true; break; case 'W': { char *cg_arg = &argv[i][2]; if(cg_arg[0] == 'c' && cg_arg[1] == 'g' && cg_arg[2] == ',') options->cg_args.push_back(&cg_arg[3]); } break; } } else break; } if(i+2!=argc) usage(); options->src_file = argv[i]; options->dst_file = argv[i+1]; #ifdef __CYGWIN__ //workaround to solve full path file source problem with cygwin & cg.dll if (options->src_file == NULL || options->dst_file == NULL) return; if (options->src_file[0] == '/') { getcwd(currdir, sizeof(currdir)); char *fname, *path; if (options->dst_file[0] != '/') { sprintf(destfile, "%s/%s",currdir, options->dst_file); options->dst_file = destfile; } fname = basename((char *)options->src_file); path = (char *)dirname((char *)options->src_file); chdir(path); options->src_file = fname; } #endif }
c++
18
0.574417
90
26.043478
46
inline
#!/bin/python # Describes enc_chats.data import binascii import pprint import click def hexToStr(byte): return binascii.hexlify(byte).decode() def printByte(label, byte): print(label + ': ' + hexToStr(byte)) @click.command() @click.argument('path') def extract(path): with open(path, 'rb') as f: labels = [ ('constructor', 4), ('id', 4), ('access_hash', 8), ('date', 4), ('admin_id', 4), ('participant_id', 4), ('g_a lengh', 4), ('g_a_or_b', 256), ('key_fingerprint', 8) ] for label, count in labels: byte = f.read(count) printByte(label, byte) if __name__ == '__main__': extract()
python
12
0.526253
74
20.487179
39
starcoderdata
package me.chanjar.weixin.open.bean.minishop.goods; import lombok.Data; import java.io.Serializable; @Data public class WxMinishopAddGoodsSkuData implements Serializable { private static final long serialVersionUID = -2596988603027040989L; private Long skuId; private String createTime; }
java
9
0.803175
69
21.5
14
starcoderdata
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using AmpScm.Buckets.Interfaces; namespace AmpScm.Buckets.Specialized { public class TlsBucket : WrappingBucket, IBucketWriter, IBucketWriterStats { readonly byte[] _inputBuffer; BucketBytes _unread; readonly SslStream _stream; bool _writeEof, _readEof; Task? _writing; bool _authenticated; readonly string _targetHost; long _bytesRead; IBucketWriter InnerWriter { get; } int BufferSize { get; } WaitForDataBucket WriteBucket { get; } = new WaitForDataBucket(); public TlsBucket(Bucket reader, IBucketWriter writer, string targetHost, int bufferSize = 16384) : base(reader) { InnerWriter = writer; BufferSize = bufferSize; _inputBuffer = new byte[BufferSize]; _stream = new SslStream(Inner.AsStream(InnerWriter)); _targetHost = targetHost; } protected override void Dispose(bool disposing) { try { if (disposing) _stream.Dispose(); } finally { base.Dispose(disposing); } } protected override async ValueTask DisposeAsyncCore() { #if NETFRAMEWORK _stream.Dispose(); #else await _stream.DisposeAsync().ConfigureAwait(false); #endif await base.DisposeAsyncCore().ConfigureAwait(false); } public async ValueTask ShutdownAsync() { if (_authenticated) await _stream.ShutdownAsync().ConfigureAwait(false); } public override BucketBytes Peek() { return _unread; } public override async ValueTask ReadAsync(int requested = int.MaxValue) { if (!_authenticated) { await _stream.AuthenticateAsClientAsync(_targetHost).ConfigureAwait(false); _authenticated = true; } Task reading = DoRead(requested); Task ready; do { if (_writeEof) break; // Use wait at return for reading _writing ??= HandleWriting(); ready = await Task.WhenAny(reading, _writing).ConfigureAwait(false); if (ready == _writing) _writing = null; } while (ready != reading); return await reading.ConfigureAwait(false); } async Task DoRead(int requested) { if (_unread.Length > 0) { var bb = _unread.Slice(0, Math.Min(requested, _unread.Length)); _unread = _unread.Slice(bb.Length); return bb; } else if (_readEof) return BucketBytes.Eof; #if NETFRAMEWORK int len = await _stream.ReadAsync(_inputBuffer, 0, _inputBuffer.Length).ConfigureAwait(false); #else int len = await _stream.ReadAsync(new Memory #endif if (len > 0) { _bytesRead += len; if (len > requested) { _unread = new BucketBytes(_inputBuffer, requested, len - requested); return new BucketBytes(_inputBuffer, 0, requested); } else { return new BucketBytes(_inputBuffer, 0, len); } } else { _readEof = true; return BucketBytes.Eof; } } public override long? Position => _bytesRead - _unread.Length; public long BytesWritten { get; private set; } async Task HandleWriting() { while (true) { var bb = await WriteBucket.ReadAsync().ConfigureAwait(false); if (bb.IsEof) { if (!_writeEof) { _writeEof = true; } } if (bb.Length > 0) { #if NETFRAMEWORK var (arr, offs) = bb.ExpandToArray(); await _stream.WriteAsync(arr!, offs, bb.Length).ConfigureAwait(false); #else await _stream.WriteAsync(bb.Memory).ConfigureAwait(false); #endif BytesWritten += bb.Length; } } } public void Write(Bucket bucket) { WriteBucket.Write(bucket); } public override bool CanReset => false; public override string Name => $"TLS[{_stream.SslProtocol}]>{Inner.Name}"; } }
c#
20
0.515228
106
27.480663
181
starcoderdata
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.nokia.as.log.admin.impl.log4j2helper; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.LoggerConfig; import org.apache.logging.log4j.core.layout.PatternLayout; import com.nokia.as.log.service.admin.LogHandler; public class Log4j2Helper { private final static String APPENDER_NAME = Log4j2Helper.class.getName(); public void setLevel(String loggerName, String lev, LoggerContext ctx) { Level level = Level.valueOf(lev); boolean isRoot = "rootLogger".equals(loggerName) || loggerName.isEmpty(); Configuration conf = ctx.getConfiguration(); if (isRoot) { conf.getRootLogger().setLevel(level); for (LoggerConfig logConf : conf.getLoggers().values()) { logConf.setLevel(level); } } else { LoggerConfig logConf = conf.getLoggerConfig(loggerName); if (!logConf.equals(conf.getRootLogger())) { if (!logConf.getLevel().equals(level)) { logConf.setLevel(level); } } for (Logger l : ctx.getLoggers()) { if (l.getName().startsWith(loggerName)) { LoggerConfig loggerConfig = conf.getLoggerConfig(l.getName()); if (!loggerConfig.equals(conf.getRootLogger())) { loggerConfig.setLevel(level); } else { loggerConfig = new LoggerConfig(l.getName(), level, true); loggerConfig.setParent(conf.getRootLogger()); conf.addLogger(l.getName(), loggerConfig); } } } } ctx.updateLoggers(); } public String getLevel(String loggerName) { Logger logger; if ("rootLogger".equals(loggerName)) { logger = LogManager.getRootLogger(); } else { logger = LogManager.getLogger(loggerName); } if (logger != null) { Level level = logger.getLevel(); level = level == null ? Level.WARN : level; return level.name(); } return null; } public void addLogHandler(LogHandler logHandler, LoggerContext ctx, boolean format) { String appenderName = getAppenderName(logHandler); Configuration conf = ctx.getConfiguration(); for (final LoggerConfig loggerConfig : conf.getLoggers().values()) { if (loggerConfig.getAppenders().get(appenderName) != null) { throw new IllegalArgumentException("appender already registered"); } } PatternLayout layout = PatternLayout.newBuilder().withPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN).build(); LogConsumerAppender appender = new LogConsumerAppender(logHandler, appenderName, conf.getFilter(), layout, false, format); appender.start(); conf.addAppender(appender); for (final LoggerConfig loggerConfig : conf.getLoggers().values()) { loggerConfig.addAppender(appender, null, null); } conf.getRootLogger().addAppender(appender, null, null); ctx.updateLoggers(); } public void removeLogHandler(LogHandler logHandler, LoggerContext ctx) { String appenderName = getAppenderName(logHandler); Configuration conf = ctx.getConfiguration(); for (final LoggerConfig loggerConfig : conf.getLoggers().values()) { loggerConfig.removeAppender(appenderName); } conf.getRootLogger().removeAppender(appenderName); ctx.updateLoggers(); } private String getAppenderName(LogHandler logHandler) { StringBuilder sb = new StringBuilder(); sb.append(APPENDER_NAME); sb.append("-"); sb.append(System.identityHashCode(logHandler)); return sb.toString(); } }
java
19
0.731746
124
30.5
120
starcoderdata
let uploadFile = (file, callback) => { return callback('https://www.gstatic.cn/gsx/express_apple-touch-icon.png'); }; let embedImage = (url, uuid) => { console.log(url, uuid); $dom = $(' $dom.css({ width: '40px', height: 'auto', marginRight: '5px', }); $dom.attr('src', url); $('.' + uuid + ' .file-list').append($dom); $('.' + uuid).removeClass('hide'); }; (function () { $('.panel-comment').on('click', '.comment-reply-link', function () { let comment = $('.comment-reply.comment-' + $(this).attr('data-comment-id')); comment.toggleClass('hide'); comment.find('textarea').focus(); return false; }); if (location.hash.substr(1, 8) == 'comment-') { $(location.hash).addClass('bg-warning'); } $('.panel-comment').on('change', '.form-comment-create input[type="file"]', function (event) { let files = event.currentTarget.files; $(files).each((i, file) => { uploadFile(file, (url) => { embedImage(url, $(this).attr('data-class')) }); }); }); $('.panel-comment').on('paste', '.form-comment-create textarea', function (event) { let files = event.originalEvent.clipboardData.files; $(files).each((i, file) => { uploadFile(file, (url) => { embedImage(url, $(this).attr('data-class')) }); }); }); })()
javascript
20
0.522289
98
31
47
starcoderdata
#include "asf_meta.h" #include "meta_init.h" #include "dateUtil.h" #include "radarsat2.h" #include "asf_nan.h" meta_parameters* radarsat2meta(radarsat2_meta *radarsat2) { ymd_date date, imgStartDate, imgStopDate; hms_time time, imgStartTime, imgStopTime; meta_parameters *meta; char *mon[13]={"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep", "Oct","Nov","Dec"}; double lat, lon, height, re, rp; // Allocate memory for metadata structure meta = raw_init(); // General block strcpy(meta->general->basename, radarsat2->filename); strcpy(meta->general->sensor, radarsat2->satellite); strcpy(meta->general->sensor_name, radarsat2->sensor); strcpy(meta->general->mode, radarsat2->beamModeMnemonic); sprintf(meta->general->processor, "%s %s", radarsat2->processingFacility, radarsat2->softwareVersion); meta->general->data_type = REAL32; if (strcmp_case(radarsat2->dataType, "COMPLEX") == 0) meta->general->image_data_type = COMPLEX_IMAGE; //else if (strcmp_case(radarsat2->dataType, "DETECTED") == 0) // meta->general->image_data_type = AMPLITUDE_IMAGE; meta->general->radiometry = r_AMP; date_terrasar2date(radarsat2->zeroDopplerAzimuthTime, &date, &time); sprintf(meta->general->acquisition_date, "%02d-%s-%4d %02d:%02d:%02.0lf", date.day, mon[date.month], date.year, time.hour, time.min, time.sec); //meta->general->orbit = radarsat2->absOrbit; if (strcmp_case(radarsat2->passDirection, "ASCENDING") == 0) meta->general->orbit_direction = 'A'; else if (strcmp_case(radarsat2->passDirection, "DESCENDING") == 0) meta->general->orbit_direction = 'D'; if (strcmp_case(radarsat2->dataType, "COMPLEX") == 0) meta->general->band_count = radarsat2->band_count * 2; else meta->general->band_count = radarsat2->band_count; strcpy(meta->general->bands, radarsat2->bands); meta->general->line_count = radarsat2->numberOfLines; meta->general->sample_count = radarsat2->numberOfSamplesPerLine; meta->general->start_line = 0; meta->general->start_sample = 0; meta->general->x_pixel_size = radarsat2->sampledPixelSpacing; meta->general->y_pixel_size = radarsat2->sampledLineSpacing; //meta->general->center_latitude = radarsat2->sceneCenterCoordLat; //meta->general->center_longitude = radarsat2->sceneCenterCoordLon; meta->general->re_major = radarsat2->semiMajorAxis; meta->general->re_minor = radarsat2->semiMinorAxis; // SAR block meta->sar = meta_sar_init(); if (strcmp_case(radarsat2->productType, "SLC") == 0) meta->sar->image_type = 'S'; if (strcmp_case(radarsat2->antennaPointing, "LEFT") == 0) meta->sar->look_direction = 'L'; else if (strcmp_case(radarsat2->antennaPointing, "RIGHT") == 0) meta->sar->look_direction = 'R'; //meta->sar->look_count = 4; meta->sar->look_count = radarsat2->numberOfAzimuthLooks; // TO BE ADDED: radarsat2->numberOfRangeLooks meta->sar->deskewed = 1; meta->sar->original_line_count = meta->general->line_count; meta->sar->original_sample_count = meta->general->sample_count; meta->sar->line_increment = 1; meta->sar->sample_increment = 1; date_terrasar2date(radarsat2->zeroDopplerTimeFirstLine, &imgStartDate, &imgStartTime); date_terrasar2date(radarsat2->zeroDopplerTimeLastLine, &imgStopDate, &imgStopTime); meta->sar->azimuth_time_per_pixel = date_difference(&imgStopDate, &imgStopTime, &imgStartDate, &imgStartTime) / meta->general->line_count; meta->sar->range_time_per_pixel = meta->general->x_pixel_size * 2.0 / speedOfLight; meta->sar->slant_range_first_pixel = radarsat2->slantRangeNearEdge; meta->sar->slant_shift = 0.0; meta->sar->time_shift = 0.0; meta->sar->wavelength = SPD_LIGHT / radarsat2->radarCenterFrequency; meta->sar->prf = radarsat2->pulseRepetitionFrequency; meta->sar->satellite_height = radarsat2->satelliteHeight; meta->sar->azimuth_processing_bandwidth = radarsat2->totalProcessedAzimuthBandwidth; // FIXME: chirp_rate ??? meta->sar->pulse_duration = radarsat2->pulseLength; meta->sar->range_sampling_rate = radarsat2->adcSamplingRate; strcpy(meta->sar->polarization, radarsat2->polarizations); if (strcmp_case(radarsat2->dataType, "COMPLEX") == 0) meta->sar->multilook = FALSE; // FIXME: pitch, roll, yaw ??? // Doppler block meta->doppler = radarsat2->doppler; // State vectors meta->state_vectors = radarsat2->state_vectors; // Propagate the state vectors to start, center, end int vector_count = 3; double data_int = date_difference(&imgStopDate, &imgStopTime, &imgStartDate, &imgStartTime) / 2.0; while (fabs(data_int) > 10.0) { data_int /= 2; vector_count = vector_count*2-1; } propagate_state(meta, vector_count, data_int); // Location block meta->location = meta_location_init(); meta->location->lat_start_near_range = radarsat2->sceneCornerCoord1Lat; meta->location->lon_start_near_range = radarsat2->sceneCornerCoord1Lon; meta->location->lat_start_far_range = radarsat2->sceneCornerCoord2Lat; meta->location->lon_start_far_range = radarsat2->sceneCornerCoord2Lon; meta->location->lat_end_near_range = radarsat2->sceneCornerCoord3Lat; meta->location->lon_end_near_range = radarsat2->sceneCornerCoord3Lon; meta->location->lat_end_far_range = radarsat2->sceneCornerCoord4Lat; meta->location->lon_end_far_range = radarsat2->sceneCornerCoord4Lon; // Still need to determine center location, really only needed to get // the earth radius straight meta->general->center_longitude = (radarsat2->sceneCornerCoord1Lon + radarsat2->sceneCornerCoord2Lon + radarsat2->sceneCornerCoord3Lon + radarsat2->sceneCornerCoord4Lon) / 4.0; location_to_latlon(meta, meta->general->sample_count/2, meta->general->line_count/2, 0.0, &lat, &lon, &height); meta->general->center_latitude = lat; meta->general->center_longitude = lon; lat = meta->general->center_latitude * D2R; re = meta->general->re_major; rp = meta->general->re_minor; meta->sar->earth_radius = (re*rp) / sqrt(rp*rp*cos(lat)*cos(lat)+re*re*sin(lat)*sin(lat)); meta->sar->satellite_height += meta->sar->earth_radius; return meta; }
c
13
0.699161
75
42.328671
143
starcoderdata
#include "catch2/catch.hpp" #include "../src/util/allocator.hpp" #include <iostream> TEST_CASE( "image_allocator", "[util]" ) { struct Thing { int &counter; Thing(int &counter) : counter(counter) { counter++; } ~Thing() { counter--; } }; int thingCounter = 0; const int INITIAL_CAPACITY = 3; auto thingAllocator = [&thingCounter]() { return std::make_unique<Thing>(thingCounter); }; util::Allocator<Thing> allocator(thingAllocator, INITIAL_CAPACITY); REQUIRE(thingCounter == INITIAL_CAPACITY); auto thing1 = allocator.next(); auto thing2 = allocator.next(); REQUIRE(thingCounter == INITIAL_CAPACITY); { auto thing3 = allocator.next(); REQUIRE(thingCounter == INITIAL_CAPACITY); } auto thing3 = allocator.next(); REQUIRE(thingCounter == INITIAL_CAPACITY); auto thing4 = allocator.next(); REQUIRE(thingCounter > INITIAL_CAPACITY); }
c++
12
0.607035
71
23.875
40
research_code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Functional; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.ModelBinding; using Valigator.Core; namespace Valigator.AspNetCore { public class ValigatorActionFilter : IActionFilter, IOrderedFilter { public static int Order => -2500; int IOrderedFilter.Order => Order; private readonly Func<ModelError[], IActionResult> _resultErrorCreator; public ValigatorActionFilter(Func<ModelError[], IActionResult> resultErrorCreator) => _resultErrorCreator = resultErrorCreator; public void OnActionExecuting(ActionExecutingContext context) { List modelErrors = null; var currentErrors = GetValidationErrorsFromContext(context).ToDictionary(k => k.ParameterDescriptor); foreach (var parameter in context.ActionDescriptor.Parameters.OfType => !currentErrors.ContainsKey(p))) { var validateAttributes = GetValidateAttributes(parameter); var (isSet, value) = GetValueForParameter(context, parameter); IEnumerable errors = null; if (validateAttributes.Any()) (context.ActionArguments[parameter.Name], errors) = VerifyValueForParameter(parameter, validateAttributes, isSet, value); else if (isSet) errors = Model.Verify(value).Match(_ => null, _ => _); if (errors != null) (modelErrors ?? (modelErrors = new List errors)); } if (currentErrors.Any()) (modelErrors ?? (modelErrors = new List => CreateModelErrorsForParameter(e.ParameterDescriptor, e.ValidationErrors))); if (modelErrors?.Any() ?? false) context.Result = _resultErrorCreator.Invoke(modelErrors.ToArray()); } private IEnumerable<(ParameterDescriptor ParameterDescriptor, ValidationError[] ValidationErrors)> GetValidationErrorsFromContext(ActionExecutingContext context) => context .ModelState .Values .Where(v => v.ValidationState == ModelValidationState.Invalid) .SelectMany(GetValidationErrorsFromModelStateEntry); private IEnumerable<(ParameterDescriptor ParameterDescriptor, ValidationError[] ValidationErrors)> GetValidationErrorsFromModelStateEntry(ModelStateEntry value) => value .Errors .Select(e => e.Exception) .OfType .Select(exception => (exception.ParameterDescriptor, exception.ValidationErrors)); private ValidateAttribute[] GetValidateAttributes(ControllerParameterDescriptor parameter) => parameter .ParameterInfo .GetCustomAttributes(typeof(ValidateAttribute), true) .OfType .ToArray(); private (bool isSet, object value) GetValueForParameter(ActionExecutingContext context, ControllerParameterDescriptor parameter) { if (context.ActionArguments.TryGetValue(parameter.Name, out var value)) return (true, value); if (parameter.ParameterInfo.HasDefaultValue) return (true, parameter.ParameterInfo.DefaultValue); return (false, default); } private (object value, IEnumerable errors) VerifyValueForParameter(ControllerParameterDescriptor parameter, ValidateAttribute[] validateAttributes, bool isSet, object value) { List errors = null; foreach (var attribute in validateAttributes) { Result<object, ValidationError[]> result; if (isSet) result = attribute.Verify(Option.Create(value != null, value)); else result = attribute.Verify(); isSet = true; result .Match ( success => value = success, failure => { (errors ?? (errors = new List return null; } ); } return (value, errors?.SelectMany(_ => _)); } private ModelSource ConvertBindingSourceToModelSource(BindingSource source) { if (source == BindingSource.Body) return ModelSource.Body; if (source == BindingSource.Header) return ModelSource.Header; if (source == BindingSource.Path) return ModelSource.Path; if (source == BindingSource.Query) return ModelSource.Query; return ModelSource.Other; } private IEnumerable CreateModelErrorsForParameter(ParameterDescriptor parameter, IEnumerable validationErrors) { var name = parameter.BindingInfo?.BinderModelName ?? parameter.Name ?? String.Empty; var source = ConvertBindingSourceToModelSource(parameter.BindingInfo?.BindingSource); return validationErrors.Select(error => new ModelError(name, source, error)); } public void OnActionExecuted(ActionExecutedContext context) { } } }
c#
27
0.749489
192
33.223776
143
starcoderdata
<?php namespace LLoadoutComponents; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; use Illuminate\View\Compilers\BladeCompiler; use Livewire\Livewire; use LLoadoutComponents\Http\Livewire\BarChart; use LLoadoutComponents\Http\Livewire\LineChart; use LLoadoutComponents\Http\Livewire\PieChart; use LLoadoutComponents\Http\Livewire\Signature; class LLoadoutComponentsServiceProvider extends ServiceProvider { public function boot() { $this->bootResources(); $this->bootLivewireComponents(); $this->bootBladeComponents(); $this->bootDirectives(); } protected function bootResources() { $this->loadViewsFrom(__DIR__ . '/../resources/views', 'load'); } protected function bootBladeComponents() { $this->callAfterResolving(BladeCompiler::class, function () { Blade::component('load::blade.charts.barchart', "load-barchart"); Blade::component('load::blade.charts.piechart', "load-piechart"); Blade::component('load::blade.charts.linechart', "load-linechart"); Blade::component('load::blade.forms.select', "load-select"); Blade::component('load::blade.forms.daterange', "load-daterange"); Blade::component('load::blade.signature.signature', "load-signature"); }); } protected function bootLivewireComponents() { Livewire::component('barchart', BarChart::class); Livewire::component('piechart', PieChart::class); Livewire::component('linechart', LineChart::class); Livewire::component('signature', Signature::class); } private function bootDirectives(): void { Blade::directive('lloadoutScripts', function () { return "<?php echo LLoadoutComponents\\LLoadoutComponents::outputScripts(); ?>"; }); } }
php
16
0.670037
92
32.553571
56
starcoderdata
package it.polimi.ingsw.exceptions; import it.polimi.ingsw.enumeration.ErrorMessages; /** * Inompatible resource swap, if user try to do a swap wich broke game rules */ public class IllegalSwap extends AckManager{ public IllegalSwap(String message) { super("Illegal swap" + message); this.setErrorCode(ErrorMessages.IllegalSwap); } }
java
9
0.717277
76
22.875
16
starcoderdata
async def main(): # Create client and connect. client = AioClient() async with client.connect('127.0.0.1', 10800): # Create cache cache = await client.get_or_create_cache('test_async_cache') # Load data concurrently. await asyncio.gather( *[cache.put(f'key_{i}', f'value_{i}') for i in range(0, 20)] ) # Key-value queries. print(await cache.get('key_10')) print(await cache.get_all([f'key_{i}' for i in range(0, 10)])) # value_10 # {'key_3': 'value_3', 'key_2': 'value_2', 'key_1': 'value_1','....} # Scan query. async with cache.scan() as cursor: async for k, v in cursor: print(f'key = {k}, value = {v}') # key = key_42, value = value_42 # key = key_43, value = value_43 # key = key_40, value = value_40 # key = key_41, value = value_41 # key = key_37, value = value_37 # key = key_51, value = value_51 # key = key_20, value = value_20 # ...... # Clean up. await cache.destroy()
python
15
0.502698
76
32.727273
33
inline
import ObjectWrapper from '../../utils/object-wrapper'; const {sin, cos} = Math; export const WATERFALL_ANIM = 'waterfall_anim'; export const GROUND_ANIM = 'ground_anim'; export const OVERGROUND_DECORATION_01 = 'overground_decoration_01'; export const OVERGROUND_DECORATION_02 = 'overground_decoration_02'; export const CHESTS = 'chests'; export const SECRET = 'secret'; export default class Animations { constructor(map) { this.create(map); } create(map) { const layers = [WATERFALL_ANIM, GROUND_ANIM, OVERGROUND_DECORATION_01, OVERGROUND_DECORATION_02, CHESTS, SECRET]; const objects = layers.reduce((arr, name) => arr.concat(map.layer[name].objects), []); this.wrapper = new ObjectWrapper(objects, map.width); this.containers = layers.reduce((ob, name) => { ob[name] = map.layer[name].container; return ob; }, {}); this.counter = 0; } processItem = (visible, item) => { this.counter += 0.001; if (visible) { switch (item.layer) { case CHESTS: item.sprite.rotation = sin(this.counter) * 0.2; item.sprite.position.y = item.sprite.height / 2 + cos(this.counter) * 6; break; case GROUND_ANIM: item.sprite.position.y = item.sprite.position.y + 0.5; // console.log('GROUND_ANIM', item.sprite.position.y); break; default: } } if (typeof item.sprite.playing === 'undefined') { return; } if (visible) { if (!item.sprite.playing) { item.sprite.play(); } } else { if (item.sprite.playing) { item.sprite.stop(); } } } update(camera) { this.wrapper.update(camera, this.processItem); } }
javascript
19
0.536847
121
30.015873
63
starcoderdata
package xreliquary.blocks; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.state.IntegerProperty; import net.minecraft.state.StateContainer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ActionResultType; import net.minecraft.util.Hand; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockRayTraceResult; import net.minecraft.util.math.shapes.IBooleanFunction; import net.minecraft.util.math.shapes.ISelectionContext; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShapes; import net.minecraft.world.IBlockReader; import net.minecraft.world.World; import xreliquary.blocks.tile.ApothecaryCauldronTileEntity; import xreliquary.reference.Names; import javax.annotation.Nullable; public class ApothecaryCauldronBlock extends BaseBlock { public static final IntegerProperty LEVEL = IntegerProperty.create("level", 0, 3); private static final VoxelShape INSIDE = makeCuboidShape(2.0D, 4.0D, 2.0D, 14.0D, 16.0D, 14.0D); private static final VoxelShape SHAPE = VoxelShapes.combineAndSimplify(VoxelShapes.fullCube(), VoxelShapes.or(makeCuboidShape(0.0D, 0.0D, 4.0D, 16.0D, 3.0D, 12.0D), makeCuboidShape(4.0D, 0.0D, 0.0D, 12.0D, 3.0D, 16.0D), makeCuboidShape(2.0D, 0.0D, 2.0D, 14.0D, 3.0D, 14.0D), INSIDE), IBooleanFunction.ONLY_FIRST); public ApothecaryCauldronBlock() { super(Names.Blocks.APOTHECARY_CAULDRON, Properties.create(Material.IRON).hardnessAndResistance(1.5F, 5.0F).notSolid()); setDefaultState(stateContainer.getBaseState().with(LEVEL, 0)); } @Override protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) { builder.add(LEVEL); } public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) { return SHAPE; } public VoxelShape getRaytraceShape(BlockState state, IBlockReader worldIn, BlockPos pos) { return INSIDE; } @Override public void onEntityCollision(BlockState state, World world, BlockPos pos, Entity entity) { if (!world.isRemote) { ApothecaryCauldronTileEntity cauldron = (ApothecaryCauldronTileEntity) world.getTileEntity(pos); if (cauldron != null) { cauldron.handleCollidingEntity(world, pos, entity); } } } @Override public ActionResultType onBlockActivated(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockRayTraceResult hit) { ItemStack heldItem = player.getHeldItem(hand); if (world.isRemote) { return !heldItem.isEmpty() ? ActionResultType.SUCCESS : ActionResultType.CONSUME; } else { if (heldItem.isEmpty()) { return ActionResultType.CONSUME; } else { ApothecaryCauldronTileEntity cauldron = (ApothecaryCauldronTileEntity) world.getTileEntity(pos); if (cauldron != null) { return cauldron.handleBlockActivation(world, player, hand); } } } return ActionResultType.CONSUME; } @Override public void fillWithRain(World world, BlockPos pos) { if (world.rand.nextInt(20) == 1) { ApothecaryCauldronTileEntity cauldron = (ApothecaryCauldronTileEntity) world.getTileEntity(pos); if (cauldron != null) { cauldron.fillWithRain(); } } } /** * If this returns true, then comparators facing away from this block will * use the value from getComparatorInputOverride instead of the actual * redstone signal strength. */ @Override public boolean hasComparatorInputOverride(BlockState state) { return true; } /** * If hasComparatorInputOverride returns true, the return value from this is * used instead of the redstone signal strength when this block inputs to a * comparator. */ @Override public int getComparatorInputOverride(BlockState state, World world, BlockPos pos) { ApothecaryCauldronTileEntity cauldron = (ApothecaryCauldronTileEntity) world.getTileEntity(pos); if (cauldron != null) { return cauldron.getLiquidLevel(); } return 0; } @Override public boolean hasTileEntity(BlockState state) { return true; } @Nullable @Override public TileEntity createTileEntity(BlockState state, IBlockReader world) { return new ApothecaryCauldronTileEntity(); } }
java
14
0.772706
314
34.16129
124
starcoderdata
@Test public void test14() throws IOException { // test starting locality group after default locality group was started TestRFile trf = new TestRFile(conf); trf.openWriter(false); trf.writer.startDefaultLocalityGroup(); try { trf.writer.startNewLocalityGroup("lg1", newColFamByteSequence("a", "b")); fail(); } catch (IllegalStateException ioe) { } try { trf.writer.startDefaultLocalityGroup(); fail(); } catch (IllegalStateException ioe) { } trf.writer.close(); }
java
11
0.651292
79
21.625
24
inline
using System; using System.Reflection; using System.Threading.Tasks; using Plugin.Iconize; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Xamarin.Forms; using Xamarin.Forms.Platform.UWP; [assembly: ExportRenderer(typeof(IconNavigationPage), typeof(IconNavigationPageRenderer))] namespace Plugin.Iconize { /// /// Defines the <see cref="IconNavigationPage" /> renderer. /// /// <seealso cref="Xamarin.Forms.Platform.UWP.NavigationPageRenderer" /> public class IconNavigationPageRenderer : NavigationPageRenderer { /// /// Initializes a new instance of the <see cref="IconNavigationPageRenderer"/> class. /// public IconNavigationPageRenderer() { MessagingCenter.Subscribe IconToolbarItem.UpdateToolbarItemsMessage, OnUpdateToolbarItems); ElementChanged += OnElementChanged; } /// /// Called when [element changed]. /// /// <param name="sender">The sender. /// <param name="e">The <see cref="VisualElementChangedEventArgs"/> instance containing the event data. private void OnElementChanged(Object sender, VisualElementChangedEventArgs e) { ContainerElement.Loaded += OnContainerLoaded; ContainerElement.Unloaded += OnContainerUnloaded; } /// /// Called when [container unloaded]. /// /// <param name="sender">The sender. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data. private void OnContainerUnloaded(Object sender, RoutedEventArgs e) { ContainerElement.Unloaded -= OnContainerUnloaded; ContainerElement.Loaded -= OnContainerLoaded; } /// /// Called when [container loaded]. /// /// <param name="sender">The sender. /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data. private void OnContainerLoaded(Object sender, RoutedEventArgs e) { MessagingCenter.Send(sender, IconToolbarItem.UpdateToolbarItemsMessage); } /// /// Called when [update toolbar items]. /// private async void UpdateToolbarItems() { var platform = Element.Platform; FieldInfo fInfo = typeof(Platform).GetField("_container", BindingFlags.NonPublic | BindingFlags.Instance); Canvas canvas = fInfo.GetValue(platform) as Canvas; if (canvas?.Children?[0] is MasterDetailControl masterDetailControl) { var mInfo = typeof(MasterDetailControl).GetTypeInfo().GetDeclaredMethod("Xamarin.Forms.Platform.UWP.IToolbarProvider.GetCommandBarAsync"); var commandBar = await (mInfo.Invoke(masterDetailControl, new Object[] { }) as Task commandBar.UpdateToolbarItems(); } } /// /// Called when [update toolbar items]. /// /// <param name="sender">The sender. private async void OnUpdateToolbarItems(Object sender) { if (Element is null) return; // a workaround for MasterDetailPage if (Element.Parent is MasterDetailPage) { var ms = Element.Parent as MasterDetailPage; ms.IsPresentedChanged += (s, e) => UpdateToolbarItems(); UpdateToolbarItems(); } var method = typeof(NavigationPageRenderer).GetTypeInfo().GetDeclaredMethod("Xamarin.Forms.Platform.UWP.IToolbarProvider.GetCommandBarAsync"); var bar = await (method.Invoke(this, new Object[] { }) as Task bar.UpdateToolbarItems(); } } }
c#
22
0.629296
154
40.444444
99
starcoderdata
/** * a program that repeats a word a certain number of times * * @author aahmed1 * Created: Wednesday, Feb 2 */ #include #include #include /** * @brief function that repeats a word a certain number of times * * @param wort to repeat * @param size of word * @param count number of times to repeat */ void repeat(const char * word, int count, int size) { size++; int new_size = count*size*sizeof(char); if (count == 0) return; char * newword = (char *)malloc(new_size); if (newword == NULL) { printf("Cannot allocate new string. Exiting...\n"); return; } strcpy (newword, word); while (--count > 0) { strcat (newword, word); } puts (newword); free(newword); printf("\n"); } int main() { char word[32]; int count; printf("\nEnter a word: "); scanf(" %s" , word); printf("\nEnter a count: "); scanf(" %d", &count); printf("\n"); repeat(word,count,strlen(word)); return 0; }
c
9
0.572666
64
19.372549
51
starcoderdata
'use strict' module.exports = (token) => { return function verifyTokenMiddleware (req, res, next) { // If token isn't set, we're not verifying if (!token) { return next() } let message = req.slapp let verifyToken = message && message.meta && message.meta.verify_token // test verify token if (token !== verifyToken) { res.status(403).send('Invalid token') return } next() } }
javascript
15
0.598174
74
19.857143
21
starcoderdata
package com.thinkgem.jeesite.lbst.service; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.thinkgem.jeesite.lbst.dao.AccountDao; import com.thinkgem.jeesite.lbst.entities.Account; /** * 站内账户操作类 * @author hcc * 下午2:00:11 */ @Service public class AccountService { @Autowired private AccountDao accountDao; //简单注册一个用户的时候 创建账户 @Transactional public int addAccount(String phoneNo){ if(phoneNo != null){ int i = accountDao.addAccount(phoneNo); return i; } return 0; } //根据phoneNo查找accountId @Transactional(readOnly=true) public Integer getAccountId(String phoneNo){ if(phoneNo != null){ Integer accountId = accountDao.getAccountId(phoneNo); return accountId; } return null; } //根据phoneNo查找userId @Transactional(readOnly=true) public Integer getUserId(String phoneNo){ if(phoneNo != null){ Integer accountId = accountDao.getUserId(phoneNo); return accountId; } return null; } //更新自己的app_user中的accountId列 @Transactional public int updateAppUser(Map map){ int i = accountDao.updateAppUser(map); return i; } //查找自己的账户 @Transactional(readOnly=true) public Account getAccount(String phoneNo){ if(phoneNo != null){ Account account = accountDao.getAccount(phoneNo); return account; } return null; } //账户充值或者消费 @Transactional public int updateAccount(Account account){ if(account != null){ int i = accountDao.updateAccount(account); return i; } return 0; } }
java
11
0.736196
64
19.632911
79
starcoderdata
private void checkDeviceConnection() { boolean connected = false; int status = -1; //not connected boolean retry = true; ArduinoDeviceConnector deviceConnector = null; try { //first try with the real device deviceConnector = new LouisDeviceConnector(); deviceConnector.setContext(getApplicationContext()); tryConnectDevice(deviceConnector); } catch(Exception ex){ Toast aToast = Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG); aToast.show(); } }
java
12
0.587065
82
22.230769
26
inline
fn emit(&mut self, kind: Token) -> Spanned<Token, F> { let start = self.start; let column = self.pos; // wrap around on newline let line = if kind == Token::NewLine { self.start = 0; self.pos = 0; self.line - 1 } else { self.line }; let span = Span::new(self.file, start, column, line); self.start = self.pos; Spanned::new(kind, span) }
rust
9
0.480519
61
26.235294
17
inline
List <?php $this->load->view('header.php'); ?> <!-- DataTables CSS --> <script src="<?php echo base_url()."assets/";?>js/jquerya.js"> <!-- DataTables CSS --> <link rel="stylesheet" type="text/css" href="<?php echo base_url()."assets/";?>css/jquery.dataTables.css"> <!-- jQuery --> <script src="<?php echo base_url()."assets/";?>js/jquery-1.11.3.min.js"> var jq = $.noConflict(); <!-- DataTables --> <script src="<?php echo base_url()."assets/";?>js/jquery.dataTables.js"> jq(document).ready(function() { jq('#example').DataTable(); } ); var oTable; jq(document).ready(function() { jq('#myForm').submit( function() { var sData = oTable.$('input').serialize(); $.ajax({ type: "POST", url: "<?php echo base_url()."master/employee_act/upstat_emp";?>", data: sData, success:function(data) { alert(data); location.reload(); }, error:function(data){ alert(data); } }); return false; } ); oTable = jq('#example').dataTable(); } ); <section id="container"> <?php $this->load->view('sidebar.php'); ?> <section id="main-content"> <section class="wrapper"> <div class="row mt"> <div class="col-lg-12"> <div class="form-panel"> <form method="post" action="#"> <h1 class="mb" align="center">Employee List <div class="row"> <div class="col-md-1" style="margin-right:10px;"> <a href='<?php echo base_url()."master/employee_act/tambah";?>' class="btn btn-success btn-xs"> Add Employee <div class="col-md-2"> <?php // <form id="myForm"> // <button type="button" onclick="return confirm('Anda yakin menghapus data ini (menonaktifkan) ?');" id="del" class="btn btn-danger btn-xs">Delete // ?> <table id="example" class="display" cellspacing="0" width="100%"> <tr bgcolor="#696969"> <?php echo "<td style='color:white'> echo "<td style='color:white' width='15%'> echo "<td style='color:white'> echo "<td style='color:white'> Title echo "<td style='color:white'> Status echo "<td style='color:white'> Status echo "<td style='color:white'> echo "<td style='color:white' width='7%'> echo " ?> <?php foreach($employee as $d) { echo "<tr id='row_".$d->ID_EMPLOYEE."'>"; echo " echo " href='".base_url()."master/employee_act/edit/".$d->ID_DETAIL."'>".$d->NAME." echo " echo " echo " if($d->ACTIVE_STATUS=='1') { echo " } else { echo " } switch ($d->LOCATION) { case '1': echo " break; case '2': echo " break; case '3': echo " break; case '4': echo " break; default: echo " break; } echo " <button type='button' class='btn btn-xs btn-success' onclick='active(".$d->ID_EMPLOYEE.")' "; echo $d->ACTIVE_STATUS=='1'?'style="display:none;"':''; echo"><i class='fa fa-user'> Active <button type='button' class='btn btn-xs btn-danger' onclick='hapus(".$d->ID_EMPLOYEE.")' "; echo $d->ACTIVE_STATUS=='2'?'style="display:none;"':''; echo"><i class='fa fa-times'> Delete echo " } ?> end.wrapper --> function hapus(id) { var cek = confirm("apakah anda yakin ingin Non Active kan data ini ?"); if (cek) { $.ajax({ url : '<?php echo base_url() ?>master/employee_act/hapus', type : 'post', data : {'id':id}, success : function(r) { location.reload(); }, error : function(r) { alert("Maaf data tidak dapat di hapus, cek transaksi yang terhubung dengan data ini !."); } }); } else{ location.reload(); } } function active(id) { var cek = confirm("apakah anda yakin ingin mengactive kan data ini ?"); if (cek) { $.ajax({ url : '<?php echo base_url() ?>master/employee_act/active', type : 'post', data : {'id':id}, success : function(r) { location.reload(); }, error : function(r) { alert("Maaf data tidak dapat di hapus, cek transaksi yang terhubung dengan data ini !."); } }); } else{ location.reload(); } } <?php $this->load->view("footer.php"); ?>
php
12
0.499382
209
28.05641
195
starcoderdata
const getAccessToken = require('../helpers/get-access-token') const fidcPost = require('../helpers/fidc-post') const restartFidc = async (argv) => { const { FIDC_URL } = process.env try { const accessToken = await getAccessToken(argv) const requestUrl = `${FIDC_URL}/environment/startup?_action=restart` await fidcPost(requestUrl, {}, accessToken, false) console.log('Server restart initiated.') } catch (error) { console.error(error.message) process.exit(1) } } module.exports = restartFidc
javascript
12
0.688679
72
24.238095
21
starcoderdata
<?php namespace Drupal\Tests\rest_example\Funtional; use Drupal\Tests\BrowserTestBase; /** * Verify that the Views are accessible. * * @ingroup rest_example * @group rest_example * @group examples */ class RestExampleActionTest extends BrowserTestBase { /** * Modules to enable. * * @var array */ public static $modules = ['rest_example']; /** * The installation profile to use with this test. * * @var string */ protected $profile = 'minimal'; /** * {@inheritdoc} * * @throws \Drupal\Core\Entity\EntityStorageException */ public function setUp() { parent::setup(); global $base_url; $account = $this->drupalCreateUser(); $this->drupalLogin($account); $config_factory = \Drupal::configFactory(); $rest_config = $config_factory->getEditable('rest_example.settings'); $rest_config ->set('server_url', $base_url) ->set('server_username', $account->get('name')->value) ->set('server_password', $account-> ->save(); } /** * Test that we access the client side View. * * @throws \Behat\Mink\Exception\ExpectationException */ public function testClientNode() { $this->drupalGet('examples/rest-client-actions'); $this->assertSession()->responseContains('Nodes on the remote Drupal server'); } /** * Test that we can access the server side View. * * @throws \Behat\Mink\Exception\ExpectationException */ public function testServerView() { $this->drupalGet('rest/node'); $this->assertSession()->responseContains('[]'); } }
php
16
0.653396
106
21.773333
75
starcoderdata
public void visitConstantInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, ConstantInstruction constantInstruction) { int constantIndex = constantInstruction.constantIndex; switch (constantInstruction.opcode) { case InstructionConstants.OP_LDC: case InstructionConstants.OP_LDC_W: case InstructionConstants.OP_LDC2_W: stack.push(classConstantValueFactory.constantValue(clazz, constantIndex)); break; case InstructionConstants.OP_GETSTATIC: case InstructionConstants.OP_PUTSTATIC: case InstructionConstants.OP_GETFIELD: case InstructionConstants.OP_PUTFIELD: case InstructionConstants.OP_INVOKEVIRTUAL: case InstructionConstants.OP_INVOKESPECIAL: case InstructionConstants.OP_INVOKESTATIC: case InstructionConstants.OP_INVOKEINTERFACE: invocationUnit.invokeMember(clazz, method, codeAttribute, offset, constantInstruction, stack); break; case InstructionConstants.OP_NEW: stack.push(constantValueFactory.constantValue(clazz, constantIndex).referenceValue()); break; case InstructionConstants.OP_ANEWARRAY: { ReferenceValue referenceValue = constantValueFactory.constantValue(clazz, constantIndex).referenceValue(); stack.push(valueFactory.createArrayReferenceValue(referenceValue.internalType(), referenceValue.getReferencedClass(), stack.ipop())); break; } case InstructionConstants.OP_CHECKCAST: // TODO: Check cast. ReferenceValue castValue = stack.apop(); ReferenceValue castResultValue = castValue.isNull() == Value.ALWAYS ? castValue : castValue.isNull() == Value.NEVER ? constantValueFactory.constantValue(clazz, constantIndex).referenceValue() : constantValueFactory.constantValue(clazz, constantIndex).referenceValue().generalize(valueFactory.createReferenceValueNull()); stack.push(castResultValue); break; case InstructionConstants.OP_INSTANCEOF: { ReferenceValue referenceValue = constantValueFactory.constantValue(clazz, constantIndex).referenceValue(); int instanceOf = stack.apop().instanceOf(referenceValue.getType(), referenceValue.getReferencedClass()); stack.push(instanceOf == Value.NEVER ? valueFactory.createIntegerValue(0) : instanceOf == Value.ALWAYS ? valueFactory.createIntegerValue(1) : valueFactory.createIntegerValue()); break; } case InstructionConstants.OP_MULTIANEWARRAY: { int dimensionCount = constantInstruction.constant; for (int dimension = 0; dimension < dimensionCount; dimension++) { // TODO: Use array lengths. IntegerValue arrayLength = stack.ipop(); } stack.push(constantValueFactory.constantValue(clazz, constantIndex).referenceValue()); break; } default: throw new IllegalArgumentException("Unknown constant pool instruction ["+constantInstruction.opcode+"]"); } }
java
14
0.580466
183
48.077922
77
inline
'use strict'; const net = require('net'); function resolveorcb (cb, defer, resolved) { if (cb) { return cb(resolved); } return defer[resolved ? 'resolve' : 'reject'](); } module.exports = function test_port (port, host, cb) { let defer = Promise.defer(); cb = cb || host; host = typeof host === 'string' ? host : undefined; let tester = net.createConnection({port, host}); tester.on('error', () => { tester.destroy(); resolveorcb(cb, defer, false); }); tester.on('timeout', () => { tester.destroy(); resolveorcb(cb, defer, false); }); tester.setTimeout(2000); tester.on('connect', () => { tester.destroy(); resolveorcb(cb, defer, true); }); return defer.promise; }
javascript
13
0.594558
54
17.375
40
starcoderdata
package com.li.spring; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean CityService cityService() { return new CityService(); } }
java
10
0.757669
62
22.285714
14
starcoderdata
/*! * time-stamp * * Copyright (c) 2015, * Licensed under the MIT License. */ 'use strict'; /** * Parse the given pattern and return a formatted * timestamp. * * @param {String} `pattern` Date pattern. * @param {Date} `date` Date object. * @return {String} */ module.exports = function timestamp(pattern, date) { if (typeof pattern !== 'string') { date = pattern; pattern = 'YYYY:MM:DD'; } date = date || new Date(); return pattern.replace(/([YMDHms]{2,4})(:\/)?/g, function(_, key, sep) { var increment = method(key); if (!increment) return _; sep = sep || ''; var res = '00' + String(date[increment[0]]() + (increment[2] || 0)); return res.slice(-increment[1]) + sep; }); }; function method(key) { return ({ YYYY: ['getFullYear', 4], YY: ['getFullYear', 2], // getMonth is zero-based, thus the extra increment field MM: ['getMonth', 2, 1], DD: ['getDate', 2], HH: ['getHours', 2], mm: ['getMinutes', 2], ss: ['getSeconds', 2], ms: ['getMilliseconds', 3] })[key]; }
javascript
18
0.566305
74
23
48
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GoogleMapsComponents.Maps.Visualization { /// /// A data point entry for a heatmap. This is a geographical data point with a weight attribute. /// public class WeightedLocation { /// /// The location of the data point. /// public LatLngLiteral Location { get; set; } /// /// The weighting value of the data point. /// public float Weight { get; set; } } }
c#
8
0.617504
100
25.826087
23
starcoderdata
#define USE_PRECOMPILED_PROTOBUF_TYPEMODEL using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using ProtoBuf; using ProtoBuf.Meta; using TrackableData; using TrackableData.Protobuf; using Unity.Data; namespace Basic { class ProtobufExample { private static TypeModel _protobufTypeModel; private static TypeModel ProtobufTypeModel { get { if (_protobufTypeModel != null) return _protobufTypeModel; #if USE_PRECOMPILED_PROTOBUF_TYPEMODEL var model = new DataProtobufSerializer(); #else var model = TypeModel.Create(); model.Add(typeof(TrackablePocoTracker false) .SetSurrogate(typeof(TrackableUserDataTrackerSurrogate)); model.Add(typeof(TrackableDictionaryTracker<int, string>), false) .SetSurrogate(typeof(TrackableDictionaryTrackerSurrogate<int, string>)); model.Add(typeof(TrackableSetTracker false) .SetSurrogate(typeof(TrackableSetTrackerSurrogate model.Add(typeof(TrackableListTracker false) .SetSurrogate(typeof(TrackableListTrackerSurrogate #endif return _protobufTypeModel = model; } } private static byte[] Serialize(object obj) { byte[] buf; using (var stream = new MemoryStream()) { ProtobufTypeModel.Serialize(stream, obj); buf = stream.ToArray(); } return buf; } private static T Deserialize buf) { using (var stream = new MemoryStream(buf)) { return (T)ProtobufTypeModel.Deserialize(stream, null, typeof(T)); } } private static byte[] PrintBytes(byte[] buf) { var c = 0; foreach (var b in buf) { Log.Write(b.ToString("X2")); if ((++c % 8) == 0) Log.Write(" "); } Log.WriteLine(string.Format(" (Len: {0})", buf.Length)); return buf; } private static void RunTrackablePoco() { Log.WriteLine("***** TrackablePoco (Protobuf) *****"); var u = new TrackableUserData(); u.SetDefaultTracker(); u.Name = "Bob"; u.Level = 1; u.Gold = 10; var buf = PrintBytes(Serialize(u.Tracker)); Log.WriteLine(Deserialize u.Tracker.Clear(); u.Level += 10; u.Gold += 100; var buf2 = PrintBytes(Serialize(u.Tracker)); Log.WriteLine(Deserialize u.Tracker.Clear(); Log.WriteLine(); } private static void RunTrackableDictionary() { Log.WriteLine("***** TrackableDictionary (Protobuf) *****"); var dict = new TrackableDictionary<int, string>(); dict.SetDefaultTracker(); dict.Add(1, "One"); dict.Add(2, "Two"); dict.Add(3, "Three"); var buf = PrintBytes(Serialize(dict.Tracker)); Log.WriteLine(Deserialize<TrackableDictionaryTracker<int, string>>(buf).ToString()); dict.Tracker.Clear(); dict.Remove(1); dict[2] = "TwoTwo"; dict.Add(4, "Four"); var buf2 = PrintBytes(Serialize(dict.Tracker)); Log.WriteLine(Deserialize<TrackableDictionaryTracker<int, string>>(buf2).ToString()); dict.Tracker.Clear(); Log.WriteLine(); } private static void RunTrackableSet() { Log.WriteLine("***** TrackableSet (Protobuf) *****"); var set = new TrackableSet set.SetDefaultTracker(); set.Add(1); set.Add(2); set.Add(3); var buf = PrintBytes(Serialize(set.Tracker)); Log.WriteLine(Deserialize set.Tracker.Clear(); set.Remove(1); set.Add(4); var buf2 = PrintBytes(Serialize(set.Tracker)); Log.WriteLine(Deserialize set.Tracker.Clear(); Log.WriteLine(); } private static void RunTrackableList() { Log.WriteLine("***** TrackableList (Protobuf) *****"); var list = new TrackableList list.SetDefaultTracker(); list.Add("One"); list.Add("Two"); list.Add("Three"); var buf = PrintBytes(Serialize(list.Tracker)); Log.WriteLine(Deserialize list.Tracker.Clear(); list.RemoveAt(0); list[1] = "TwoTwo"; list.Add("Four"); var buf2 = PrintBytes(Serialize(list.Tracker)); Log.WriteLine(Deserialize list.Tracker.Clear(); Log.WriteLine(); } public static void Run() { RunTrackablePoco(); RunTrackableDictionary(); RunTrackableSet(); RunTrackableList(); } } }
c#
18
0.537164
97
29.596774
186
starcoderdata
@Test public void requestULProofDoesNotAnswer() { Integer epoch = 1; String uname = "User3"; String bDestUname = "User1"; String destUname = "User5"; buuServices.get(bDestUname).setMode(DOES_NOT_ANSWER); new Thread( () -> { sleep(1000); buuServices.get(bDestUname).setMode(ALWAYS_SIGN); }) .start(); // This User Retries its Requests // Because a Man In the Middle is Dropping a Request Map<String, byte[]> idProofs = uuFrontends.get(uname).getIdProofs(epoch); assertTrue(idProofs.containsKey(destUname) && idProofs.containsKey(bDestUname)); }
java
13
0.628659
84
31.5
20
inline
using System.Threading; using System.Threading.Tasks; using DistanceCalculator.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace DistanceCalculator.Application.Common.Interfaces { public interface IDistanceCalculatorData { DbSet Locations { get; set; } Task SaveChanges(CancellationToken cancellationToken); } }
c#
8
0.765864
70
28.533333
15
starcoderdata
import os import requests import time import sched, time import get_temp server = "https://nikitech.eu/" controller = "nikihome/" function = "temperature_post.php" url = server + controller + function hour = 60 * 60 scheduler = sched.scheduler(time.time, time.sleep) def post_temperature(scheduler_param): inside_temp = get_temp.read_temp(get_temp.inside_device) outside_temp = get_temp.read_temp(get_temp.outside_device) date = int(round(time.time() * 1000)) inside_temp = str(inside_temp) outside_temp = str(outside_temp) date = str(date) print("Posting temperature: ") print("inside: " + inside_temp) print("outside: " + outside_temp) print("______________________") print("\n") data = { 'inside': inside_temp, 'outside': outside_temp, 'date': date } request = requests.post(url, data = data) print("Response: " + request.text) if scheduler_param is not None: scheduler.enter(hour, 1, post_temperature, (scheduler_param,)) print("Uploading current temperature") post_temperature(None) print("Next upload will be in one hour") scheduler.enter(hour, 1, post_temperature, (scheduler,)) scheduler.run()
python
12
0.639225
70
21.944444
54
starcoderdata
string Process::getPath() { HMODULE hmod; DWORD junk; char String[255]; EnumProcessModules(d->my_handle, &hmod, 1 * sizeof(HMODULE), &junk); //get the module from the handle GetModuleFileNameEx(d->my_handle,hmod,String,sizeof(String)); //get the filename from the module string out(String); return(out.substr(0,out.find_last_of("\\"))); }
c++
10
0.677596
105
35.7
10
inline
var assert = require('assert') , Colors = require('../lib/Colors') describe('Colors', function () { it('Should have colors that do not change', function () { }) it('Should properly wrap a string in colors', function () { var str = Colors.wrap(Colors.red, 'Should be wrapped in red') assert.equal(str, '$31_start$Should be wrapped in red$color_end$', 'Colorized string mismatch') }) it('Should properly tokenize a wraped color string', function () { var str = Colors.tokenize(Colors.wrap(Colors.red, 'Should be wrapped in red')) assert.equal(str, '\u001b[' + Colors.red + 'mShould be wrapped in red\u001b[0m', 'Colorized string mismatch') }) it('Should remove color tokens if told to do so', function () { var str = Colors.tokenize(Colors.wrap(Colors.red, 'Should be wrapped in red'), true) assert.equal(str, 'Should be wrapped in red', 'Colorized string mismatch') }) })
javascript
18
0.647182
117
40.652174
23
starcoderdata
int guacenc_buffer_copy(guacenc_buffer* dst, guacenc_buffer* src) { /* Resize destination to exactly fit source */ if (guacenc_buffer_resize(dst, src->width, src->height)) return 1; /* Copy surface contents identically */ if (src->surface != NULL) { /* Destination must be non-NULL as its size is that of the source */ assert(dst->cairo != NULL); /* Reset state of destination */ cairo_t* cairo = dst->cairo; cairo_reset_clip(cairo); /* Overwrite destination with contents of source */ cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE); cairo_set_source_surface(cairo, src->surface, 0, 0); cairo_paint(cairo); /* Reset operator of destination to default */ cairo_set_operator(cairo, CAIRO_OPERATOR_OVER); } return 0; }
c
10
0.618203
76
28.206897
29
inline
def Traverse_Trees(tree, write_file, print_table): # define the recursive function # Initialise the variables: cell_ID = tree.ID frm_st = int(tree.start) frm_en = int(tree.end) cct_m = (int(tree.end) - int(tree.start)) * 4 cct_h = round(float(cct_m / 60), 2) gen = int(tree.depth) is_root = True if tree.depth == 0 else False is_leaf = tree.leaf details = [str(item) for item in [cell_ID, frm_st, frm_en, cct_m, cct_h, gen, is_root, is_leaf]] # Write into the file: if write_file is True: txt_file = open("/Users/kristinaulicna/Documents/Rotation_2/temporary.txt", 'a') detail_string = '' for item in details: detail_string += item + "\t" detail_string = detail_string[:-1] detail_string += "\n" txt_file.write(detail_string) # Print into the table: if print_table is True: table.add_row(details) print(table.draw()) # Check if the current node your just processed branches further: if tree.leaf is False: Traverse_Trees(tree.children[0], write_file, print_table) Traverse_Trees(tree.children[1], write_file, print_table)
python
12
0.613636
100
36.15625
32
inline