Dataset Viewer (First 5GB)
The table contains 100 rows per page, up to 5GB.
Auto-converted to Parquet
Full Screen
code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.97
max_line_length
int64
13
399
avg_line_length
float64
5.04
137
num_lines
int64
7
299
source
stringclasses
4 values
// Copyright (c) ( All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Website: https://www.blazor.zone or https://argozhang.github.io/ using BootstrapBlazor.Components; using Microsoft.AspNetCore.Components; using Microsoft.Extensions.Localization; using Microsoft.JSInterop; namespace BootstrapBlazor.Shared.Samples.Table; /// /// 折行演示示例代码 /// public sealed partial class TablesWrap { [NotNull] private IEnumerable CellItems { get; set; } [Inject] [NotNull] private IStringLocalizer Localizer { get; set; } /// /// OnInitialized 方法 /// protected override void OnInitialized() { base.OnInitialized(); CellItems = Foo.GenerateFoo(Localizer, 4); } private Task OnQueryAsync(QueryPageOptions options) { var items = Foo.GenerateFoo(Localizer); // 设置记录总数 var total = items.Count; // 内存分页 items = items.Skip((options.PageIndex - 1) * options.PageItems).Take(options.PageItems).ToList(); return Task.FromResult(new QueryData { Items = items, TotalCount = total, IsSorted = true, IsFiltered = true, IsSearch = true }); } /// /// OnAfterRenderAsync 方法 /// /// <param name="firstRender"> /// protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (firstRender) { await JSRuntime.InvokeVoidAsync("$.table_wrap"); } } }
c#
19
0.630016
111
25.362319
69
starcoderdata
private void Update() { if (listen) { loudness = LevelMax() * 100;//for volume before speech Debug.Log("Loudness : " + loudness); if (loudness > 8) { Microphone.End(MicDeviceName); Debug.Log("Sent Record"); TryStartRecord(); } } if (!isChoosedMic) { int t = -1; string text_ = UI_FirstPage[1].GetComponent<InputField>().text; if (!string.IsNullOrEmpty(text_) && text_ != "-") t = System.Convert.ToInt32(UI_FirstPage[1].GetComponent<InputField>().text); if (!string.IsNullOrEmpty(text_) && t <= devices.Length && t > 0) { UI_FirstPage[2].GetComponent<Button>().interactable = true; UI_FirstPage[2].GetComponent<Button>().gameObject.GetComponent<Image>().color = Color.green; } else { UI_FirstPage[2].GetComponent<Button>().interactable = false; UI_FirstPage[2].GetComponent<Button>().gameObject.GetComponent<Image>().color = Color.red; } } //play last rec audio button if(RecordedClip != null) UI_SecondPage[1].GetComponent<Button>().interactable = true; else UI_SecondPage[1].GetComponent<Button>().interactable = false; //---------------------------------------------- if(!string.IsNullOrEmpty(sendToGoogle.GetResponse) && !isGetRequest) { isGetRequest = true; RequestWords = sendToGoogle.GetWords(); if (RequestWords == null) return; for (int i = 0; i < RequestWords.Length; i++) Debug.Log (RequestWords[i]); //PostLog(RequestWords[i], 1); isGetRequest = false; } }
c#
19
0.471849
112
31.918033
61
inline
<?php $__env->startSection('content'); ?> <div class="row"> <div class="row"> <?php if(auth()->user()->hasRole('administrator')): ?> <button type="button " class="btn btn-primary fa fa-home" data-toggle="modal" data-target=".bs-example-modal-lg"> <?php endif; ?> <button type="button" class="btn btn-primary fa fa-envelope" data-toggle="modal" data-target=".bs-example-modal-lk"> <a class="btn btn-primary" href="<?php echo e(route('admin.repairs.show', [$apartment->id])); ?>"> <i class="fa fa-briefcase" aria-hidden="true"> <a class="btn btn-primary" href="<?php echo e(route('admin.payments.show', [$apartment->id])); ?>"> <i class="fa fa-money" aria-hidden="true"> <a class="btn btn-primary" href="<?php echo e(route('admin.chats.show', [$apartment->id])); ?>"> <i class="fa fa-comment-o" aria-hidden="true"> <div class="row"> <div class="row"> <table class="table table-striped table-hover"> echo e($apartment->name); ?> <?php echo e($apartment->description); ?> <?php echo e($apartment->location); ?> At echo e($apartment->created_at); ?> (<?php echo e($apartment->created_at->diffForHumans()); ?>) At echo e($apartment->updated_at); ?> (<?php echo e($apartment->updated_at->diffForHumans()); ?>) <div class="row"> <table class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%"> No. <?php $__currentLoopData = $apartment->houses; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $house): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> <?php if(auth()->user()->hasRole('administrator') ||auth()->user()->hasRole('caretaker') || App\Http\Controllers\Admin\HouseController::getUserHouses($house->id,auth()->user()->id)): ?> echo e($house->house_number); ?> echo e($house->floor); ?> <?php if(!isset($house->UserHouse->user_id)): ?><span class="label label-warning">Vacant <?php else: ?> <span class="label label-success">Not Vacant <?php endif; ?> <a class="btn btn-xs btn-primary" href="<?php echo e(route('admin.houses.show', [$house->id])); ?>" data-toggle="tooltip" data-placement="top" data-title="<?php echo e(__('views.admin.users.index.show')); ?>"> <i class="fa fa-eye"> <?php if(auth()->user()->hasRole('administrator')): ?> <a class="btn btn-xs btn-info" href="<?php echo e(route('admin.house.edit', [$house->id])); ?>" data-toggle="tooltip" data-placement="top" data-title="<?php echo e(__('views.admin.users.index.edit')); ?>"> <i class="fa fa-pencil"> <a class="btn btn-xs btn-danger" href="<?php echo e(route('admin.houses.delete', [$house->id])); ?>" data-toggle="tooltip" data-placement="top" data-title="delete"> <i class="fa fa-trash"> <?php endif; ?> <?php endif; ?> <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?> <div class="pull-right"> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">× <h4 class="modal-title" id="myModalLabel">New House <div class="modal-body"> <div class="row"> <div class="login_wrapper"> <div class="animate form"> <section class="login_content"> <?php echo e(Form::open(['url' => 'admin/housestore/'.$apartment->id,'method'=>'post'])); ?> <input type="text" name="house_number" class="form-control" placeholder="House number" value="<?php echo e(old('house_number')); ?>" required autofocus/> class="select2_group form-control" id="bedroom" name="bedroom"> <optgroup label="Not Ensuit"> <option value="1">1 bedroom <option value="2">2 bedrooms <optgroup label="All Ensuit"> <option value="3">1 bedroom <option value="4">2 bedrooms <option value="5">3 bedrooms <option value="6">4 bedrooms ype="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Add House <option value="7">5 bedrooms <optgroup label="Not all Ensuit"> <option value="8">2 bedrooms & 1 ensuit <option value="9">3 bedrooms & 1 ensuit <option value="10">4 bedrooms & 1 ensuit <option value="11">5 bedrooms & 1 ensuit <select id="kitchen" name="kitchen" class="form-control" required=""> <option value="">select type of kitchen <option value="1">American Kitchen <option value="2">British Kitchen <select id="bathroom" name="bathroom" class="form-control" required=""> <option value="">number of bathroom <option value="1">1 bathroom <option value="2">2 bathrooms <option value="3">3 bathrooms <option value="4">4 bathrooms <option value="5">5 bathrooms <option value="6">6 bathrooms <select id="toilet" name="toilet" class="form-control" required=""> <option value="">number of toilet <option value="1">1 toilet <option value="2">2 toilets <option value="3">3 toilets <option value="4">4 toilets <option value="5">5 toilets <option value="6">6 toilets <select id="balcony" name="balcony" class="form-control" required=""> <option value="">number of balcony <option value="0">none <option value="1">1 balcony <option value="2">2 balconies <select id="floor" name="floor" class="form-control" required=""> <option value="">floor number <option value="1">1st floor <option value="2">2nd floor <option value="3">3rd floor <option value="4">4th floor <option value="5">5th floor <option value="6">6th floor <option value="7">7th floor <option value="8">8th floor <input type="text" name="price" class="form-control" placeholder="Monthly price" value="<?php echo e(old('price')); ?>" required autofocus/> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel <button type="submit" class="btn btn-default submit">Add <?php echo e(Form::close()); ?> <div class="modal-footer"> <div class="modal fade bs-example-modal-lk" tabindex="-1" role="dialog" aria-hidden="true" style="display: none;"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">× <h4 class="modal-title" id="myModalLabel">New Notification <div class="modal-body"> <div class="row"> <div class="login_wrapper"> <div class="animate form"> <section class="login_content"> <?php echo e(Form::open(array('route' => array('admin.notificationstore',auth()->user()->id,Request::route('apartment'))))); ?> Notification <input type="text" name="message" class="form-control" placeholder="message" required/> <button type="submit" class="btn btn-default submit">Add <?php echo e(Form::close()); ?> <div class="modal-footer"> <?php $__env->stopSection(); ?> <?php echo $__env->make('admin.layouts.admin', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>
php
18
0.347466
201
52.275862
290
starcoderdata
package net.dodogang.marbles.mixin.world.gen; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.source.BiomeAccess; import net.minecraft.world.biome.source.HorizontalVoronoiBiomeAccessType; import net.minecraft.world.biome.source.VoronoiBiomeAccessType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; @Mixin(HorizontalVoronoiBiomeAccessType.class) public class HorizontalVoronoiBiomeAccessTypeMixin { /** * Allows for 3D biomes in any dimension. * Very almost an @Overwrite but let's pretend it's not. */ @Inject(method = "getBiome", at = @At("HEAD"), cancellable = true) private void amendY(long seed, int x, int y, int z, BiomeAccess.Storage storage, CallbackInfoReturnable cir) { cir.setReturnValue(VoronoiBiomeAccessType.INSTANCE.getBiome(seed, x, y, z, storage)); } }
java
9
0.764319
121
44.347826
23
starcoderdata
""" XmitMsgHandler defines a handler function to call for messages from a particular service. Create new instance with: self.h = xmit_msg.XmitMsgHandler(size) where "size" is the number of handlers you will add. The list will be appended to if you add more handlers than size so this paramter is more for performance. To add a handler call self.h.add_handler(xmit_from, handler_func, rexmit_flag) where xmit_from - defines who the xmit message is from handler_func - defines a function to receive the xmit message if it was from xmit_from. MUST be an async function. rexmit_flag - should xmit be forwarded to controller if xmit_from was matched but handler_func return false? self.h.process_xmit(xmit, q_out) will traverse the list of handlers in the order defined until one returns True OR the rexmit flag is True. If a handler returns false and the rexmit_flag is true, the xmit will immediately be forwarded to the controller and True returned. Note that this skips any further checks of the handlers. Note also that the xmit_flag is NOT checked if the xmit_from was not matched. If message is not matched and Otherwise returns false. Example: # service_dht11 receives messages from service_ir but only handles the ir POWER_KEY # see service_dht11.py for complete program import xmit_msg import service_ir def __init__(self, svc_def): # only 1 handler. If not handled, forward to Controller self.h = xmit_msg.XmitMsgHandler(1) self.h.add_handler(xmit_ir_remote.XMIT_FROM_NAME,self.toggle_led,True) ... other init stuff # handle LED toggle xmit from IR input device async def toggle_led(self,xmit): if xmit.get_msg() == service_ir.POWER_BUTTON: ... do toggle LED stuff... return True return False # in main event loop async def run(self): ... run startup stuff q_in = self.get_input_queue() q_out = self.get_output_queue() while True: while not q_in.empty(): xmit = await q_in.get() handled = await self.h.process_xmit(xmit, q_out) ... if needed, handle xmit that wasn't handled ... but usually just ignore? ... remainder of run main loop """ XMIT_FROM_IDX = 0 XMIT_HANDLER_IDX = 1 REXMIT_FLAG = 2 # Name of controller service CTL_SERVICE_NAME = "controller" class XmitMsgHandler: def __init__(self,size=5): self.handlers = [size] self.handler_cnt = 0 def add_handler(self, xmit_from, handler_func, rexmit_flag): handler = [xmit_from, handler_func, rexmit_flag] if len(self.handlers) > self.handler_cnt: self.handlers[self.handler_cnt] = handler else: self.handlers.append(handler) self.handler_cnt = self.handler_cnt + 1 async def process_xmit(self, xmit, q_out): xmit_fr = xmit.get_from() rexmit = False for i in range(self.handler_cnt): if xmit_fr == self.handlers[i][XMIT_FROM_IDX]: handled = await self.handlers[i][XMIT_HANDLER_IDX](xmit) if handled: return True # retransmit the message to the controller? if self.handlers[i][REXMIT_FLAG]: await self.rexmit(xmit, q_out) return True # No handlers returned true and no retransmits were triggered return False # retransmit a message to the controller async def rexmit(self, xmit, q_out): xmit.set_to(CTL_SERVICE_NAME) await q_out.put(xmit)
python
16
0.588919
87
33.262712
118
starcoderdata
#include "buzzer.h" #include "debug.h" #ifndef __TACT_BUZZER_MULTIPLEXER__ #include #endif namespace tact { #ifdef __TACT_BUZZER_MULTIPLEXER__ Buzzer::Buzzer() { // default configuration pin_ = config::kBuzzerID; address_ = 0x40; frequency_ = 800; PCA9685_ = new Adafruit_PWMServoDriver(address_); } Buzzer::~Buzzer() { PCA9685_->~Adafruit_PWMServoDriver(); PCA9685_ = nullptr; } void Buzzer::Initialize() { if (!Wire.busy()) { Wire.begin(); } PCA9685_->begin(); PCA9685_->setOscillatorFrequency(27000000); PCA9685_->setPWMFreq(frequency_); Wire.setClock(400000); initialized_ = true; } void Buzzer::NoTone(uint32_t length) { if (!initialized_) { Initialize(); } PCA9685_->setPWM(pin_, 0, 0); delay(length); } void Buzzer::Tone(uint32_t length) { if (!initialized_) { Initialize(); } PCA9685_->setPWM(pin_, 0, 3000); if (length > 1) { delay(length); NoTone(0); } } void Buzzer::PlayInitSequence() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG Tone(100); NoTone(50); Tone(100); NoTone(50); Tone(100); NoTone(50); } void Buzzer::PlayConfirm() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG Tone(50); NoTone(10); } void Buzzer::PlaySuccess() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG Tone(50); NoTone(20); Tone(50); NoTone(20); } void Buzzer::PlayFail() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG Tone(100); NoTone(20); Tone(200); NoTone(20); } #else Buzzer::Buzzer(uint8_t pin, uint8_t pwm_channel) { pin_ = pin; pwm_channel_ = pwm_channel; initialized_ = false; } void Buzzer::Initialize() { initialized_ = true; } void Buzzer::PlayInitSequence() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG tone(pin_, NOTE_C4, 60, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_E4, 60, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_G4, 60, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_B4, 60, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_C5, 60, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_E5, 80, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_G5, 100, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_B5, 150, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_B5, 200, pwm_channel_); noTone(pin_, pwm_channel_); } void Buzzer::PlayConfirm() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG tone(pin_, NOTE_C4, 100, pwm_channel_); noTone(pin_, pwm_channel_); } void Buzzer::PlayFail() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG tone(pin_, NOTE_C3, 100, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_C2, 200, pwm_channel_); noTone(pin_, pwm_channel_); } void Buzzer::PlaySuccess() { #ifdef TACT_DEBUG debug::println(__FILE__, __func__, "", debug::DebugLevel::verbose); #endif //TACT_DEBUG tone(pin_, NOTE_C4, 100, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_E4, 100, pwm_channel_); noTone(pin_, pwm_channel_); tone(pin_, NOTE_G4, 100, pwm_channel_); noTone(pin_, pwm_channel_); } #endif //__TACT_BUZZER_MULTIPLEXER__ }
c++
13
0.62395
69
19.505556
180
starcoderdata
void DroneNode::height_callback(const sensor_msgs::msg::Range::SharedPtr msg) const { // Read the system boot time. (Is this a hack?) std::pair< mavsdk::Info::Result, mavsdk::Info::FlightInfo > information = _info->get_flight_information(); // Pass the height to the flight controller to ease landing mavlink_message_t message; float quaternion = 0.0; mavlink_msg_distance_sensor_pack( _passthrough->get_our_sysid(), // ID of this system _passthrough->get_our_compid(), // ID of this component (e.g. 200 for IMU) &message, // The MAVLINK message to compress the data into information.second.time_boot_ms, // [ms] Time since system boot msg->min_range * 100, // [cm] Minimum distance sensor can measure. ROS message is in Meters! msg->max_range * 100, // [cm] Maximum distance sensor can measure. ROS message is in Meters! (msg->range - height_sensor_z_offset_) * 100, // [cm] Current distance reading. ROS message is in Meters! MAV_DISTANCE_SENSOR::MAV_DISTANCE_SENSOR_INFRARED, // Type of distance sensor. This is not aligned with msg->radiation_type, 0, // Onboard ID of sensor MAV_SENSOR_ORIENTATION::MAV_SENSOR_ROTATION_PITCH_270, // Direction the sensor faces 255, // [cm^2] Measurement Variance. Mx Standard Deviation is 6cm, UINT8_MAX is unknown msg->field_of_view, // [rad] Horizontal field of view msg->field_of_view, // [rad] Vertical field of view &quaternion, // This field is required if orientation is set to MAV_SENSOR_ROTATION_CUSTOM. Set to 0 if invalid) 0 // Signal quality. 0 = unknown. 1 = invalid signal, 100 = perfect signal ); _passthrough->send_message(message); }
c++
10
0.541128
159
68.83871
31
inline
public int insert( Map x ) { int result = 0; // sanity checks if ( x == null || x.size() == 0 ) return result; if ( mConnection == null ) throw new RuntimeException( c_error ); // FIXME: Create a true bulk mode. This is inefficient, but will // get the job done (for now). Set lfns = x.keySet(); for ( Iterator i=lfns.iterator(); i.hasNext(); ) { String lfn = (String) i.next(); List value = (List) x.get(lfn); if ( value != null && value.size() > 0 ) { for ( Iterator j=value.iterator(); j.hasNext(); ) { result += insert( lfn, (ReplicaCatalogEntry) j.next() ); } } } // done return result; }
java
16
0.520833
72
29.041667
24
inline
/* Copyright (C) 2002 Dept. of Computer Science, Univ. of Massachusetts, Amherst This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This program toolkit free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For more details see the GNU General Public License and the file README-LEGAL. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** @author */ package edu.umass.cs.mallet.projects.seg_plus_coref.anaphora; import edu.umass.cs.mallet.base.types.*; import edu.umass.cs.mallet.base.pipe.*; import edu.umass.cs.mallet.base.pipe.iterator.*; import edu.umass.cs.mallet.base.util.PropertyList; import java.util.*; /* This class obtains features related to part of speech */ public class PartOfSpeechMentionPair extends Pipe { public PartOfSpeechMentionPair () { } public Instance pipe (Instance carrier) { String preTermString, prePOS, postTermString, postPOS, antecedentPOS, ahead; MentionPair pair = (MentionPair)carrier.getData(); if (pair.nullPair()) // Do nothing if antecedent is NULL return carrier; Mention antecedent = pair.getAntecedent(); MalletPhrase antPH = antecedent.getMalletPhrase(); Mention referent = pair.getReferent(); MalletPhrase refPH = referent.getMalletPhrase(); MalletPreTerm preLexPT = antPH.getPreceedingPreTerm(); MalletPreTerm postLexPT = antPH.getFollowingPreTerm(); if (preLexPT != null) { preTermString = preLexPT.getString(); prePOS = preLexPT.getPartOfSpeech(); if (prePOS != null) prePOS = prePOS.toUpperCase(); else prePOS = "NULL"; } else { preTermString = "NULL"; prePOS = "NULL"; } if (postLexPT != null) { postTermString = postLexPT.getString(); postPOS = postLexPT.getElement().getAttributeValue("pos"); if (postPOS != null) postPOS = postPOS.toUpperCase(); else postPOS = "NULL"; } else { postTermString = "NULL"; postPOS = "NULL"; } MalletPreTerm antHeadPT = antPH.getHeadPreTerm(); String featureName = new String("AntecedentContext").concat(preTermString).concat(prePOS).concat(postTermString).concat(postPOS); //System.out.println(featureName); if (antHeadPT != null) ahead = antHeadPT.getString().toUpperCase(); else ahead = "NULL"; String fn2 = new String("AntecedentHead".concat(ahead).concat("PronounGender").concat(referent.getGender())); if (antHeadPT != null) antecedentPOS = antHeadPT.getElement().getAttributeValue("pos"); else antecedentPOS = null; if (antecedentPOS != null) antecedentPOS = antecedentPOS.toUpperCase(); else antecedentPOS = "NULL"; String fn3 = new String("AntecedentPOS".concat(antecedentPOS).concat("PronounGender").concat(referent.getGender())); pair.setFeatureValue (featureName, 1); pair.setFeatureValue (fn2, 1); pair.setFeatureValue (fn3, 1); return carrier; } }
java
14
0.71829
118
30.752294
109
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Input; namespace RobotShootans.Engine { /// /// For future use to help make it easier to work cross platform /// public class Controls { //Keys _jumpKey; //Buttons _jumpButton; //Keys _moveUpKey; //Buttons _moveUpButton; //Keys _moveDownKey; //Buttons _moveDownButton; //Keys _moveLeftKey; //Buttons _moveLeftButton; //Keys _moveRightKey; //Buttons _moveRightButton; //Keys _shootKey; //Buttons _shootButton; } }
c#
5
0.609792
68
22.241379
29
starcoderdata
module.exports = (function() { var self = {}; var crypt = require("crypt/api"); function getPath(isMakeFile){ if( OS_ANDROID ){ var newDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "save"); if( newDir == null || !newDir.exists() ) newDir.createDirectory(); var file = Ti.Filesystem.getFile(newDir.nativePath, "save_file.json"); if( isMakeFile && (file == null || !file.exists()) ) file.write(""); return file.nativePath; } else return globals.SAVE_FILE_PATH; } self.getPath = getPath; function getRSAPath(isMakeFile){ if( OS_ANDROID ){ var newDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "jithd"); if( newDir == null || !newDir.exists() ) newDir.createDirectory(); var file = Ti.Filesystem.getFile(newDir.nativePath, "jithd.json"); if( isMakeFile && (file == null || !file.exists()) ) file.write(""); return file.nativePath; } else return globals.CRYPT_FILE_PATH; } self.getRSAPath = getRSAPath; function getData(){ var f = Ti.Filesystem.getFile( getPath(false) ); var data = f.read(); if ( !data || data.length <= 0 ) data = "{}"; else{ try{ var rsa_info = loadRsa(); var RSAkey = (globals.Crypt_key == null)? (globals.Crypt_key = crypt.loadRSAkey(rsa_info.a)): globals.Crypt_key; var DecryptionResult = crypt.decrypt(data.toString(), RSAkey); data = DecryptionResult.plaintext; if( checkExists() && (data == undefined || data.length <= 0) ) throw new Error(""); } catch(e){ throw new Error("*** Access deny."); } } return JSON.parse(data); } self.data = null; self.init = function(){ var f = Ti.Filesystem.getFile( getPath(false) ); if( f != null && f.exists() ){ f.deleteFile(); } var f2 = Ti.Filesystem.getFile( getRSAPath(false) ); if( f2 != null && f2.exists() ) f2.deleteFile(); var f3 = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "qr_address.png"); if( f3 != null && f3.exists() ) f3.deleteFile(); Ti.App.Properties.setString("current_address", null); load(); }; function loadRsa(){ var f = Ti.Filesystem.getFile( getRSAPath(false) ); var json = f.read(); if ( !json || json.length <= 0 ) json = "{}"; return JSON.parse(json); }; self.loadRsa = loadRsa; function checkExists(){ var exists = false; if( OS_ANDROID ){ var newDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "save"); var f = null; var f2 = null; if( newDir != null && newDir.exists() ){ f = Ti.Filesystem.getFile(newDir.nativePath, "save_file.json"); } var newDir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "jithd"); if( newDir != null && newDir.exists() ){ f2 = Ti.Filesystem.getFile(newDir.nativePath, "jithd.json"); } var a = (f == null)? false: f.exists(); var b = (f2 == null)? false: f2.exists(); exists = a && b; } else{ var f = Ti.Filesystem.getFile( getPath(false) ); var f2 = Ti.Filesystem.getFile( getRSAPath(false) ); exists = f != null && f.exists() && f2 != null && f2.exists(); } return exists; }; self.checkExists = checkExists; self.saveRsa = function( data ){ var f = Ti.Filesystem.getFile( getRSAPath(true) ); f.write(JSON.stringify( data )); }; function load(){ try{ globals.datas = getData(); self.data = globals.datas; return true; } catch(e){ return false; } }; self.load = load; self.save = function(){ var f = Ti.Filesystem.getFile( getPath(true) ); var str_data = JSON.stringify(self.data); var rsa_info = loadRsa(); var RSAkey = (globals.Crypt_key == null)? (globals.Crypt_key = crypt.loadRSAkey(rsa_info.a)): globals.Crypt_key; var PubKey = crypt.publicKeyString(RSAkey); var EncryptionResult = crypt.encrypt(str_data, PubKey); str_data = EncryptionResult.cipher; f.write(str_data); }; return self; }());
javascript
22
0.62674
117
27.34507
142
starcoderdata
package edu.jhu.privtext.test; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import android.test.ActivityInstrumentationTestCase2; import android.widget.TextView; import edu.jhu.privtext.android.SendMessageView; public class SendTextTest extends ActivityInstrumentationTestCase2 { private SendMessageView mActivity; private TextView mView; private String resourceString; public SendTextTest() { super("edu.jhu.privtext.android", SendMessageView.class); } protected void setUp() throws Exception { super.setUp(); SendMessageView localSendMessage = (SendMessageView) getActivity(); this.mActivity = localSendMessage; } public void testJavaCryptoProvider() throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, ShortBufferException, IllegalBlockSizeException, BadPaddingException { } public void testPreconditions() { assertNotNull(this.mView); } public void testText() { String str1 = this.resourceString; String str2 = (String) this.mView.getText(); assertEquals(str1, str2); } }
java
10
0.813885
85
28.456522
46
starcoderdata
using System; using System.Windows; namespace Sample.RouteEventTest { /// /// 需要引用PresentationCore.dll、Windowsbase.dll /// public class MyRouteEvent : UIElement { //第一步:定义路由事件 public static readonly RoutedEvent SayHelloEvent; //第二步:注册SayHello事件 static MyRouteEvent() { MyRouteEvent.SayHelloEvent = EventManager.RegisterRoutedEvent("SayHello",RoutingStrategy.Bubble,typeof(RoutedEventHandler),typeof(MyRouteEvent)); } //第三步:按传统方式封装事件 public event RoutedEventHandler SayHello { add { base.AddHandler(MyRouteEvent.SayHelloEvent, value); } remove { base.RemoveHandler(MyRouteEvent.SayHelloEvent, value); } } //备注:共享路由事件参考MainWindow.cs } }
c#
14
0.641026
157
25.419355
31
starcoderdata
var _ = require('lodash'); var keystone = require('keystone'); /** Initialises the standard view locals */ exports.initLocals = function(req, res, next) { var locals = res.locals; locals.tenet = req.session.tenet || req.tenet || null; locals.user = req.user; locals.brand = keystone.get('brand'); next(); }; exports.initNav = function(req, res, next) { var locals = res.locals; locals.brand = keystone.get('brand'); next(); }; /* Fetches and clears the flashMessages before a view is rendered */ exports.flashMessages = function(req, res, next) { var flashMessages = { info: req.flash('info'), success: req.flash('success'), warning: req.flash('warning'), error: req.flash('error') }; res.locals.messages = _.filter(flashMessages, function(msgs) { return msgs.length; }) ? flashMessages : false; next(); }; /** Prevents people from accessing protected pages when they're not signed in */ exports.requireUser = function(req, res, next) { if (!req.user) { req.flash('error', 'Please sign in to access this page.'); res.redirect(`/${keystone.get('admin path')}/signin`); } else { next(); } };
javascript
12
0.644781
74
18.16129
62
starcoderdata
#include <stdio.h> #include <stdlib.h> #define LL long long #define MAXDIV(a, b) ((a)/(b) + (((a)%(b) != 0)? 1 : 0) ) LL digit_sum(LL num) { LL sum = 0, divide, digit = 1; while((divide = num/digit) != 0) { sum += (divide % 10); digit *= 10; } return sum; } LL most_digit(LL num) { //何桁あるか求める LL digits = 1, cnt = 0; while(num / digits != 0) { digits *= 10; ++cnt; } return cnt; } double digit_div(LL num) { return (double)num / digit_sum(num); } LL snuke(LL num) { LL cnt = 0, m_digits = most_digit(num) + 1; LL d = 10, tmp; //num以上のsnuke数xがx > numであるときの場合 LL x = d * ( num/d + 1) - 1; for(cnt = 1; cnt <= m_digits; ++cnt) { d = d * 10; tmp = d * ( num/d + 1) - 1; if(digit_div(tmp) < digit_div(x)) { x = tmp; } } //num以上のsnuke数xがx == numであるときの場合 if(digit_div(num) <= digit_div(x)) { x = num; } return x; } void solve(LL num) { LL n = 0, i; for(i = 0; i < num; ++i) { n = snuke(n+1); printf("%lld\n", n); } } int main() { LL k; scanf("%lld", &k); solve(k); return 0; }
c
12
0.479646
57
18.842105
57
codenet
'use strict'; //Testing modules const chai = require('chai'), chaiAsPromised = require('chai-as-promised'); chai.should(); chai.use(chaiAsPromised); const Sinon = require('sinon'); //Module to test const Board = require('../../../src/model/Board.js'); const Thread = require('../../../src/model/Thread.js'); const Post = require('../../../src/model/Post'); const User = require('../../../src/model/User'); const DB = require('../../../src/model/db'); const moment = require('moment'); describe('Thread model', () => { let sandbox, parentID; beforeEach(() => { return Promise.resolve().then(() => { sandbox = Sinon.createSandbox(); }) .then(() => DB.initialise({ database: { client: 'sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } })).then(() => Board.addBoard({ Owner: 1, Name: 'Board1' }) ).then((ids) => { parentID = ids[0]; }); }); afterEach(() => { return Promise.resolve().then(() => DB.teardown()) .then(() => { sandbox.restore(); }); }); describe('CRUD', () => { it('should construct', () => { const fakeThread = { ID: Math.random(), Board: Math.random(), Title: 'some thread' }; const expected = { Title: fakeThread.Title, ID: fakeThread.ID, Board: fakeThread.Board }; new Thread(fakeThread).data.should.deep.equal(expected); new Thread(fakeThread).Canonical.should.equal(`/api/threads/${fakeThread.ID}`); }); it('should add a thread', () => { return Thread.addThread({ Title: 'A Thread', Board: parentID }).should.eventually.contain(1); }); it('should add a thread object', () => { return Thread.addThread(new Thread({ Title: 'A Thread', Board: parentID })).should.eventually.contain(1); }); it('should add a second thread', () => { return Thread.addThread({ Title: 'Thread 1', Board: parentID }).then(() => Thread.addThread({ Title: 'Thread 2', Board: parentID })).should.eventually.contain(2); }); it('should reject missing required fields', () => { return Thread.addThread({}).should.be.rejectedWith(Error); }); it('should find an existing thread by ID', () => { return Thread.addThread({ Title: 'A Thread', Board: parentID }).then(() => Thread.getThread(1)).should.eventually.contain.all({ID: 1}); }); it('should not find a non-existant thread by ID', () => { return Thread.getThread(0).should.eventually.equal(null); }); it('should save and retrieve thread', () => { const thread = new Thread({ Title: `A Thread ${Math.random()}`, Board: parentID }); let ID = undefined; return Thread.addThread(thread) .then((id) => { ID = id[0]; return Thread.getThread(ID); }) .then((dbthread) => { thread.Title.should.equal(dbthread.Title); dbthread.ID.should.equal(ID); }); }); it('should update thread', () => { let thread = new Thread({ Title: `A Thread ${Math.random()}`, Board: parentID }); let ID = undefined; return Thread.addThread(thread) .then((id) => { ID = id[0]; return Thread.getThread(ID); }) .then((dbthread) => { thread = dbthread; thread.Title = `Awesome new Title ${Math.random()}`; return thread.save(); }) .then(() => Thread.getThread(ID)) .then((dbthread) => { thread.data.should.deep.equal(dbthread.data); }); }); it('should serialize', () => { const fakeThread = { ID: Math.random(), Title: 'some thread' }; const expected = { Title: fakeThread.Title, Canonical: `/api/threads/${fakeThread.ID}`, PostCount: 0, ID: fakeThread.ID }; new Thread(fakeThread).serialize().should.deep.equal(expected); }); it('should set thread title', () => { const expected = `title ${Math.random()}`; const thred = new Thread({ Title: expected, Board: parentID }); thred.Title.should.equal(expected); }); it('should update thread title', () => { const expected = `title ${Math.random()}`; const thred = new Thread({ Title: 'not correct', Board: parentID }); thred.Title = expected; thred.data.Title.should.equal(expected); }); }); describe('with Boards', () => { it('should find threads by parent board', () => { return Thread.addThread({ Title: 'A Thread', Board: parentID }).then(() => Thread.getThreadsInBoard(parentID)).should.eventually.have.length(1); }); it('should find all by parent board', () => { return Thread.addThread({ Title: 'Thread 1', Board: parentID }).then(() => Thread.addThread({ Title: 'Thread 2', Board: parentID })).then(() => Thread.getThreadsInBoard(parentID)).should.eventually.have.length(2); }); }); describe('with Posts', () => { beforeEach(() => { sandbox.stub(User, 'getUser').resolves({ Username: 'Shrek' }); return Thread.addThread({ Title: 'A Thread', Board: parentID }); }); it('should return last post statistics', () => { const now = moment(); sandbox.stub(Post, 'getPostsInThread').resolves([{ Thread: 1, Body: 'This is a post', Poster: 1, Created: now }]); return Thread.getThread(1).then((thread) => { return thread.getThreadStatistics().should.eventually.deep.equal({ Posts: 1, LastPostTime: now.toDate(), LastPosterId: 1, LastPoster: 'Shrek' }); }); }); it('should calculate latest post', () => { sandbox.stub(Post, 'getPostsInThread').resolves([{ Thread: 1, ID: 1, Body: 'This is a post', Poster: 1, Created: moment('1988-04-30T04:00:00.000Z') }, { Thread: 1, ID: 2, Body: 'This is a post', Poster: 1, Created: moment('1998-10-30T04:00:00.000Z') }]); return Thread.getThread(1).then((thread) => { return thread.getThreadStatistics().should.eventually.deep.equal({ Posts: 2, LastPostTime: moment('1998-10-30T04:00:00.000Z').toDate(), LastPosterId: 1, LastPoster: 'Shrek' }); }); }); it('should not error if no posts', () => { sandbox.stub(Post, 'getPostsInThread').resolves([]); return Thread.getThread(1).then((thread) => { return thread.getThreadStatistics().should.eventually.deep.equal({ Posts: 0, LastPostTime: 'never', LastPosterId: 0, LastPoster: 'nobody' }); }); }); }); });
javascript
30
0.587208
87
22.368231
277
starcoderdata
/* * (C) Copyright Itude Mobile B.V., The Netherlands * * 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.itude.mobile.mobbl.core.util; import java.io.File; import java.lang.reflect.Field; import android.test.ApplicationTestCase; import android.util.Log; import com.itude.mobile.mobbl.core.MBApplicationCore; import com.itude.mobile.mobbl.core.model.MBDocument; import com.itude.mobile.mobbl.core.services.MBDataManagerService; import com.itude.mobile.mobbl.core.services.MBMetadataService; public class MBCacheManagerTest extends ApplicationTestCase { public final static String C_GENERIC_REST_REQUEST = "MBGenericRestRequest"; public final static String C_EMPTY_DOC = "MBEmptyDoc"; public MBCacheManagerTest() { super(MBApplicationCore.class); } @Override protected void setUp() throws Exception { createApplication(); MBMetadataService.setConfigName("unittests/config_unittests.xml"); MBMetadataService.setEndpointsName("testconfig/endpoints.xml"); super.setUp(); } public void testInit() { MBCacheManager cacheManager = MBCacheManager.getInstance(); assertNotNull(cacheManager); Field[] fields = cacheManager.getClass().getDeclaredFields(); for (Field field : fields) { if (!("_operationQueue".equals(field.getName()))) { field.setAccessible(true); try { assertNotNull("Field " + field.getName() + " is null", field.get(cacheManager)); } catch (Exception e) { fail(e.getMessage()); } } } } public void testCache() { String test = "Test string for testing the MBCacheManager"; doPutInCache("test", test.getBytes(), 0); doGetFromCache("test", test.getBytes()); } public void testCacheExpiration() { String test = "Test string for testing the MBCacheManager"; doPutInCache("test", test.getBytes(), 0); // test successful caching doGetFromCache("test", test.getBytes()); // now test expiration MBCacheManager.expireDataForKey("test"); doGetFromCache("test", null); } public void testCacheTimedExpiration() { String test = "Test string for testing the MBCacheManager"; doPutInCache("test", test.getBytes(), 3); // cache for 3 seconds // test successful caching doGetFromCache("test", test.getBytes()); // wait for 5 seconds try { Thread.sleep(5000); } catch (Exception e) { Log.d(MBConstants.APPLICATION_NAME, "Thread.sleep failed"); } // now test expiration doGetFromCache("test", null); } public void testDocumentCache() { MBDocument document = MBDataManagerService.getInstance().loadDocument(C_GENERIC_REST_REQUEST); assertNotNull(document); doPutDocumentInCache(document.getUniqueId(), document, 0); doGetDocumentFromCache(document.getUniqueId(), document); } public void testDocumentCacheExpiration() { MBDocument document = MBDataManagerService.getInstance().loadDocument(C_GENERIC_REST_REQUEST); assertNotNull(document); doPutDocumentInCache(document.getUniqueId(), document, 0); // test successful caching doGetDocumentFromCache(document.getUniqueId(), document); // now test expiration MBCacheManager.expireDocumentForKey(document.getUniqueId()); doGetDocumentFromCache(document.getUniqueId(), null); } public void testDocumentCacheTimedExpiration() { MBDocument document = MBDataManagerService.getInstance().loadDocument(C_GENERIC_REST_REQUEST); assertNotNull(document); doPutDocumentInCache(document.getUniqueId(), document, 3); // cache for 3 seconds // test successful caching doGetDocumentFromCache(document.getUniqueId(), document); // wait for 5 seconds try { Thread.sleep(5000); } catch (Exception e) { Log.d(MBConstants.APPLICATION_NAME, "Thread.sleep failed"); } // now test expiration doGetDocumentFromCache(document.getUniqueId(), null); } public void testExpireAllDocumentsInCache() { MBDocument documentOne = MBDataManagerService.getInstance().loadDocument(C_GENERIC_REST_REQUEST); assertNotNull(documentOne); MBDocument documentTwo = MBDataManagerService.getInstance().loadDocument(C_EMPTY_DOC); assertNotNull(documentTwo); doPutDocumentInCache(documentOne.getUniqueId(), documentOne, 0); doPutDocumentInCache(documentTwo.getUniqueId(), documentTwo, 0); // test successful caching doGetDocumentFromCache(documentOne.getUniqueId(), documentOne); doGetDocumentFromCache(documentTwo.getUniqueId(), documentTwo); // now test expiration MBCacheManager.expireAllDocuments(); doGetDocumentFromCache(documentOne.getUniqueId(), null); doGetDocumentFromCache(documentTwo.getUniqueId(), null); } private void doPutInCache(String key, byte[] data, int ttls) { MBCacheManager.setData(data, key, ttls); // lets give MBCacheManager the oppertunity to write to file try { Thread.sleep(2000); } catch (Exception e) { fail("Sleep went wrong"); } } private void doPutDocumentInCache(String key, MBDocument document, int ttls) { MBCacheManager.setDocument(document, document.getUniqueId(), ttls); // lets give MBCacheManager the oppertunity to write to file try { Thread.sleep(2000); } catch (Exception e) { fail("Sleep went wrong"); } } private void doGetFromCache(String key, byte[] expected) { byte[] resultBytes = MBCacheManager.getDataForKey(key); if (expected == null) assertNull(resultBytes); else { assertTrue(resultBytes.length == expected.length); for (int i = 0; i < resultBytes.length; i++) assertEquals(expected[i], resultBytes[i]); } } private void doGetDocumentFromCache(String key, MBDocument expected) { MBDocument result = MBCacheManager.documentForKey(key); if (expected == null) assertNull(result); else { assertNotNull(result); assertEquals(expected.getUniqueId(), result.getUniqueId()); } } @Override protected void tearDown() throws Exception { File cacheDir = new File(getContext().getFilesDir(), "cache"); if (cacheDir.exists() && cacheDir.isDirectory()) { File[] files = cacheDir.listFiles(); if (files.length > 0) { for (File file : files) file.delete(); } cacheDir.delete(); } super.tearDown(); } }
java
18
0.693276
101
27.612
250
starcoderdata
package cz.ackee.androidskeleton.event; /** * Event that is fired when issue is modified * Created by on {3. 7. 2015} **/ public class IssueModifiedEvent { public static final String TAG = IssueModifiedEvent.class.getName(); }
java
7
0.760218
114
32.363636
11
starcoderdata
package solutions.tveit.nissanconnect; public class NissanConnectException extends RuntimeException { public NissanConnectException(String message) { super(message); } public NissanConnectException(Exception e) { super(e); } }
java
7
0.737705
62
22.461538
13
starcoderdata
package com.incloud.hcp.jco.distribucionflota.dto; public class TercerosDto { private String CodPlanta; private String DescPlanta; private double PescDeclProp; private double EmbaPescProp; private double CbodProp; public double getPescDeclProp() { return PescDeclProp; } public void setPescDeclProp(double pescDeclProp) { PescDeclProp = pescDeclProp; } public double getEmbaPescProp() { return EmbaPescProp; } public void setEmbaPescProp(double embaPescProp) { EmbaPescProp = embaPescProp; } public double getCbodProp() { return CbodProp; } public void setCbodProp(double cbodProp) { CbodProp = cbodProp; } public String getCodPlanta() { return CodPlanta; } public void setCodPlanta(String codPlanta) { CodPlanta = codPlanta; } public String getDescPlanta() { return DescPlanta; } public void setDescPlanta(String descPlanta) { DescPlanta = descPlanta; } }
java
7
0.655042
54
19.803922
51
starcoderdata
public void generateAPIs() { // Start code generation of the application developer files APIGenerator apiGen = new APIGenerator(systemModel.getSystemModel(), systemModel.getToolConfig(), containerOutputDir); apiGen.generate(); // Generate build files BuildGeneratorAPI buildGen = new BuildGeneratorAPI(systemModel.getSystemModel(), stepsDir, containerOutputDir); buildGen.generateBuildFiles(); // End of code generator LOGGER.info("ECOA API Code Generator Completed!"); }
java
9
0.778004
120
36.846154
13
inline
/* SDL C++ Classes Copyright (C) 2017-2018 This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include #include #include "window.hpp" #include "renderer.hpp" using SDL::Window; using SDL::Renderer; const int ERR_SDL_INIT = -1; bool init(Uint32 sdlInitFlags) { return SDL_Init(sdlInitFlags) == 0; } void quit() { SDL_Quit(); } void gameLoop() { // setting the window dimensions to something smaller would likely // require repositioning of some primitives Window window("test", 800, 600); window.makeRenderer(); SDL_Rect rect1{0, 200, 100, 200}; SDL_Rect rect2{450, 275, 100, 50}; // we could've all of the drawing operations outside of the main loop // since they never change, but this way we can also measure CPU usage // with this test // bool quit = false; while(!quit) { SDL_Event e; while(SDL_PollEvent(&e)) { if(e.type == SDL_QUIT) { quit = true; } } window.renderer->setDrawColor(0x00, 0x00, 0x00); window.renderer->clear(); window.renderer->setDrawColor(0xff, 0xff, 0xff); window.renderer->drawPoint(400, 150); window.renderer->setDrawColor(0x00, 0xff, 0x00); window.renderer->drawPoints(std::vector {50, 100}, {100, 100}, {150, 100}, {200, 100}, {250, 100}, {300, 100}, {350, 100}, {400, 100}, {500, 100}, {550, 100}, {600, 100}, {650, 100}, {700, 100} }); window.renderer->setDrawColor(0x00, 0x00, 0xff); window.renderer->drawLine(0, 0, 800, 600); window.renderer->setDrawColor(0xff, 0x00, 0x00); window.renderer->drawLines(std::vector {200, 200}, {200, 400}, {350, 300}, {200, 200} }); window.renderer->setDrawColor(0xff, 0xff, 0x00); window.renderer->drawRect(&rect1); window.renderer->setDrawColor(0x00, 0xff, 0xff); window.renderer->drawRects(std::vector {650, 200, 100, 50}, {700, 250, 100, 50}, {650, 300, 100, 50}, {700, 350, 100, 50} }); window.renderer->setDrawColor(0xff, 0x00, 0xff); window.renderer->fillRect(&rect2); window.renderer->setDrawColor(0x72, 0x2f, 0x37); // wine window.renderer->fillRects(std::vector {600, 200, 50, 50}, {750, 200, 50, 50}, {600, 250, 100, 50}, {600, 300, 50, 50}, {750, 300, 50, 50}, {600, 350, 100, 50} }); window.renderer->present(); } } int main(int argc, char **argv) { if(!init(SDL_INIT_VIDEO)) { SDL_LogCritical(SDL_LOG_CATEGORY_ERROR, "couldn't initialize SDL\n"); return ERR_SDL_INIT; } gameLoop(); quit(); return 0; }
c++
13
0.675959
76
25.688
125
starcoderdata
package com.photo.bas.core.service.common; import com.photo.bas.core.dao.common.AbsZoneRepository; import com.photo.bas.core.model.common.AbsZone; import com.photo.bas.core.service.entity.AbsMaintenanceService; import com.photo.bas.core.utils.PageInfo; /** * @author FengYu * */ public abstract class AbsZoneService<T extends AbsZone, P extends PageInfo extends AbsMaintenanceService<T, P>{ protected abstract AbsZoneRepository getRepository(); @Override public boolean isCommonAccess() { return true; } }
java
8
0.755064
115
28.166667
18
starcoderdata
<?php /** * | --------------------------------------------------------------------------------------------------- * | ProjectName: ticket * | --------------------------------------------------------------------------------------------------- * | Author:johnxu * | --------------------------------------------------------------------------------------------------- * | Home: https://www.xfjpeter.cn * | --------------------------------------------------------------------------------------------------- * | Data: 201905242019-05-24 * | --------------------------------------------------------------------------------------------------- * | Desc: * | --------------------------------------------------------------------------------------------------- */ namespace app\api\controller; use johnxu\tool\Hash; use johnxu\tool\Str; use think\Db; class User extends Api { /** * @var \app\api\model\User */ protected $model; protected function initialize() { parent::initialize(); $this->model = model('user'); } // 用户列表 public function index() { $users = $this->model->page($this->page, $this->limit)->select(); $total = $this->model->count('*'); foreach ($users as $key => $user) { $users[$key]['role_id'] = Db::name('user_role')->where('user_id', $user['id'])->value('role_id'); unset($users[$key]['password'], $users[$key]['id']); } return json([ 'err_code' => 0, 'message' => 'success', 'data' => [ 'list' => $users, 'total' => $total, ], ]); } // 获取指定用户 public function get(string $uid = '') { $user = $this->model->get(['uid' => $uid]); if (!$user) { return json([ 'err_code' => 1, 'message' => 'Not found user', ]); } // 查询用户的角色 $user['role_id'] = Db::name('user_role')->where('user_id', $user->id)->value('role_id'); unset($user['id'], $user['password']); return json([ 'err_code' => 0, 'message' => 'success', 'data' => $user, ]); } // 编辑用户信息 public function save(string $uid = '') { $data = $this->request->post(); $user = $this->model->get(['uid' => $uid]); if (!$user) { return json([ 'err_code' => 1, 'message' => 'Not found user', ]); } // 判断有没有密码 if (isset($data['password']) && !empty($data['password'])) { $data['password'] = Hash::make($data['password']); } else { unset($data['password']); } $res = $user->save($data); if ($res !== false) { $this->updateUserRole($data, $user->id); return json([ 'err_code' => 0, 'message' => 'success', 'data' => $data, ]); } else { return json([ 'err_code' => 1, 'message' => 'Update user fail', ]); } } // 添加用户 public function add() { $data = $this->request->post(); $data['uid'] = Str::getInstance()->generateUid(); if (isset($data['password']) && !empty($data['password'])) { $data['password'] = Hash::make($data['password']); } else { $data['password'] = } $user = $this->model::create($data); if ($user) { $this->updateUserRole($data, $user->id); unset($data['password']); return json([ 'err_code' => 0, 'message' => 'Add user success', 'data' => $data, ]); } else { return json([ 'err_code' => 1, 'message' => 'Add user fail', ]); } } // 删除用户 public function delete(string $uid = '') { $is = $this->model->where(['uid' => $uid, 'system' => 0])->delete(); if ($is) { return json([ 'err_code' => 0, 'message' => 'Delete user success', ]); } else { return json([ 'err_code' => 1, 'message' => 'Delete user fail', ]); } } // 登录 public function login() { $data = $this->request->post(); $user = $this->model->get(['username' => $data['username']]); if (!$user) { return json([ 'err_code' => 1, 'message' => 'username or password error', ]); } elseif (!Hash::check($data['password'], $user['password'])) { return json([ 'err_code' => 1, 'message' => 'username or password error', ]); } elseif ($user['status'] !== 1) { return json([ 'err_code' => 1, 'message' => '账号被禁用', ]); } else { unset($user['password'], $user['id']); $user['authorization'] = $this->jwt->getToken($this->getJwtPayload(['uid' => $user['uid']])); return json([ 'err_code' => 0, 'message' => 'success', 'data' => $user, ]); } } // 检测登录状态 public function check() { $authorization = $this->request->header('Authorization'); $result = $this->jwt->verify($authorization); if (!$result) { return json(['err_code' => 401, 'message' => '登录过期']); } else { return json(['err_code' => 0, 'message' => '登录正常']); } } // 更新用户角色 protected function updateUserRole(array $data, $userId) { if (isset($data['role_id']) && !empty($data['role_id'])) { $userRole = Db::name('user_role')->where('user_id', $userId)->find(); if ($userRole) { Db::name('user_role')->where('user_id', $userId)->update(['role_id' => $data['role_id']]); } else { Db::name('user_role')->insert(['role_id' => $data['role_id'], 'user_id' => $userId]); } } } }
php
20
0.372601
109
28.912037
216
starcoderdata
#!/usr/bin/python ## Download files from Amazon S3 (e.g. raw photos for 3D models) ## 15-Jun-2014, updated 21-Nov-2014 __author__ = 'ahb108' ## Currently for Python 2.7.5 (tested on MacOSX 10.9.2) launched in a virtual environment: from PIL import Image # Pillow with libjpeg support from PIL import ImageDraw import urllib3 import json import re import numpy as np import argparse import os # Argument parser parser = argparse.ArgumentParser(description='This is a script to combine vector polygon masks into a binary raster mask for 3d modelling.') parser.add_argument('-a','--app',help='MicroPasts application', required=True) parser.add_argument('-w','--wd', help='Working directory',required=True) args = parser.parse_args() ## Global settings ## os.chdir(args.wd) app = args.app pybinst = 'http://crowdsourced.micropasts.org' ################################### # Get the raw jpg files from working directory ext = ['.JPG', '.jpg', '.jpeg', '.JPEG'] files = [ f for f in os.listdir('.') if f.endswith(tuple(ext)) ] print("Masking each individual photograph...") for q in range(0, len(files)): # Open an example image img = Image.open(files[q]) imnameonly = os.path.splitext(files[q])[0] # Get JSON data for tasks and find task ID for this file url = str(pybinst) + '/app/' + str(app) + '/tasks/export?type=task&format=json' http = urllib3.PoolManager() jurl = http.urlopen('GET', url, preload_content=False) jtasks = json.loads(jurl.read()) # Loop through looking for those tasks with the necessary # look-up image (almost always one unless tasks have been duplicated, # but allowing more than one just in case) imtasks = [] for elm in range(0, len(jtasks)): onetask = jtasks[elm] onetaskurl = onetask['info']['url_b'].encode('utf-8') if re.search(files[q], onetaskurl): imtasks.extend([onetask['id']]) # Get JSON data for task runs (even if they are duplicated) jtaskruns = [] for a in range(0, len(imtasks)): url = str(pybinst) + '/app/' + str(app) + '/' + str(imtasks[a]) + '/results.json' jurl = http.urlopen('GET', url, preload_content=False) jtaskruns.extend(json.loads(jurl.read())) # Loop through and extract outlines for a in range(0, len(jtaskruns)): jtaskrun = jtaskruns[a] # one contributor imtmp = Image.new("L", img.size, color=0) draw = ImageDraw.Draw(imtmp) # Loop through outline (or possible multiple outline polygons) for outs in range(0, len(jtaskrun['info']['outline'])): # Extract the outline and convert to tuples o0 = jtaskrun['info']['outline'][outs][0] p = [] # Empty list for outline vertices h = img.size[1] # Get image height for x in range(0, len(o0)): xy = o0[x] xy[1] = h - xy[1] # reverse y-coordinates p.append(tuple(xy)) draw.polygon(tuple(p), fill=255) # Loop through holes in same way for hls in range(0, len(jtaskrun['info']['holes'])): h0 = jtaskrun['info']['holes'][hls][0] ph = [] for x in range(0, len(h0)): xy = h0[x] xy[1] = h - xy[1] ph.append(tuple(xy)) draw.polygon(tuple(ph), fill=0) # imtmp.show() if jtaskrun['user_id'] is None: fn = imnameonly + '_mask_' + str(a) + '_anon.JPG' else: fn = imnameonly + '_mask_' + str(a) + '_user' + str(jtaskrun['user_id']) + '.JPG' imtmp.save(fn) if a is 1: fn1 = imnameonly + '_mask.JPG' imtmp.save(fn1) print("Done.")
python
16
0.596822
140
39.358696
92
starcoderdata
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os import jinja2 import webapp2 JINJA_ENVIRONMENT = jinja2.Environment( loader = jinja2.FileSystemLoader(os.path.dirname(__file__))) class MainHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('index.html') title = "Event Seeker | Find Your Events" navText = " CREATE EVENT" navHref = "create_event.html" navIcon = "glyphicon glyphicon-plus" # glyphicon glyphicon-eye-open template_vars = { 'title' : title, 'navText' : navText, 'navHref': navHref, 'navIcon' : navIcon } self.response.out.write(template.render(template_vars)) class aboutHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('about.html') title = "Event Seeker | About Us" navText = " CREATE EVENT" navHref = "create_event.html" navIcon = "glyphicon glyphicon-plus" # glyphicon glyphicon-eye-open template_vars = { 'title' : title, 'navText' : navText, 'navHref': navHref, 'navIcon' : navIcon } self.response.out.write(template.render(template_vars)) class createHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('create_event.html') title = "Event Seeker | Create an Event" createStyle = "css/create_event.css" navText = " BROWSE EVENT" navHref = "index.html" navIcon = "glyphicon glyphicon-eye-open" # glyphicon glyphicon-eye-open template_vars = { 'title' : title, 'createStyle' : createStyle, 'navText' : navText, 'navHref': navHref, 'navIcon' : navIcon } self.response.out.write(template.render(template_vars)) class eventIntroHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('eventintro.html') title = "Event Seeker | Event Details" navText = " CREATE EVENT" navHref = "create_event.html" navIcon = "glyphicon glyphicon-plus" template_vars = { 'title' : title, 'navText' : navText, 'navHref': navHref, 'navIcon' : navIcon } self.response.out.write(template.render(template_vars)) class loginHandler(webapp2.RequestHandler): def get(self): template = JINJA_ENVIRONMENT.get_template('login.html') title = "Event Seeker | Login" createStyle = "css/login.css" navText = " CREATE EVENT" navHref = "create_event.html" navIcon = "glyphicon glyphicon-plus" # glyphicon glyphicon-eye-open template_vars = { 'title' : title, 'createStyle' : createStyle, 'navText' : navText, 'navHref': navHref, 'navIcon' : navIcon } self.response.out.write(template.render(template_vars)) app = webapp2.WSGIApplication([ ('/', MainHandler), ('/index.html', MainHandler), ('/about.html', aboutHandler), ('/create_event.html', createHandler), ('/eventintro.html', eventIntroHandler), ('/login.html', loginHandler) ], debug=True)
python
11
0.631812
79
33.863636
110
starcoderdata
public static void test_settings() { // Choose setting configuration ad load the data setting.crypt = true; setting.SetLocation(SettLocation.PROGDATA, "ProgramName/"); setting.Load(); // Change a some values setting.data.Uses += 1; // Save the setting to file setting.Save(); // Read a value from the setting data string name = setting.data.Name; }
c#
10
0.523139
71
30.125
16
inline
void ReversiScene::CreateStone(bool stoneColor, int xcor, int ycor)//0 black 1 white { if(stones[ycor][xcor]==nullptr){ stones[ycor][xcor] = new Stone(stoneColor,this); stones[ycor][xcor]->setPos(X0+xcor*Xdif, Y0+ycor*Ydif); this->addItem(stones[ycor][xcor]); } }
c++
11
0.647458
84
36
8
inline
Trick::JobData * Trick::ScheduledJobQueue::find_next_job(long long time_tics ) { JobData * curr_job ; long long next_call ; /* Search through the rest of the queue starting at curr_index looking for the next job with it's next execution time is equal to the current simulation time. */ while (curr_index < list_size ) { curr_job = list[curr_index] ; if ( curr_job->next_tics == time_tics ) { /* If the job does not reschedule itself (system_job_classes), calculate the next time it will be called. */ if ( ! curr_job->system_job_class ) { // calculate the next job call time next_call = curr_job->next_tics + curr_job->cycle_tics ; /* If the next time does not exceed the stop time, set the next call time for the module */ if (next_call > curr_job->stop_tics) { curr_job->next_tics = TRICK_MAX_LONG_LONG ; } else { curr_job->next_tics = next_call; } /* Track next lowest job call time after the current time for jobs that match the current time. */ if ( curr_job->next_tics < next_job_time ) { next_job_time = curr_job->next_tics ; } } curr_index++ ; if ( !curr_job->disabled ) { return(curr_job) ; } } else { /* Track next lowest job call time after the current time for jobs that do not match the current time */ if ( curr_job->next_tics > time_tics && curr_job->next_tics < next_job_time ) { next_job_time = curr_job->next_tics ; } curr_index++ ; } } return(NULL) ; }
c++
15
0.530067
120
41.785714
42
inline
package _206_reverse_linked_list import "github.com/yigenshutiao/Golang-algorithm-template/util" type ListNode = util.ListNode func reverseList(head *ListNode) *ListNode { // 这里不能声明为 pre := &ListNode{}, 因为会初始化,这里只需要声明,不需要初始化 var pre *ListNode // 当前值要声明到head上... cur := head // head不会动,这里的变量是游标cur, 判断时应用cur进行判断 for cur != nil { tmp := cur.Next cur.Next = pre pre = cur cur = tmp } return pre }
go
8
0.717622
63
21.428571
21
starcoderdata
#include #include "include/vpc.h" #include "include/ops.h" int main(int argc, const char* argv[]) { vpc::registers_t registers{0}; vpc::operations_t operations = vpc::make_instructions(); vpc::memory_t memory{0}; int i = 0; auto next = [&i](){return i++;}; // DATA memory[240] = vpc::create_data(0x00); // start memory[241] = vpc::create_data(0x01); // step memory[242] = vpc::create_data(0x0F); // end memory[243] = vpc::create_data(0x0A); // newline constant // PROGRAM memory[next()] = vpc::create_instruction({vpc::CPU_LDA, 0xF0}); memory[next()] = vpc::create_instruction({vpc::CPU_LDB, 0xF2}); memory[next()] = vpc::create_instruction({vpc::CPU_CMP}); memory[next()] = vpc::create_instruction({vpc::CPU_JIE, 0x0B}); memory[next()] = vpc::create_instruction({vpc::CPU_LDA, 0xF0}); memory[next()] = vpc::create_instruction({vpc::CPU_LDB, 0xF1}); memory[next()] = vpc::create_instruction({vpc::CPU_ADD}); memory[next()] = vpc::create_instruction({vpc::CPU_EMT, 0xF0}); memory[next()] = vpc::create_instruction({vpc::CPU_STA, 0xF0}); memory[next()] = vpc::create_instruction({vpc::CPU_PRT, 0xF3}); memory[next()] = vpc::create_instruction({vpc::CPU_JMP, 0x00}); memory[next()] = vpc::create_instruction({vpc::CPU_HLT}); vpc::execute(operations, registers, memory); return 0; }
c++
9
0.620617
67
30.711111
45
starcoderdata
# -*- coding: utf-8 -*- import ast def get_content_files(file_names): """ Получает контент списка файлов @param file_names: список файлов (итерируемый объект) @return: генератор """ for file_name in file_names: with open(file_name, 'r', encoding='utf-8') as attempt_handler: file_content = attempt_handler.read() yield file_content def get_source_trees(contents): """ Получить синтаксические деревья по списку контентов @param contents: список контентов (итерируемый объект) @return: генератор """ for file_content in contents: try: tree = ast.parse(file_content) yield tree except SyntaxError: pass def get_names_functions_from_tree(tree): """ Получить список имён функций из ast-объекта (генератор) @param tree: дерево синтаксического разбора @return генератор """ for node in ast.walk(tree): if isinstance(node, ast.FunctionDef): yield node.name.lower() def get_names_functions_without_magic(names_functions): """ Получить из списка имён функций список не магических имён функций @param names_functions: список имён функций @return генератор """ for name_function in names_functions: if not (name_function.startswith('__') and name_function.endswith('__')): yield name_function def get_names_functions_without_magic_from_trees(trees): """ Получить список имён функций(без магических) из ast-объектов (генератор) @param trees: итерируемый объект из деревьев синтаксического разбора """ for tree in trees: for name_function in get_names_functions_without_magic(get_names_functions_from_tree(tree)): yield name_function
python
13
0.661379
100
28.015873
63
starcoderdata
import maf_iterate from intervaltree import Interval, IntervalTree import logging # start with finding indels between hg19 and mm10. args = maf_iterate.get_args() anchor = 'hg19' source = 'mm10' flank5k = 'chr1_hg19_mm10_5k.maf' exact = 'chr1_hg19_mm10_0.maf' flanking = 5000 curr_insertion = {} curr_deletion = {} insertiontree = IntervalTree() deletiontree = IntervalTree() for block in maf_iterate.maf_iterator(args.maf): if source in block['req']: # only + strain in anchor genome start = block['req'][anchor]['start'] end = block['req'][anchor]['start'] + block['req'][anchor]['length'] if block['req'][source]['aln'] == 1 and block['req'][source]['leftCount'] > 0: if 'end' in curr_insertion or 'start' not in curr_insertion: logging.warning("another half of insertion incorrect!") curr_insertion = {} else: curr_insertion['end'] = end curr_insertion['part2'] = block insertiontree[curr_insertion['start']:curr_insertion['end']] = curr_insertion curr_insertion = {} elif block['req'][source]['aln'] == 1 and block['req'][source]['rightCount'] > 0: if curr_insertion == {}: curr_insertion['start'] = start curr_insertion['part1'] = block else: logging.warning("insertion part already exist?") curr_insertion = {} elif block['req'][source]['aln'] == 0: if 'part' in curr_deletion and block['req'][source] == curr_deletion['part']['req'][source]: deletiontree.removei(curr_deletion['start'], curr_deletion['end'], curr_deletion) curr_deletion['end'] = end deletiontree[curr_deletion['start']:curr_deletion['end']] = curr_deletion else: curr_deletion['start'] = start curr_deletion['end'] = end curr_deletion['part'] = block deletiontree[curr_deletion['start']:curr_deletion['end']] = curr_deletion with open(flank5k, 'w') as flanking_outfile: with open(exact, 'w') as exact_outfile: for Iobj in sorted(insertiontree): Dset = sorted(deletiontree.search(Iobj.begin, Iobj.end)) closeset = sorted(deletiontree.search(Iobj.begin - flanking, Iobj.end + flanking)) for closeobj in closeset: if closeobj in Dset: maf_iterate.print_block(Iobj.data['part1'], flanking_outfile) maf_iterate.print_block(Iobj.data['part2'], flanking_outfile) maf_iterate.print_block(closeobj.data['part'], flanking_outfile) else: maf_iterate.print_block(Iobj.data['part1'], exact_outfile) maf_iterate.print_block(Iobj.data['part2'], exact_outfile) maf_iterate.print_block(closeobj.data['part'], exact_outfile)
python
17
0.58
104
44.454545
66
starcoderdata
import requests class WebApi(object): def __init__(self, url_base): self.url_base = url_base def _endpoint(self, path): return self.url_base + path def request(self, path): response = requests.get(self._endpoint(path)) if response.status_code != 200: raise Exception( "Failed to talk to endpoint: {}".format(_endpoint(path)) ) return response.json()
python
14
0.571749
72
25.235294
17
starcoderdata
private static void applyR2Rml(List<String> mappingFiles, String scenario) throws Exception { SesameAdapter eval = SesameAdapter.getInstance(RepoType.EVALUATION); // execute mappings (db2triples): Connection jdbc = RdbmsUtil.getConnection(); try { for (String r2rmlFile : mappingFiles) { SesameDataSet ds; if (Config.getInstance().getSelectDbms().equals("mysql")) { jdbc.createStatement().execute("USE " + scenario); ds = R2RMLProcessor.convertDatabase(jdbc, r2rmlFile, "urn:base-uri-", DriverType.MysqlDriver); } else { jdbc.createStatement().execute("SET SEARCH_PATH TO " + scenario); ds = R2RMLProcessor.convertDatabase(jdbc, r2rmlFile, "urn:base-uri-", DriverType.PostgreSQL); } eval.add(ds.tuplePattern(null, null, null)); } } catch (Exception e) { throw new RuntimeException("Error while executing R2RML mappings: " + e); } finally { jdbc.close(); } }
java
14
0.698601
99
33.444444
27
inline
<?php $sjbg =array( "1" => "https://cdn.9yo.cc/sjbg1.jpg", "2" => "https://cdn.9yo.cc/sjbg2.jpg", "3" => "https://cdn.9yo.cc/sjbg3.jpg", "4" => "https://cdn.9yo.cc/sjbg4.jpg", "5" => "https://cdn.9yo.cc/sjbg5.jpg", "6" => "https://cdn.9yo.cc/sjbg6.jpg", "7" => "https://cdn.9yo.cc/sjbg7.jpg", "8" => "https://cdn.9yo.cc/sjbg8.jpg", "9" => "https://cdn.9yo.cc/sjbg9.jpg", "10" => "https://cdn.9yo.cc/sjbg10.jpg", "11" => "https://cdn.9yo.cc/sjbg11.jpg", "12" => "https://cdn.9yo.cc/sjbg12.jpg", "13" => "https://cdn.9yo.cc/sjbg13.jpg", "14" => "https://cdn.9yo.cc/sjbg14.jpg", "15" => "https://cdn.9yo.cc/sjbg15.jpg", "16" => "https://cdn.9yo.cc/sjbg16.jpg", "17" => "https://cdn.9yo.cc/sjbg17.jpg", "18" => "https://cdn.9yo.cc/sjbg18.jpg", "19" => "https://cdn.9yo.cc/sjbg19.jpg", "20" => "https://cdn.9yo.cc/sjbg20.jpg", "21" => "https://cdn.9yo.cc/sjbg21.jpg", "22" => "https://cdn.9yo.cc/sjbg22.jpg", "23" => "https://cdn.9yo.cc/sjbg23.jpg", ); $r =rand(1,count($sjbg)); ?>
php
10
0.581854
40
32.8
30
starcoderdata
function first(callback) { setTimeout(function () { console.log("I GO FIRST"); callback(); }, 1000); } function second() { console.log("I GO SECOND"); } // first(second); // console.log("A GO THIRD"); // let prom = new Promise(function (resolve, reject) { // let res = 1 + 1; // if (res === 2) { // resolve("YES WE MADE IT!"); // } else { // reject("1 + 1 should be 2!"); // } // }); // prom // .then(function (result) { // console.log(result); // }) // .catch(function (error) { // console.log(error); // }) // .finally(function () { // console.log("I AM EXECUTED ANYWAY"); // }); // function learnJSBasic(learningTime) { // return new Promise(function (resolve, reject) { // if (learningTime <= 0) { // reject("There is no way you could learn JS Basic in no time"); // } // setTimeout(function () { // resolve("I FINALLY LEARNED JS Basic!"); // }, learningTime); // }); // } // function learnJSAdvanced() { // console.log("I HAVE LEARNED JS ADVANCED!"); // } // learnJSBasic(0) // .then(function (result) { // console.log(result); // learnJSAdvanced(); // }) // .catch(function (error) { // console.log(error); // }); function getDocuments() { return new Promise(function (resolve, reject) { $.ajax({ url: "https://raw.githubusercontent.com/sedc-codecademy/skwd9-04-ajs/main/Samples/documents.json", success: function (res) { const data = JSON.parse(res); resolve(data); }, error: function (error) { reject(error); }, }); }); } function filterImportantDocuments(documents) { return new Promise(function (resolve, reject) { if (documents.length === 0) { reject("There is no documents to be filtered!"); } let importantDocuments = []; for (let doc of documents) { if (doc.important) { importantDocuments.push(doc); } } resolve(importantDocuments); }); } // getDocuments() // .then(function (documents) { // return filterImportantDocuments(documents); // }) // .then(function (importantDocuments) { // console.log(importantDocuments); // }) // .catch(function (err) { // console.log(err); // }); // getDocuments() // .then(function (documents) { // filterImportantDocuments(documents) // .then(function (filteredDocuments) { // console.log(filteredDocuments); // }) // .catch(function (error) { // console.log(error); // }); // }) // .catch(function (err) { // console.log(err); // }); // fetch( // "https://raw.githubusercontent.com/sedc-codecademy/skwd9-04-ajs/main/Samples/documents.json" // ) // .then(function (response) { // console.log(response); // return response.json(); // }) // .then(function (documents) { // return filterImportantDocuments(documents); // }) // .then(function (importantDocuments) { // console.log(importantDocuments); // }) // .catch(function (error) { // console.log(error); // }) // .finally(function () { // console.log("THE WORK IS DONE FINALLY!"); // }); async function getDataFromFetch() { try { let result = await fetch( "https://raw.githubusercontent.com/sedc-codecademy/skwd9-04-ajs/main/Samples/documents.json" ); let documents = await result.json(); let filteredDocuments = await filterImportantDocuments(documents); let starWarsPerson = await getStarWarsPerson(); createList(filteredDocuments); } catch (error) { console.log("Something went wrong, please try again later", error); let h1 = document.createElement("h1"); h1.textContent = "Something went wrong, please try again later"; h1.style.color = "red"; document.getElementsByTagName("body")[0].appendChild(h1); } } // Behind the scene (promises) // function getDataFromFetch() { // fetch( // "https://raw.githubusercontent.com/sedc-codecademy/skwd9-04-ajs/main/Samples/documents.json" // ) // .then(function (result) { // return result.json(); // }) // .then(function (documents) { // return filterImportantDocuments(documents); // }) // .then(function (filteredDocuments) { // return { person: getStarWarsPerson(), filteredDocuments }; // }) // .then(function (res) { // createList(res.filteredDocuments); // }); // } async function getStarWarsPerson() { let result = await fetch("https://swapi.dev/api/people/1/"); let person = await result.json(); return person; } function createList(documents) { console.log("List created for: ", documents); } getDataFromFetch(); fetch("https://restcountries.com/v3.1/alpha/MKD") .then((result) => result.json()) .then((country) => console.log(country)); async function getCountry() { try { const res = await fetch("https://restcountries.com/v3.1/alpha/MKD"); const data = await res.json(); let mkd = data[0]; let borderCountriesPromises = []; for (const border of mkd.borders) { const res = await fetch(`https://restcountries.com/v3.1/alpha/${border}`); borderCountriesPromises.push(res.json()); } // wait all promises to be resolved Promise.all let promisesResults = await Promise.all(borderCountriesPromises); // something that will be learned in following classes (map) const countries = promisesResults.map(function (country) { return country[0]; }); console.log(countries); // console.log(promisesResults); } catch (error) { console.log(error); } } getCountry();
javascript
19
0.611508
104
25.149533
214
starcoderdata
@extends('guest/template/index') @section('content') @if(Auth::check()) @section('content') <div class="main"> <div class="wrapper"> <!-- left --> <article class="col-left"> <ul class="list-group"> <li class="bg-primary" style="text-align:center;">Thông tin người dùng <li class="list-group-item text-right" style="background:#FDF282;"><span class="pull-left"><strong class="">Tên tài khoản: {{Auth::user()->username}} <li class="list-group-item text-right" style="background:#FDF282;"><span class="pull-left"><strong class="">Tên người dùng: {{Auth::user()->name}} <li class="list-group-item text-right" style="background:#FDF282;"><span class="pull-left"><strong class="">Tuổi: {{Auth::user()->age}} <li class="list-group-item text-right" style="background:#FDF282;"><span class="pull-left"><strong class="">Giới tính: @if(Auth::user()->gender == 1) Nam @else Nữ @endif <!-- right--> <article class="col-right"> <div class="indent-right"> <h3 class="prev-indent-bot">Thực đơn đã đăng ký <hr class="prev-indent-bot-bg" /> <div class="col-md-12" > <table class="table"> <tr class="bg-primary"> thực đơn thực đơn yêu cầu <?php $totalMoney = 0;?> {{Form::open(array("route"=>array("customerDeleteMenu")))}} @foreach($registered as $order) <tr class="active"> <td style="background:#FDF282;">{{$order->order_id}} <td style="background:#FDF282;">{{$order->menu_name}} <td style="background:#FDF282;">{{$order->menu_price}} VNĐ <td style="background:#FDF282;">{{$order->order_date}} <td style="background:#FDF282;"><input type="checkbox" value="1" name="del[{{$order->order_id}}]"> <?php $totalMoney += $order->menu_price;?> @endforeach <tr class="bg-info"> tiền VNĐ <td colspan="8" class="bg-info"><input type="submit" value="Xác nhận" name="ok" class="btn btn-default pull-right confirm" id="del" > {{Form::close()}} <tr class="last"> <td colspan="8">{{$registered->links()}} <!-- thuc don trong thang --> <div class="indent-right"> <h3 class="prev-indent-bot">Đã ăn trong tháng <hr class="prev-indent-bot-bg" /> <div class="col-md-12" > <table class="table"> <tr class="bg-primary"> thực đơn thực đơn yêu cầu <?php $totalMoney2 = 0;?> @foreach($eated as $order) <tr class="active"> <td style="background:#FDF282;">{{$order->order_id}} <td style="background:#FDF282;">{{$order->menu_name}} <td style="background:#FDF282;">{{$order->menu_price}} VNĐ <td style="background:#FDF282;">{{$order->order_date}} <?php $totalMoney2 += $order->menu_price;?> @endforeach <tr class="bg-info"> tiền VNĐ <td colspan="8" class="bg-info"><input type="submit" value="Xác nhận" name="ok" class="btn btn-default pull-right confirm" id="del" > <tr class="last"> <td colspan="8">{{$registered->links()}} @stop @else Bạn chưa đăng nhập, vui lòng đăng nhập! @endif @stop
php
5
0.404324
209
49.463636
110
starcoderdata
/* * Copyright (c) 2010, * All rights reserved. * * Made available under the BSD license - see the LICENSE file */ package sim.components; import sim.Config; public class OutputPort extends Port { private Credit m_inputCredit; private OutputVC[] m_vcs; public OutputPort(Console console, int nodeId, int portNum, Link link, int numVCs) { super(console, nodeId, portNum, link); m_vcs = new OutputVC[numVCs]; for(int i=0; i<m_vcs.length; i++) m_vcs[i] = new OutputVC(portNum, i, console); m_inputCredit = null; } /* * Read a credit input and return it */ public Credit readInputCredit() { if(m_inputCredit != null) { Credit c = m_inputCredit; m_inputCredit = null; return c; } return null; } /* * Add a flit to an output VC */ public void addFlit(int outputVC, Flit flit) { m_vcs[outputVC].addFlit(flit); //console("O["+getPortNum()+":"+outputVC+"] added flit "+flit.toShortStr()); } /* * Pick the next active VC round-robin and send the queued flit. Also, increment the hop count */ public void writeOutputFlit() { for(int j=1; j<m_vcs.length+1; j++) { int index = (getCurrVC() + j) % m_vcs.length; if(m_vcs[index].isActive() && m_vcs[index].hasFlit()) { setCurrVC(index); Flit flit = m_vcs[getCurrVC()].takeFlit(); flit.incHops(); //System.out.println("Output port wrote flit on VC "+getCurrVC()); getLink().setInputFlit(flit); console("O["+getPortNum()+":"+getCurrVC()+"] wrote flit "+flit+" to link "+getLink().getId()); return; } } /*if(m_vcs[getCurrVC()].isActive() && m_vcs[getCurrVC()].hasFlit()) { Flit flit = m_vcs[getCurrVC()].takeFlit(); flit.incHops(); getLink().setInputFlit(flit); console("O["+getPortNum()+":"+getCurrVC()+"] wrote flit "+flit+" to link "+getLink().getId()); }*/ } /* * Allocate a virtual channel: one that is idle and has full credits, this * removes the possibility of a dependence between the current and waiting VCs * * The available number of virtual channels is bouned by a configuration parameter * for comparision of segment with lashtor */ public int allocVC() { for(int i=0; i<(int)Math.min(Config.availableVCs(), m_vcs.length); i++) { if(m_vcs[i].isIdle() && m_vcs[i].hasFullCredits()) { //System.out.println("OP "+getPortNum()+" allocated VC "+i); return i; } } return -1; } /* * Attempt to allocate a specific virtual channel */ public int allocVC(int vcIndex) { if(m_vcs[vcIndex].isIdle() && m_vcs[vcIndex].hasFullCredits()) { //System.out.println("OP "+getPortNum()+" allocated VC "+i); return vcIndex; } return -1; } public void reset() { for(OutputVC vc : m_vcs) vc.resetState(); m_inputCredit = null; setCurrVC(0); } public void incrementCredits(int vcIndex) { m_vcs[vcIndex].incCredits(); //console("Got credit for OP["+getPortNum()+":"+vcIndex+"]"); } public void setupConnection(int vcIndex, int inputPortNum, int inputVC) { m_vcs[vcIndex].setupConnection(inputPortNum, inputVC); } public String toString() { String s = ""; for(int i=0; i<m_vcs.length; i++) { //s += "O["+getPortNum()+":"+i+"]"+(getCurrVC()==i?"*":"")+"\t"+m_vcs[i]+"\n"; String port = "O["+getPortNum()+":"+i+"]"+(getCurrVC()==i?"*":""); s += String.format("%-12s%s\n", port, m_vcs[i].toString(getDownStreamNodeId(), getDownStreamNodePort())); } return s; } public int getDownStreamNodeId() { return getLink().getToPort().getNodeId(); } // could neaten this public int getDownStreamNodePort() { return getLink().getToPort().getPortNum(); } // could neaten this public int getConnectedInputPort(int vc) { return m_vcs[vc].getConnectedInputPort(); } public int getConnectedInputVC(int vc) { return m_vcs[vc].getConnectedInputVC(); } public void setCreditInput(Credit credit) { m_inputCredit = credit; } public boolean hasCredits(int vcIndex) { return !m_vcs[vcIndex].isWaitingCdt(); } public boolean isEmpty(int vcIndex) { return !m_vcs[vcIndex].hasFlit(); } }
java
21
0.640675
113
30.229008
131
starcoderdata
<?php /** * WasabiLib http://www.wasabilib.org * * @link https://github.com/WasabilibOrg/wasabilib * @license The MIT License (MIT) Copyright (c) 2015 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace WasabiLib\View; use Wasabi\Modal\Exception; /** * Class Button * @package WasabiLib\view * * @example * EXAMPLE 1: */ class Button extends WasabiViewModel { const ACTION = "action"; const PARAM = "param"; const DATA_HREF = "data-href"; const DATA_EVENT = "data-event"; const DATA_JSON = "data-json"; const TEXT = "text"; const EVENT_TYPE = "eventType"; const AJAX_ELEMENT_CLASS = "ajax_element"; const CLICK_EVENT = "click"; /** * Construct * * @param string $text The button text. */ public function __construct($text = "") { parent::__construct(); $this->setText($text); $this->setTemplate("view/button"); } /** * Sets the route to a controller action. * @param string $action */ public function setAction($action) { $this->setVariable(self::ACTION, $this->assembleAssignmentString(self::DATA_HREF, $action)); $this->setEventType(self::CLICK_EVENT); $this->addClass(self::AJAX_ELEMENT_CLASS); if(!$this->getId()) { $this->setId("button_".floor(rand(0, 1000))); } } /** * Returns the route to a controller action. * @return string */ public function getAction() { return $this->extractValueFromAssignmentString($this->getVariable(self::ACTION)); } /** * Sets the button text. * @param string $text */ public function setText($text) { $this->setVariable(self::TEXT, $text); } /** * Returns the button text. * @return string */ public function getText() { return $this->getVariable(self::TEXT); } /** * Sets the event type of the button. Default is "click". * @param string $eventType */ public function setEventType($eventType) { $this->setVariable(self::EVENT_TYPE, $this->assembleAssignmentString(self::DATA_EVENT, $eventType)); } /** * Returns the event type of the button. Default is "click". * @return string */ public function getEventType() { return $this->extractValueFromAssignmentString($this->getVariable(self::EVENT_TYPE)); } /** * Sets an optional parameter which is send to the server if the by the event type specified event occurred. * @param string $paramJsonString */ public function setParam($paramJsonString) { $this->setVariable(self::PARAM, $this->assembleAssignmentString(self::DATA_JSON, $paramJsonString)); } /** * Returns the optional parameter which is send to the server if the by the event type specified event occurred. * @return string */ public function getParam() { return $this->extractValueFromAssignmentString($this->getVariable(self::PARAM)); } }
php
18
0.642254
116
28.840336
119
starcoderdata
module.exports = { root: true, parser: "@typescript-eslint/parser", parserOptions: { tsconfigRootDir: __dirname, project: ["./packages/**/tsconfig.json"], }, plugins: ["@typescript-eslint", "eslint-plugin-jsdoc", "node", "import"], extends: [ // Core eslint recommended rules. "eslint:recommended", // Override those with TypeScript versions, where necessary. "plugin:@typescript-eslint/eslint-recommended", // Core TypeScript recommended rules - syntax only. "plugin:@typescript-eslint/recommended", // Core TypeScript recommended rules - full type checking. "plugin:@typescript-eslint/recommended-requiring-type-checking", "plugin:import/errors", "plugin:import/warnings", "plugin:import/typescript", // // JSDoc recommended // "plugin:jsdoc/recommended", ], rules: { // Importing any package in the project will likely work in dev because // of the symlinks that yarn workspaces creates in the root node_modules. // We can't prevent that, but we can tell eslint to fail. // (This rule is poorly named. It should be "no-implicit-import".) "node/no-extraneous-import": "error", // Be explicit when you must, but return type is usually inferred correctly. "@typescript-eslint/explicit-function-return-type": "off", // Avoid using "any" or "as any" wherever possible, but this is too onerous. "@typescript-eslint/no-explicit-any": "off", // Avoid foo!.bar wherever possible, but this is too onerous. "@typescript-eslint/no-non-null-assertion": "off", // Clean up unused vars before committing, but this is too onerous during dev. "@typescript-eslint/no-unused-vars": "warn", "@typescript-eslint/no-var-requires": ["off"], "@typescript-eslint/no-empty-interface": ["off"], "@typescript-eslint/ban-ts-ignore": ["off"], "@typescript-eslint/explicit-function-return-type": ["off"], "@typescript-eslint/no-empty-function": ["off"], "@typescript-eslint/no-unused-expressions": ["off"], "@typescript-eslint/no-unsafe-assignment": ["off"], "@typescript-eslint/no-unsafe-member-access": ["off"], "@typescript-eslint/no-unsafe-call": ["off"], "@typescript-eslint/no-unsafe-return": ["off"], "@typescript-eslint/restrict-template-expressions": ["off"], "@typescript-eslint/explicit-module-boundary-types": ["off"], "no-empty": ["off"], "require-await": "off", "@typescript-eslint/require-await": "off", "comma-dangle": ["warn", "always-multiline"], "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }], "@typescript-eslint/no-floating-promises": ["off"], "@typescript-eslint/no-misused-promises": ["off"], "no-async-promise-executor": "off", quotes: ["warn", "double", { allowTemplateLiterals: true, avoidEscape: true }], semi: ["error", "always"], "import/order": [ 1, { groups: ["builtin", "external", "internal", "parent", "sibling", "index"], "newlines-between": "always", }, ], "require-jsdoc": [ 1, { require: { FunctionDeclaration: true, MethodDefinition: false, ClassDeclaration: false, ArrowFunctionExpression: true, }, }, ], }, };
javascript
12
0.640436
83
36.123596
89
starcoderdata
mai=men=0 lista=[] for c in range (0,5): lista.append(int(input(f'digite um numero na posição {c} :'))) if c==0: mai=men=lista[c] else: if lista[c] > mai: mai=lista[c] if lista[c] < men: men = lista[c] print(f'\033[34mo maior numero é {mai} nas posiçoes :',end='') for i, v in enumerate (lista): if v==mai: print(f'{i}...',end='') print(f'\n\033[33mmenor valor é {men} nas posições :',end='') for i,v in enumerate (lista): if v == men: print(f'{i}...',end='') print(f'\033[31m\nvocê digitou os numeros {lista}:')
python
12
0.550079
66
28.952381
21
starcoderdata
namespace Clockwise { public enum CircuitBreakerState { /// /// Closed state meansthe circuit is available for work /// Closed = 0, /// /// Open state means the circuit is unavailable for work /// Open, /// /// HalfOpen state means that the circuit is partially able to work. /// Tshis could mean that the underlying resource is partially recovered. /// HalfOpen } }
c#
6
0.564103
81
27.789474
19
starcoderdata
package com.github.kwoin.kgate.core.command.chain; import com.github.kwoin.kgate.core.command.ICommand; import com.github.kwoin.kgate.core.message.Message; import com.github.kwoin.kgate.core.session.Session; import java.io.IOException; /** * @author */ public class Chain<T extends Message> implements ICommand { protected boolean interrupted; protected Iterable commands; public Chain(Iterable commands) { this.commands = commands; interrupted = false; } @Override public void execute(Session session, Chain callingChain, T message) throws IOException { for (ICommand command : commands) { command.execute(session, this, message); if(interrupted) { if(callingChain != null) callingChain.interrupt(); break; } } } public void interrupt() { interrupted = true; } }
java
13
0.59369
62
18.018182
55
starcoderdata
def create(self): """Create the network graph.""" # 1st Layer: Conv -> norm -> ReLu conv1 = conv(self.X, 3, 3, 64, 1, 1, padding='SAME', name='conv1') norm1 = lrn(conv1, 2, 1e-04, 0.75, name='norm1', phase=self.phase) # Apply relu function relu1 = tf.nn.relu(norm1) # 2st Layer: Conv -> norm -> ReLu conv2 = conv(relu1, 3, 3, 64, 1, 1, padding='SAME', name='conv2') norm2 = lrn(conv2, 2, 1e-04, 0.75, name='norm2', phase=self.phase) # Apply relu function relu2 = tf.nn.relu(norm2) pool2 = tf.nn.max_pool(relu2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') # 3st Layer: Conv -> norm -> ReLu conv3 = conv(pool2, 3, 3, 128, 1, 1, padding='SAME', name='conv3') norm3 = lrn(conv3, 2, 1e-04, 0.75, name='norm3', phase=self.phase) # Apply relu function relu3 = tf.nn.relu(norm3) # 4st Layer: Conv -> norm -> ReLu conv4 = conv(relu3, 3, 3, 128, 1, 1, padding='SAME', name='conv4') norm4 = lrn(conv4, 2, 1e-04, 0.75, name='norm4', phase=self.phase) # Apply relu function relu4 = tf.nn.relu(norm4) pool4 = tf.nn.max_pool(relu4, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME') # 5st Layer: Conv -> norm -> ReLu conv5 = conv(pool4, 3, 3, 128, 1, 1, padding='SAME', name='conv5') norm5 = lrn(conv5, 2, 1e-04, 0.75, name='norm5', phase=self.phase) # Apply relu function relu5 = tf.nn.relu(norm5) # 6st Layer: Conv -> norm -> ReLu conv6 = conv(relu5, 3, 3, 128, 1, 1, padding='SAME', name='conv6') norm6 = lrn(conv6, 2, 1e-04, 0.75, name='norm6', phase=self.phase) # Apply relu function relu6 = tf.nn.relu(norm6) pool6 = tf.nn.avg_pool(relu6, ksize=[1, 4, 4, 1], strides=[1, 4, 4, 1], padding='SAME') flattened = tf.reshape(pool6, [-1, 128 * 4]) self.fc7 = fc(flattened, 128 * 4, self.NUM_CLASSES, name='fc7')
python
9
0.499545
74
41.326923
52
inline
#include "sys.h" #include "usart.h" #if SYSTEM_SUPPORT_OS #include "includes.h" #endif #if 1 #pragma import(__use_no_semihosting) struct __FILE { int handle; }; FILE __stdout; void _sys_exit(int x) { x = x; } int fputc(int ch, FILE *f) { while((USART1->SR&0X40)==0); USART1->DR = (u8) ch; return ch; } #endif u8 USART_RX_BUF[USART_REC_LEN]; u16 USART_RX_STA=0; u8 aRxBuffer[RXBUFFERSIZE]; UART_HandleTypeDef huart1; void uart_init(u32 bound) { huart1.Instance=USART1; huart1.Init.BaudRate=bound; huart1.Init.WordLength=UART_WORDLENGTH_8B; huart1.Init.StopBits=UART_STOPBITS_1; huart1.Init.Parity=UART_PARITY_NONE; huart1.Init.HwFlowCtl=UART_HWCONTROL_NONE; huart1.Init.Mode=UART_MODE_TX_RX; HAL_UART_Init(&huart1); HAL_UART_Receive_IT(&huart1, (u8 *)aRxBuffer, RXBUFFERSIZE); } void HAL_UART_MspInit(UART_HandleTypeDef *huart) { GPIO_InitTypeDef GPIO_Initure; if(huart->Instance==USART1) { __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_USART1_CLK_ENABLE(); __HAL_RCC_AFIO_CLK_ENABLE(); GPIO_Initure.Pin=GPIO_PIN_9; GPIO_Initure.Mode=GPIO_MODE_AF_PP; GPIO_Initure.Pull=GPIO_PULLUP; GPIO_Initure.Speed=GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOA,&GPIO_Initure); GPIO_Initure.Pin=GPIO_PIN_10; GPIO_Initure.Mode=GPIO_MODE_AF_INPUT; HAL_GPIO_Init(GPIOA,&GPIO_Initure); #if EN_USART1_RX HAL_NVIC_EnableIRQ(USART1_IRQn); HAL_NVIC_SetPriority(USART1_IRQn,3,3); #endif } }
c
10
0.644559
61
19.706667
75
starcoderdata
<?php /** * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * @package fusionLib * @copyright Copyright (c) 2018 fusionLib. All rights reserved. * @link http://fusionlib.com */ /** * flStrideParagraph Class * * Class to define a stride paragraph. * * @package fusionLib */ class flStrideParagraph extends flStrideNode { /** * @inheritdoc */ function toJSON() { return [ 'type' => 'paragraph', 'content' => parent::toJSON() ]; } /** * Add text. * * @param string $text Text to add. * @param flStrideMarks $marks Optional marks to add to the text. * @return flStrideParagraph The paragraph object. */ function text($text, $marks = null) { $this->nodes[] = new flStrideText($text, $marks); return $this; } /** * Add bold text. * * @param string $text Text to add. * @return flStrideParagraph The paragraph object. */ function strong($text) { return $this->text($text, (new flStrideMarks())->strong()); } /** * Add italic text. * * @param string $text Text to add. * @return flStrideParagraph The paragraph object. */ function em($text) { return $this->text($text, (new flStrideMarks())->em()); } /** * Add code. * * @param string $text Text to add. * @return flStrideParagraph The paragraph object. */ function code($text) { return $this->text($text, (new flStrideMarks())->code()); } /** * Add a link. * * @param string $text Anchor text. * @param string $href The link target. * @return flStrideParagraph The paragraph object. */ function link($text, $href) { return $this->text($text, (new flStrideMarks())->link($href)); } /** * Add an emoji. * * @param string $shortName The name of the emoji. * @return flStrideParagraph The paragraph object. */ function emoji($shortName) { $this->nodes[] = new flStrideEmoji($shortName); return $this; } /** * Add a heard break. * * @return flStrideParagraph The paragraph object. */ function hardBreak() { $this->nodes[] = new flStrideHardBreak(); return $this; } /** * Add a mention. * * @param string $id The account id. * @param string $text The textual name including the leading @. * @return flStrideParagraph The paragraph object. */ function mention($id, $text) { $this->nodes[] = new flStrideMention($id, $text); return $this; } }
php
13
0.647754
71
20.508475
118
starcoderdata
import argparse import mxnet as mx from mxnet import gluon from rcnn import FasterRCNN from rcnn.metrics.voc_detection import VOC07MApMetric from dataset import VOCDetection from utils.logger import logger from utils.config import default, generate_config from dataset.dataloader import DetectionDataLoader from rcnn.transforms import FasterRCNNDefaultValTransform import os import logging from tqdm import tqdm def test_faster_rcnn(net, test_data, cfg): """Test on dataset.""" logger.info('Config for testing FasterRCNN:\n%s' % cfg) if cfg.hybridize: net.hybridize() metric = VOC07MApMetric(iou_thresh=0.5, class_names=cfg.classes) with tqdm(total=cfg.dataset_size) as pbar: for batch in test_data: pred_bboxes = [] pred_cls = [] pred_scores = [] gt_bboxes = [] gt_cls = [] gt_difficults = [] # Split and load data for multi-gpu data_list = gluon.utils.split_and_load(batch[0], ctx_list=ctx, batch_axis=0) gt_box_list = gluon.utils.split_and_load(batch[1], ctx_list=ctx, batch_axis=0) im_info_list = gluon.utils.split_and_load(batch[2], ctx_list=ctx, batch_axis=0) for data, gt_box, im_info in zip(data_list, gt_box_list, im_info_list): # get prediction results cls, scores, bboxes = net(data, im_info) pred_cls.append(cls) pred_scores.append(scores) pred_bboxes.append(bboxes) # split ground truths gt_cls.append(gt_box.slice_axis(axis=-1, begin=4, end=5)) gt_bboxes.append(gt_box.slice_axis(axis=-1, begin=0, end=4)) gt_difficults.append(gt_box.slice_axis(axis=-1, begin=5, end=6) if gt_box.shape[-1] > 5 else None) # update metric metric.update(pred_bboxes, pred_cls, pred_scores, gt_bboxes, gt_cls, gt_difficults) pbar.update(batch[0].shape[0]) return metric.get() def get_dataset(dataset, dataset_path): if dataset.lower() == 'voc': dataset = VOCDetection(splits=[(2007, 'test')], transform=FasterRCNNDefaultValTransform(cfg.image_size, cfg.image_max_size, cfg.image_mean, cfg.image_std), root=dataset_path, preload_label=True) else: raise NotImplementedError('Dataset: {} not implemented.'.format(dataset)) return dataset def get_dataloader(dataset, cfg): """Get dataloader.""" loader = DetectionDataLoader(dataset, cfg.batch_size, False, last_batch='keep', num_workers=cfg.num_workers) return loader def parse_args(): parser = argparse.ArgumentParser(description='Test Faster RCNN') parser.add_argument('--network', type=str, default=default.network, help='network name') parser.add_argument('--dataset', type=str, default=default.dataset, help='dataset name') parser.add_argument('--dataset-path', default=default.dataset_path, type=str, help='dataset path') parser.add_argument('--model-params', type=str, default=default.model_params, help='model params path') parser.add_argument('--gpus', nargs='*', type=int, default=default.gpus, help='testing with GPUs, such as --gpus 0 1 ') return parser.parse_args() if __name__ == '__main__': # set 0 to disable Running performance tests # cmd: set MXNET_CUDNN_AUTOTUNE_DEFAULT=0 args = parse_args() cfg = generate_config(vars(args)) log_file_path = cfg.save_prefix + '_test.log' log_dir = os.path.dirname(log_file_path) if log_dir and not os.path.exists(log_dir): os.makedirs(log_dir) fh = logging.FileHandler(log_file_path) logger.addHandler(fh) # testing contexts ctx = [mx.gpu(int(i)) for i in cfg.gpus] ctx = ctx if ctx else [mx.cpu()] num_anchors = len(cfg.anchor_scales) * len(cfg.anchor_ratios) test_dataset = get_dataset(cfg.dataset, cfg.dataset_path) test_data = get_dataloader(test_dataset, cfg) cfg.dataset_size = len(test_dataset) cfg.num_classes = len(test_dataset.classes) cfg.classes = test_dataset.classes net = FasterRCNN(network=cfg.network, pretrained_base=False, batch_size=cfg.batch_size, num_classes=cfg.num_classes, scales=cfg.anchor_scales, ratios=cfg.anchor_ratios, feature_stride=cfg.feature_stride, allowed_border=cfg.allowed_border, rpn_batch_size=cfg.rpn_batch_size, rpn_fg_fraction=cfg.rpn_fg_fraction, rpn_positive_threshold=cfg.rpn_positive_threshold, rpn_negative_threshold=cfg.rpn_negative_threshold, rpn_pre_nms_top_n=cfg.rpn_test_pre_nms_top_n, rpn_post_nms_top_n=cfg.rpn_test_post_nms_top_n, rpn_nms_threshold=cfg.rpn_nms_threshold, rpn_min_size=cfg.rpn_min_size, roi_batch_size=cfg.roi_batch_size, roi_fg_fraction=cfg.roi_fg_fraction, roi_fg_threshold=cfg.roi_fg_threshold, roi_bg_threshold_hi=cfg.roi_bg_threshold_hi, roi_bg_threshold_lo=cfg.roi_bg_threshold_lo, bbox_nms_threshold=cfg.bbox_nms_threshold, bbox_nms_top_n=cfg.bbox_nms_top_n, bbox_mean=cfg.bbox_mean, bbox_std=cfg.bbox_std) net.load_parameters(cfg.model_params.strip(), ctx=ctx) map_name, mean_ap = test_faster_rcnn(net, test_data, cfg) result_msg = '\n'.join(['%s=%f' % (k, v) for k, v in zip(map_name, mean_ap)]) logger.info('[Done] Test Results: \n%s' % result_msg)
python
17
0.613098
120
43.175573
131
starcoderdata
"""Slack bot that grabs the source of Slack posts.""" import hmac import json import os from hashlib import sha256 from http import HTTPStatus from sys import stderr from time import time, perf_counter from typing import Any, Dict, Tuple import flask from requests import Session TIMEOUT_POST_MESSAGE = float(os.getenv('TIMEOUT_POST_MESSAGE') or 3) TIMEOUT_GET_POST_SOURCE = float(os.getenv('TIMEOUT_GET_POST_SOURCE') or 3) _session = Session() # The following verification methods are based on: # - https://api.slack.com/docs/verifying-requests-from-slack#step-by-step_walk-through_for_validating_a_request # - https://github.com/slackapi/python-slack-events-api/blob/master/slackeventsapi/server.py def _is_valid_timestamp(timestamp: str) -> bool: """Checks if the given timestamp is at most five minutes from local time.""" return abs(time() - int(timestamp)) <= 60 * 5 def _is_valid_request_body(request_body: bytes, timestamp: str, signature: str) -> bool: """Verifies the contents of a Slack request against a signature.""" signing_secret = os.environ['SLACK_SIGNING_SECRET'] req = str.encode(f'v0:{timestamp}:') + request_body request_hash = hmac.new(str.encode(signing_secret), req, sha256) return hmac.compare_digest('v0=' + request_hash.hexdigest(), signature) def _is_valid_request(request: flask.Request) -> bool: """Verifies the timestamp and signature of an incoming Slack request.""" timestamp = request.headers.get('X-Slack-Request-Timestamp') if not _is_valid_timestamp(timestamp): # This could be a replay attack, so let's ignore it. print('Invalid timestamp', file=stderr) return False signature = request.headers.get('X-Slack-Signature') if not _is_valid_request_body(request.get_data(), timestamp, signature): print('Invalid signature', file=stderr) return False return True def _split_upto_newline(source: str, maxlen: int) -> Tuple[str, str]: """Splits a string in two, limiting the length of the first part. Splits the given string in two, such that the first part (segment) contains at most `maxlen` characters. If the source string contains a line break ('\\n') at or before maxlen, the string is split at the newline, and the newline character itself is not included in either the source or maxlen. This ensures that source code is split as cleanly as possible. Args: source: String to split. maxlen: Maximum number of characters allowed in the segment part. Returns: Tuple of (segment, remainder). If the source text has less characters than max_pos, the remainder contains the empty string (''). """ assert maxlen >= 0, f'maxlen must be nonnegative (value={maxlen!r})' split_current = split_next = maxlen if len(source) > maxlen: last_newline_pos = source.rfind('\n', 0, maxlen + 1) if last_newline_pos != -1: split_current = last_newline_pos split_next = last_newline_pos + 1 return source[:split_current], source[split_next:] def _send_response(response_url: str, text: str) -> None: """Sends text in an ephemeral message to a response URL provided by Slack. Args: response_url: URL provided by a Slack interaction request. text: Text to send """ payload = {'text': text, 'response_type': 'ephemeral'} _session.post(response_url, json=payload, timeout=TIMEOUT_POST_MESSAGE) def _send_source_message(response_url: str, heading: str, source: str) -> None: """Sends an ephemeral message containing the source of a message or post. If the source string is too long to fit in a single message, it will be split into up to 5 messages. Any remaining string after that is truncated. Args: response_url: URL provided by a Slack interaction request. heading: Heading text displayed above the source text. source: Source text of a Slack message or post. """ MAX_TEXT_LENGTH = 40000 boilerplate = f'{heading}:\n```{{source}}```' boilerplate_length = len(boilerplate.format(source='')) if len(source) <= MAX_TEXT_LENGTH - boilerplate_length: text = boilerplate.format(source=source) _send_response(response_url, text) else: boilerplate = f'{heading} ({{i}} of {{count}}):\n```{{source}}```' boilerplate_length = len(boilerplate.format(i=0, count=0, source='')) segments = [] while source and len(segments) < 5: segment, source = _split_upto_newline( source, MAX_TEXT_LENGTH - boilerplate_length ) segments.append(segment) for i, segment in enumerate(segments): text = boilerplate.format( i=i + 1, count=len(segments), source=segment ) _send_response(response_url, text) def _is_slack_post(file_info: dict) -> bool: """Checks if the file type is a valid Slack post.""" return file_info['filetype'] in ('post', 'space', 'docs') def _on_view_message_source(message: Dict[str, Any], response_url: str) -> None: """Responds to a view_message_source request. Args: message: The original message, parsed as JSON. response_url: URL provided by a Slack interaction request. """ counter_begin = perf_counter() source = json.dumps(message, indent=2, ensure_ascii=False) _send_source_message(response_url, 'Raw JSON of message', source) time_spent = perf_counter() - counter_begin print(f'view_message_source: Took {time_spent * 1000:.4f} ms') def _on_view_post_source(message: Dict[str, Any], response_url: str) -> None: """Responds to a view_post_source request. Args: message: The original message, parsed as JSON. response_url: URL provided by a Slack interaction request. """ counter_begin = perf_counter() attached_files = message.get('files', []) slack_post = next(filter(_is_slack_post, attached_files), None) if slack_post: token = os.environ['SLACK_OAUTH_TOKEN'] response = _session.get( slack_post['url_private'], headers={'Authorization': f'Bearer {token}'}, timeout=TIMEOUT_GET_POST_SOURCE, ) post_json = response.json() source = post_json.get('full') if not source: source = json.dumps(post_json, indent=2, ensure_ascii=False) _send_source_message(response_url, 'Raw source of post', source) else: _send_response(response_url, 'Error: Not a Slack post') time_spent = perf_counter() - counter_begin print(f'view_post_source: Took {time_spent * 1000:.4f} ms') def on_request(request: flask.Request) -> Any: """Handles an interaction event request sent by Slack. Args: request: The Flask Request object. Returns: Response text or object to be passed to `make_response()`. """ if request.method != 'POST': return 'Only POST requests are accepted', HTTPStatus.METHOD_NOT_ALLOWED if not _is_valid_request(request): return '', HTTPStatus.FORBIDDEN # Interaction event data is sent as JSON in the `payload` parameter, using # application/x-www-form-urlencoded format payload_str = request.values['payload'] payload = json.loads(payload_str) assert payload['type'] == 'message_action', ( f'Unexpected payload type received, see contents: {payload_str}' ) # slackclient v2.1.0 does not provide a convenience class for message # actions, so manually access the JSON fields callback_id = payload['callback_id'] original_message = payload['message'] response_url = payload['response_url'] if callback_id == 'view_message_source': _on_view_message_source(original_message, response_url) elif callback_id == 'view_post_source': _on_view_post_source(original_message, response_url) else: assert 0, f'Unexpected callback ID: {callback_id}' return '', HTTPStatus.OK
python
15
0.660634
111
35.919283
223
starcoderdata
import pygame from population import Population from pre_game_state import PreGameState def life_game(width, height): pygame.init() screen_scale = 4 screen = pygame.display.set_mode((width * screen_scale, height * screen_scale)) population = Population(width, height) clock = pygame.time.Clock() state = PreGameState(population, width, height, screen_scale) while True: screen.fill((100, 100, 100)) state = state.update(clock) if state is None: return population.draw(screen, width, height) pygame.display.flip() if __name__ == "__main__": life_game(320, 200)
python
9
0.641654
83
22.321429
28
starcoderdata
[NoTrace] private async Task<string> ReadRequestAsync(HttpRequest request) { if (request.ContentLength == null || request.ContentLength == 0) { return string.Empty; } // Allows streams to be read multiple times. request.EnableRewind(); // Read the request. byte[] requestBuffer = new byte[request.ContentLength.Value]; await request.Body.ReadAsync(requestBuffer, 0, requestBuffer.Length).ConfigureAwait(false); string requestBody = Encoding.UTF8.GetString(requestBuffer); request.Body.Position = 0; return requestBody; }
c#
13
0.585366
103
32.238095
21
inline
namespace Twining { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Twining.Commands; using Twining.Commands.Window; public static class WindowCommands { static WindowCommands() { WindowCommands.Close = new CloseCommand(); WindowCommands.Maximize = new MaximizeCommand(); WindowCommands.Minimize = new MinimizeCommand(); WindowCommands.Restore = new RestoreCommand(); WindowCommands.ShowSystemMenu = new ShowSystemMenuCommand(); } public static ICommand Close { get; private set; } public static ICommand Maximize { get; private set; } public static ICommand Minimize { get; private set; } public static ICommand Restore { get; private set; } public static ICommand ShowSystemMenu { get; private set; } } }
c#
9
0.652653
72
28.382353
34
starcoderdata
/* * nimbus-jose-jwt * * Copyright 2012-2016, Connect2id Ltd and contributors. * * 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.nimbusds.jose.crypto.impl; import java.security.AlgorithmParameters; import java.security.PrivateKey; import java.security.Provider; import java.security.interfaces.RSAPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.MGF1ParameterSpec; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.SecretKey; import javax.crypto.spec.OAEPParameterSpec; import javax.crypto.spec.PSource; import javax.crypto.spec.SecretKeySpec; import com.nimbusds.jose.JOSEException; import net.jcip.annotations.ThreadSafe; /** * RSAES OAEP (SHA-256) methods for Content Encryption Key (CEK) encryption and * decryption. Uses the BouncyCastle.org provider. This class is thread-safe * * @author * @author * @version 2017-11-27 */ @ThreadSafe public class RSA_OAEP_256 { /** * The JCA algorithm name for RSA-OAEP-256. */ private static final String RSA_OEAP_256_JCA_ALG = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; /** * Encrypts the specified Content Encryption Key (CEK). * * @param pub The public RSA key. Must not be {@code null}. * @param cek The Content Encryption Key (CEK) to encrypt. Must * not be {@code null}. * @param provider The JCA provider, or {@code null} to use the default * one. * * @return The encrypted Content Encryption Key (CEK). * * @throws JOSEException If encryption failed. */ public static byte[] encryptCEK(final RSAPublicKey pub, final SecretKey cek, final Provider provider) throws JOSEException { try { AlgorithmParameters algp = AlgorithmParametersHelper.getInstance("OAEP", provider); AlgorithmParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); algp.init(paramSpec); Cipher cipher = CipherHelper.getInstance(RSA_OEAP_256_JCA_ALG, provider); cipher.init(Cipher.ENCRYPT_MODE, pub, algp); return cipher.doFinal(cek.getEncoded()); } catch (IllegalBlockSizeException e) { throw new JOSEException("RSA block size exception: The RSA key is too short, try a longer one", e); } catch (Exception e) { // java.security.NoSuchAlgorithmException // java.security.NoSuchPaddingException // java.security.InvalidKeyException // javax.crypto.BadPaddingException throw new JOSEException(e.getMessage(), e); } } /** * Decrypts the specified encrypted Content Encryption Key (CEK). * * @param priv The private RSA key. Must not be {@code null}. * @param encryptedCEK The encrypted Content Encryption Key (CEK) to * decrypt. Must not be {@code null}. * @param provider The JCA provider, or {@code null} to use the * default one. * * @return The decrypted Content Encryption Key (CEK). * * @throws JOSEException If decryption failed. */ public static SecretKey decryptCEK(final PrivateKey priv, final byte[] encryptedCEK, final Provider provider) throws JOSEException { try { AlgorithmParameters algp = AlgorithmParametersHelper.getInstance("OAEP", provider); AlgorithmParameterSpec paramSpec = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT); algp.init(paramSpec); Cipher cipher = CipherHelper.getInstance(RSA_OEAP_256_JCA_ALG, provider); cipher.init(Cipher.DECRYPT_MODE, priv, algp); return new SecretKeySpec(cipher.doFinal(encryptedCEK), "AES"); } catch (Exception e) { // java.security.NoSuchAlgorithmException // java.security.NoSuchPaddingException // java.security.InvalidKeyException // javax.crypto.IllegalBlockSizeException // javax.crypto.BadPaddingException throw new JOSEException(e.getMessage(), e); } } /** * Prevents public instantiation. */ private RSA_OAEP_256() { } }
java
13
0.721906
133
33.398496
133
starcoderdata
package net.robinfriedli.botify.entities.xml; import javax.annotation.Nullable; import net.robinfriedli.botify.discord.property.AbstractGuildProperty; import net.robinfriedli.jxp.collections.NodeList; import net.robinfriedli.jxp.persist.Context; import org.w3c.dom.Element; public class GuildPropertyContribution extends GenericClassContribution { // invoked by JXP @SuppressWarnings("unused") public GuildPropertyContribution(Element element, NodeList childNodes, Context context) { super(element, childNodes, context); } @Nullable @Override public String getId() { return getProperty(); } public String getProperty() { return getAttribute("property").getValue(); } public String getName() { return getAttribute("name").getValue(); } public String getDefaultValue() { return getAttribute("defaultValue").getValue(); } public String getUpdateMessage() { return getAttribute("updateMessage").getValue(); } }
java
10
0.713352
96
25.121951
41
starcoderdata
public class Help { public static void printHelp() { System.out.println("***********************************************************************************************"); System.out.println(" HttpRequest [URL] Information and Examples: "); System.out.println(" HttpRequest will use the given url to pull down the information stored there \n"); System.out.println(" java Sak -HttpRequest https://www.lewisu.edu/ \n"); System.out.println(" HttpRequest [URL] Information and Examples: "); System.out.println(" HttpRequestIndex will use the give Json index and pull all information in that index \n"); System.out.println(" java Sak -HttpRequestIndex https://thunderbird-index-sp22.azurewebsites.net/index-w0a6zk195d\n"); System.out.println("***********************************************************************************************"); } }
java
9
0.456059
126
89.083333
12
starcoderdata
#ifndef GAMEFUNCTIONS_H #define GAMEFUNCTIONS_H #include "PlaceClass.hpp" int getNumberOfPlayers(string N); void initializeChance(unordered_map<int, string> &Chance); void initializeCommunityChest(unordered_map<int, string> &CommunityChest); void initializePlaces(vector &board); void constructBoard(vector &AJ, vector &board, vector &players, unordered_map<string, long> &moneyowned, int n, unordered_map<int, string> &Chance, unordered_map<int, string> &CommunityChest); #endif
c++
12
0.775221
135
30.444444
18
starcoderdata
package test.db; /** * Created by Drapegnik on 5/25/17. */ import test.config.Options; import test.models.Student; import java.sql.*; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * for connecting to database * * @author * @version 1.0 */ public class Driver { private Connection conn = null; private Statement stmt = null; private PreparedStatement pstmt = null; private ResultSet res = null; private String sql; private static String StudentsTable = Student.class.getSimpleName(); /** * SQL requests */ private static final String CREATE_STUDENT = MessageFormat.format( "INSERT INTO {0} (id, s_name, s_group, s_average, s_is_villager) VALUES(?, ?, ?, ?, ?);", StudentsTable); private static final String GET_STUDENTS = MessageFormat.format( "SELECT * FROM {0}", StudentsTable); private static final String GET_STUDENTS_COUNT = MessageFormat.format( "SELECT COUNT(id) as size FROM {0}", StudentsTable); /** * Wrapper on {@link Driver#connect()} * * @see Driver#connect() */ public Driver() { connect(); } /** * Create new database connection * * @see Options#JDBC_DRIVER * @see Options#DB_URL * @see Options#DB_USER * @see Options#DB_PASS */ private void connect() { try { Class.forName(Options.JDBC_DRIVER); System.out.println("[dbDriver] Connecting to database..."); conn = DriverManager.getConnection(Options.DB_URL + Options.DB_NAME, Options.DB_USER, Options.DB_PASS); stmt = conn.createStatement(); System.out.println("[dbDriver] Successfully connect to " + conn.getMetaData().getURL()); } catch (Exception se) { System.out.println("[dbDriver] Some problem with test.db connection"); se.printStackTrace(); System.exit(1); } } /** * Create table * * @see Options#DB_NAME */ private void createTable(String tableName, String sql) { System.out.println("[dbDriver] Creating table..."); try { stmt.executeUpdate(sql); System.out.println("Table '" + Options.DB_NAME + "." + tableName + "' created successfully."); } catch (Exception se) { se.printStackTrace(); } } /** * Create {@link Student}s table * * @see Driver#createTable(String, String) * @see Options#DB_NAME */ public void createStudentsTable() { String sql = "CREATE TABLE " + StudentsTable + "(id VARCHAR(255) not NULL, " + " s_name VARCHAR(255), " + " s_group INTEGER, " + " s_average DOUBLE, " + " s_is_villager BOOL, " + " PRIMARY KEY ( id ))"; createTable(Student.class.getSimpleName(), sql); } /** * Drop database if exist, and create new * * @see Options#DB_NAME */ private void dropDB() { try { System.out.println("[dbDriver] Drop database..."); sql = "DROP DATABASE IF EXISTS " + Options.DB_NAME; stmt.executeUpdate(sql); System.out.println("[dbDriver] Creating database..."); sql = "CREATE DATABASE " + Options.DB_NAME; stmt.executeUpdate(sql); System.out.println("[dbDriver] Database '" + Options.DB_NAME + "' created successfully."); } catch (Exception se) { se.printStackTrace(); } } /** * Insert {@link Student} object into table * * @param student {@link Student} instance */ public void createStudent(Student student) { try { pstmt = conn.prepareStatement(CREATE_STUDENT); pstmt.setString(1, student.getId()); pstmt.setString(2, student.getName()); pstmt.setInt(3, student.getGroup()); pstmt.setDouble(4, student.getAverageGrade()); pstmt.setBoolean(5, student.getIsVillager()); pstmt.executeUpdate(); } catch (Exception se) { se.printStackTrace(); } } /** * Select all {@link Student}'s objects from test.db * * @return ArrayList {@link Student}'s objects */ public ArrayList getStudents() { System.out.println("[dbDriver] Select students..."); ArrayList data = new ArrayList<>(); try { res = stmt.executeQuery(GET_STUDENTS); HashMap<String, Student> map = new HashMap<>(); while (res.next()) { String id = res.getString("id"); Student st = map.get(id); if (st == null) { st = new Student( id, res.getString("s_name"), res.getInt("s_group"), res.getDouble("s_average"), res.getBoolean("s_is_villager") ); } if (Options.DEBUG) { System.out.println("\t#" + res.getRow() + "\t" + st.getName() + "\t" + st.getAverageGrade() + "\t" + st.getGroup() + "\t" + st.getId()); } data.add(st); } System.out.println("[dbDriver] Successfully select " + data.size() + " students."); } catch (Exception se) { se.printStackTrace(); } return data; } public int getStudentCount() { int size = 0; System.out.println("[dbDriver] Get students count..."); try { res = stmt.executeQuery(GET_STUDENTS_COUNT); while (res.next()) { size = res.getInt("size"); } System.out.println("[dbDriver] " + size); return size; } catch (Exception se) { se.printStackTrace(); } return 1; } public void initDB(ArrayList data) { System.out.println("[dbDriver] Init database..."); for (Student student : data) { System.out.println('\t' + student.toString()); createStudent(student); } } /** * Drop database if exist, and create new * Create all tables * * @see Driver#dropDB() * @see Driver#createStudentsTable() * @see Driver#createMarkTable() * @see Options#DB_NAME */ public void createDB() { dropDB(); connect(); createStudentsTable(); } private void close() { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { System.out.println(se2.getMessage()); } try { if (pstmt != null) pstmt.close(); } catch (SQLException se2) { System.out.println(se2.getMessage()); } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } System.out.println("[dbDriver] Close test.db connection... Goodbye!"); } public static void main(String[] args) { Driver db = new Driver(); db.createDB(); db.initDB(Student.generateFakeData()); db.getStudents(); db.getStudentCount(); db.close(); } }
java
25
0.517772
117
28.422053
263
starcoderdata
"""This module contains a video specific speech-to-text-converter for large video files""" import wave import math import contextlib import speech_recognition as sr from moviepy.editor import AudioFileClip banner = r''' `-ohdy- .-:/:-:+ydd- -+yddy+-....../o. `-:/+shdddddhs/.````` ./oy+----.-:oyhhyo/. .-+dmddddho:..````..` `:::/:--:+yddhhhy+.`` .:ohddds/-....../o/-` .-:/:+shddddhyo:```` `-+yho/---..-:oyys+:. `.:+ydmdddhy+-.`````.` ``..-`````+. -/://--:oyhhhhs+-` ``.-.`````osyyy/`.../h+ :hosoyo/-.-/:.` ``..-.````.ssyyy-`...oddddo...-/ddh +yyhyyyyo/. ``..-`````-syyys....-ydddd/..--+dddmh::://hddh- +hhhhhhhhhssyyyo....-hdddh:..--sdddms:::/+ddhhysooooooooo+ `hhhddddddysdmy-..--hdddd+:::/oddhhyooooooooooooooooooooos ohyhmmmmmmdmm/:://sddhhyooooooooooooooooooooooooooooooooo- :hsysssdddhhsooooooooooooooooooooooooooooooooooooooooosss+ sooooooooooooooooooo+-:/+ooooooooooooooooosssssssssssssss` +ooooooooooooooooooo/ ``.:/+oosssssssssssssssssssssssss: -ooooooooooooooooooso` `.-/+oosssssssssssssssssssso soosoossssssssssssss- `./sssssssssssssssssssy` +sssssssssssssssssss+ `:osssssssyyyyyyyyyyyyy/ .yyyyyyyyyyyyyyyyyyyy.```.......:+yyyyyyyyyyyyyyyyyyyyyyys syyyyyyyyyyyyyyyyyyy/....----/syyyyyyyyyyyyyyyyyyyyyyyyyh. /yyyyyyyyyyyyyyyyyyys----::oyyyyyyyyyyyyyyyyyyyyyhhhhhhhh/ .yyyyyyyyyyyyyyyyyyyy/::+syyyyyyyyyyyyhhhhhhhhhhdddhdmhhhy syyyyyyyyyyyyyyyyyyysoyhyhhhhhhhhhhhddddsmddhhhNNmdmNdhhh. /yyyyyyyyyyyyyhhhhhhhhhhhhdddhhhmhhhdNNdhNNNNmmmdddddhhhh/ `hyhhhhhhhhhhdddddhyyyyyyhhhhdmNNNmmmddddhhhhhhhhhhhysso/` shhhddohmmdhdhmNhdmNNNmmmddddhhhhhhhhhhhyso+//:-.`` :hhhmNhNNNmmmmdddhhhhhhhhhhhhyso+/::-.` `hhhhdhhhhhhhhhhhyyso+/:-..` `ohhhhhhysso+//:-...........`````````````````` ``.-:::::::::::::::--------..........``````````````` [ [2021] Hello! Welcome to 'VIDEO2TEXT'. Enter 'q' to quit. ''' # Printing banner with welcome message print(banner) # Asking for the language of the video file prompt = """ Please specify the language of the video file. Press '1' for French. Press '2' for German. Press '3' for Italian. Press '4' for Russian. Press '5' for Dutch. Press '6' for Mandarin (Han Yu). Press '7' for Spanish. Press '8' for Turkish. Press '9' for Swedish. Press '10' for Portuguese. Press '11' for Japanese. Press '12' for Korean. Press '13' for Polish. Press '14' for Czech. Press '15' for Finnish. Press '16' for Hebrew. Press '17' for Hungarian. Press '18' for Indonesian. Press '19' for Malaysian. Press '20' for Norwegian. Press '21' for Romanian. Press '22' for Serbian. Press '23' for Slovak. Press '24' for Afrikaans. Leave blank for default (English). """ print("---------------------------------------------------------------------------------------------\n") while True: # Asking user to specify the path to the video file path = input("Please specify the full path to your video file (including file name).\nYour entry should look like this: 'C:/User/.../example.mp4' but without quotes.\n") if path == 'q': break print("\n------------------------------------------------------------------------------") lang = input(prompt) if lang == '1': language = 'fr-FR' if lang == '2': language = 'de-DE' if lang == '3': language = 'it-IT' if lang == '4': language == 'ru-RU' if lang == '5': language = 'nl-NL' if lang == '6': language = 'zh-CN' if lang == '7': language = 'es-ES' if lang == '8': language = 'tr' if lang == '9': language = 'sv-SE' if lang == '10': language = 'pt-PT' if lang == '11': language = 'ja' if lang == '12': language = 'ko' if lang == '13': language = 'pl' if lang == '14': language = 'cz' if lang == '15': language = 'fi' if lang == '16': language = 'he' if lang == '17': language = 'hu' if lang == '18': language = 'id' if lang == '19': language = 'ms-MY' if lang == '20': language = 'no-NO' if lang == '21': language = 'ro-RO' if lang == '22': language = 'sr-SP' if lang == '23': language = 'sk' if lang == '24': language = 'af' if lang == '': language = 'en-US' if lang == 'q': break print("------------------------------------------------------------------------------\n") # Specifying video and audio file transcribed_audio_file_name = 'videos/transcribed_speech.wav' video_file_name = path # Convert video to audio audioclip = AudioFileClip(video_file_name) audioclip.write_audiofile(transcribed_audio_file_name) # Getting duration of the audio file with contextlib.closing(wave.open(transcribed_audio_file_name, 'r')) as f: frames = f.getnframes() # Number of frames rate = f.getframerate() # Rate of frames per second duration = frames / float(rate) # Total number of frames divided by the rate = duration # Calculation total duration print("\n------------------------------------------------------------------------------\n") print("Calculating total duration of audio track...\nPlease do not interrupt!") total_duration = math.ceil(duration / 60) print(f"Done. This file contains {total_duration} minutes of audio material.") # Creating instance of speech recognizer print("\n------------------------------------------------------------------------------\n") print("Initializing speech recognition API...") r = sr.Recognizer() # Asking for storage path print("\n------------------------------------------------------------------------------\n") destination_folder = input("Path to local storage is required. Please enter the full path to the desired destination folder.\nYour entry should look like this: 'C:/User/...' but without quotes.\n") # Aborting if a 'q' is given if destination_folder == 'q': break # Ask for the file name file_name = input("\nPlease specify the desired file name.\nYour entry should look like this: 'example_file.txt' but without quotes.\n") # Aborting if a 'q' is given if file_name == 'q': break # Creating individual user path from destination folder and file name user_path = f"{destination_folder}/{file_name}" # Converting audio to text batchwise print("\n------------------------------------------------------------------------------\n") print("Converting audio to text batchwise...") print("\n------------------------------------------------------------------------------\n") for i in range(0, total_duration): with sr.AudioFile(transcribed_audio_file_name) as source: audio = r.record(source, offset = i*60, duration = 60) f = open(user_path, 'w') # Create file or append new data if already existing f.write(r.recognize_google(audio, language = language)) # Write into file what the Google API transcribes f.write(' ') # Leave spaces between two batches/ sentences f.close() print(f"Done.\nYou can find the transcription under '{user_path}'.") # Asking user if he/she wishes to continue question_more = input("Do you wish to transcribe another video? [y/n]\n") if question_more == 'y': print("\n------------------------------------------------------------------\n") continue if question_more == 'n': break if question_more == 'q': break
python
13
0.506643
198
38.952607
211
starcoderdata
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "connectionstate.h" #include "controller.h" #include #include class ConnectionDialog; class Controller; class QAction; class QSlider; class QWidget; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); void changeEvent(QEvent *); private: QVector<QWidget *> m_connectedWidgets; QVector<QAction *> m_connectedActions; QSlider *m_slider; QSlider *v_slider; bool volumeSliderIsBusy = false; bool actionVolume = false; int tempVolume = 0; private: void onPaletteChanged(); int m_seekPosition{}; Controller *m_controller{}; private slots: void setConnectionState(MPDConnection::State); }; #endif // MAINWINDOW_H
c
10
0.71199
50
17.813953
43
starcoderdata
package static import ( "github.com/gofiber/fiber/v2" ) // Status . func Status(ctx *fiber.Ctx) (err error) { ctx.SendStatus(200) return } // String . func String(ctx *fiber.Ctx) (err error) { ctx.SendString("Hello, World 👋!") return } // JSON . type JSON struct { Name string `json:"name" validate:"min=6,max=64,required"` } // Exec . func (req *JSON) Exec(ctx *fiber.Ctx) (result interface{}, err error) { result = map[string]string{ "message": "Hello, " + req.Name + "!", } return }
go
12
0.643426
71
15.733333
30
starcoderdata
import pyodbc as sql import pandas as pd import sqlalchemy as sa from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, DateTime, Boolean from sqlalchemy.sql.expression import insert, update, delete from datetime import date class SQL: def __init__(self, query, conn): self.query = query self.conn = conn def create_connection(self): engine = sa.create_engine(self.conn) connection = engine.connect() return connection def read_sql(self): df = pd.read_sql_query( sql=self.query, con=self.conn ) return df
python
11
0.658106
97
23.96
25
starcoderdata
/* * File: AbstractRepetitionSGMStructureFeature.java * Authors: zobenz * Company: Sandia National Laboratories * Project: Analogy LDRD * * Copyright Dec 6, 2007, Sandia Corporation. Under the terms of Contract * DE-AC04-94AL85000, there is a non-exclusive license for use of this work by * or on behalf of the U.S. Government. Export of this program may require a * license from the United States Government. See CopyrightHistory.txt for * complete details. * * Reviewers: * Review Date: * Changes Needed: * Review Comments: * * Revision History: * * $Log: AbstractRepetitionSGMStructureFeature.java,v $ * Revision 1.1 2010/12/21 15:50:08 zobenz * Migrated matrix generation code into standalone project * * Revision 1.1 2010/12/20 23:21:03 zobenz * Went from sgm package namespace to generator.matrix * * Revision 1.1 2010/12/20 18:58:37 zobenz * Renamed packages in preparation for migrating SGM code out to separate SGMT project. * * Revision 1.1 2010/12/20 17:52:30 zobenz * Refactoring to conform to Sandia Generated Matrix name for tool. * * Revision 1.3 2008/10/29 22:53:59 cewarr * Fixed bug 1293, allowing scaling and numerosity to be combined, by 1) combining scaling factor numerosity uses with existing scale factor and 2) allowing repetition (scaling/rotation) to apply one surface feature from previous cell to multiple surface features in current cell. * * Revision 1.2 2007/12/14 16:06:13 zobenz * Fixed bug with > 1 structure features per layer (by disallowing supplemental structure features when base structure feature is a logic operation) * * Revision 1.1 2007/12/13 15:54:54 zobenz * Divided up base and supplemental structure features into their own packages * * Revision 1.5 2007/12/13 15:50:17 zobenz * Made the distinction between base structure features and supplemental structure features explicit in preparation for implementing logical operation base structure features * * Revision 1.4 2007/12/11 15:20:27 zobenz * Fixed scaling transform when rendering cell; adjusted scaling setting in numerosity; removed various debug statements * * Revision 1.3 2007/12/10 20:08:47 zobenz * Rearranged classes into appropriate packages * * Revision 1.2 2007/12/07 00:00:52 zobenz * Removed some debug statements; disabled rotate structure feature again for the time being * * Revision 1.1 2007/12/06 23:28:32 zobenz * Refactored to provide more robust implementation of surface feature transformation, including support for multiple structure features per layer. * */ package gov.sandia.cognition.generator.matrix.structure.supplemental; import gov.sandia.cognition.generator.matrix.SGMFeature; import gov.sandia.cognition.generator.matrix.locationtransform.SGMLocationTransform; import gov.sandia.cognition.generator.matrix.surface.SGMSurfaceFeature; import java.util.ArrayList; import java.util.List; /** * @TODO - add description * * @author zobenz * @since 2.0 */ public abstract class AbstractRepetitionSGMStructureFeature extends AbstractSupplementalSGMStructureFeature { public AbstractRepetitionSGMStructureFeature( final SGMLocationTransform locationTransform) { super(locationTransform); } public List provideBaseSurfaceFeatures( final int sgmBaseLocationIndex, final List existingSurfaceFeaturesAtLocation) { return existingSurfaceFeaturesAtLocation; } protected abstract SGMSurfaceFeature applyTransform( final SGMSurfaceFeature feature, final SGMSurfaceFeature previousLocationFeature); public List transformSurfaceFeatures( final List surfaceFeaturesAtPreviousLocation, final List existingSurfaceFeaturesAtLocation) { if (existingSurfaceFeaturesAtLocation != null) { // Can only repeat structure feature if there is a one-to-one // mapping of the number of existing surface features from // previous location surface features // cew 081029: this restriction means that repetition (including // scaling and rotation) can't be applied after numerosity. // As a temporary fix, I'm going to assume that the parameter to // be repeated/transformed is in the previous cell's first feature // only, but this is clearly not an optimal solution. // if (surfaceFeaturesAtPreviousLocation.size() != // existingSurfaceFeaturesAtLocation.size()) // { // throw new IllegalArgumentException( // "AbstractRepetitionSGMStructureFeature requires that " + // "there be the same number of surface features at " + // "previous location and current location (" + // surfaceFeaturesAtPreviousLocation.size() + " != " + // existingSurfaceFeaturesAtLocation.size() + ")"); // } List transformedFeatures = new ArrayList existingSurfaceFeaturesAtLocation.size()); for (int i = 0; i < existingSurfaceFeaturesAtLocation.size(); i++) { // Start with a copy of existing feature at location so we can // keep everything except parameter being repeated from // previous location SGMSurfaceFeature transformedFeature = existingSurfaceFeaturesAtLocation.get(i).clone(); // Overwrite unchanged parameters with what is already // at this location, and store the transformed feature transformedFeatures.add(this.applyTransform(transformedFeature, surfaceFeaturesAtPreviousLocation.get(0))); } return transformedFeatures; } else { return surfaceFeaturesAtPreviousLocation; } } public abstract String getDescription(); public abstract boolean checkCompatibility( final SGMFeature feature); }
java
16
0.672958
280
42.675676
148
starcoderdata
func (fc *FakeClient) Put(ctx context.Context, project string, content *cpb.Chunk) (string, error) { if err := validateProject(project); err != nil { return "", err } _, err := proto.Marshal(content) if err != nil { return "", errors.Annotate(err, "marhsalling chunk").Err() } objID, err := generateObjectID() if err != nil { return "", err } name := FileName(project, objID) if _, ok := fc.Contents[name]; ok { // Indicates a test with poorly seeded randomness. return "", errors.New("file already exists") } fc.Contents[name] = proto.Clone(content).(*cpb.Chunk) return objID, nil }
go
12
0.658416
100
29.35
20
inline
<?php class Changepass_model extends CI_Model{ function checking_old_password($user_id,$old_pass){ $this->db->where('id_user', $user_id); $this->db->where('password_user', $old_pass); $query = $this->db->get('user'); return $query; } function change_password($user_id,$new_pass){ $this->db->set('password_user', $new_pass); $this->db->where('id_user', $user_id); $this->db->update('user'); } }
php
11
0.676529
92
28.882353
17
starcoderdata
import React, { Fragment, useState } from "react"; import { connect } from "react-redux"; import { Link, Redirect } from "react-router-dom"; import { setAlert } from "../../actions/alert"; // import { register } from '../../actions/auth'; change this import PropTypes from "prop-types"; import ReCAPTCHA from "react-google-recaptcha"; // import "../../css/forms.css"; import Navbar from "../layout/Navbar"; import axios from "axios"; const AddEvent = ({ setAlert }) => { const [formData, setFormData] = useState({ name: "", Type: "", information: "", address: "", Age: "", pay: "", Capacity: "", Details: "" }); const { name, type, information, address, Age, pay, Capacity, Details } = formData; const onChange = e => setFormData({ ...formData, [e.target.name]: e.target.value }); const onSubmit = async e => { e.preventDefault(); const config = { headers: { "Content-Type": "application/json" } }; formData.organizer = localStorage.user_id; // cchangeeeeeeee axios .post("/api/events", formData, config) .then(response => { console.log(response.data); }) .catch(e => { console.log(e); }); console.log(formData); // addevent({ name, // Type, // Information, // Location, // Age, // Address, // Pay, // Capacity, // Details }); }; return ( <section className=""> <div className=""> <div class=""> <div class="jumbotron text-center" style={{ backgroundColor: "lightblue", height: "110px" }} > <h2 style={{ padding: "10px" }}>Add an Event or Venue <div className="container"> <form onSubmit={e => onSubmit(e)}> <div class="form-group"> Name <input type="text" class="form-control" placeholder="Add Name of Event" name="name" value={name} onChange={e => onChange(e)} /> <div class="form-group"> Venue <input type="text" class="form-control" placeholder="Add Venue " name="name" value={name} onChange={e => onChange(e)} /> <div class="form-group"> <label >Event Description <textarea class="form-control" type="Information" placeholder="Information" name="information" value={information} onChange={e => onChange(e)} rows="5" > <div className="form-group"> <label >Age Restrictions <select value={Age} className="form-control" name="Age" onChange={e => onChange(e)} > <option value="Attendee">Over 21 <option value="Organizer">Over 18 <div className="form-group"> <label >Free/Paid <select className="form-control" value={pay} name="pay" onChange={e => onChange(e)} > <option value="Attendee">Free <option value="Organizer">Chargeble <div className="form-group"> <label >Event Capacity <input className="form-control" type="Capacity" placeholder="Enter Max Capacity" name="Capacity" value={Capacity} onChange={e => onChange(e)} > <div className="form-group"> <input type="Details" className="form-control" placeholder="Any more Details to Add?" name="Details" value={Details} onChange={e => onChange(e)} /> <br /> <input type="submit" class="btn btn-info"value="Submit" style={{textALign:"center",width:"120px",backgroundColor:"lightBlue", height:"40px"}}/> ); }; AddEvent.propTypes = { // setAlert: PropTypes.func.isRequired, // register: PropTypes.func.isRequired, // isAuthenticated: PropTypes.bool }; const mapStateToProps = state => ({ isAuthenticated: state.auth.isAuthenticated }); export default connect(mapStateToProps)(AddEvent);
javascript
22
0.423277
161
27.44335
203
starcoderdata
YAML Metadata Warning: empty or missing yaml metadata in repo card (https://huggingface.co/docs/hub/datasets-cards)

This dataset contains deduplicated data from StarCoder, The-Vault-inline and Project_CodeNet.

Cleaning:

  • We removed the metadata tags (file-name, number of stars etc) from starcoder split of the dataset

We filtered the data by:

  • AST parsability: we extracted only the AST parsable codes
  • AST Depth: only samples with depth from 2.0 to 31.0
  • Maximum Line Length: only samples with maximum of 12.0 to 400.0 characters
  • Average Line Length: only samples with 5.0 to 140.0 characters on average
  • Alphanumeric Fraction of samples is greater than 0.2
  • Number of Lines: from 6.0 to 300.0
Downloads last month
27