code
stringlengths
0
29.6k
language
stringclasses
9 values
AST_depth
int64
3
30
alphanumeric_fraction
float64
0.2
0.86
max_line_length
int64
13
399
avg_line_length
float64
5.02
139
num_lines
int64
7
299
source
stringclasses
4 values
// Copyright (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
// Automatically generated file. Edit generated/error.html and run // 'make ini' to update this documentation! const char* error_str = "" "<!doctype html>\r\n" "\r\n" "<html lang=\"en\">\r\n" " " <meta charset=\"utf-8\">\r\n" " Error " <meta name=\"description\" content=\"\">\r\n" " <meta name=\"author\" content=\"\">\r\n" " " body {font-family: arial, helvetica, sans;}\r\n" " h1 {border-bottom: 1px solid gray;}\r\n" " .detail {display: none;}\r\n" " p {padding-top: 0; margin-top: 0;}\r\n" " " "\r\n" " " <p id=\"dsc\"> " " " <div class=\"detail\" id=\"err0\">Ok " <div class=\"detail\" id=\"err1\">Argument 1 missing. " <div class=\"detail\" id=\"err2\">Failed to find current directory. getcwd() or realpath() failed to resolve the app directory. " <div class=\"detail\" id=\"err3\">Failed to create ph.ini, permission denied. " <div class=\"detail\" id=\"err4\">Failed to create ph.ini, unable to write to file. " <div class=\"detail\" id=\"err5\">Failed to parse ini file. " <div class=\"detail\" id=\"err6\">Wrong path or program is not executable. " <div class=\"detail\" id=\"err7\">No inisection found. " <div class=\"detail\" id=\"err8\">While generating the commandline string, too many arguments were passed in via query and/or configuration. The limit is: MAX_PARAMS. " <div class=\"detail\" id=\"err9\">Failed to open file for replacement. " <div class=\"detail\" id=\"err10\">Failed to parse regular expression. " <div class=\"detail\" id=\"err11\">Could not allocate enough memmory to read the file into RAM for replacement. " <div class=\"detail\" id=\"err12\">replace_file set but replace_regex empty or missing. " <div class=\"detail\" id=\"err13\">Failed to find ini Section. " <div class=\"detail\" id=\"err14\">Failed to expand environment variable. " <div class=\"detail\" id=\"err15\">Missing `cmd` directive in ini file. " <div class=\"detail\" id=\"err16\">Failed to delete log file. " <div class=\"detail\" id=\"err17\">Failed to rename log file. " <div class=\"detail\" id=\"err18\">Failed to find userdir (APPDATA/HOME) in environment variables. " <div class=\"detail\" id=\"err19\">Failed to open config file. " <div class=\"detail\" id=\"err20\">Failed to open log file. " <div class=\"detail\" id=\"err21\">Failed to download config file. " <div class=\"detail\" id=\"err22\">Failed to zeropad an url parameter, string too long. " <div class=\"detail\" id=\"err23\">cmd file not executable. " <div class=\"detail\" id=\"err24\">`user_param` not found in url query. " <div class=\"detail\" id=\"err25\">File not found. Most probably an application is not installed. " <div class=\"detail\" id=\"err33\">No equal sign found in expression expansion. " <div class=\"detail\" id=\"err34\">No colon found in expression expansion. " <div class=\"detail\" id=\"err35\">Failed to dynamically allocate memmory while expanding variables (malloc). " <div class=\"detail\" id=\"err36\">Ennvironment variable not found while trying to expand. " <div class=\"detail\" id=\"err37\">Query parameter not found while expaning. " <div class=\"detail\" id=\"err38\">Failed to dynamically allocate memmory while expanding variables (realloc). " <div class=\"detail\" id=\"err128\">Failed to parse URI, protocol missing. " <div class=\"detail\" id=\"err129\">Failed to parse URI, authority missing. " <div class=\"detail\" id=\"err130\">Failed to parse URI, error in query string. " <div class=\"detail\" id=\"err131\">Failed to parse URI, error in fragment. "\r\n" " " \r\n" " <div id=\"var\" style=\"display: none\"> " <div id=\"hostname\"> " <div id=\"url\"> " <div id=\"date\"> " <span id=\"code\"> " <hr size=\"1\"/>\r\n" " the error log for more information. " " \r\n" " "<script type=\"text/javascript\">\r\n" "var query = window.location.search.slice(1);\r\n" "var vars = query.split('&');\r\n" "var code = 0;\r\n" "var url = \"\";\r\n" "var description = \"\";\r\n" "var hostname = \"\";\r\n" "\r\n" "for (var i = 0; i < vars.length; i++) {\r\n" " var pair = vars[i].split('=');\r\n" " if (decodeURIComponent(pair[0]) == \"code\") {\r\n" " code = decodeURIComponent(pair[1]);\r\n" " }\r\n" " if (decodeURIComponent(pair[0]) == \"url\") {\r\n" " url = decodeURIComponent(pair[1]);\r\n" " }\r\n" " if (decodeURIComponent(pair[0]) == \"str\") {\r\n" " if(pair[1])\r\n" " description = decodeURIComponent(pair[1]);\r\n" " }\r\n" " if (decodeURIComponent(pair[0]) == \"hostname\") {\r\n" " if(pair[1])\r\n" " hostname = decodeURIComponent(pair[1]);\r\n" " }\r\n" " if (decodeURIComponent(pair[0]) == \"var\") {\r\n" " if(pair[1]) {\r\n" " document.getElementById(\"var\").innerHTML = \"Variable: + decodeURIComponent(pair[1]) + \" " document.getElementById(\"var\").style.display = \"block\";\r\n" " }\r\n" " }\r\n" "}\r\n" "\r\n" "document.getElementById(\"code\").innerHTML = code;\r\n" "document.getElementById(\"url\").innerHTML = \"url: \" + url;\r\n" "document.getElementById(\"dsc\").innerHTML = \"Error: \" + description;\r\n" "document.getElementById(\"hostname\").innerHTML = \"Hostname: \" + hostname;\r\n" "\r\n" "try {\r\n" " document.getElementById(\"err\"+code).style.display = \"block\";\r\n" "} catch (e) {;}\r\n" "var d = new Date();\r\n" "document.getElementById(\"date\").innerHTML = d;\r\n" " "
c
5
0.620338
180
50.543103
116
starcoderdata
<?php defined('BASEPATH') OR exit('No direct script access allowed'); require_once dirname(__FILE__).'/Socializer/Facebook.php'; require_once dirname(__FILE__).'/Socializer/Twitter.php'; require_once dirname(__FILE__).'/Socializer/Google.php'; require_once dirname(__FILE__).'/Socializer/Instagram.php'; require_once dirname(__FILE__).'/Socializer/Linkedin.php'; /** * Base class of Socializer module. * Declaration of required functions */ class Socializer { const FBERRCODE = 5; const TWERRCODE = 6; public static function factory($social_name, $user_id = null, $token = null) { $social_media = 'Socializer_'.$social_name; return new $social_media($user_id, $token); } // public abstract function getLoginLink(); }
php
10
0.67979
80
29.52
25
starcoderdata
package com.github.jumpt57.kijiji.engine.executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public enum CachedThreadPool { INSTANCE; private ExecutorService executorService; CachedThreadPool() { executorService = Executors.newCachedThreadPool(); } public ExecutorService getExecutorService() { return this.executorService; } }
java
10
0.741007
58
19.85
20
starcoderdata
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cct.cprocessor; import java.util.logging.Logger; /** * * @author vvv900 */ public class AssignmentOperator implements CommandInterface { static final Logger logger = Logger.getLogger(AssignmentOperator.class.getCanonicalName()); public CommandInterface ciInstance() { return new AssignmentOperator(); } /** * Assumes variable as the first argument and its value as the second one * * @param args * @return * @throws Exception */ public Object ciExecuteCommand(Object[] args) throws Exception { if (args == null || args.length != 2) { throw new Exception("Assignment operator expects for two arguments"); } if (!(args[0] instanceof Variable)) { throw new Exception("Assignment operator: first argument should be of type " + Variable.class.getCanonicalName() + " Got: " + args[0].getClass().getCanonicalName()); } Variable var = (Variable) args[0]; var.setValue(args[1]); return new Boolean(true); } public Object[] ciParseCommand(String[] tokens) throws Exception { throw new Exception("Not implemented yet"); } }
java
15
0.697254
98
29.086957
46
starcoderdata
import json import scrapy from io import BytesIO from zipfile import ZipFile from kingfisher_scrapy.base_spider import BaseSpider class Zambia(BaseSpider): name = 'zambia' custom_settings = { 'ITEM_PIPELINES': { 'kingfisher_scrapy.pipelines.KingfisherPostPipeline': 400 }, 'HTTPERROR_ALLOW_ALL': True, } def start_requests(self): yield scrapy.Request( 'https://www.zppa.org.zm/ocds/services/recordpackage/getrecordpackagelist', callback=self.parse_list ) def parse_list(self, response): if response.status == 200: json_data = json.loads(response.body_as_unicode()) files_urls = json_data['packagesPerMonth'] if self.is_sample(): files_urls = [files_urls[0]] for file_url in files_urls: yield scrapy.Request( file_url, meta={'kf_filename': '%s.json' % file_url[-16:].replace('/', '-')}, ) else: yield { 'success': False, 'file_name': 'list.json', "url": response.request.url, "errors": {"http_code": response.status} } def parse(self, response): if response.status == 200: zip_files = ZipFile(BytesIO(response.body)) for finfo in zip_files.infolist(): data = zip_files.open(finfo.filename).read() yield self.save_data_to_disk(data, finfo.filename, data_type='record_package', url=response.request.url) else: yield { 'success': False, 'file_name': response.request.meta['kf_filename'], 'url': response.request.url, 'errors': {'http_code': response.status} }
python
22
0.548668
120
31.533333
60
starcoderdata
package io.github.jroy.tagger; import fr.minuskube.inv.InventoryManager; import io.github.jroy.tagger.command.TagCommand; import io.github.jroy.tagger.sql.DatabaseManager; import io.github.jroy.tagger.util.StonksIntegration; import net.milkbowl.vault.economy.Economy; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import java.sql.SQLException; import java.util.Objects; public class Tagger extends JavaPlugin { public static Economy economy; @Override public void onEnable() { getLogger().info("Loading Config..."); getConfig().addDefault("mysql.username", ""); getConfig().addDefault("mysql.password", ""); getConfig().options().copyDefaults(true); saveConfig(); reloadConfig(); getLogger().info("Loaded Config!"); getLogger().info("Loading DatabaseManager..."); getLogger().info("Registering Glow Enchantment..."); DatabaseManager databaseManager; try { databaseManager = new DatabaseManager(this); } catch (ClassNotFoundException | SQLException e) { getLogger().severe("Error while initializing DatabaseManager, disabling..."); e.printStackTrace(); getPluginLoader().disablePlugin(this); return; } getServer().getPluginManager().registerEvents(databaseManager, this); getLogger().info("Loaded DatabaseManager!"); if (getServer().getPluginManager().getPlugin("Stonks") != null) { new StonksIntegration(this, databaseManager); } InventoryManager inventoryManager = new InventoryManager(this); inventoryManager.init(); TagCommand tagCommand = new TagCommand(databaseManager, inventoryManager); Objects.requireNonNull(getCommand("tags")).setExecutor(tagCommand); Objects.requireNonNull(getCommand("tags")).setTabCompleter(tagCommand); RegisteredServiceProvider rsp = getServer().getServicesManager().getRegistration(Economy.class); if (rsp != null) { economy = rsp.getProvider(); } } }
java
12
0.728856
109
35.545455
55
starcoderdata
const prettier = require('prettier') const compile = require('./vue-compiler') module.exports = function ({ template, data = {}, options = {}, components = {} } = {}, { prettier: usePrettier = true } = {}) { let component = compile({ template, data, options, components }) if (usePrettier) { // workaround for prettier to avoid it // throwing error of bad formated code component = `export default ${component}` component = prettier.format(component, { parser: 'babylon', semi: false, singleQuote: true }) component = component.replace(/^export default /, '') } return component }
javascript
11
0.637394
57
21.0625
32
starcoderdata
fn main() { println!( "Creating genesis binary blob at {} from configuration file {}", GENESIS_LOCATION, CONFIG_LOCATION ); let config = default_config(); config .save_config(CONFIG_LOCATION) .expect("Unable to save genesis config"); let mut file = File::create(GENESIS_LOCATION).unwrap(); // Must use staged stdlib files file.write_all(&generate_genesis_blob(stdlib_modules( StdLibOptions::Staged, ))) .unwrap(); }
rust
14
0.623984
72
28
17
inline
package org.bouncycastle.tls.crypto.impl.jcajce; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.TlsFatalAlert; import org.bouncycastle.tls.TlsUtils; import org.bouncycastle.tls.crypto.impl.TlsAEADCipherImpl; import org.bouncycastle.util.Pack; public class JceChaCha20Poly1305 implements TlsAEADCipherImpl { private static final int BUF_SIZE = 32 * 1024; private static final byte[] ZEROES = new byte[15]; protected final Cipher cipher; protected final Mac mac; protected final int cipherMode; protected SecretKey cipherKey; protected byte[] additionalData; public JceChaCha20Poly1305(JcaJceHelper helper, boolean isEncrypting) throws GeneralSecurityException { this.cipher = helper.createCipher("ChaCha7539"); this.mac = helper.createMac("Poly1305"); this.cipherMode = isEncrypting ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE; } public int doFinal(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws IOException { /* * NOTE: When using the Cipher class, output may be buffered prior to calling doFinal, so * getting the MAC key from the first block of cipher output reliably is awkward. We are * forced to use a temp buffer and extra copies to make it work. In the case of decryption * it has the additional downside that full decryption is performed before we are able to * check the MAC. */ try { if (cipherMode == Cipher.ENCRYPT_MODE) { int ciphertextLength = inputLength; byte[] tmp = new byte[64 + ciphertextLength]; System.arraycopy(input, inputOffset, tmp, 64, inputLength); runCipher(tmp); System.arraycopy(tmp, 64, output, outputOffset, ciphertextLength); initMAC(tmp); updateMAC(additionalData, 0, additionalData.length); updateMAC(tmp, 64, ciphertextLength); byte[] lengths = new byte[16]; Pack.longToLittleEndian(additionalData.length & 0xFFFFFFFFL, lengths, 0); Pack.longToLittleEndian(ciphertextLength & 0xFFFFFFFFL, lengths, 8); mac.update(lengths, 0, 16); mac.doFinal(output, outputOffset + ciphertextLength); return ciphertextLength + 16; } else { int ciphertextLength = inputLength - 16; byte[] tmp = new byte[64 + ciphertextLength]; System.arraycopy(input, inputOffset, tmp, 64, ciphertextLength); runCipher(tmp); initMAC(tmp); updateMAC(additionalData, 0, additionalData.length); updateMAC(input, inputOffset, ciphertextLength); byte[] expectedMac = new byte[16]; Pack.longToLittleEndian(additionalData.length & 0xFFFFFFFFL, expectedMac, 0); Pack.longToLittleEndian(ciphertextLength & 0xFFFFFFFFL, expectedMac, 8); mac.update(expectedMac, 0, 16); mac.doFinal(expectedMac, 0); boolean badMac = !TlsUtils.constantTimeAreEqual(16, expectedMac, 0, input, inputOffset + ciphertextLength); if (badMac) { throw new TlsFatalAlert(AlertDescription.bad_record_mac); } System.arraycopy(tmp, 64, output, outputOffset, ciphertextLength); return ciphertextLength; } } catch (GeneralSecurityException e) { throw new RuntimeException(e); } } public int getOutputSize(int inputLength) { return cipherMode == Cipher.ENCRYPT_MODE ? inputLength + 16 : inputLength - 16; } public void init(byte[] nonce, int macSize, byte[] additionalData) throws IOException { if (nonce == null || nonce.length != 12 || macSize != 16) { throw new TlsFatalAlert(AlertDescription.internal_error); } try { cipher.init(cipherMode, cipherKey, new IvParameterSpec(nonce), null); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } this.additionalData = additionalData; } public void setKey(byte[] key, int keyOff, int keyLen) throws IOException { this.cipherKey = new SecretKeySpec(key, keyOff, keyLen, "ChaCha7539"); } protected void initMAC(byte[] firstBlock) throws InvalidKeyException { mac.init(new SecretKeySpec(firstBlock, 0, 32, "Poly1305")); for (int i = 0; i < 64; ++i) { firstBlock[i] = 0; } } protected void runCipher(byte[] buf) throws GeneralSecurityException { // to avoid performance issue in FIPS jar 1.0.0-1.0.2, process in chunks int readOff = 0, writeOff = 0; while (readOff < buf.length) { int updateSize = Math.min(BUF_SIZE, buf.length - readOff); writeOff += cipher.update(buf, readOff, updateSize, buf, writeOff); readOff += updateSize; } writeOff += cipher.doFinal(buf, writeOff); if (buf.length != writeOff) { throw new IllegalStateException(); } } protected void updateMAC(byte[] buf, int off, int len) { mac.update(buf, off, len); int partial = len % 16; if (partial != 0) { mac.update(ZEROES, 0, 16 - partial); } } }
java
15
0.609497
105
32.461111
180
starcoderdata
package edu.mtu.examples.houghton.steppables; import edu.mtu.examples.houghton.model.HoughtonParameters; import edu.mtu.steppables.LandUseGeomWrapper; import edu.mtu.steppables.ParcelAgent; import edu.mtu.steppables.ParcelAgentType; import edu.mtu.examples.houghton.vip.VipBase; import edu.mtu.examples.houghton.vip.VipFactory; @SuppressWarnings("serial") public abstract class NipfAgent extends ParcelAgent { // VIP attributes private boolean vipDisqualifed = false; private boolean vipAware = false; private boolean vipEnrollee = false; protected boolean vipHarvested = false; private int vipCoolDown = 0; private int vipCoolDownDuration = 0; private final static double vipAwarenessRate = 0.14; // The odds that the NIPFO will accept VIP information from neighbors private final static double vipInformedRate = 0.05; // The odds that the NIPFO will be informed of the VIP after activation // WTH attributes protected double wthPerAcre = 0.0; protected abstract void doAgentPolicyOperation(); protected abstract double getMinimumDbh(); public NipfAgent(ParcelAgentType type, LandUseGeomWrapper lu) { super(type, lu); } @Override public void doHarvestedOperation() { // Set the flag indicating we harvested since enrolling in the VIP vipHarvested = vipEnrollee; } @Override protected void doPolicyOperation() { // Return if the VIP doesn't apply to us if (vipDisqualifed) { return; } // Return if there is no policy if (!VipFactory.getInstance().policyExists()) { return; } // Return if the VIP is not introduced VipBase vip = VipFactory.getInstance().getVip(); if (!vip.isIntroduced()) { return; } // Return if we don't have enough area if (getParcelArea() < vip.getMinimumAcerage()) { vipDisqualifed = true; return; } // If we aren't aware if the VIP see if we should be if (!vipAware) { if (vipInformedRate < state.random.nextDouble()) { return; } awareOfVip(); } // Update the cool down for the VIP and return if the agent is still cooling down vipCoolDown -= (vipCoolDown > 0) ? 1 : 0; if (vipCoolDown > 0) { return; } doAgentPolicyOperation(); } /** * Get the millage rate for the agent's parcel. */ public double getMillageRate() { if (vipEnrollee) { return HoughtonParameters.MillageRate - VipFactory.getInstance().getVip().getMillageRateReduction(this, state); } return HoughtonParameters.MillageRate; } public boolean inVip() { return vipEnrollee; } private void awareOfVip() { // Guard against multiple updates if (vipAware) { return; } // Set our flag and inform the model vipAware = true; VipFactory.getInstance().getVip().nipfoInformed(); getGeometry().setAwareOfVip(true); state.updateAgentGeography(this); } protected void enrollInVip() { vipEnrollee = true; vipHarvested = false; VipFactory.getInstance().getVip().enroll(this, state); getGeometry().setEnrolledInVip(true); state.updateAgentGeography(this); } protected void unenrollInVip() { vipEnrollee = false; vipCoolDown = vipCoolDownDuration; VipFactory.getInstance().getVip().unenroll(getParcel()); getGeometry().setEnrolledInVip(false); state.updateAgentGeography(this); } protected double getHarvestDbh() { if (getMinimumDbh() == 0) { throw new IllegalArgumentException("Minimum DBH cannot be zero."); } // Now determine what sort of DBH we will harvest at double dbh = getMinimumDbh(); if (vipEnrollee) { dbh = VipFactory.getInstance().getVip().getMinimumHarvestingDbh(); } return dbh; } /** * Inform this NIFPO of the VIP. */ public void informOfVip() { // If we already know, return if (vipAware) { return; } // If we haven't been fully activated yet, return if (!phasedIn()) { return; } // Do we care about this information? if (state.random.nextDouble() <= vipAwarenessRate) { awareOfVip(); } } /** * Set the VIP cool down duration. */ public void setVipCoolDownDuration(int value) { vipCoolDownDuration = value; } /** * Set the WTH for the agent and calculate how much they want for the parcel */ public void setWthPerAcre(double value) { wthPerAcre = value; } }
java
11
0.682162
126
24.298246
171
starcoderdata
package no.nav.data.catalog.policies.app.policy.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import no.nav.data.catalog.policies.app.policy.entities.Policy; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class PolicyRequest { private Long id; private String legalBasisDescription; private String purposeCode; private String datasetTitle; private String fom; private String tom; @JsonIgnore private String datasetId; @JsonIgnore private Policy existingPolicy; }
java
5
0.79602
63
24.935484
31
starcoderdata
namespace NetFlow.Web.ViewModels.Post { using Microsoft.AspNetCore.Http; using NetFlow.Common.GlobalConstants; using System.ComponentModel.DataAnnotations; public class CreatePostViewModel { public int Id { get; set; } [Required] [MinLength(PostsConstants.POST_TITLE_MIN_LENGTH)] [MaxLength(PostsConstants.POST_TITLE_MAX_LENGTH)] public string Title { get; set; } [Required] public IFormFile Picture { get; set; } [Required] [MinLength(PostsConstants.POST_MIN_DESCRIPTION_LENGTH)] [MaxLength(PostsConstants.POST_MAX_DESCRIPTION_LENGTH)] public string Content { get; set; } } }
c#
11
0.657554
63
26.8
25
starcoderdata
def prepare_trans_no(client_code, bse_order_type): ''' trans_no is a unique number sent with every transaction creation request sent to BSE If it is not unique transaction creation request is rejected by BSE I follow this form for trans_no: eg. 20160801L0000011 - digit 1 to 8: today's date in YYYYMMDD - digit 9: '1' for lumpsum order and '2' for Xsip - digit 10 to 15: client_code(bse) or user_id(internal) padded with 0s to make it 6 digit long - digit 16 onwards: counter starting from 1, gets incremented with every order in TransactionBse or TransactionXsipBse table. counter reset to 1 every day ''' # pad client code with 0s till it is CC_LEN digits CC_LEN = 6 # pad client_code with 0s cc_str = str(client_code) cc_str = '0'* (CC_LEN - len(cc_str)) + cc_str # prepare unique trans_no by looking for the last transaction made by the client today import datetime now = datetime.datetime.now() # If this is testing environment, replace first digit of year with 1 if settings.LIVE == 0: today_str = '00' + now.strftime('%y%m%d') + bse_order_type else: today_str = now.strftime('%Y%m%d') + bse_order_type try: if (bse_order_type == '1'): relevant_trans = TransactionBSE.objects.filter(client_code=client_code, trans_no__contains=today_str) elif (bse_order_type == '2'): ## for basanti-2: since xsip orders cannot be placed in off-market hours, placing a lumpsum order instead relevant_trans = TransactionXsipBSE.objects.filter(client_code=client_code, trans_no__contains=today_str) max_trans_no = 0 for trans in relevant_trans: prev_trans_no = int(trans.trans_no[CC_LEN+9:]) if (prev_trans_no > max_trans_no): max_trans_no = prev_trans_no if (max_trans_no >= 99): raise Exception( "BSE error 647: 99 transactions already placed today for this user" ) trans_no = today_str + cc_str + str(max_trans_no + 1) except (TransactionBSE.DoesNotExist, TransactionXsipBSE.DoesNotExist) as e : trans_no = today_str + cc_str + '1' # print 'trans_no', trans_no return trans_no
python
14
0.706712
109
40.979592
49
inline
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * */ class Duyurular_model extends CI_Model { function __construct() { parent::__construct(); } public function site_ayarlar() { return $this->db->get("siteayarlar")->row(); } public function duyurular($limit) { if(isset($limit)){ return $this->db->get("duyurular",6,$limit)->result(); }else{ return $this->db->get("duyurular")->result(); } } public function duyuru($id) { $this->db->where("duyuruId",$id); return $this->db->get("duyurular")->row(); } } ?>
php
14
0.60241
63
13.195122
41
starcoderdata
/* Copyright (c) 2018 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Scanner; import java.util.Objects; import java.sql.*; /** * Domain classes used to produce command line user interface for database. * * This class contains the controller and UI. * * * @since 1.0 * @author * @version 1.0 */ public final class BookFinder { private static Scanner reader; private static Connection database; // For database wrapper. /** * Utility class for accessing database. * */ private BookFinder() { } /** * This is the main method which is the controller. * @param args */ public static void main(String[] args) { reader = new Scanner(System.in); // Connect to SQL database. try { Class.forName("org.sqlite.JDBC"); database = DriverManager.getConnection("jdbc:sqlite:books.db"); // Prevent database from being edited. database.setAutoCommit(false); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } // Main UI loop. while (true) { // UI options. System.out.println("Type the option you would like to select.\n"); System.out.println("authors: List authors"); System.out.println("genre: List books by genre"); // System.out.println("3: List books by publisher"); System.out.println("exit: Exit"); String choice = reader.nextLine().trim(); if (Objects.equals(choice, new String("exit"))){ break; } // UI options logic. switch (choice) { case "authors": listAuthors(); break; case "genre": listByGenre(); break; default: System.out.println("Invalid option."); break; } } reader.close(); } /** * Print all authors. */ private static void listAuthors() { // Print all authors. try { Statement statement = database.createStatement(); ResultSet rs = statement.executeQuery("SELECT name FROM AUTHOR;"); while (rs.next()) { String name = rs.getString("name"); System.out.println(name); } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } } /** * List genra chosen by user. */ private static void listByGenre() { // Get genre from user. System.out.println("Select a genre: Fantasy, Fiction, Nonfiction"); String genre = reader.nextLine(); // Print all books in genre. try { PreparedStatement statement = database.prepareStatement("SELECT " + "BOOK.title," + "author.name,publisher.name," + "book.genre, book.rating," + "book.series FROM BOOK INNER JOIN AUTHOR ON " + "BOOK.author_id=author.id INNER JOIN PUBLISHER ON " + "BOOK.publisher_id=publisher.id WHERE GENRE = ?"); statement.setString(1, genre); // Get selected genre from database. ResultSet rs = statement.executeQuery(); while (rs.next()) { // Column String title = rs.getString("title"); System.out.println(String.format("Title: %s, Author: %s, " + "Publisher: %s, " + "Genre: %s, Rating: %s, Series: %s", rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6))); } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); System.exit(0); } } /** * Implement next. */ private static void listByPublisher() { // To do. } }
java
18
0.569586
79
31.267081
161
starcoderdata
/* * Copyright (c) 2019 by European Commission * * Licensed under the EUPL, Version 1.2 or - as soon they will be * approved by the European Commission - subsequent versions of the * EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * https://joinup.ec.europa.eu/page/eupl-text-11-12 * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. * */ package eu.eidas.auth.engine.core.validator.eidas; import eu.eidas.auth.commons.EidasParameterKeys; import eu.eidas.auth.commons.EidasParameters; import eu.eidas.engine.exceptions.ValidationException; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.saml.common.SAMLVersion; import org.opensaml.saml.saml2.core.Response; import org.opensaml.saml.saml2.core.StatusCode; import org.w3c.dom.Element; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import static eu.eidas.auth.engine.core.validator.eidas.EidasValidator.validateNotNull; import static eu.eidas.auth.engine.core.validator.eidas.EidasValidator.validateOK; import static java.nio.charset.StandardCharsets.UTF_8; /** * eIDAS validator for {@link Response}. */ public class EidasResponseValidator extends ResponseSchemaValidator implements EidasValidator { static final String[] CONSENT_ALLOWED_VALUES = { "urn:oasis:names:tc:SAML:2.0:consent:obtained", "urn:oasis:names:tc:SAML:2.0:consent:prior", "urn:oasis:names:tc:SAML:2.0:consent:current-implicit", "urn:oasis:names:tc:SAML:2.0:consent:current-explicit", "urn:oasis:names:tc:SAML:2.0:consent:unspecified", "urn:oasis:names:tc:SAML:2.0:consent:unavailable", "urn:oasis:names:tc:SAML:2.0:consent:inapplicable" }; public EidasResponseValidator() { super(); } /** * Validates a single {@link Response} and throws a {@link ValidationException} if the validation fails. * * @param response the {@link Response} to validate * @throws ValidationException when an invalid value was found */ @Override public void validate(Response response) throws ValidationException { Element node = Objects.requireNonNull(response.getDOM()); int responseSize = SerializeSupport.prettyPrintXML(node).getBytes(UTF_8).length; validateOK(responseSize <= getMaxSize(), "SAML Response exceeds max size."); super.validate(response); validateNotNull(response.getID(), "ID is required"); validateNotNull(response.getInResponseTo(), "InResponseTo is required"); validateNotNull(response.getVersion(), "Version is required."); validateOK(SAMLVersion.VERSION_20.equals(response.getVersion()), "Version is invalid."); validateNotNull(response.getIssueInstant(), "IssueInstant is required"); validateNotNull(response.getDestination(), "Destination is required"); validateConsent(response.getConsent()); validateNotNull(response.getIssuer(), "Issuer is required."); validateNotNull(response.getStatus(), "Status is required."); validateNotNull(response.getSignature(), "Signature is required."); validateOK((!StatusCode.SUCCESS.equals(response.getStatus().getStatusCode().getValue()) || !(response.getAssertions() == null || response.getAssertions().isEmpty())), "Assertion is required"); } /** * Validates the consent, it is optional, but when not null, it should be one of: * * * * * * * * * * * @param consent the consent * @throws ValidationException when the consent is invalid */ private static void validateConsent(String consent) throws ValidationException { // Consent is optional if (consent != null) { Optional consentOptional = Stream.of(CONSENT_ALLOWED_VALUES) .filter(consent::equals) .findAny(); validateOK(consentOptional.isPresent(), "Consent is invalid"); } } private int getMaxSize(){ return EidasParameters.getMaxSizeFor(EidasParameterKeys.SAML_RESPONSE); } }
java
17
0.678852
108
40.773109
119
starcoderdata
/******************************************************************************* * Cloud Foundry * Copyright (c) [2009-2016] Pivotal Software, Inc. All Rights Reserved. * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product includes a number of subcomponents with * separate copyright notices and license terms. Your use of these * subcomponents is subject to the terms and conditions of the * subcomponent's license, as noted in the LICENSE file. *******************************************************************************/ package org.cloudfoundry.identity.uaa.integration; import org.cloudfoundry.identity.uaa.ServerRunning; import org.cloudfoundry.identity.uaa.account.PasswordChangeRequest; import org.cloudfoundry.identity.uaa.scim.ScimUser; import org.cloudfoundry.identity.uaa.test.TestAccountSetup; import org.cloudfoundry.identity.uaa.test.UaaTestAccounts; import org.junit.Assume; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpResponse; import org.springframework.security.oauth2.client.http.OAuth2ErrorHandler; import org.springframework.security.oauth2.client.test.BeforeOAuth2Context; import org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration; import org.springframework.security.oauth2.client.test.OAuth2ContextSetup; import org.springframework.security.oauth2.common.util.RandomValueStringGenerator; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.util.Collections; import java.util.Map; import static org.junit.Assert.assertEquals; /** * @author * */ public class PasswordChangeEndpointIntegrationTests { private final String JOE = "joe_" + new RandomValueStringGenerator().generate().toLowerCase(); private final String userEndpoint = "/Users"; @Rule public ServerRunning serverRunning = ServerRunning.isRunning(); private UaaTestAccounts testAccounts = UaaTestAccounts.standard(serverRunning); @Rule public TestAccountSetup testAccountSetup = TestAccountSetup.standard(serverRunning, testAccounts); @Rule public OAuth2ContextSetup context = OAuth2ContextSetup.withTestAccounts(serverRunning, testAccounts); private RestOperations client; private ScimUser joe; private ResponseEntity createUser(String username, String firstName, String lastName, String email) { ScimUser user = new ScimUser(); user.setUserName(username); user.setName(new ScimUser.Name(firstName, lastName)); user.addEmail(email); user.setPassword(" user.setVerified(true); return client.postForEntity(serverRunning.getUrl(userEndpoint), user, ScimUser.class); } @Before public void createRestTemplate() throws Exception { Assume.assumeTrue(!testAccounts.isProfileActive("vcap")); client = serverRunning.getRestTemplate(); ((RestTemplate)serverRunning.getRestTemplate()).setErrorHandler(new OAuth2ErrorHandler(context.getResource()) { // Pass errors through in response entity for status code analysis @Override public boolean hasError(ClientHttpResponse response) throws IOException { return false; } @Override public void handleError(ClientHttpResponse response) throws IOException { } }); } @BeforeOAuth2Context @OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class) public void createAccount() throws Exception { client = serverRunning.getRestTemplate(); ResponseEntity response = createUser(JOE, "Joe", "User", " joe = response.getBody(); assertEquals(JOE, joe.getUserName()); } // curl -v -H "Content-Type: application/json" -X PUT -H // "Accept: application/json" --data // "{\"password\":\" // http://localhost:8080/uaa/User/{id}/password @Test @OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class) public void testChangePasswordSucceeds() throws Exception { PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword(" HttpHeaders headers = new HttpHeaders(); ResponseEntity result = client .exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password", HttpMethod.PUT, new HttpEntity<>(change, headers), Void.class, joe.getId()); assertEquals(HttpStatus.OK, result.getStatusCode()); } @Test @OAuth2ContextConfiguration(OAuth2ContextConfiguration.ClientCredentials.class) public void testChangePasswordSameAsOldFails() { PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword(" HttpHeaders headers = new HttpHeaders(); ResponseEntity result = client .exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password", HttpMethod.PUT, new HttpEntity<>(change, headers), Void.class, joe.getId()); assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, result.getStatusCode()); } @Test @OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.Implicit.class, initialize = false) public void testUserChangesOwnPassword() throws Exception { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); parameters.set("source", "credentials"); parameters.set("username", joe.getUserName()); parameters.set("password", " context.getAccessTokenRequest().putAll(parameters); PasswordChangeRequest change = new PasswordChangeRequest(); change.setOldPassword(" change.setPassword(" HttpHeaders headers = new HttpHeaders(); ResponseEntity result = client .exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password", HttpMethod.PUT, new HttpEntity<>(change, headers), Void.class, joe.getId()); assertEquals(HttpStatus.OK, result.getStatusCode()); } @Test @OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.Implicit.class, initialize = false) public void testUserMustSupplyOldPassword() throws Exception { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); parameters.set("source", "credentials"); parameters.set("username", joe.getUserName()); parameters.set("password", " context.getAccessTokenRequest().putAll(parameters); PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword(" HttpHeaders headers = new HttpHeaders(); ResponseEntity result = client .exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password", HttpMethod.PUT, new HttpEntity<>(change, headers), Void.class, joe.getId()); assertEquals(HttpStatus.BAD_REQUEST, result.getStatusCode()); } @Test @OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.ClientCredentials.class, initialize = false) public void testUserAccountGetsUnlockedAfterPasswordChange() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.set("Authorization", testAccounts.getAuthorizationHeader("app", "appclientsecret")); MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>(); data.put("grant_type", Collections.singletonList("password")); data.put("username", Collections.singletonList(joe.getUserName())); data.put("password", Collections.singletonList(" ResponseEntity result = serverRunning.postForMap( serverRunning.buildUri("/oauth/token").build().toString(), data, headers); assertEquals(HttpStatus.OK, result.getStatusCode()); // Lock out the account data.put("password", Collections.singletonList(" for (int i = 0; i < 5; i++) { result = serverRunning.postForMap(serverRunning.buildUri("/oauth/token").build().toString(), data, headers); assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); } // Check that it is locked result = serverRunning.postForMap(serverRunning.buildUri("/oauth/token").build().toString(), data, headers); assertEquals("Your account has been locked because of too many failed attempts to login.", result.getBody().get("error_description")); assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword(" MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); parameters.set("grant_type", "client_credentials"); parameters.set("username", "admin"); parameters.set("password", " context.getAccessTokenRequest().putAll(parameters); // Change the password HttpHeaders passwordChangeHeaders = new HttpHeaders(); ResponseEntity passwordChangeResult = client.exchange(serverRunning.getUrl(userEndpoint) + "/{id}/password", HttpMethod.PUT, new HttpEntity<>(change, passwordChangeHeaders), Void.class, joe.getId()); assertEquals(HttpStatus.OK, passwordChangeResult.getStatusCode()); MultiValueMap<String, String> newData = new LinkedMultiValueMap<String, String>(); newData.put("grant_type", Collections.singletonList("password")); newData.put("username", Collections.singletonList(joe.getUserName())); newData.put("password", Collections.singletonList(" ResponseEntity updatedResult = serverRunning.postForMap(serverRunning.buildUri("/oauth/token").build() .toString(), newData, headers); assertEquals(HttpStatus.OK, updatedResult.getStatusCode()); } }
java
16
0.681616
142
45.147541
244
starcoderdata
""" An example module for the homework (hint 1: you can read this comment using: `homeworkmodule.__doc__`) """ def func1(param1: int, param2: dict[str, int]): """ This function has two parameters (hint 2: you can read this comment using: `homeworkmodule.func1.__doc__`) (hint 3: you can read the annotations using: `homeworkmodule.func1.__annotations__`) """ print("Hello") def func2() -> list: """ This function has no parameters and a return value. """ return [1, 2, 3]
python
8
0.652557
88
24.772727
22
starcoderdata
public void updateThemeItems() { // Update Title themeTitle.setText(Launcher.theme); // Update ThemeBackground backgroundPanel.setIcon(themeBackground); // Update Icons fiveFieldElementIcon.setIcon(fiveFieldElementIconFromSide); fourFieldElementIcon.setIcon(fourFieldElementIconFromSide); threeFieldElementIcon.setIcon(threeFieldElementIconFromSide); twoFieldElementIcon.setIcon(twoFieldElementIconFromSide); // Update Element Names fiveFieldElementText.setText(fiveFieldElementCount + "x " + fiveFieldElementName); fourFieldElementText.setText(fourFieldElementCount + "x " + fourFieldElementName); threeFieldElementText.setText(threeFieldElementCount + "x " + threeFieldElementName); twoFieldElementText.setText(twoFieldElementCount + "x " + twoFieldElementName); // Update Buttons fiveFieldElementCountIncrease.setToolTipText("Anzahl erhöhen: " + fiveFieldElementName); fiveFieldElementCountDecrease.setToolTipText("Anzahl senken: " + fiveFieldElementName); fourFieldElementCountIncrease.setToolTipText("Anzahl erhöhen: " + fourFieldElementName); fourFieldElementCountDecrease.setToolTipText("Anzahl senken: " + fourFieldElementName); threeFieldElementCountIncrease.setToolTipText("Anzahl erhöhen: " + threeFieldElementName); threeFieldElementCountDecrease.setToolTipText("Anzahl senken: " + threeFieldElementName); twoFieldElementCountIncrease.setToolTipText("Anzahl erhöhen: " + twoFieldElementName); twoFieldElementCountDecrease.setToolTipText("Anzahl senken: " + twoFieldElementName); }
java
9
0.818475
92
54.321429
28
inline
int main() { List<int> a{}; append(a, 12); append(a, 42); append(a, 27); List<int> b{a}; // this should end up calling the copy ctor! append(b, 42); append(b, 1337); List<int> c{}; c = b; append(c, 9000); std::cout << "a:\n"; forEach(a, print); std::cout << "b:\n"; forEach(b, print); std::cout << "c:\n"; forEach(c, print); }
c++
7
0.523288
62
13.64
25
inline
import os,sys import math import random import time def map_add(mp, key1,key2, value): if (key1 not in mp): mp[key1] = {} if (key2 not in mp[key1]): mp[key1][key2] = 0.0 mp[key1][key2] += value def map_add1(mp,key): if (key not in mp): mp[key] = 0 mp[key]+=1 f = open("data/relation2id.txt","r") relation2id = {} id2relation = {} relation_num = 0 for line in f: seg = line.strip().split() relation2id[seg[0]] = int(seg[1]) id2relation[int(seg[1])]=seg[0] id2relation[int(seg[1])+1345]="~"+seg[0] relation_num+=1 f.close() ent2id, id2ent = dict(), dict() for line in open('data/entity2id.txt', 'r'): [ent, id] = line.split() ent2id[ent] = int(id) id2ent[int(id)] = ent f = open("data/train.txt","r") ok = {} a ={} num=0 step=0 for line in f: seg = line.strip().split() e1 = seg[0] e2 = seg[1] rel = seg[2] if (e1+" "+e2 not in ok): ok[e1+" "+e2]={} ok[e1+" "+e2][relation2id[rel]]=1 if (e2+" "+e1 not in ok): ok[e2+" "+e1]={} ok[e2+" "+e1][relation2id[rel]+relation_num]=1 if (e1 not in a): a[e1]={} if (relation2id[rel] not in a[e1]): a[e1][relation2id[rel]]={} a[e1][relation2id[rel]][e2]=1 if (e2 not in a): a[e2]={} if ((relation2id[rel]+relation_num) not in a[e2]): a[e2][relation2id[rel]+relation_num]={} a[e2][relation2id[rel]+relation_num][e1]=1 f.close() f = open("data/test.txt","r") for line in f: seg = line.strip().split() if (seg[0]+" "+seg[1] not in ok): ok[seg[0]+' '+seg[1]]={} if (seg[1]+" "+seg[0] not in ok): ok[seg[1]+' '+seg[0]]={} f.close() h_e_p = {} f = open("data/e1_e2.txt","r") for line in f: seg = line.strip().split() ok[seg[0]+" "+seg[1]] = {} ok[seg[1]+" "+seg[0]] = {} f.close() g = open("data/path2.txt","w") path_dict = {} path_r_dict = {} train_path = {} step = 0 time1= time.time() path_num = 0 h_e_p={} for e1 in a: step+=1 print step, for rel1 in a[e1]: e2_set = a[e1][rel1] for e2 in e2_set: map_add1(path_dict,str(rel1)) for key in ok[e1+' '+e2]: map_add1(path_r_dict,str(rel1)+"->"+str(key)) map_add(h_e_p,e1+' '+e2,str(rel1),1.0/len(e2_set)) for rel1 in a[e1]: e2_set = a[e1][rel1] for e2 in e2_set: if (e2 in a): for rel2 in a[e2]: e3_set = a[e2][rel2] for e3 in e3_set: map_add1(path_dict,str(rel1)+" "+str(rel2)) if (e1+" "+e3 in ok): for key in ok[e1+' '+e3]: map_add1(path_r_dict,str(rel1)+" "+str(rel2)+"->"+str(key)) if (e1+" "+e3 in ok):# and h_e_p[e1+' '+e2][str(rel1)]*1.0/len(e3_set)>0.01): map_add(h_e_p,e1+' '+e3,str(rel1)+' '+str(rel2),h_e_p[e1+' '+e2][str(rel1)]*1.0/len(e3_set)) ''' for rel1 in a[e1]: e2_set = a[e1][rel1] for e2 in e2_set: if (e2 in a): for rel2 in a[e2]: e3_set = a[e2][rel2] for e3 in e3_set: if (e1+" "+e3 in h_e_p and str(rel1)+' '+str(rel2) in h_e_p[e1+" "+e3]): for rel3 in a[e3]: e4_set = a[e3][rel3] if (h_e_p[e1+" "+e3][str(rel1)+' '+str(rel2)]/len(e4_set)<0.01): continue for e4 in e4_set: if (e1+" "+e4 in ok): map_add(h_e_p,e1+' '+e4,str(rel1)+' '+str(rel2)+" "+str(rel3),h_e_p[e1+" "+e3][str(rel1)+' '+str(rel2)]*1.0/len(e4_set)) ''' for e2 in a: e_1 = e1 e_2 = e2 if (e_1+" "+e_2 in h_e_p): path_num+=len(h_e_p[e_1+" "+e_2]) bb = {} aa = {} g.write(str(e_1)+" "+str(e_2)+"\n") sum = 0.0 for rel_path in h_e_p[e_1+' '+e_2]: bb[rel_path] = h_e_p[e_1+' '+e_2][rel_path] sum += bb[rel_path] for rel_path in bb: bb[rel_path]/=sum if bb[rel_path]>0.01: aa[rel_path] = bb[rel_path] g.write(str(len(aa))) for rel_path in aa: train_path[rel_path] = 1 g.write(" "+str(len(rel_path.split()))+" "+rel_path+" "+str(aa[rel_path])) g.write("\n") print path_num, time.time()-time1 sys.stdout.flush() g.close() g = open("data/confidence.txt","w") for rel_path in train_path: out = [] for i in range(0,relation_num): if (rel_path in path_dict and rel_path+"->"+str(i) in path_r_dict): out.append(" "+str(i)+" "+str(path_r_dict[rel_path+"->"+str(i)]*1.0/path_dict[rel_path])) if (len(out)>0): g.write(str(len(rel_path.split()))+" "+rel_path+"\n") g.write(str(len(out))) for i in range(0,len(out)): g.write(out[i]) g.write("\n") g.close() def work(dir): f = open("data/"+dir+".txt","r") g = open("data/"+dir+"_pra.txt","w") for line in f: seg = line.strip().split() e1 = seg[0] e2 = seg[1] rel = relation2id[seg[2]] g.write(str(ent2id[e1])+" "+ent2id([e2])+' '+str(rel)+"\n") b = {} a = {} if (e1+' '+e2 in h_e_p): sum = 0.0 for rel_path in h_e_p[e1+' '+e2]: b[rel_path] = h_e_p[e1+' '+e2][rel_path] sum += b[rel_path] for rel_path in b: b[rel_path]/=sum if b[rel_path]>0.01: a[rel_path] = b[rel_path] g.write(str(len(a))) for rel_path in a: g.write(" "+str(len(rel_path.split()))+" "+rel_path+" "+str(a[rel_path])) g.write("\n") g.write(str(e2)+" "+str(e1)+' '+str(rel+relation_num)+"\n") e1 = seg[1] e2 = seg[0] b = {} a = {} if (e1+' '+e2 in h_e_p): sum = 0.0 for rel_path in h_e_p[e1+' '+e2]: b[rel_path] = h_e_p[e1+' '+e2][rel_path] sum += b[rel_path] for rel_path in b: b[rel_path]/=sum if b[rel_path]>0.01: a[rel_path] = b[rel_path] g.write(str(len(a))) for rel_path in a: g.write(" "+str(len(rel_path.split()))+" "+rel_path+" "+str(a[rel_path])) g.write("\n") f.close() g.close() work("train") work("test")
python
26
0.43499
160
28.612335
227
starcoderdata
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using GamesPortal.Client.Interfaces.Entities; using Spark.Wpf.Common.ViewModels; namespace GamesPortal.Client.ViewModels { public class GameInfrastructuresSelector : ViewModelBase { public GameInfrastructuresSelector(GameInfrastructure[] infrastructures, bool defaultSelected) { this.Infrastructures = infrastructures.Distinct().OrderBy(i => i.GameTechnology).ThenBy(i => i.PlatformType).Select(r => new ItemSelector defaultSelected)).ToArray(); SubscribeToItemsPropertyChanged(); this.SelectAllCommand = new Command(() => SelectAll(true)); this.UnselectAllCommand = new Command(() => SelectAll(false)); } private void SelectAll(bool isSelected) { UnsubscribeFromItemsPropertyChanged(); try { foreach (var r in this.Infrastructures) r.Selected = isSelected; OnPropertyChanged(nameof(SelectedInfrastructures)); } finally { SubscribeToItemsPropertyChanged(); } } private void SubscribeToItemsPropertyChanged() { foreach (var r in this.Infrastructures) r.PropertyChanged += R_PropertyChanged; } private void UnsubscribeFromItemsPropertyChanged() { foreach (var r in this.Infrastructures) r.PropertyChanged -= R_PropertyChanged; } public ICommand SelectAllCommand { get; private set; } public ICommand UnselectAllCommand { get; private set; } private void R_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName == nameof(ItemSelector { OnPropertyChanged(nameof(SelectedInfrastructures)); } } public ItemSelector Infrastructures { get; private set; } public GameInfrastructure[] SelectedInfrastructures { get { return this.Infrastructures.Where(r => r.Selected).Select(r => r.Item).ToArray(); } } } }
c#
21
0.619975
201
32.054795
73
starcoderdata
package co.cask.cdap.apps.sentiment.web; import com.google.common.base.Throwables; import com.google.common.io.ByteStreams; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Proxies POST requests to a given url (specified thru cdap.host and cdap.port system properties). * By default proxies to http://localhost:11015. * Needed for resolving cross-domain javascript complexities. */ public class ProxyServlet extends HttpServlet { private static final Logger LOG = LoggerFactory.getLogger(ProxyServlet.class); private String cdapURL; @Override public void init() throws ServletException { String host = System.getProperty("cdap.host"); host = host == null ? "localhost" : host; String port = System.getProperty("cdap.port"); port = port == null ? "11015" : port; cdapURL = String.format("http://%s:%s", host, port); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncHttpClient client = new AsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(1000).build()); try { String url = cdapURL + req.getPathInfo(); byte[] bytes = ByteStreams.toByteArray(req.getInputStream()); String responseBody; try { responseBody = client.preparePost(url).setBody(bytes).execute().get().getResponseBody(); } catch (Exception e) { LOG.error("handling request failed", e); e.printStackTrace(); throw Throwables.propagate(e); } PrintWriter out = resp.getWriter(); out.write(responseBody); out.close(); } finally { client.close(); } } @Override protected void doGet(HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { AsyncHttpClient client = new AsyncHttpClient(new AsyncHttpClientConfig.Builder().setRequestTimeoutInMs(1000).build()); try { String url = cdapURL + req.getPathInfo() + "?" + req.getQueryString(); try { client.prepareGet(url).execute(new AsyncCompletionHandler @Override public Response onCompleted(Response response) throws Exception { PrintWriter out = resp.getWriter(); resp.setStatus(response.getStatusCode()); try { out.write(response.getResponseBody()); } finally { out.close(); } return response; } }).get(); } catch (Exception e) { LOG.error("handling request failed", e); e.printStackTrace(); throw Throwables.propagate(e); } } finally { client.close(); } } }
java
24
0.681238
117
32.698925
93
starcoderdata
const { assert } = require("chai"); const LocalAuthority = artifacts.require("LocalAuthority.sol"); contract("LocalAuthority", () => { let localAuthority = null; let medicament = null; let lab = null; before(async () => { medicament = { nom: "nametest", dosage: "dosagetest", forme: "formetest", presentation: "presentationtest", conditionnement: "conditionnementtest", specification: "specificationtest", dci: "dcitest", classement_VEIC: "classement_VEICtest", classe_therapeutic: "classe_therapeutictest", sous_classe: "sous_classetest", tableau: "tableautest", duree_conservation: "duree_conservationtest", generique: "generiquetest", }; lab = { nom: "labtest", countryCode: "1451245" }; localAuthority = await LocalAuthority.deployed(); reclamation = { sender: localAuthority.address, image: "imagetest", longitude: "longitudetest", latitude: "latitude", nom: "nomtest", dosage: "dosagetest", forme: "formetest", presentation: "presentationtest", }; }); it("Should deploy smart contract properly", async () => { assert(localAuthority.adress !== ""); }); it("Should add AMM", async () => { const result = await localAuthority.addAMM(medicament, 0, "datetest", lab); const resultMed = result.logs[0].args.amm.medicament; const resultLab = result.logs[0].args.amm.lab; assert(resultMed.nom === medicament.nom); assert(resultMed.dosage === medicament.dosage); assert(resultMed.forme === medicament.forme); assert(resultMed.presentation === medicament.presentation); assert(resultMed.conditionnement === medicament.conditionnement); assert(resultMed.specification === medicament.specification); assert(resultMed.dci === medicament.dci); assert(resultMed.classement_VEIC === medicament.classement_VEIC); assert(resultMed.classe_therapeutic === medicament.classe_therapeutic); assert(resultMed.sous_classe === medicament.sous_classe); assert(resultMed.tableau === medicament.tableau); assert(resultMed.duree_conservation === medicament.duree_conservation); assert(resultMed.generique === medicament.generique); assert(resultLab.nom === lab.nom); assert(resultLab.countryCode === lab.countryCode); assert(result.logs[0].args.amm.dateAMM === "datetest"); }); it("Should check drug veracity", async () => { const result = await localAuthority.checkDrugVeracity( "nametest", "dosagetest", "formetest", "presentationtest" ); assert(result === true); }); it("Should display drug details", async () => { const resultMed = await localAuthority.displayDrugDetails( "nametest", "dosagetest", "formetest", "presentationtest" ); assert(resultMed.nom === medicament.nom); assert(resultMed.dosage === medicament.dosage); assert(resultMed.forme === medicament.forme); assert(resultMed.presentation === medicament.presentation); assert(resultMed.conditionnement === medicament.conditionnement); assert(resultMed.specification === medicament.specification); assert(resultMed.dci === medicament.dci); assert(resultMed.classement_VEIC === medicament.classement_VEIC); assert(resultMed.classe_therapeutic === medicament.classe_therapeutic); assert(resultMed.sous_classe === medicament.sous_classe); assert(resultMed.tableau === medicament.tableau); assert(resultMed.duree_conservation === medicament.duree_conservation); assert(resultMed.generique === medicament.generique); }); it("Should update AMM", async () => { const result = await localAuthority.updateAMM( medicament, 0, "datetest2", lab, 1 ); const checkVeracity = await localAuthority.checkDrugVeracity( "nametest", "dosagetest", "formetest", "presentationtest" ); status = result.logs[0].args.amm.status; const resultMed = result.logs[0].args.amm.medicament; const resultLab = result.logs[0].args.amm.lab; assert(resultMed.nom === medicament.nom); assert(resultMed.dosage === medicament.dosage); assert(resultMed.forme === medicament.forme); assert(resultMed.presentation === medicament.presentation); assert(resultMed.conditionnement === medicament.conditionnement); assert(resultMed.specification === medicament.specification); assert(resultMed.dci === medicament.dci); assert(resultMed.classement_VEIC === medicament.classement_VEIC); assert(resultMed.classe_therapeutic === medicament.classe_therapeutic); assert(resultMed.sous_classe === medicament.sous_classe); assert(resultMed.tableau === medicament.tableau); assert(resultMed.duree_conservation === medicament.duree_conservation); assert(resultMed.generique === medicament.generique); assert(resultLab.nom === lab.nom); assert(resultLab.countryCode === lab.countryCode); assert(result.logs[0].args.amm.dateAMM === "datetest2"); assert(status == 1); }); it("Send Reclammation", async () => { const result = await localAuthority.sendReclamation(reclamation); reclamationReceived = result.logs[0].args.reclamation; assert(reclamationReceived.sender !== ""); assert(reclamationReceived.image === reclamation.image); assert(reclamationReceived.longitude === reclamation.longitude); assert(reclamationReceived.latitude === reclamation.latitude); assert(reclamationReceived.nom === reclamation.nom); assert(reclamationReceived.dosage === reclamation.dosage); assert(reclamationReceived.forme === reclamation.forme); assert(reclamationReceived.presentation === reclamation.presentation); }); });
javascript
21
0.685773
79
35.427673
159
starcoderdata
from js9 import j class Repo: def __init__(self, path): self.repo = j.clients.git.get(path) @classmethod def clone(cls, url, branch='master'): path = j.clients.git.pullGitRepo(url, branch=branch) return cls(path) def branch_or_tag(self): return self.repo.getBranchOrTag() def pull(self): self.repo.pull() def fetch(self): self.repo.fetch() def switch_branch(self, branch): self.repo.switchBranch(branch, create=False) def switch_tag(self, tag): self.repo.checkout(tag) class RepoCheckoutError(Exception): """ Exception raised when the checkout of a branch/tag/revision failed on a repo """ def __init__(self, msg, original_exception): super().__init__(msg + (": %s" % original_exception)) self.original_exception = original_exception
python
12
0.627624
80
22.815789
38
starcoderdata
package com.example.opencvdemo2; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import static org.opencv.core.Core.compare; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mRect; private Button mLinefg; private Button mShow; private Button mLinebg; private LinearLayout mImage; private Bitmap mbitmap; private DrawView mdrawView; private Paint mpaint; //画笔 private int mode; private static final int drawWithLinebg = 10; //背景 private static final int drawWithLinefg = 11; //前景 private static final int drawWithRect = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iniLoadOpencv(); init(); setLinster(); } private void init() { mRect = (Button)findViewById(R.id.rect); mLinefg = (Button)findViewById(R.id.linefg); mLinebg = (Button)findViewById(R.id.linebg); mShow = (Button)findViewById(R.id.showFront); mImage = (LinearLayout) findViewById(R.id.srcImage); mbitmap = BitmapFactory.decodeResource(getResources(), R.drawable.test2); mdrawView = new DrawView(MainActivity.this, mbitmap); mImage.addView(mdrawView); } private void setLinster(){ mRect.setOnClickListener(this); mLinefg.setOnClickListener(this); mShow.setOnClickListener(this); mLinebg.setOnClickListener(this); } /** * 加载opencv库 */ private void iniLoadOpencv(){ boolean success = OpenCVLoader.initDebug(); if(success){ Log.i("CV_TAG","opencv"); }else{ Toast.makeText(this.getApplicationContext(),"WARNING: not",Toast.LENGTH_SHORT).show(); } } @Override public void onClick(View view) { switch (view.getId()){ case R.id.rect: mdrawView.clear(); mode = drawWithRect; mdrawView.setMode(mode); break; case R.id.linebg: mdrawView.clear(); mode = drawWithLinebg; mdrawView.setMode(mode); break; case R.id.linefg: mdrawView.clear(); mode = drawWithLinefg; mdrawView.setMode(mode); break; case R.id.showFront: mdrawView.showFront(); break; } } }
java
11
0.648657
98
27.632479
117
starcoderdata
public Filter findFilterByName(String name) { Filter filter = null; SQLiteDatabase db = getReadableDatabase(); Cursor cursor = db.query(FILTERS_TABLE, new String[] { KEY_NAME, KEY_ADDRESS }, KEY_NAME + "=?", new String[] { name }, null, null, null); while (cursor.moveToNext()) { if (filter != null) { // There must be only one filter with this name. throw new AssertionError(); } String address = cursor.getString(1); List<String> contentFilters = getContentFilters(name); filter = new Filter(name, address, contentFilters); } cursor.close(); db.close(); return filter; }
java
10
0.647335
66
31.684211
19
inline
import { cleanup } from "@testing-library/react"; import { renderWithTheme } from "../../utils"; import ItemListEdit from "../ItemListEdit.js"; const mockData = { "title": "keywords", "items": [ { "id": 10, "name": " "description": null, "category": 4, "created_at": "2021-10-29", "updated_at": "2021-10-29" }, { "id": 11, "name": "Team leading", "description": null, "category": 4, "created_at": "2021-10-29", "updated_at": "2021-10-29" } ] } describe.only("ItemlistEdit component", () => { afterEach(cleanup); it("should render without crashing", () => { const { container } = renderWithTheme(<ItemListEdit items={mockData.items} onRemove={()=>{}}/>); expect(container).toBeTruthy(); }); it("should render items", () => { const { getByText } = renderWithTheme(<ItemListEdit items={mockData.items} onRemove={()=>{}} />); expect(getByText(mockData.items[0].name)).toBeInTheDocument(); expect(getByText(mockData.items[1].name)).toBeInTheDocument(); }) it("should remove correct item, and call onRemove with correct items", () =>{ const onRemove = jest.fn(); const { getAllByLabelText } = renderWithTheme(<ItemListEdit items={mockData.items} onRemove={onRemove}/>); const deleteButtons = getAllByLabelText('delete'); expect(deleteButtons.length).toEqual(2); deleteButtons[0].click(); expect(onRemove).toBeCalledWith(mockData.items[0]); }) });
javascript
21
0.596277
110
33.622222
45
starcoderdata
using System; using Optional; namespace NukedBit.NRepo.Services { public class ConsoleService : IConsoleService { public void WriteLine(string inputString) => Console.WriteLine(inputString); public void WriteLine() => Console.WriteLine(); public void WriteLineColored(ConsoleColor color, string inputString) { var currentColor = Console.ForegroundColor; Console.ForegroundColor = color; Console.WriteLine(inputString); Console.ForegroundColor = currentColor; } public string ReadLine() => Console.ReadLine(); public bool AskForConfirmation() { Console.Write("Yes/No:"); while (true) { var line = Console.ReadLine()?.ToLowerInvariant()?.Trim(); if (line == "yes") { return true; } else if (line == "no") { return false; } else { Console.WriteLine("What?"); Console.Write("Yes/No:"); } } } public Option ReadInputNumber(int min, int max) { var defaultColor = Console.ForegroundColor; while (true) { Console.ForegroundColor = ConsoleColor.Yellow; Console.Write(">"); Console.ForegroundColor = defaultColor; var line = Console.ReadLine(); if (int.TryParse(line, out var result) && result >= min && result <= max) { return Option.Some(result); } if (line?.Trim() == "exit") { break; } } return Option.None } } }
c#
19
0.464066
89
27.647059
68
starcoderdata
package ru.otus.listener.homework; import ru.otus.Message; import ru.otus.listener.Listener; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; public class ListenerMessageHistory implements Listener { private class MessageHistoryRecord { private final Message oldMessage; private final Message newMessage; private final LocalDate dateMessage; public MessageHistoryRecord(Message oldMessage, Message newMessage, LocalDate dateMessage) { this.oldMessage = new Message(oldMessage); this.newMessage = new Message(newMessage); this.dateMessage = dateMessage; } public String toString() { return String.format("\n[%s]:\noldMsg:%s\nnewMsg:%s", LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), oldMessage, newMessage); } } private final List msgHistory = new ArrayList<>(); @Override public void onUpdated(Message oldMsg, Message newMsg) { msgHistory.add(new MessageHistoryRecord(oldMsg, newMsg, LocalDate.now())); } public List printHistory() { List res = new ArrayList<>(); for (MessageHistoryRecord record : msgHistory) { res.add(record.toString()); } return res; } }
java
15
0.680606
157
32.02381
42
starcoderdata
func (b *Bot) StoreMessages(user *User, msgs []Message) error { // check if bot belongs to user exists, err := rowExists("SELECT * FROM Bot WHERE BotID=$1 AND User=$2", b.ID, user.ID) if err != nil { log.Println("cannot check for bot:", err) return ErrInternalServerError } else if !exists { return ErrBotDoesNotBelongToUser } // start a new database transaction tx, err := dbConnection.db.Begin() if err != nil { log.Fatal(err) } stmt, err := tx.Prepare(` INSERT INTO Message(Bot,Sender,Timestamp,Content) VALUES($1,$2,$3,$4)`) if err != nil { tx.Rollback() log.Println("cannot rollback:", err) return ErrInternalServerError } defer stmt.Close() for _, m := range msgs { if len(m.Content) > MessageMaxLength { tx.Rollback() return ErrMessageToLong } _, err := stmt.Exec(b.ID, m.Sender, m.Timestamp, m.Content) if err != nil { tx.Rollback() log.Println("cannot store message:", err) return ErrInternalServerError } } err = tx.Commit() if err != nil { log.Println("cannot commit changes:", err) return ErrInternalServerError } return nil }
go
11
0.667268
88
24.813953
43
inline
package com.uantwerp.algorithms; import java.util.Timer; import javax.swing.SwingUtilities; import com.uantwerp.algorithms.Efficiency.VariablesTimer; import com.uantwerp.algorithms.common.GraphParameters; import com.uantwerp.algorithms.gui.SubgraphMiningGUI; import com.uantwerp.algorithms.utilities.AlgorithmUtility; import com.uantwerp.algorithms.utilities.MultipleTestingCorrection; import com.uantwerp.algorithms.utilities.OutputUtility; import com.uantwerp.algorithms.utilities.PrintUtility; public class BasicRepresentation extends Thread { protected Timer myTimer; protected SubgraphMiningGUI mainThread; public BasicRepresentation(Timer t, SubgraphMiningGUI mainThread) { this.myTimer = t; this.mainThread = mainThread; } @Override public void run() { try { this.updateGUI("start"); // Import graphs, labels, set of interest and background files and store as // HashMaps and HashSets HashGeneration.graphGeneration(); // if (GraphParameters.verbose == 1) PrintUtility.printSummary(); GraphParameters.supportcutoff = AlgorithmUtility.supportTreshold(); // Check interrupted to stop the analysis if (!Thread.interrupted()) { this.runAnalysis(); } // Check interrupted to stop the analysis if (!Thread.interrupted()) { this.recalculateAndPrintResults(); } } catch (Exception e) { SubgraphMining.exceptionBehaviour(e); } finally { if (VariablesTimer.stateFinish) VariablesTimer.writeResults(GraphParameters.statistics); this.updateGUI("stop"); } } private void updateGUI(String status) { if (mainThread == null) return; SwingUtilities.invokeLater(new Runnable() { public void run() { mainThread.updateGUI(status); } }); } protected void runAnalysis() { // Do nothing here // This should be overridden by sub-class. } protected void recalculateAndPrintResults() { // if a file with interesting vertices was provided // evaluates to 0 for both empty or non-existent files // if (GraphParameters.interestFile != null && GraphParameters.interestFile.length() != 0) { if (GraphParameters.frequentMining == false) { // print information on which type of subgraphs will be shown (all supported // with raw p-values or only p <= alpha) // OutputUtility.preResultStatistics(); // perform multiple testing correction and store number of significant subgraphs MiningState.supportedMotifsAdjustedPValues = MultipleTestingCorrection .adjustPValues(MiningState.supportedMotifsPValues, GraphParameters.correctionMethod); // generate table with motifs, freqs and p-values (also stores the number of // significant subgraphs after correction) String outputTable = OutputUtility.createTable(); // write output files or print to stdout OutputUtility.writeOutputFiles(outputTable); // print summary statistics OutputUtility.printStatistics(); } // if no interesting vertices were provided = frequent subgraph mode else { // print information on which type of subgraphs will be shown (support > // threshold) // OutputUtility.preResultStatisticsFrequent(); // generate table with motifs and support values String outputTable = OutputUtility.createTableFrequent(); // write output files or print to stdout OutputUtility.writeOutputFiles(outputTable); // print summary statistics OutputUtility.printStatisticsFrequent(); } VariablesTimer.finishProcess(); myTimer.cancel(); } }
java
13
0.751841
93
28.663866
119
starcoderdata
var config = require('../../transpile-config'); var sassTypesToWatch = [ `${config.src}/**/*.scss`, `${config.src}/**/*.sass` ]; var sassTypesToTranspile = sassTypesToWatch.concat([ `!${config.src}/**/_*.scss`, `!${config.src}/**/_*.sass` ]); module.exports = gulp=> { config.deployModes.forEach(mode=> { gulp.task(`sass:${mode}`, ()=> { var mainPiper = transPileSassInEnv(mode); setWatcherInEnv(mode); return mainPiper.getActiveStream(); }); }); function transPileSassInEnv(mode) { return sourceSassInEnv(mode) .pipeSourcemapsInit() .pipeSass() .pipeSourmapsWrite() .pipeDest(); } function sourceSassInEnv(mode) { var sourcemaps = require('gulp-sourcemaps'); var store = { wrappedStream: gulp.src(sassTypesToTranspile) }; var isDebugNeeded = !!config.inEnv[mode].debug; var that = {}; that = { pipeSourcemapsInit() { if (!isDebugNeeded) return that; store.wrappedStream = store.wrappedStream.pipe(sourcemaps.init()); return that; }, pipeSass() { var sass = require('gulp-sass'); store.wrappedStream = store.wrappedStream.pipe( sass(isDebugNeeded ? undefined : { outputStyle: 'compressed' }) ); return that; }, pipeSourmapsWrite() { if (!isDebugNeeded) return that; store.wrappedStream = store.wrappedStream.pipe(sourcemaps.write()); return that; }, pipeDest() { store.wrappedStream = store.wrappedStream.pipe( gulp.dest(`${config.targetPathFor[mode]}/css`) ); return that; }, getActiveStream(){ return store.wrappedStream; } }; return that; } function setWatcherInEnv(mode) { var isWatchifyNeeded = config.inEnv[mode].watchify; if (!isWatchifyNeeded) return; var log = require('gulp-util').log; log('Started watching for Sass changes...'); return gulp.watch(sassTypesToWatch, ()=> { transPileSassInEnv(mode); }).on('change', e=> { log('Sass file changed at ', e.path); }); } };
javascript
22
0.507626
83
30.182927
82
starcoderdata
package controllers; import com.google.common.io.Files; import com.google.inject.Inject; import models.Product; import models.Tag; import static play.mvc.Http.MultipartFormData; import play.api.db.Database; import play.data.Form; import play.data.FormFactory; import play.mvc.Result; import play.mvc.Controller; import play.mvc.With; import utils.Catch; import views.html.products.details; import views.html.products.list; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by Xavier on 1/17/2016. */ @Catch public class Products extends Controller { private Database db; FormFactory formFactory; Form productForm; @Inject public Products(FormFactory formFactory, Database db){ this.formFactory = formFactory; this.productForm = this.formFactory.form(Product.class); this.db = db; } public Result index(){ return redirect(routes.Products.list(0)); } public Result list(Integer page){ List products = Product.find.all(); return ok(list.render(products)); } public Result newProduct(){ return ok(details.render(productForm)); } public Result details(String ean){ final Product product = Product.find.byId((long) 0); if(product == null){ return notFound(String.format("Product %s does not exist.", ean)); } Form filledForm = productForm.fill(product); return ok(details.render(filledForm)); } // public Result details(Product product){ // Form filledForm = productForm.fill(product); // return ok(details.render(filledForm)); // } //TODO Fix this function public Result save(){ Form boundForm = productForm.bindFromRequest(); if(boundForm.hasErrors()){ flash("error","Please correct the form below."); return badRequest(details.render(boundForm)); } Product product = boundForm.get(); MultipartFormData body = request().body().asMultipartFormData(); MultipartFormData.FilePart part = body.getFile("picture"); if(part != null){ File picture = (File) part.getFile(); try { product.picture = Files.toByteArray(picture); } catch (IOException e) { return internalServerError("Error reading file upload"); } } product.save(); flash("success", String.format("Saved product %s", product)); return redirect(routes.Products.list(1)); } public Result delete(String ean){ // final Product product = Product.findByEan(ean); // if(product == null){ // return notFound(String.format("Product %s does not exist.", ean)); // } // Product.remove(product); // return redirect(routes.Products.list(1)); return TODO; } public Result picture(String ean) { // final Product product = Product.findByEan(ean); // if(product == null) return notFound(); // return ok(product.picture); return TODO; } }
java
14
0.635994
80
28.583333
108
starcoderdata
package org.uberfire.java.nio.fs.k8s; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.uberfire.java.nio.base.WatchContext; import org.uberfire.java.nio.file.Path; import org.uberfire.java.nio.file.WatchEvent; import org.uberfire.java.nio.file.WatchEvent.Kind; import org.uberfire.java.nio.file.WatchKey; import org.uberfire.java.nio.file.Watchable; import static org.uberfire.java.nio.fs.k8s.K8SFileSystemConstants.K8S_FS_NO_IMPL; @SuppressWarnings("serial") public class K8SWatchKey implements WatchKey { private final transient K8SWatchService service; private final transient Path path; private final AtomicReference state = new AtomicReference<>(State.READY); private final AtomicBoolean valid = new AtomicBoolean(true); private final BlockingQueue events = new LinkedBlockingQueue<>(); @SuppressWarnings("rawtypes") private final transient Map<Kind, Event> eventKinds = new ConcurrentHashMap<>(); K8SWatchKey(K8SWatchService service, Path path) { this.service = service; this.path = path; } @Override public boolean isValid() { return !service.isClose() && valid.get(); } @Override public List pollEvents() { List result = new ArrayList<>(events.size()); events.drainTo(result); eventKinds.clear(); return Collections.unmodifiableList(result); } @Override public boolean reset() { if (isValid()) { events.clear(); eventKinds.clear(); return state.compareAndSet(State.SIGNALLED, State.READY); } else { return false; } } @Override public void cancel() { valid.set(false); } @Override public Watchable watchable() { return this.path; } @SuppressWarnings("rawtypes") protected boolean postEvent(WatchEvent.Kind kind) { Event event = eventKinds.computeIfAbsent(kind, k -> { Event e = new Event(kind, new Context(K8SWatchKey.this.path.getFileName())); return events.offer(e) ? e : null; }); if (event == null) { return false; } else { event.increaseCount(); return true; } } protected boolean isQueued() { return state.get() == State.SIGNALLED; } protected void signal() { state.compareAndSet(State.READY, State.SIGNALLED); } enum State { READY, SIGNALLED } @SuppressWarnings("rawtypes") private static final class Event implements WatchEvent { private final AtomicInteger count = new AtomicInteger(0); private final transient Kind kind; private final transient Context context; private Event(Kind kind, Context context) { this.kind = kind; this.context = context; } @SuppressWarnings("unchecked") @Override public Kind kind() { return this.kind; } @Override public int count() { return count.get(); } @Override public Context context() { return this.context; } private int increaseCount() { return count.incrementAndGet(); } } private static final class Context implements WatchContext { private final Path path; private Context(Path path) { this.path = path; } @Override public Path getPath() { return this.path; } @Override public Path getOldPath() { return this.path; } @Override public String getSessionId() { return K8S_FS_NO_IMPL; } @Override public String getMessage() { return K8S_FS_NO_IMPL; } @Override public String getUser() { return K8S_FS_NO_IMPL; } } }
java
20
0.614756
88
25.69697
165
starcoderdata