language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
1,723
2.828125
3
[]
no_license
import speech_recognition import pyttsx3 from datetime import date, datetime #Robot nghe robot_ear = speech_recognition.Recognizer() robot_mouth = pyttsx3.init() robot_brain = "" # Test get audio #with speech_recognition.WavFile("output.wav") as source: # use "test.wav" as the audio source # robot_ear.adjust_for_ambient_noise(source) # listen for 1 second to calibrate the energy threshold for ambient noise levels # audio = robot_ear.record(source) # End test audio while True: with speech_recognition.Microphone() as mic: print ("Robot: I'm Listening") robot_ear.adjust_for_ambient_noise(mic) # listen for 1 second to calibrate the energy threshold for ambient noise levels audio = robot_ear.listen(mic) print("Robot: ...") try: you = robot_ear.recognize_google(audio) except: you = "" print ("You: " + you) # Robot suy nghi if you == "": robot_brain = "I can't hear you, try again" elif "hello" in you: robot_brain = "Hello Thai. How are you? What are you doing?" elif "today" in you: today = date.today() robot_brain=today.strftime("%B %d, %Y") #print(robot_brain) elif "time" in you: now = datetime.now() robot_brain = now.strftime("%H hours %M minutes %S seconds ") #print(robot_brain) # Textual month, day and year elif "robot" in you: robot_brain = "Hello Thai. Why do you say me Robot? I'm not Robot! I'm your friend." elif "bye" in you: robot_brain = "Good bye Thai" robot_mouth.say(robot_brain) print ("Robot: " + robot_brain) robot_mouth.runAndWait() break else: robot_brain = "I don't know what you say" print ("Robot: " + robot_brain) # Robot tra loi robot_mouth.say(robot_brain) robot_mouth.runAndWait()
Java
UTF-8
557
2.46875
2
[]
no_license
package com.logibeat.cloud.common.enumtype; /** * Created by Yujinjun on 2017/2/10. */ public enum EntStatus { Unknown(0, "未知(全部)"), Enter(1, "已入驻"), UnClaim(2,"待认领"), UnEnter(3,"未入驻"); private Integer value; private String description; EntStatus(Integer value, String description) { this.value = value; this.description = description; } public Integer getValue() { return value; } public String getDescription() { return description; } }
Java
UTF-8
954
2.328125
2
[]
no_license
package com.bonc.dw3.common.util; import org.apache.hadoop.hbase.client.Get; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; public class MyThread extends Thread { private static Logger log = LoggerFactory.getLogger(MyThread.class); List<Get> listGet; String tableName; public List<String> rs; public MyThread(List<Get> listGet,String tableName){ this.listGet = listGet; this.tableName = tableName; } @Override public void run() { //List<String> rs=new ArrayList<>(); try { //long time=System.currentTimeMillis(); this.rs=HbaseRexUtil.getListByHtable(tableName,listGet); //System.out.println("线程:[],时间为:"+(System.currentTimeMillis()-time)+"ms"); //System.out.println("result from hbase:...." + this.rs); } catch (Exception e) { e.printStackTrace(); } } }
TypeScript
UTF-8
386
3.3125
3
[]
no_license
function singleNumbers(nums: number[]): number[] { let res = nums.reduce((prev, curr) => prev ^ curr, 0); let div = 1; while ((res & div) === 0) { div = div << 1; } let a = 0; let b = 0; nums.forEach(num => { if (num & div) { a ^= num } else { b ^= num } }); return [a, b]; }; const nums = [4, 1, 4, 6]; console.log(singleNumbers(nums));
Python
UTF-8
389
2.6875
3
[]
no_license
#The number of Class I Drug Recalls issued by # the U.S. Food and Drug Administration since 2012 import requests from bs4 import BeautifulSoup url = 'http://www.fda.gov/Drugs/DrugSafety/DrugRecalls/default.htm' r = requests.get(url) soup = BeautifulSoup(r.content, 'lxml') # Style: display:none appears in every row of the table. print(len(soup.find_all('td', {"style":"display:none"})))
C++
UTF-8
2,718
2.578125
3
[ "BSD-2-Clause" ]
permissive
/* * Copyright (c) 2014 Burkhard Ritter * This code is distributed under the two-clause BSD License. */ #ifndef JACKMIDI_HPP #define JACKMIDI_HPP #include <jack/jack.h> #include <jack/midiport.h> template<class MessageQueue> class JackMidi { private: // Can or should I use smart pointers instead? jack_client_t* client; jack_port_t* output_port; bool active; MessageQueue& queue; public: JackMidi (MessageQueue& queue_) : queue(queue_) {} bool init () { client = jack_client_open("footswitchmidi", JackNullOption, nullptr); if (client == nullptr) return false; jack_set_process_callback(client, process_callback, this); jack_set_sample_rate_callback(client, sample_rate_callback, this); jack_on_shutdown(client, shutdown_callback, this); output_port = jack_port_register(client, "midi_out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0); if (output_port == nullptr) return false; if (jack_activate(client) != 0) return false; return true; } bool deinit () { if (jack_deactivate(client) != 0) return false; if (jack_client_close(client) != 0) return false; return true; } private: int process (jack_nframes_t nframes) { void* port_buffer = jack_port_get_buffer(output_port, nframes); jack_midi_clear_buffer(port_buffer); typename MessageQueue::Message m; while (queue.pop(m)) { const unsigned char channel = 0; const unsigned char controller_number = 20 + m.button; unsigned char controller_value; if (m.on) controller_value = 127; else controller_value = 0; jack_midi_data_t* buffer = jack_midi_event_reserve(port_buffer, 0, 3); buffer[0] = 0xB0 + channel; buffer[1] = controller_number; buffer[2] = controller_value; } return 0; } int sample_rate (jack_nframes_t nframes) { return 0; } void shutdown () { } static int process_callback (jack_nframes_t nframes, void* arg) { JackMidi* self = static_cast<JackMidi*>(arg); return self->process(nframes); } static int sample_rate_callback (jack_nframes_t nframes, void* arg) { JackMidi* self = static_cast<JackMidi*>(arg); return self->sample_rate(nframes); } static void shutdown_callback (void* arg) { JackMidi* self = static_cast<JackMidi*>(arg); return self->shutdown(); } }; #endif /* JACKMIDI_HPP */
C++
UTF-8
13,101
2.703125
3
[]
no_license
// // Created by F1 on 5/31/2016. // #include "Skeleton.hpp" int Skeleton::set_fps(float fps) { frame_time = 1.0f / fps; return 1; } int Skeleton::set_default_anim(int anim, int end_type) { if (anim < 0 || anim > anim_count) { LOGE("Error: tried setting animation to %d when only %d animations are loaded by this skeleton.\n", anim, anim_count); return 0; } default_anim = anim; default_anim_end_type = end_type; } int Skeleton::anim_is_valid(int anim) { if (anim < 0 || anim > anim_count) return 0; return 1; } int Skeleton::play_anim(int anim, int end_type) { if (!anim_is_valid(anim)) { LOGE("Error: tried setting animation to %d when only %d animations are loaded by this skeleton.\n", anim, anim_count); return 0; } current_anim_end_type = end_type; current_anim = anim; current_frame = 0; dest_frame = 1; playing_anim = true; return 1; } int Skeleton::play_default_anim() { if (!anim_is_valid(default_anim)) { LOGE("Error: tried playing invalid default animation %d.", default_anim); return 0; } playing_default_anim = true; current_anim = default_anim; current_frame = 0; dest_frame = 1; current_anim_end_type = default_anim_end_type; return 1; } int Skeleton::stop_anim() { playing_anim = false; current_anim = -1; current_anim_end_type = END_TYPE_ROOT_POSE; current_frame = 0; dest_frame = 0; return 1; } //Calculate pose matrices somewhere between current_frame and dest_frame void Skeleton::calc_lerped_pose_mats() { //Getting lerping factor: float ctime = time(); float t = 1.0f - (time_for_next_frame - ctime) / frame_time; t = fmaxf(fminf(t, 1.0f), 0.0f); //Repopulating our current frame matrices with the new correct bone matrices Mat4 bone_trans; Mat3 bone_IT_trans; float *trans_a; float *trans_b; float *trans_IT_a; float *trans_IT_b; for (int i = 0; i < bone_count; i++) { //Calculate transformation Mat4 trans_a = (anims[current_anim]) + (bone_count * 16 * current_frame) + (i * 16); trans_b = (anims[current_anim]) + (bone_count * 16 * dest_frame) + (i * 16); bone_trans = Mat4::LERP(Mat4(trans_a), Mat4(trans_b), t); //Copying transformation Mat4 into the float array for (int j = 0; j < 16; j++) { current_pose_mat4s[16 * i + j] = bone_trans.m[j]; } //Calculate inverse-transpose Mat3 trans_IT_a = (anims_IT[current_anim]) + (bone_count * 9 * current_frame) + (i * 9); trans_IT_b = (anims_IT[current_anim]) + (bone_count * 9 * dest_frame) + (i * 9); bone_IT_trans = Mat3::LERP(Mat3(trans_IT_a), Mat3(trans_IT_b), t); //Copying inverse-transpose Mat3 into the float array for (int j = 0; j < 9; j++) { current_pose_mat3s[9 * i + j] = bone_IT_trans.m[j]; } } } //Calculate at current frame (no lerp) void Skeleton::calc_pose_mats() { //Repopulating our current frame matrices with the new correct bone matrices Mat4 bone_trans; Mat3 bone_IT_trans; float *trans; float *trans_IT; for (int i = 0; i < bone_count; i++) { //Calculate transformation Mat4 trans = (anims[current_anim]) + (bone_count * 16 * current_frame) + (i * 16); bone_trans = Mat4(trans); //Copying transformation Mat4 into the float array for (int j = 0; j < 16; j++) { current_pose_mat4s[16 * i + j] = bone_trans.m[j]; } //Calculate inverse-transpose Mat3 trans_IT = (anims_IT[current_anim]) + (bone_count * 9 * current_frame) + (i * 9); bone_IT_trans = Mat3::ROTATE(trans_IT); //Copying inverse-transpose Mat3 into the float array for (int j = 0; j < 9; j++) { current_pose_mat3s[9 * i + j] = bone_IT_trans.m[j]; } } } //Ran every frame to update animation frame logic (calculate interpolation data, increment frame, etc) int Skeleton::update_frame() { if (!playing_anim) return 1; float ctime = time(); if (ctime > time_for_next_frame) { current_frame += 1; dest_frame += 1; time_for_next_frame = ctime + frame_time; if (current_frame >= anim_lengths[current_anim]) { switch (current_anim_end_type) { case END_TYPE_ROOT_POSE: default: stop_anim(); return 1; case END_TYPE_FREEZE: current_frame--; dest_frame = current_frame; break; case END_TYPE_LOOP: current_frame = 0; dest_frame = 1; break; case END_TYPE_DEFAULT_ANIM: if (anim_is_valid(default_anim)) { play_default_anim(); } else { LOGW("Warning: anim end type of play_default_anim was summoned with an invalid default anim of %d\n", default_anim); stop_anim(); return 1; } break; } } //next_frame = current_frame + 1; //dest_frame = next_frame + 1; //Setting the frame to lerp to if (dest_frame >= anim_lengths[current_anim]) { switch (current_anim_end_type) { case END_TYPE_ROOT_POSE: default: case END_TYPE_FREEZE: dest_frame--; break; case END_TYPE_LOOP: dest_frame = 0; break; case END_TYPE_DEFAULT_ANIM: //Technically next frame is going to be frame 0 of default anim... I sense complications here //TODO / FIXME: this isn't lerped correctly //We have to handle fading different anims before figuring this out //Don't lerp for now. FIXME dest_frame = current_frame;//FIXME should be first frame of next anim? or just current frame? (no lerp) break; } } } if (current_frame != dest_frame) calc_lerped_pose_mats(); else calc_pose_mats(); return 1; } //Returns a pointer to the current frame matrix generation data float *Skeleton::get_current_pose() { if (!playing_anim) { return rest_pose_ident_mat4s; } return current_pose_mat4s; } //Returns a pointer to the current frame's inverse-transpose matrix generation data float *Skeleton::get_current_pose_IT() { if (!playing_anim) { return rest_pose_ident_mat3s; } return current_pose_mat3s; } //Returns the ith bone's current transform matrix generation data (within animation) Mat4 Skeleton::get_bone_transform(int i) { if (!playing_anim) { return Mat4::IDENTITY(); } if (i < 0 || i >= bone_count) { LOGE("Error: tried getting transform of out of bounds bone index %d, bone_count=%d\n", i, bone_count); return Mat4::IDENTITY(); } float *data = current_pose_mat4s + (i * 16); return Mat4(data); } int Skeleton::load(const char *filepath) { raw_data = (unsigned int *) File_Utils::load_raw_asset(filepath); if (!raw_data) { LOGE("Error: failed to load \"%s\"\n", filepath); return 0; } //File Schematics //First int is the bone count //List thereafter is a list of matrices in order as they are accessed by the model bone_count = raw_data[0]; rest_pose = (float *) raw_data + 1; //Populating a list of identity matrices for displaying the skeleton's rest post Mat4 ident4 = Mat4::IDENTITY(); rest_pose_ident_mat4s = (float *) malloc(sizeof(float) * bone_count * 16); current_pose_mat4s = (float *) malloc(sizeof(float) * bone_count * 16); for (int i = 0; i < 16; i++) { for (int j = 0; j < bone_count; j++) { rest_pose_ident_mat4s[j * 16 + i] = ident4.m[i]; //Initializing current pose mat4s to identity matrices current_pose_mat4s[j * 16 + i] = ident4.m[i]; } } Mat3 ident3 = Mat3::IDENTITY(); rest_pose_ident_mat3s = (float *) malloc(sizeof(float) * bone_count * 9); current_pose_mat3s = (float *) malloc(sizeof(float) * bone_count * 9); for (int i = 0; i < 9; i++) { for (int j = 0; j < bone_count; j++) { rest_pose_ident_mat3s[j * 9 + i] = ident3.m[i]; //Initializing current pose mat3s to identity matrices current_pose_mat3s[j * 9 + i] = ident3.m[i]; } } return 1; } //Returns the rest transform of the ith bone Mat4 Skeleton::get_bone_rest_transform(int i) { if (i < 0 || i >= bone_count) { LOGE("Error: tried getting rest transform of out of bounds bone index %d, bone_count=%d\n", i, bone_count); return Mat4::IDENTITY(); } float *data = rest_pose + (i * 16); return Mat4(data); } void Skeleton::unload() { if (raw_data) free((void *) raw_data); if (all_anims_raw_data) { for (int i = 0; i < anim_count; i++) { free((void *) all_anims_raw_data[i]); } free(all_anims_raw_data); free(anims); free(anims_IT); free(anim_lengths); } if (rest_pose_ident_mat4s) free(rest_pose_ident_mat4s); if (rest_pose_ident_mat3s) free(rest_pose_ident_mat3s); if (current_pose_mat4s) free(current_pose_mat4s); if (current_pose_mat3s) free(current_pose_mat3s); } Skeleton::Skeleton(const char *filepath) { load(filepath); } Skeleton::~Skeleton() { unload(); } int Skeleton::load_animation(const char *filepath) { unsigned int *loaded_anim = (unsigned int *) File_Utils::load_raw_asset(filepath); if (!loaded_anim) { LOGE("Error: failed to load \"%s\"\n", filepath); return 0; } if (loaded_anim[0] != bone_count) { LOGE("Error: cannot load animation with %ud bones to a skeleton with %ud bones!\n", loaded_anim[0], bone_count); return 0; } anim_count++; //Creating new arrays that can hold all of the animations const unsigned int **new_anims_data = (const unsigned int **) malloc( sizeof(int *) * anim_count); unsigned int *new_anim_lengths = (unsigned int *) malloc(sizeof(unsigned int) * anim_count); float **new_anims = (float **) malloc(sizeof(float *) * anim_count); float **new_anims_IT = (float **) malloc(sizeof(float *) * anim_count); if (all_anims_raw_data && anim_lengths && anims && anims_IT) { //Copying all of the old values for (int i = 0; i < anim_count - 1; i++) { new_anims_data[i] = all_anims_raw_data[i]; new_anim_lengths[i] = anim_lengths[i]; new_anims[i] = anims[i]; new_anims_IT[i] = anims_IT[i]; } //Freeing the old arrays free(all_anims_raw_data); free(anim_lengths); free(anims); free(anims_IT); } //Handing off the array location to the class variables all_anims_raw_data = new_anims_data; anim_lengths = new_anim_lengths; anims = new_anims; anims_IT = new_anims_IT; int cindex = anim_count - 1; //File Schematics //First int is the bone count //Second int is the frame count //List thereafter is a list of frames //Each frame holds a list of data to build matrices per bone //This data is 16 floats for the 4x4 transform matrix //List thereafter is a list of frames //Each frame in this list holds the data needed to build inverse transpose 3x3 Matrix of the bone matrices //This data is 9 floats for the 3x3 matrix //animation_bone_count = animation_raw_data[0]; //Assigning the new just-loaded stuff all_anims_raw_data[cindex] = loaded_anim; anim_lengths[cindex] = all_anims_raw_data[cindex][1]; anims[cindex] = (float *) all_anims_raw_data[cindex] + 2; anims_IT[cindex] = (float *) all_anims_raw_data[cindex] + 2 + (16 * bone_count * anim_lengths[cindex]); return 1; } Mat4 Entity_Bone_Joint::get_world_transform(bool modify_trans) { if (!parent_skel) { LOGE("Error: Entity_Bone_Joint skeletal parent not set.\n"); return Mat4::IDENTITY(); } if (transform_calculated && modify_trans) { return world_transform; } transform = parent_skel->get_bone_transform(parent_bone_index) * parent_skel->get_bone_rest_transform(parent_bone_index); if (modify_trans) transform_calculated = true; //Bone transforms seem to introduce a roll of 90 degrees, so undoing it Quat fix_roll(HALF_PI, Vec3::FRONT()); return parent_skel->get_world_transform(modify_trans) * transform * Mat4::ROTATE(fix_roll); }
C#
UTF-8
4,438
2.578125
3
[]
no_license
using Entities; using Microsoft.Practices.EnterpriseLibrary.Data; using Services; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL { public class DALBitacoraSQL : DataAccessComponent { private Services.ConexionSQL conexion = new Services.ConexionSQL(); public void CrearBitacoraSQL(BitacoraSQL objeto) { BitacoraSQL Bitacora = new BitacoraSQL(); Bitacora.ComputerName = System.Net.Dns.GetHostName(); Bitacora.IP = System.Net.Dns.GetHostEntry(Bitacora.ComputerName).AddressList[0].ToString(); Bitacora.WindowsUser = Environment.UserName; Bitacora.fecha = DateTime.Now; Bitacora.CustomError = objeto.CustomError; Bitacora.Usuario = objeto.Usuario; Bitacora.mensaje = objeto.mensaje; Bitacora.tipo = objeto.tipo; try { Services.ConexionSQL conexion = new Services.ConexionSQL(); var link = conexion.ConectarBaseDatos(); SqlCommand cmd = new SqlCommand("InsertarBitacora", link); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Fecha_Bitacora", SqlDbType.DateTime).Value = Bitacora.fecha; cmd.Parameters.Add("@Mensaje_Bitacora", SqlDbType.NVarChar).Value = Bitacora.mensaje; cmd.Parameters.Add("@ComputerName_Bitacora", SqlDbType.NVarChar).Value = Bitacora.ComputerName; cmd.Parameters.Add("@Ip_Bitacora", System.Data.SqlDbType.NVarChar).Value = Bitacora.IP; cmd.Parameters.Add("@WindowsUser_Bitacora", SqlDbType.NVarChar).Value = Bitacora.WindowsUser; cmd.Parameters.Add("@usuario_bitacora", SqlDbType.NVarChar).Value = Bitacora.Usuario; cmd.Parameters.Add("@tipo_bitacora", SqlDbType.NVarChar).Value = Bitacora.tipo; cmd.Parameters.Add("@customError_Bitacora", SqlDbType.NVarChar).Value = Bitacora.CustomError; cmd.ExecuteNonQuery(); } catch (Exception ex) { throw ex; } } /// <summary> /// /// </summary> /// <returns></returns> public List<BitacoraSQL> SelectBitacora() { // WARNING! Performance const string sqlStatement = "SELECT [Fecha_Bitacora], [Mensaje_Bitacora], [ComputarName_Bitacora], [Ip_Bitacora], [WindowsUser_Bitacora], [tipo_Bitacora] ,[usuario_Bitacora], [customError_Bitacora] FROM dbo.Bitacora"; var result = new List<BitacoraSQL>(); var db = DatabaseFactory.CreateDatabase(ConnectionName); using (var cmd = db.GetSqlStringCommand(sqlStatement)) { using (var dr = db.ExecuteReader(cmd)) { while (dr.Read()) { var bitacora = LoadBitacora(dr); // Mapper result.Add(bitacora); } } } return result; } private void agregarParametro(SqlCommand cmd, string nombre, object valor, ParameterDirection direccion, SqlDbType tipo) { SqlParameter parametro = cmd.CreateParameter(); parametro.ParameterName = nombre; parametro.Direction = direccion; parametro.SqlDbType = tipo; parametro.Value = valor; cmd.Parameters.Add(parametro); } private static BitacoraSQL LoadBitacora(IDataReader dr) { var bitacora = new BitacoraSQL { fecha = GetDataValue<DateTime>(dr, "Fecha_Bitacora"), mensaje = GetDataValue<string>(dr, "Mensaje_Bitacora"), ComputerName = GetDataValue<string>(dr, "ComputarName_Bitacora"), IP = GetDataValue<string>(dr, "Ip_Bitacora"), WindowsUser = GetDataValue<string>(dr, "WindowsUser_Bitacora"), tipo = GetDataValue<string>(dr, "tipo_Bitacora"), Usuario = GetDataValue<string>(dr, "usuario_Bitacora"), CustomError = GetDataValue<string>(dr, "customError_Bitacora"), }; return bitacora; } } }
C#
UTF-8
1,009
2.671875
3
[]
no_license
using System; using System.Configuration; using System.Reflection; using DB.Interface; namespace Reflection { /// <summary> /// 创建对象 /// </summary> public class Factory { private static string IDBHelper = ConfigurationManager.AppSettings["IDBHelperConfig"]; private static string DllName = IDBHelper.Split(',')[1]; private static string TypeName = IDBHelper.Split(',')[0]; public static IDBHelper CreateHelper() { // 加载dll // Assembly assembly = Assembly.Load("DB.MySQL"); Assembly assembly = Assembly.Load(DllName); // 获取类型信息 // Type type = assembly.GetType("DB.MySQL.MySQLHelper"); Type type = assembly.GetType(TypeName); // 创建对象 object oHelper = Activator.CreateInstance(type); // 类型转换 IDBHelper iDbHelper = (IDBHelper)oHelper; return iDbHelper; } } }
Python
UTF-8
1,222
2.59375
3
[]
no_license
import sys import os FOOD = [] AMBIENCE = [] SERVICE = [] PRICE = [] def main(): if len(sys.argv) != 2: print "USAGE: python basebuilder.py <path to labels folder>" sys.exit(0) for root, _, files in os.walk(sys.argv[1]): for feat_file in files: print 'processing ' + feat_file with open(root + '/' + feat_file) as f: for line in f: item = eval(line) for category in item[2]: if category == 'F': FOOD.append(item[0]) if category == 'S': SERVICE.append(item[0]) if category == 'A': AMBIENCE.append(item[0]) if category == 'P': PRICE.append(item[0]) # dump the data to model file model = open('features.model', 'w') model.write(', '.join(map(str, FOOD)) + '\n') model.write(', '.join(map(str, AMBIENCE)) + '\n') model.write(', '.join(map(str, SERVICE)) + '\n') model.write(', '.join(map(str, PRICE)) + '\n') model.close() return if __name__ == "__main__": main()
Python
UTF-8
308
3.65625
4
[]
no_license
import collections class Queue: def __init__(self): self._data = collections.deque() def enqueue(self,x): self._data.append(x) def dequeue(self): return self._data.popleft() def max(self): return max(self._data) q= Queue() q.enqueue(7) q.enqueue(4) q.enqueue(1) q.dequeue() x = q.max() print(x)
JavaScript
UTF-8
1,352
2.75
3
[]
no_license
const Pokego = require('pokemon-go-node-api/pokego'); module.exports = { parseInventory: parseInventory }; function parseInventory (inventory) { inventory = inventory.inventory_delta.inventory_items; return inventory.reduce((inventory, item) => { const pokemon = item.inventory_item_data.pokemon; const bagItem = item.inventory_item_data.item; const candy = item.inventory_item_data.pokemon_family; const stats = item.inventory_item_data.player_stats; if (pokemon !== null && pokemon.pokemon_id !== null) { inventory.pokemons.push(Pokego.pokemonlist[parseInt(pokemon.pokemon_id, 10) - 1]); } else if (bagItem !== null && bagItem.item !== null) { inventory.items.push({ item: Pokego.whatItem(bagItem.item), count: bagItem.count || 0 }); } else if (candy !== null && candy.family_id !== null) { inventory.candies.push({ candy: Pokego.whatFamily(candy.family_id), count: candy.candy || 0 }); } else if (pokemon !== null && pokemon.is_egg === true) { inventory.eggs.push(pokemon); console.log('An egg', pokemon); } else if (stats !== null) { inventory.stats.push(stats); } else { console.log(item); } return inventory; }, { pokemons: [], items: [], candies: [], stats: [], eggs: [] }); }
Shell
UTF-8
2,477
4.28125
4
[]
no_license
#!/bin/bash # # This script tries to monitor Wireshark fuzz testing, when it finds there's a failure, # - moves the problematic capture file to a tmp directory, and # - restart fuzz testing # It supports several fuzz testing suite so that multiple fuzz testing can run simutaneously. # PROGRAM_NAME=`basename $0` test_dir="/home/yami/test" tmp_dir="/home/yami/tmp" bin_dir="/home/yami/project/wsclean/wireshark/tools" FUZZ_MAX=1 FUZZ_TEST_SH=("$bin_dir/fuzz-test.sh") FUZZ_SUITE=(all) FUZZ_CAPDIR=("$test_dir/all") FUZZ_TMPDIR=("$tmp_dir/all") # in seconds FUZZ_CHECK_INTERVAL=30 function fuzz_log () { echo "[`date`] $*" } function get_fuzzcap () { local logfile=$1 local capfile=`grep "Output file: " $logfile | awk -F ':' '{print $2;}'` if [ -z "$capfile" ]; then echo "ERROR: $logfile has not fuzzed capture file!" exit 2 fi echo "$capfile" } function get_origcap () { local logfile=$1 local origcap=`grep "Original file: " $logfile | awk -F ':' '{print $2;}'` if [ -z "$origcap" ]; then echo "ERROR: $logfile has not original capture file!" exit 2 fi echo "$origcap" } function fuzz_index () { local fuzz="$1" local idx="0" for f in "${FUZZ_SUITE[@]}"; do if [ "$f" == "fuzz" ]; then echo "$idx" return 0 fi (( idx++ )) done return 1 } function start_fuzz () { local i=$1 touch ${FUZZ_SUITE[$i]}.log ${FUZZ_TEST_SH[$i]} -d ${FUZZ_TMPDIR[$i]} -c ${FUZZ_CAPDIR[$i]} >& ${FUZZ_SUITE[$i]}.log & } function start_all () { for ((i=0; i<FUZZ_MAX; i++)); do fuzz_log "start fuzz: ${FUZZ_SUITE[$i]}" start_fuzz $i done } function restart_fuzz () { local fuzz="$1" local i=`fuzz_index "$fuzz"` local gout=`ps aux | grep -v "grep" | grep "${FUZZ_TEST_SH[$i]}.*${fuzz}"` if [ -z "$gout" ]; then start_fuzz $i fi } # main # fuzz_log "start main" start_all while true; do sleep $FUZZ_CHECK_INTERVAL for fuzz in "${FUZZ_SUITE[@]}"; do if grep "^Processing failed\. Capture info follows" ${fuzz}.log; then fuzz_log "bug found: $fuzz" stamp=`date +%Y_%m_%d_%H_%M_%S` idx=`fuzz_index ${fuzz}` tmp="${FUZZ_TMPDIR[$idx]}" cp -p ${fuzz}.log $tmp/${fuzz}.log."$stamp" mv `get_origcap "${fuzz}.log"` $tmp/ restart_fuzz "$fuzz" fi done done
Java
UTF-8
3,940
2.03125
2
[]
no_license
package com.kuaichumen.whistle; import android.app.Application; import android.content.Context; import android.text.TextUtils; import com.google.gson.Gson; import com.igexin.sdk.PushManager; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache; import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.utils.StorageUtils; import com.qiniu.android.storage.UploadManager; import com.squareup.picasso.OkHttpDownloader; import com.squareup.picasso.Picasso; import java.io.File; import java.util.List; import KSData.ApplicationSettings; import KSModel.ActivityInfo; import KSUtil.DownLoaderDir; import KSUtil.PhoneDeviceUtil; /** * Created by Simpfy on 15/6/25. */ public class WhistleApplication extends Application { private static Context context; public static UploadManager uploadManager; public static WhistleApplication whistleApplication; public static WhistleApplication getInstance() { return whistleApplication; } public static Context getAppContext() { return WhistleApplication.context; } public ActivityInfo activityInfo; public boolean hasNewVersion; public int versionCode; @Override public void onCreate() { super.onCreate(); whistleApplication = this; WhistleApplication.context = getApplicationContext(); uploadManager = new UploadManager(); ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( getApplicationContext()) .threadPoolSize(5) .threadPriority(Thread.NORM_PRIORITY - 2) .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new HashCodeFileNameGenerator()) .discCacheFileCount(500) .tasksProcessingOrder(QueueProcessingType.LIFO) .discCache( new UnlimitedDiscCache(StorageUtils .getOwnCacheDirectory(this, "koushao/image/cache"))).build(); ImageLoader.getInstance().init(config); PushManager.getInstance().initialize(this.getApplicationContext()); loadImageCache(); CheckUpdate(); } private void CheckUpdate(){ hasNewVersion = ApplicationSettings.getBoolean("hasNewVersion",context); if(hasNewVersion){ versionCode = ApplicationSettings.getInt("versionCode", context); if(PhoneDeviceUtil.getVersionCode(context)>=versionCode){ hasNewVersion = false; ApplicationSettings.putBoolean("hasNewVersion",false, context); } } } private void loadImageCache() { String imageCacheDir = DownLoaderDir.cacheDir; File file = new File(imageCacheDir); if (!file.exists()) { file.mkdirs(); } Picasso picasso = new Picasso.Builder(this).downloader(new OkHttpDownloader(file)).build(); Picasso.setSingletonInstance(picasso); } public ActivityInfo getActivityInfo() { if(activityInfo==null){ String activity_data = ApplicationSettings.getString("activity_data",context); if(!TextUtils.isEmpty(activity_data)){ ActivityInfo activityInfo = new Gson().fromJson(activity_data,ActivityInfo.class); WhistleApplication.getInstance().setActivityInfo(activityInfo); }else{ activityInfo = new ActivityInfo(); } } return activityInfo; } public void setActivityInfo(ActivityInfo activityInfo) { this.activityInfo = activityInfo; } }
Java
UTF-8
1,588
3.5
4
[]
no_license
package algorithm.bubleSort; public class BubleSortPractice { static int [] array={12,3,7,15,21,6,31,19,8,31,5,75,95,101,211,87,35,49,66,78,54}; static void bubleSort(int[] array){ for (int j = array.length-1; j >0; j--) { for (int i = 0; i < j; i++) { if(array[i]>array[i+1]){ swap(array,i,i+1); } } } } static void bubleSortRe(int[] array){ bubleSort_o(array,array.length-1); } private static void bubleSort_o(int[] array, int round) { if(round==0)return; bubleSort_i(array,round,0); bubleSort_o(array,round-1); } private static void bubleSort_i(int[] array, int round, int check) { if(check==round)return; if(array[check]>array[check+1]){ swap(array,check,check+1); } bubleSort_i(array,round,check+1); } private static void swap(int[] array, int i, int i1) { int temp=array[i]; array[i]=array[i+1]; array[i+1]=temp; } public static void main(String[] args) { long a=System.currentTimeMillis(); BubleSortPractice.bubleSort(BubleSortPractice.array); long b=System.currentTimeMillis(); BubleSortPractice.bubleSortRe(BubleSortPractice.array); long c=System.currentTimeMillis(); System.out.println("a="+a); System.out.println("b="+b); System.out.println("c="+c); System.out.println("迴圈spend="+(b-a)+"毫秒"); System.out.println("遞迴spend="+(c-b)+"毫秒"); } }
C++
UTF-8
1,811
3.328125
3
[]
no_license
/************************************************************************* > File Name: 括号匹配-3.cpp > Author: dofo-eat > Mail:2354787023@qq.com > Created Time: 2020年02月10日 星期一 19时50分37秒 ************************************************************************/ #include<iostream> #include<stack> #include<string> using namespace std; bool ismatch(string str) { stack<char> sta; int len = str.length(); for(int i = 0; i < len; i++) { if(str[i] == '(') { sta.push('('); } else if (str[i] == '[') { sta.push('['); } else if (str[i] == '{') { sta.push('{'); } else if (str[i] == ')') { if(sta.empty()) { return 0; } else { char temp = sta.top(); sta.pop(); if(temp == '(') { return 0; } } } else if(str[i] == ']') { if(sta.empty()) { return 0; } else { char temp = sta.top(); sta.pop(); if(temp == '[') { return 0; } } } else if(str[i] == '}') { if(sta.empty()) { return 0; } else { char temp = sta.top(); sta.pop(); if(temp == '{') { return 0; } } } else { continue; } } if(sta.size() != 0) { return 0; } return 1; } int main () { string str; cin >> str; if(ismatch(str)) { cout << "Yes" << endl; } else { cout << "No" << endl; } return 0; }
Go
UTF-8
2,170
2.796875
3
[ "MIT" ]
permissive
package cmd import ( "bytes" "errors" "fmt" "os" "strings" "time" "github.com/a8uhnf/suich/pkg/utils" "github.com/spf13/cobra" ) const ( podInfoNameTitle = "NAME" ) var ( follow = false ) // GetLogsCmd builds the logs cobra command for suich func GetLogsCmd() *cobra.Command { logsCMD := &cobra.Command{ Use: "logs", Short: "Get logs for a certain pod", Long: "Prompts the user with a list of pods names to display the logs", RunE: getLogs, } logsCMD.Flags().StringP("namespace", "n", "", "The namespace to work on") logsCMD.Flags().BoolVarP(&follow, "follow", "f", false, "Watch the logs") return logsCMD } func getLogs(cmd *cobra.Command, args []string) error { second() return nil client := getKubernetesClient() var namespace string nList, err := getNamespaceNames(client) if err != nil { namespace, err = cmd.Flags().GetString("namespace") if err != nil { return err } } else { namespace, err = utils.RunPrompt(nList, "Select Namespace") if err != nil { return err } } if namespace == "" { return errors.New("Must provide namespace flag as you do not have access to list namespaces") } var podsBfr bytes.Buffer if err := utils.ExecCommand(&podsBfr, "kubectl", "get", "pods", "-n", namespace); err != nil { return err } pns := readAllPods(podsBfr) pod, err := utils.RunPrompt(pns, "Select Pod") if err != nil { return err } if follow { if err := utils.ExecCommand(os.Stdout, "kubectl", "logs", pod, "-n", namespace, "-f"); err != nil { return err } } else { if err := utils.ExecCommand(os.Stdout, "kubectl", "logs", pod, "-n", namespace); err != nil { return err } } return nil } func second() { loc := time.FixedZone("some_common_name", 6*60*60) tp := time.Date(1970, 1, 1, 0, 0, 0, 0, loc) ts := time.Now().Sub(tp) fmt.Printf("%v", ts) } func readAllPods(out bytes.Buffer) []string { podInfos := strings.Split(out.String(), "\n") podNames := []string{} for _, pi := range podInfos { info := strings.Split(pi, " ") if info[0] == podInfoNameTitle || info[0] == "" { continue } podNames = append(podNames, info[0]) } return podNames }
Java
UTF-8
444
1.78125
2
[]
no_license
package com.anirban.myapp.assignment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; /** * Created by me on 6/21/2016. */ public class RelativeLayoutClass extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.relative_example); } }
Python
UTF-8
396
2.9375
3
[ "MIT" ]
permissive
from nan_value_filler.classes.nan_filler.nan_filler import NanFiller class FillWithZero(NanFiller): def __init__(self): super().__init__() self.name = "fill_with_zero" def fill_nan_values(self, data_set_info, filling_column_name): data_set_info.data_set[filling_column_name] = data_set_info.data_set[filling_column_name].fillna(0) return data_set_info
Markdown
UTF-8
1,411
2.53125
3
[]
no_license
# Fnorder ## Description An implementation of Steve Jackson Games' Fnorder. Fnorder generates messages from the Illuminati to use in your application. This project produces a .DLL to be used by other applications. Some more information about Fnorder as well as a compiled copy of the complete WinFnord application (as well as solutions in other languages and runtimes) can be found at the [Legacy Fnorders](http://www.sjgames.com/misc/fnord.html) page of the Steve Jackson Games website. ## Requirements This was originally written in July 2007 with VisualStudio 2005 and .NET 2.0. I _assume_ that it will compile under recent versions of VS and the .NET runtime. I have not tested this. This project is just the Fnorder library itself. You could grab a copy of [WinFnord project](https://github.com/Williams-Christopher/WinFnord) as an example of a WinForms application that uses this Fnorder library. ## Use Compile Fnorder to a .dll and reference it in your project. Fnorder exposes a single public function `getMessage()` that returns a string created from lists of different parts of speech according to various rules and calls to Random. ## Legalish stuff I do not hold or claim any copyrights to the Fnorder produced by Steve Jackson Games. I do not work for them or contract with them. Do with this particular project what you like knowing that I offer you no warranties or gurantees of any kind.
C#
UTF-8
1,233
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NeuralNetwork { class Program { static void Main(string[] args) { List<Matrix> l = new List<Matrix> (); double[,] ar = new double[,] { { 1 }, { 0 }, { 1 } }; double[,] ar1 = new double[,] { {0 }, {0 }, {1 } }; double[,] ar2 = new double[,] { { 0}, { 1}, { 0} }; double[,] ar3 = new double[,] { { 0}, {1 }, {1 } }; double[,] ar4 = new double[,] { { 1}, { 0}, { 0} }; double[,] ar5 = new double[,] { { 0}, { 0}, { 0} }; double[,] ar6 = new double[,] { { 1}, { 1}, { 0} }; double[,] ar7 = new double[,] { { 1}, { 1}, { 1} }; l.Add(new Matrix(ar)); l.Add(new Matrix(ar1)); l.Add(new Matrix(ar2)); l.Add(new Matrix(ar3)); l.Add(new Matrix(ar4)); l.Add(new Matrix(ar5)); l.Add(new Matrix(ar6)); l.Add(new Matrix(ar7)); List<double> res = new List<double> { 1,1,0,0,1,0,0,1}; PartyNN p = new PartyNN(0.1); int epoch = 3000; for (int i = 0; i < epoch; i++) { for (int j = 0; j < l.Count; j++) { p.train(l[j], res[j]); } } Console.ReadKey(true); } } }
Rust
UTF-8
1,566
2.921875
3
[]
no_license
use chrono::{offset::Local, Duration, NaiveDateTime}; use console::Term; pub struct Schedule { text: String, datetime: NaiveDateTime, } impl Schedule { pub fn new() -> Self { Self { text: String::from( "\ ------------------ 01 08:30 -- 09:15 02 09:20 -- 10:05 ------------------ 03 10:25 -- 11:10 04 11:15 -- 12:00 ------------------ 05 14:00 -- 14:45 06 14:50 -- 15:35 07 15:40 -- 16:25 ------------------ 08 16:35 -- 17:20 09 17:25 -- 18:10 10 18:20 -- 19:05 ------------------ 11 19:20 -- 20:05 12 20:10 -- 20:55 13 21:00 -- 21:45 ------------------", ), datetime: "2020-07-09T00:00:00".parse().unwrap(), } } pub fn run(&self) -> std::io::Result<()> { println!("{}", self.text); let term = Term::stderr(); loop { let mut duration = Local::now().naive_local() - self.datetime; let days = duration.num_days(); duration = duration - Duration::days(days); let hours = duration.num_hours(); duration = duration - Duration::hours(hours); let minutes = duration.num_minutes(); duration = duration - Duration::minutes(minutes); let seconds = duration.num_seconds(); term.write_str(&format!( "Return School {} days {:02}:{:02}:{:02}", days, hours, minutes, seconds ))?; std::thread::sleep(std::time::Duration::from_micros(5000)); term.clear_line()?; } } }
Python
UTF-8
16,288
2.6875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """swim - a simple, no-frills web crawler. In a nutshell: you seed it with a bunch of URLs, you give it a function that extracts more URLs from the HTTP responses, and swim does the rest. Noticeable features are: - multithreaded, possibility to enable rate limiting - kill the crawler and resume it later without losing data - all crawling-related information is persisted in a database swim is minimalistic by design. There are plenty of powerful crawlers out there; the goal of this one is to provide a simple, no-frills basis that is easy to adapt to your needs. Here's a small snippet that illustrates the API. import re import swim def process(body): for match in re.finditer(r'<a.*?href="(?P<url>.*?)">', body): yield match.group('url') config = { 'folder': "./crawl", 'processor': process, 'max_workers': 4, 'rate': 2.0, } manager = swim.Manager(**config) manager.run(seeds=["http://lucas.maystre.ch/"]) """ import codecs import contextlib import cPickle import datetime import futures import logging import os.path import Queue import requests import sqlite3 import threading import time import urlparse from storm.locals import (Bool, DateTime, Float, Int, ReferenceSet, Store, Storm, Unicode, create_database) SQL_SCHEMA = """ CREATE TABLE IF NOT EXISTS resource ( id INTEGER PRIMARY KEY, url TEXT, final_url TEXT, method TEXT, created TEXT DEFAULT CURRENT_TIMESTAMP, -- UTC time. updated TEXT DEFAULT CURRENT_TIMESTAMP, -- UTC time. duration REAL, status_code INTEGER, successful BOOLEAN ); CREATE INDEX IF NOT EXISTS resource_url_idx ON resource(url); CREATE TABLE IF NOT EXISTS edge ( id INTEGER PRIMARY KEY, src INTEGER REFERENCES resource, dst INTEGER REFERENCES resource, created TEXT DEFAULT CURRENT_TIMESTAMP, -- UTC time. new_dst BOOLEAN, UNIQUE (src, dst) ON CONFLICT IGNORE ); """ UA_STRING = 'swim/1.0' def _setup_logger(): """Set up and return the logger for the module.""" template = "%(asctime)s %(name)s:%(levelname)s - %(message)s" logger = logging.getLogger(__name__) handler = logging.StreamHandler() # Logs to stderr. handler.setFormatter(logging.Formatter(fmt=template)) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger LOGGER = _setup_logger() def _ensure_folder(folder): """Make sure a given folder exists. The given path can actually consist of a hierarchy of multiple unexisting folders which will all be created. """ if os.path.exists(folder): if not os.path.isdir(folder): raise ValueError("path exists but is not a folder") else: os.makedirs(folder) def set_loglevel(loglevel): """Set the level for the module-wide logger. loglevel is a a string such as "debug", "info" or "warning". """ if isinstance(loglevel, basestring): # Getting the relevant constant, e.g. `logging.DEBUG`. loglevel = getattr(logging, loglevel.upper()) LOGGER.setLevel(loglevel) class Resource(Storm): """ORM class for the resource table.""" __storm_table__ = 'resource' id = Int(primary=True) url = Unicode() final_url = Unicode() method = Unicode() created = DateTime() updated = DateTime() duration = Float() status_code = Int() is_successful = Bool(name='successful') # References parents = ReferenceSet('Resource.id', 'Edge.dst', 'Edge.src', 'Resource.id') children = ReferenceSet('Resource.id', 'Edge.src', 'Edge.dst', 'Resource.id') def __init__(self, url): self.url = url class Edge(Storm): """ORM class for the edge table.""" __storm_table__ = 'edge' id = Int(primary=True) src = Int() dst = Int() created = DateTime() is_new_dst = Bool(name='new_dst') def __init__(self, src, dst): self.src = src self.dst = dst class Fetcher(threading.Thread): """Concurrent URL fetcher. The fetcher takes care of performing the HTTP URLs. It enforces a rate limit, but if requests takes time it can also fetch several URLs in parallel. It can be stopped / resumed thanks to functions that pickle / unpickle its state. """ TIMEOUT = 1 # In seconds. def __init__(self, max_workers=2, rate=100, ua_string=UA_STRING): """Initialize a fetcher.""" super(Fetcher, self).__init__() self._max_workers = max_workers self._rate = rate self._ua_string = ua_string self._in = Queue.Queue() self._out = Queue.Queue() self._shutdown = False self._session = requests.Session() self._session.headers.update({'User-Agent': self._ua_string}) if max_workers > requests.adapters.DEFAULT_POOLSIZE: # This is need as self._session might be called concurrently. See: # https://github.com/ross/requests-futures. kwargs = {'pool_connections': max_workers, 'pool_maxsize': max_workers} self._session.mount('https://', requests.adapters.HTTPAdapter(**kwargs)) self._session.mount('http://', requests.adapters.HTTPAdapter(**kwargs)) LOGGER.debug('fetcher initialized') @classmethod def from_pickle(cls, path): """Recreate a fetcher from a pickle.""" with open(path, 'rb') as f: data = cPickle.load(f) instance = cls(max_workers=data['max_workers'], rate=data['rate'], ua_string=data['ua_string']) for key, url in data['pending']: instance.add_url(key, url) return instance def add_url(self, key, url): """Add a URL to fetch. The key paramater allows to maps URLs to responses when fetching elements from the output queue. """ self._in.put_nowait((key, url)) def get_result(self, block=True, timeout=None): """Fetch a result from the output queue. Returns a tuple (key, response) to facilitate mapping with the corresponding URL / request. """ return self._out.get(block, timeout) def stop(self): """Gracefully shut down the fetcher. Blocks until all pending requests are done. This method can be called only once the fetcher has started. """ assert self.is_alive(), "fetcher is not running." self._shutdown = True LOGGER.debug("Stopping the fetcher...") self.join() def save_pickle(self, path): """Save remaining URLs and fetcher parameters as a pickle.""" assert not self.is_alive(), "cannot save a running fetcher" self._in.put('♥') # Small hack to be able to iterate over a queue. data = { 'max_workers': self._max_workers, 'rate': self._rate, 'pending': list(iter(self._in.get_nowait, '♥')), 'ua_string': self._ua_string, } with open(path, 'wb') as f: cPickle.dump(data, f) LOGGER.debug("fetcher setup saved as a pickle") def is_working(self): """Check whether the fetcher is still actively fetching.""" # I'm not sure that this is part of the official Queue.Queue API. return self._in.unfinished_tasks > 0 def run(self): LOGGER.debug("starting the fetcher with max {} workers" .format(self._max_workers)) kwargs = {'max_workers': self._max_workers} with futures.ThreadPoolExecutor(**kwargs) as executor: pending = list() while not self._shutdown: # Update pending jobs. pending = filter(lambda f: not f.done(), pending) if len(pending) < self._max_workers: try: key, url = self._in.get(timeout=self.TIMEOUT) LOGGER.debug("processing job {} ({})".format(key, url)) future = executor.submit(self._fetch, key, url) pending.append(future) except Queue.Empty: pass if self._rate is not None: time.sleep(1.0 / self._rate) else: futures.wait(pending, return_when=futures.FIRST_COMPLETED) def _fetch(self, key, url): """Fetch a URL and parse the response. Also, notify the input queue that the task is done, and put the parsed reponse in the output queue. """ data = {'method': u"GET"} try: LOGGER.info("fetching '{}'...".format(url)) response = self._session.get(url) data['success'] = True data['duration'] = response.elapsed.total_seconds() data['status_code'] = response.status_code data['body'] = response.text data['final_url'] = response.url except Exception as e: LOGGER.warning("exception while processing URL {}: {}" .format(url, repr(e))) data['success'] = False finally: data['updated'] = datetime.datetime.utcnow() self._out.put_nowait((key, data)) self._in.task_done() LOGGER.debug("done with job {}".format(key)) class Manager(object): """Manage a fetcher. The fetcher simply takes URLs and returns HTTP responses. This class does the rest: keep track of requests in the database, write responses to disk, send new URLs to the fetcher based on the responses, and listen to keyboard interrupts. In principle, this should be the only class of the module that gets called in user code. The rest is just here to support this one. """ def __init__(self, folder="./swim", processor=None, fetcher_pickle=None, max_workers=2, rate=1.0, ua_string=UA_STRING): """Initialize a crawl manager. Keyword arguments: folder -- the folder where the output will be stored (default './swim') processor -- a function that takes a string containing the response body and returns an iterable over URLs (default None) fetcher_pickle -- a pickle used to resume a previous crawl, overrides the next two arguments (default None) max_workers -- the maximum number of worker threads to spawn (default 2) rate -- the rate at which to crawl, in URLs per second (default 1.0) """ _ensure_folder(folder) self._store = self._get_store(os.path.join(folder, "crawl.db")) self._data_dir = os.path.join(folder, "data") self._pickle_path = os.path.join(folder, "fetcher.pickle") _ensure_folder(self._data_dir) self._process = processor if fetcher_pickle is None: self._fetcher = Fetcher(max_workers=max_workers, rate=rate, ua_string=ua_string) else: self._fetcher = Fetcher.from_pickle(fetcher_pickle) LOGGER.info("manager initialized") def _get_store(self, db_path): """Return a storm Store from a path.""" # Initialize store. Context automatically commits and closes. with contextlib.closing(sqlite3.connect(db_path)) as conn: conn.executescript(SQL_SCHEMA) return Store(create_database("sqlite:{}".format(db_path))) @contextlib.contextmanager def _manage(self, fetcher, save=None): """Manage interruptions and exceptions. This is a context manager that wraps around the crawl manager's operations and takes care of handling exceptions and trying to gracefully shut down (and save) the fetcher. """ fetcher.start() should_save = False try: yield fetcher except KeyboardInterrupt: LOGGER.info("caught an interruption") should_save = True except Exception as e: # Another exception happened, we should save in case. LOGGER.error("crawl manager caught an exception") should_save = True raise e finally: fetcher.stop() try: # Process everything in the output queue. while True: key, res = fetcher.get_result(block=False) self._handle_result(key, res) except Queue.Empty: pass if should_save and save is not None: fetcher.save_pickle(save) def run(self, seeds=()): """Start crawling. If we are not resuming a previous crawl, we will typically need to provide a few seeds to bootstrap the fetcher. """ for url in seeds: self._add_resource(url, None) with self._manage(self._fetcher, self._pickle_path) as fetcher: while fetcher.is_working(): # This is the main loop: wait for results and process them. try: key, res = fetcher.get_result(timeout=1) except Queue.Empty: pass else: self._handle_result(key, res) self._store.commit() self._store.close() LOGGER.info("crawl manager has finished") def _add_resource(self, url, parent_id): """Handle a URL output by the processor. Finds out whether the URL is already in the database and inserts it if necessary, creates an edge with its parent resource, and adds it to the fetcher's URL queue if needed. """ resource = self._store.find(Resource, Resource.url == url).one() if resource is None: # We've never seen this URL---we need to crawl it. resource = Resource(url) self._store.add(resource) self._store.flush() LOGGER.debug("resource {} not fetched yet, creating a new job" .format(resource.id)) self._fetcher.add_url(resource.id, url) if parent_id is not None: # Add an edge. LOGGER.debug("adding edge between {} and {}" .format(parent_id, resource.id)) self._store.add(Edge(parent_id, resource.id)) self._store.commit() def _handle_result(self, key, result): """Handle a result (HTTP response) from the fetcher. Includes updating the corresponding entry in the database, writing the response to disk, and extracting further URLs to crawl. """ LOGGER.debug("handling result for key {}".format(key)) resource = self._store.get(Resource, key) # Update the resource with the new information. resource.final_url = result.get('final_url') resource.method = result.get('method') resource.updated = result.get('updated') resource.duration = result.get('duration') resource.status_code = result.get('status_code') resource.is_successful = result.get('success') self._store.commit() # Process the body of the response, if there is one. if 'body' in result and result['body'] is not None: LOGGER.debug("writing response body to disk for key {}" .format(key)) # Save the file to disk. path = os.path.join(self._data_dir, "{}.html".format(resource.id)) with codecs.open(path, 'w', encoding='utf8') as f: f.write(result['body']) # Extract more jobs. if self._process is not None: for url in self._process(result['body']): # urljoin handles all quirky cases of URL resolution. canonical = urlparse.urljoin(resource.final_url, url) # Get rid of any fragment (we have to do it ourselves...) canonical = canonical.split('#', 1)[0] self._add_resource(canonical, resource.id)
Python
UTF-8
4,855
2.828125
3
[]
no_license
import algorithm import click import random import time from multiprocessing import Pool import numpy as np from itertools import product initial_list = [300] # number of initial nodes connectivity_list = [0.025, 0.05, 0.1, 0.20] nops_list = [500] initial_terminals_list = [40] fquery_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9] def test(initial, connectivity, nops, initial_terminals, fquery): # Create graphs baseline = algorithm.Baseline() ours = algorithm.VDSTGraph() baseline_stats = [] our_stats = [] # Seed with some initial data for i in range(initial): baseline.add_node(i) ours.add_node(i) if i == 0: continue for j in range(max(1, int(connectivity * i))): other = np.random.randint(i) weight = np.random.uniform(0, 100) baseline.decrease_edge_weight(i, other, weight) ours.decrease_edge_weight(i, other, weight) # Compile operation list ops = [] terminals = set() n_nodes = initial for i in range(nops): if len(terminals) < initial_terminals: idx = np.random.randint(n_nodes) if len(terminals) > 0: other = np.random.choice(list(terminals)) weight = np.random.uniform(100, 200) ops.append(lambda ds, idx=idx, other=other, weight=weight: ds.decrease_edge_weight(idx, other, weight)) ops.append(lambda ds, idx=idx: ds.add_terminal(idx)) terminals.add(idx) continue r = np.random.random() if r < fquery: ops.append(lambda ds: (baseline_stats if ds.is_baseline else our_stats).append(ds.get_steiner_tree()[1])) else: r = int(12 * (r - fquery) / (1 - fquery)) if r < 3: # Add a node and edge ops.append(lambda ds, n_nodes=n_nodes: ds.add_node(n_nodes)) other = np.random.randint(n_nodes) weight = np.random.uniform(0, 100) ops.append(lambda ds, n_nodes=n_nodes, other=other, weight=weight: ds.decrease_edge_weight(n_nodes, other, weight)) n_nodes += 1 elif r < 6: a = np.random.randint(0, initial - 10) b = np.random.randint(initial - 10, n_nodes) weight = np.random.uniform(0, 100) ops.append(lambda ds, a=a, b=b, weight=weight: ds.decrease_edge_weight(a, b, weight)) elif r < 9: idx = np.random.randint(n_nodes) other = np.random.choice(list(terminals)) weight = np.random.uniform(100, 200) ops.append(lambda ds, idx=idx, other=other, weight=weight: ds.decrease_edge_weight(idx, other, weight)) ops.append(lambda ds, idx=idx: ds.add_terminal(idx)) terminals.add(idx) else: idx = np.random.choice(list(terminals)) ops.append(lambda ds, idx=idx: ds.remove_terminal(idx)) terminals.remove(idx) # Execute operation list -- baseline print('Executing baseline') start = time.perf_counter() for op in ops: op(baseline) baseline_time = time.perf_counter() - start print('-> took {} seconds'.format(baseline_time)) # Execute operation list -- our method print('Executing our method') start = time.perf_counter() for op in ops: op(ours) our_time = time.perf_counter() - start print('-> took {} seconds'.format(our_time)) # Write to file with open('test_{}_{}_{}_{}_{}.txt'.format(initial, connectivity, nops, initial_terminals, fquery), 'w') as f: f.write('{}, {}\n'.format(our_time, baseline_time)) for our_perf, baseline_perf in zip(our_stats, baseline_stats): f.write('{}, {}\n'.format(our_perf, baseline_perf)) print('Finished') def main(): p = Pool(60) p.starmap(test, product(initial_list, connectivity_list, nops_list, initial_terminals_list, fquery_list)) def test1(): graph = algorithm.Graph() # run tests here for i in range(5): graph.add_node(i) for i in range(4): graph.decrease_edge_weight(i, i+1, 1.) graph.add_terminal(0) graph.add_terminal(2) graph.add_terminal(4) steiner_tree, _ = graph.get_steiner_tree() for edge in steiner_tree.edges(): print(edge) def test2(): graph = algorithm.Graph() # run tests here for i in range(10): graph.add_node(i) for i in range(8): graph.decrease_edge_weight(i, i+1, 1) graph.decrease_edge_weight(i, i+2, 1) graph.add_terminal(3) graph.add_terminal(8) steiner_tree, _ = graph.get_steiner_tree() for edge in steiner_tree.edges(): print(edge) if __name__ == '__main__': main()
Ruby
UTF-8
1,101
2.53125
3
[]
no_license
require "selenium-webdriver" require 'xdo/keyboard' require 'xdo/mouse' require 'xdo/xwindow' driver = Selenium::WebDriver.for :chrome driver.manage().window().maximize() # Acessing the Discord page driver.navigate.to "https://discord.com/" # Clicking the button that leads to login page login = driver.find_element(xpath: "//a[@href='//discord.com/login']") login.click # Logging to your discord account email = driver.find_element(name: 'email') password = driver.find_element(name: 'password') email.send_keys "your@email.com" password.send_keys "yourpassword" password.submit sleep 15 # Acessing the Server that you want to spam server = driver.find_element(xpath: "//a[@aria-label='Your Server Name']") server.click sleep 5 # Acessing the text channel you will spam text_channel = driver.find_element(xpath: "//div[@aria-label='yourvoicechatname (text channel)']") text_channel.click repeat = 10 # How many messages you want do send cooldown = 5 # The time in seconds between the messages repeat.times do XDo::Keyboard.type('Message to be spammed', 0) XDo::Keyboard.return sleep cooldown end
C++
UTF-8
1,210
2.578125
3
[]
no_license
#include "enginecryptographichashing.h" EngineCryptographicHashing::EngineCryptographicHashing() { } // Calculate md5 for chunks indexing. QString EngineCryptographicHashing::calculateHash(QByteArray chunk_stream) { QCryptographicHash crypto(QCryptographicHash::Md5); crypto.addData(chunk_stream); QByteArray hash = crypto.result(); return hash.toHex(); } // Calculate MD5. QByteArray EngineCryptographicHashing::calculateMd5(QByteArray byte_stream) { QCryptographicHash crypto(QCryptographicHash::Md5); crypto.addData(byte_stream); QByteArray hash = crypto.result(); return hash; } // Calculate SHA1. QByteArray EngineCryptographicHashing::calculateSha1(QByteArray byte_stream) { QCryptographicHash crypto(QCryptographicHash::Sha1); crypto.addData(byte_stream); QByteArray hash = crypto.result(); return hash; } // Calculate md4 for masking names. QString EngineCryptographicHashing::calculateHash(QString chunk_name) { QCryptographicHash crypto(QCryptographicHash::Md4); crypto.addData(chunk_name.toStdString().c_str(), chunk_name.size()); QByteArray hash = crypto.result(); return hash.toHex(); }
Java
UTF-8
148
1.710938
2
[]
no_license
package com.niit.cdstack.service; import com.niit.cdstack.model.UserRoles; public interface UserRoleService { void addUserRoles(UserRoles ur); }
Markdown
UTF-8
2,613
3.015625
3
[]
no_license
# Google Kubernetes Kubernetes is a container orchestration system that helps deploy and manage containerised applications. ## The Kubernetes Cluster Kubernetes cluster is a set of node machines for running containerised applications. At a minimum, a cluster contains a control plane and one or more worker nodes. ## The Kubernetes Master Node Kubernetes is a set of tools and scripts that help to host containers (Docker hosts) in an environment. <br /> The master node is the cluster control panel or control plane. It is a collection of processes that control Kubernetes nodes. This is where all decisions are made, such as scheduling, and detecting/responding to events. * API Server ~ is the front end for Kubernetes, The users, management devices and the (kubectl) command-line interface communicate with the API server to interact with Kubernetes. * ETCD ~ is a distributed key-value store for data used to manage the cluster containing information configuration management, service discovery and logs to ensure that there are no conflicts between the nodes. * Scheduler ~ is responsible for distributing the work (containers) across multiple nodes. * Controller Manager ~is responsible for noticing when nodes, containers go down and for making the decision to bring up new nodes and container. ## Nodes This is the virtual machine. Nodes are worker servers that perform the requested tasks i.e. run the application(s) assigned by the control plane. * Kubelet ~ is responsible for making sure the containers are running as expected.  * Kube-proxy It is responsible for routing traffic to the appropriate container based on IP and port number of the incoming request. ## Pod A pod defines the logical unit of the application. It is a group of one or more containers with shared storage/network resources deployed to a single node. Each pod contains specific information on how containers should be run. ## Container Runtime The software used to run the container e.g. Docker ## Container A container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries, and settings. Container images become containers at runtime. ## Deployment A deployment ensures the desired number of pods are running and available at all times automatically replacing any instances that fail or become unresponsive. ## Features Description of important features. * [Create a Kubernetes Cluster](<01 - Create a Kubernetes Cluster.md>) * [Create, View, Delete a Pod](<02 - Create View Delete a Pod.md>)
Python
UTF-8
767
2.921875
3
[]
no_license
from matplotlib.pylab import scatter,text,show,cm,figure from matplotlib.pylab import subplot,imshow,NullLocator from sklearn import manifold, datasets # load the digits dataset # 901 samples, about 180 samples per class # the digits represented 0,1,2,3,4 digits = datasets.load_digits(n_class=5) X = digits.data color = digits.target # running Isomap # 5 neighbours will be considered and reduction on a 2d space for i in range(1,11): Y = manifold.Isomap(i, 2).fit_transform(X) # plotting the result figure(i) scatter(Y[:,0], Y[:,1], c='k', alpha=0.3, s=10) for i in range(Y.shape[0]): text(Y[i, 0], Y[i, 1], str(color[i]), color=cm.Dark2(color[i] / 5.), fontdict={'weight': 'bold', 'size': 11}) show()
C++
UTF-8
440
2.53125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; bool got[2000001]; int M[2000001]; int main() { int n; vector<int> A; cin >> n; A.resize(n); for(int i=0;i<n;i++) cin >> A[i], got[A[i]]=1; for(int i=0;i<=2000000;i++) if(got[i]) M[i] = i; else M[i] = M[i-1]; int m=0; for(int i=2;i<=1000000;i++) if(got[i]) for(int j=2*i-1;j<=2000000;j+=i) m = max(m, M[j]%i); cout << m << endl; return 0; }
C#
UTF-8
2,048
2.921875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; namespace HatcheryManagement { class DbHatchery { public List<RuiFish> ruiList = new List<RuiFish>(); public List<KatlaFish> katlaList = new List<KatlaFish>(); public List<IlishFish> ilishList = new List<IlishFish>(); private static DbHatchery instance; private static readonly object lockCheck = new object(); private static int count = 0; private DbHatchery() { count++; Console.WriteLine("Counter Value DBHatchery: " + count); } public static DbHatchery GetInstance() { lock (lockCheck) { if (instance == null) { instance = new DbHatchery(); instance.initRui(); instance.initKatla(); instance.initIlish(); } return instance; } } public void initRui() { for (int i = 1; i <= 1000; i++) { string name = "rui" + Convert.ToString(i); string weight = "rui" + Convert.ToString((i % 3)); RuiFish rui = new RuiFish(name, weight); ruiList.Add(rui); } } public void initKatla() { for (int i = 1; i <= 1000; i++) { string name = "katla" + Convert.ToString(i); string weight = "katla" + Convert.ToString((i % 3)); KatlaFish katla = new KatlaFish(name, weight); katlaList.Add(katla); } } public void initIlish() { for (int i = 1; i <= 1000; i++) { string name = "ilish" + Convert.ToString(i); string weight = "ilish" + Convert.ToString((i % 3)); IlishFish ilish = new IlishFish(name, weight); ilishList.Add(ilish); } } } }
C++
UTF-8
3,095
2.703125
3
[ "CC-BY-SA-4.0", "MIT" ]
permissive
#ifdef UVW_AS_LIB # include "loop.h" #endif #include "config.h" namespace uvw { UVW_INLINE Loop::Loop(std::unique_ptr<uv_loop_t, Deleter> ptr) noexcept : loop{std::move(ptr)} {} UVW_INLINE std::shared_ptr<Loop> Loop::create() { auto ptr = std::unique_ptr<uv_loop_t, Deleter>{new uv_loop_t, [](uv_loop_t *l) { delete l; }}; auto loop = std::shared_ptr<Loop>{new Loop{std::move(ptr)}}; if(uv_loop_init(loop->loop.get())) { loop = nullptr; } return loop; } UVW_INLINE std::shared_ptr<Loop> Loop::create(uv_loop_t *loop) { auto ptr = std::unique_ptr<uv_loop_t, Deleter>{loop, [](uv_loop_t *) {}}; return std::shared_ptr<Loop>{new Loop{std::move(ptr)}}; } UVW_INLINE std::shared_ptr<Loop> Loop::getDefault() { static std::weak_ptr<Loop> ref; std::shared_ptr<Loop> loop; if(ref.expired()) { auto def = uv_default_loop(); if(def) { auto ptr = std::unique_ptr<uv_loop_t, Deleter>(def, [](uv_loop_t *) {}); loop = std::shared_ptr<Loop>{new Loop{std::move(ptr)}}; } ref = loop; } else { loop = ref.lock(); } return loop; } UVW_INLINE Loop::~Loop() noexcept { if(loop) { close(); } } UVW_INLINE void Loop::close() { auto err = uv_loop_close(loop.get()); return err ? publish(ErrorEvent{err}) : loop.reset(); } template<Loop::Mode mode> bool Loop::run() noexcept { auto utm = static_cast<std::underlying_type_t<Mode>>(mode); auto uvrm = static_cast<uv_run_mode>(utm); return (uv_run(loop.get(), uvrm) == 0); } UVW_INLINE bool Loop::alive() const noexcept { return !(uv_loop_alive(loop.get()) == 0); } UVW_INLINE void Loop::stop() noexcept { uv_stop(loop.get()); } UVW_INLINE int Loop::descriptor() const noexcept { return uv_backend_fd(loop.get()); } UVW_INLINE std::pair<bool, Loop::Time> Loop::timeout() const noexcept { auto to = uv_backend_timeout(loop.get()); return std::make_pair(to == -1, Time{to}); } UVW_INLINE Loop::Time Loop::idleTime() const noexcept { return Time{uv_metrics_idle_time(loop.get())}; } UVW_INLINE Loop::Time Loop::now() const noexcept { return Time{uv_now(loop.get())}; } UVW_INLINE void Loop::update() const noexcept { return uv_update_time(loop.get()); } UVW_INLINE void Loop::fork() noexcept { auto err = uv_loop_fork(loop.get()); if(err) { publish(ErrorEvent{err}); } } UVW_INLINE void Loop::data(std::shared_ptr<void> uData) { userData = std::move(uData); } UVW_INLINE const uv_loop_t *Loop::raw() const noexcept { return loop.get(); } UVW_INLINE uv_loop_t *Loop::raw() noexcept { return const_cast<uv_loop_t *>(const_cast<const Loop *>(this)->raw()); } // explicit instantiations #ifdef UVW_AS_LIB template bool Loop::run<Loop::Mode::DEFAULT>() noexcept; template bool Loop::run<Loop::Mode::ONCE>() noexcept; template bool Loop::run<Loop::Mode::NOWAIT>() noexcept; #endif // UVW_AS_LIB } // namespace uvw
JavaScript
UTF-8
671
4.34375
4
[]
no_license
//Array-plus-array https://www.codewars.com/kata/5a2be17aee1aaefe2a000151/train/javascript //description: I want to get the sum of two arrays...actually the sum of all their elements function arrayPlusArray(arr1, arr2) { return arr1.reduce((acc, num) => acc + num) + arr2.reduce((acc, num) => acc + num) } let arrayPlusArray = (arr1, arr2) => arr1.reduce((acc, num) => acc + num) + arr2.reduce((acc, num) => acc + num) console.log(arrayPlusArray([1, 2, 3], [4, 5, 6]), 21); console.log(arrayPlusArray([-1, -2, -3], [-4, -5, -6]), -21); console.log(arrayPlusArray([0, 0, 0], [4, 5, 6]), 15); console.log(arrayPlusArray([100, 200, 300], [400, 500, 600]), 2100);
JavaScript
UTF-8
1,245
2.59375
3
[]
no_license
module.exports = { getHouses: (req, res) => { // console.log(req) const db =req.app.get('db') // console.log(db) db.get_houses().then( results => { res.status(200).send(results) }).catch(er => { console.log(er) res.status(500).send('Cannot Get House List') }) }, addHouse: (req, res) => { const db = req.app.get('db') // console.log(req.body) let {name, address, city, state, zip} = req.body db.create_house([name, address, city, state, zip]).then(results => { res.status(200).send(results) }).catch((error) => { res.status(500).send("Could not PUT", error) }) }, deleteHouse: (req,res) => { const db = req.app.get('db') const {id} = req.params db.delete_house(id).then( results => { res.status(200).send(results) }) }, updateHouse: (req, res) => { const db = req.app.get('db') const {name, address, city, state, zip} = req.body const {id} = req.params db.update_house([name, address, city, state, zip, id]).then(results =>{ res.status(200).send(results) }) } }
C++
UTF-8
16,481
2.828125
3
[]
no_license
#include "long.h" void longz_init(longz_ptr rec) { rec->length = 0; rec->number = new unsigned char[LONGZSIZE]; } void longz_clear(longz_ptr rec) { delete rec->number; } void longz_cpy(longz_ptr rec, longz source) { rec->length = source->length; for(unsigned int i = 0; i < rec->length; i++) rec->number[i] = source->number[i]; } void longz_set_str(longz_ptr rec, char *source, unsigned int cap) { int i, j, k, tmp; if(cap == 16) { rec->length = (strlen(source) % 2 ? strlen(source) / 2 + 1 : strlen(source) / 2); for(i = rec->length - 1, j = strlen(source) - 1, tmp; i >= 0; i--, j -= 2) { if(j <= 0) tmp = 0; else tmp = source[j - 1] - (source[j - 1] >= 'a' ? 'a' - 10 : '0'); tmp <<= 4; tmp |= source[j] - (source[j] >= 'a' ? 'a' - 10 : '0'); rec->number[i] = (unsigned char)tmp; } } else if(cap == 2) { rec->length = (strlen(source) % 8 ? strlen(source) / 8 + 1 : strlen(source) / 8); for(i = rec->length - 1, j = strlen(source) - 1, tmp; i >= 0; i--, j-= 8) { for(k = 7, tmp = 0; k >= 0; k--) if((j - k) >= 0) { tmp |= (source[j - k] - '0') & 1; tmp <<= 1; } rec->number[i] = (unsigned char)tmp; } } } void longz_set_ui(longz_ptr rec, unsigned long source) { unsigned long tmp = source; int i; rec->length = 0; while(tmp) { rec->length++; for(i = rec->length; i > 0; i--) rec->number[i] = rec->number[i - 1]; rec->number[0] = tmp & 0xFF; tmp >>= 8; } } void longz_get_str(char *rec, unsigned int cap, longz source) { char tmps[2]; if(cap == 16) { strcpy(rec,""); for(unsigned int i = 0, tmp; i < source->length; i++) { tmp = ((source->number[i] >> 4) & 0xF); if(i || tmp) { sprintf(tmps,"%01x",tmp); strcat(rec,tmps); } tmp = (source->number[i] & 0xF); sprintf(tmps,"%01x",tmp); strcat(rec,tmps); } sprintf(tmps,"%c",'\0'); strcat(rec,tmps); } } int longz_cmp(longz op1, longz op2) { if(op1->length > op2->length) return 1; else if(op1->length < op2->length) return -1; else { for(unsigned int i = 0; i < op1->length; i++) { if(op1->number[i] > op2->number[i]) return 1; else if (op1->number[i] < op2->number[i]) return -1; } } return 0; } int longz_cmp_ui(longz op1, unsigned long op2) { unsigned long tmp = 0; if(op1->length > (sizeof(unsigned long) / sizeof(unsigned char))) return 1; for(unsigned int i = 0; i < op1->length; i++) { tmp <<= 8; tmp |= op1->number[i]; } if(tmp > op2) return 1; else if (tmp < op2) return -1; else return 0; } void longz_add(longz_ptr rec, longz op1, longz op2) { unsigned long length = (op1->length >= op2->length ? op1->length : op2->length); unsigned int tmprec = 0; unsigned char tmp1, tmp2; for(int i = op1->length - 1, j = op2->length - 1, k = length - 1; k >= 0; i--, j--, k--) { if(i >= 0) tmp1 = op1->number[i]; else tmp1 = 0; if(j >= 0) tmp2 = op2->number[j]; else tmp2 = 0; tmprec += tmp1 + tmp2; rec->number[k] = tmprec & 0xFF; tmprec >>= 8; } if(tmprec) { rec->length = length + 1; for(int i = length; i > 0; i--) { rec->number[i] = rec->number[i - 1]; } rec->number[0] = tmprec; } else rec->length = length; } void longz_add_ui(longz_ptr rec, longz op1, unsigned long op2) { unsigned long long tmprec = op2; unsigned char tmp1; for(int i = op1->length - 1; i >= 0; i--) { if(i >= 0) tmp1 = op1->number[i]; else tmp1 = 0; tmprec += tmp1; rec->number[i] = tmprec & 0xFF; tmprec >>= 8; } rec->length = op1->length; while(tmprec) { rec->length++; for(int i = rec->length - 1; i > 0; i--) rec->number[i] = rec->number[i - 1]; rec->number[0] = tmprec & 0xFF; tmprec >>= 8; } } int longz_sub(longz_ptr rec, longz op1, longz op2) { int sign = 1; longz_ptr buf1 = op1, buf2 = op2; if(longz_cmp(op1, op2) < 0) { sign = -1; buf1 = op2; buf2 = op1; } if(longz_cmp(op1, op2) == 0) { rec->length = 0; return 0; } int i, j, tmprec = 0; unsigned char tmp1, tmp2; rec->length = buf1->length; for(i = buf1->length - 1, j = buf2->length - 1; i >= 0; i--, j--) { tmp1 = buf1->number[i]; if(j >= 0) tmp2 = buf2->number[j]; else tmp2 = 0; tmprec += tmp1 - tmp2; rec->number[i] = (unsigned int)tmprec & 0xFF; if(tmprec >> 8) tmprec = -1; else tmprec = 0; } if(tmprec == -1) return -1; for(i = 0; rec->number[i] == 0 && i < buf1->length; i++) {} for(j = 0; j < buf1->length - i; j++) rec->number[j] = rec->number[j + i]; rec->length = buf1->length - i; return sign; } int longz_sub_ui(longz_ptr rec, longz op1, unsigned long op2) { if(longz_cmp_ui(op1, op2) < 0) return -1; if(longz_cmp_ui(op1, op2) == 0) { rec->length = 0; return 0; } unsigned long tmp2 = op2; int i, j, tmprec = 0; unsigned char tmp1; for(i = op1->length - 1; i >= 0; i--) { if(i >= 0) tmp1 = op1->number[i]; else tmp1 = 0; tmprec += tmp1 - (tmp2 & 0xFF); rec->number[i] = (unsigned int)tmprec & 0xFF; tmp2 >>= 8; if(tmprec >> 8) tmprec = -1; else tmprec = 0; } for(i = 0; rec->number[i] == 0 && i < op1->length; i++) {} for(j = 0; j < op1->length - i; j++) rec->number[j] = rec->number[j + i]; rec->length = op1->length - i; return 0; } void longz_mul(longz_ptr rec, longz op1, longz op2) { longz buf1, buf2; int i, j; longz_init(buf1); longz_init(buf2); for (i = op2->length - 1; i >= 0; i--) { longz_mul_uc(buf2, op1, op2->number[i]); for(j = (op2->length - 1) - i; j > 0; j--) buf2->number[op2->length - 1 + j] = 0; buf2->length += (op2->length - 1) - i; longz_add(rec, buf1, buf2); longz_cpy(buf1, rec); } longz_clear(buf1); longz_clear(buf2); } void longz_mul_uc(longz_ptr rec, longz op1, unsigned char op2) { unsigned int tmp = 0; for(int i = op1->length - 1; i >= 0; i--) { tmp += op1->number[i] * op2; rec->number[i] = tmp & 0xFF; tmp >>= 8; } if(tmp) { rec->length = op1->length + 1; for(int i = op1->length; i > 0; i--) { rec->number[i] = rec->number[i - 1]; } rec->number[0] = tmp; } else rec->length = op1->length; } void longz_mul_ui(longz_ptr rec, longz op1, unsigned long op2) { longz buf; longz_init(buf); longz_set_ui(buf, op2); longz_mul(rec, op1, buf); longz_clear(buf); } int longz_div(longz_ptr q, longz_ptr r, longz n, longz d) { longz buf1, buf2; int i, j; int k; int qq; int nptr = 0; int nr = 0; q->length = 0; r->length = 0; if (d->length == 0) { return -1; } if (n->length == 0 || (n->length < d->length)) { q->length = 0; longz_cpy(r, n); return 0; } else { longz_init(buf1); longz_init(buf2); nr = d->length; for(k = 0; k < nr; k++) buf1->number[k] = n->number[k]; buf1->length = nr; nptr += nr; int fuck = 0; do { fuck ++; if (fuck == 43) fuck++; qq = 1; i = buf1->length; if (buf1->length == 1 && buf1->number[0] == 0) { buf1->length = 0; i--; } if ((n->length - nptr) > 0 && i < nr) { buf1->number[buf1->length++] = n->number[nptr]; nptr++; i++; qq = 0; if (buf1->length == 1 && buf1->number[0] == 0) { buf1->length = 0; i--; q->number[q->length++] = 0; qq = 1; } while (i < nr && (n->length - nptr)) { buf1->number[buf1->length++] = n->number[nptr]; if ( !qq ) q->number[q->length++] = 0; qq = 0; nptr++; i++; if (buf1->number[0] == 0) { buf1->length = 0; i--; } } if (buf1->length < d->length && (n->length - nptr) == 0) { if (!qq) q->number[q->length++] = 0; if (q->length == 0 ) q->number[q->length++] = 0; if (buf1->length != 0) longz_cpy(r, buf1); else r->number[r->length++] = 0; longz_clear (buf1); longz_clear (buf2); return 1; } } for (i = 0; i < buf1->length; i++) { if (buf1->number[i] < d->number[i]) { if ((n->length - nptr)) { buf1->number[buf1->length++] = n->number[nptr]; if (q->length && !qq ) { q->number[q->length++] = 0; qq = 0; } nptr++; break; } else { if (q->length == 0) q->number[q->length++] = 0; if (!qq) q->number[q->length++] = 0; longz_cpy(r, buf1); longz_clear (buf1); longz_clear (buf2); return 0; } } else if (buf1->number[i] > d->number[i]) break; } i = 0; while (longz_sub(buf2, buf1, d) >= 0) { longz_cpy(buf1, buf2); i++; } q->number[q->length++] = i; } while (n->length - nptr); longz_cpy(r, buf1); if (r->length == 0) r->number[r->length++] = 0; } longz_clear (buf1); longz_clear (buf2); return 1; } int longz_div_ui(longz_ptr q, longz_ptr r, longz n, unsigned long d) { longz buf; longz_init(buf); longz_set_ui(buf, d); return longz_div(q, r, n, buf); longz_clear(buf); } int longz_mod(longz_ptr rec, longz op1, longz op2) { if(longz_cmp_ui(op2, 0) == 0) return -1; else if(longz_cmp(op1, op2) < 0) { longz_cpy(rec, op1); return 0; } else if(longz_cmp(op1, op2) == 0) { longz_set_ui(rec, (unsigned long)0); return 0; } else { longz buf1, buf2, buf3; long i, j; unsigned int nptr2; longz_init(buf1); longz_init(buf2); longz_init(buf3); longz_cpy(rec, op1); while(longz_cmp(rec, op2) >= 0) { for(i = 0, nptr2 = op1->length; longz_cmp(rec, op2) >= 0; i++) { rec->length--; nptr2--; } if(longz_cmp(rec, op2) < 0) { rec->length++; nptr2++; } buf2->length = 0; for(j = 1; longz_cmp(buf2, rec) <= 0 ;j++) { longz_mul_ui(buf2, op2, (unsigned long)j); } if(longz_cmp(buf2, rec) > 0) longz_mul_uc(buf2, op2, (unsigned long)j - 2); else longz_mul_uc(buf2, op2, (unsigned long)j - 1); longz_sub(buf3, rec, buf2); longz_cpy(buf1, buf3); for(i = 0; i < op1->length - nptr2; i++) { buf1->number[buf1->length] = op1->number[nptr2 + i]; buf1->length++; } longz_cpy(rec, buf1); } longz_clear(buf1); longz_clear(buf2); longz_clear(buf3); return 0; } } int longz_mod_ui(longz_ptr rec, longz op1, unsigned long op2) { int intrec; longz buf; longz_init(buf); longz_set_ui(buf, op2); intrec = longz_mod(rec, op1, buf); longz_clear(buf); return intrec; } void longz_powm(longz_ptr rec, longz base, longz exp, longz mod) { longz r, a, n, buf1, buf2, buf3; longz_init(r); longz_init(a); longz_init(n); longz_init(buf1); longz_init(buf2); longz_init(buf3); longz_set_ui(r, (unsigned long)1); longz_cpy(a, base); longz_cpy(n, exp); while(longz_cmp_ui(n, (unsigned long)0) > 0) { if((unsigned char)(n->length > 0 ? n->number[n->length - 1] : 0) % 2 == 0) { longz_set_ui(buf3, (unsigned long)2); longz_div(buf1, buf2, n, buf3); longz_cpy(n, buf1); longz_mul(buf1, a, a); longz_div(buf2, a, buf1, mod); } else { longz_sub_ui(buf1, n, (unsigned long)1); longz_cpy(n, buf1); longz_mul(buf1, r, a); longz_div(buf2, r, buf1, mod); } } longz_cpy(rec, r); longz_clear(r); longz_clear(a); longz_clear(n); longz_clear(buf1); longz_clear(buf2); longz_clear(buf3); } void longz_powm_ui(longz_ptr rec, longz base, unsigned long exp, longz mod) { longz buf; longz_init(buf); longz_set_ui(buf, exp); longz_powm(rec, base, buf, mod); longz_clear(buf); } void longz_gcd(longz_ptr rec, longz op1, longz op2) { longz a, b, q, r; longz_init(a); longz_init(b); longz_init(q); longz_init(r); if(longz_cmp(op1, op2) == 0) { longz_cpy(rec, op1); longz_clear(a); longz_clear(b); longz_clear(q); longz_clear(r); return; } else if(longz_cmp(op1, op2) < 0) { longz_cpy(a, op2); longz_cpy(b, op1); } else { longz_cpy(b, op2); longz_cpy(a, op1); } if(longz_cmp_ui(b,(unsigned long)0) == 0) { longz_cpy(rec, a); return; } while(longz_cmp_ui(b,(unsigned long)0) > 0) { longz_div(q, r, a, b); longz_cpy(a, b); longz_cpy(b, r); } longz_cpy(rec, a); longz_clear(a); longz_clear(b); longz_clear(q); longz_clear(r); } void longz_gcd_ui(longz_ptr rec, longz op1, unsigned long op2) { longz buf; longz_init(buf); longz_set_ui(buf, op2); longz_gcd(rec, op1, buf); longz_clear(buf); } int longz_invert(longz_ptr rec, longz op1, longz op2) { longz buf1, buf2, buf3; longz_init(buf1); longz_init(buf2); longz_init(buf3); longz_set_ui(rec, (unsigned long)1); while(longz_cmp(rec, op2) < 0) { longz_mul(buf3, rec, op1); longz_div(buf1, buf2, buf3, op2); if(longz_cmp_ui(buf2, (unsigned long)1) == 0) { longz_clear(buf1); longz_clear(buf2); longz_clear(buf3); return 1; } longz_cpy(buf1, rec); longz_add_ui(rec, buf1, (unsigned long)1); } return -1; longz_clear(buf1); longz_clear(buf2); longz_clear(buf3); }
Markdown
UTF-8
1,368
3
3
[]
no_license
## 第三章 开关的进化——从机械到芯片 错误: | 页码 | 具体位置 | 原内容 | 修改后的内容 | 贡献者 | | ---- | ---------------------- | ------ | ------------ | ------ | | P171 | 右下 | 模拟电路计算机 |“模” 字应加颜色 | | |P187 | 左下 |pMOS本身的电阻变得较小 | pMOS改成nMOS | | | P197 | 右上 |N材料去 | N材料区 | | |P221|右下倒数第三行|视逻辑不通|视逻辑不同| | P235 | 右上 | 路基1 | 逻辑1 | | | P238 | 右下倒数第6行 | 右边低电平左边高电平 | 左边低电平右边高电平 | | |P241|右上第6行|图3-228|图3-238|| |P251|图3-264||图最上方的三行字,“左”和“右”调换 ![](assets/3-264.png)|| |P254|左下|图1-111|图1-114|| |P256|最后一段第8行|逻辑1|逻辑0|| | P257 | 右下 | 虽然之前示例的程序代码写那叫一个烂 | 虽然之前示例的程序代码写得那叫一个烂 | - | | P257 | 左下 | 意义当然无存 | 意义荡然无存 | - | | 脑图 |-- | 连通楚泽的住宅 | 连同楚泽的住宅 | - | |脑图|--|193|1938|| 建议: | 页码 | 具体位置 | 原内容 | 修改后的内容 | 贡献者 | | ---- | ---------------------- | ------ | ------------ | ------ | | | | | | - |
Python
UTF-8
198
4.03125
4
[]
no_license
#题目:输入三个整数x,y,z,请把这三个数由小到大输出 m=input('输入三个整数,用空格键分开:\n') list=m.split(' ') list=sorted(list) for i in list: print(int(i))
Java
UTF-8
1,026
1.789063
2
[]
no_license
/** * */ package com.tour.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.tour.entity.HashTag; import com.tour.entity.TravelStory; /** * @author Ramanand * */ @Repository public interface TravelStoryRepository extends JpaRepository<TravelStory, Long> { @Query("select t from TravelStory t order by t.createDate desc") public List<TravelStory> findAll(); @Query("select t from TravelStory t order by t.view desc") public List<TravelStory> findAllByView(); // @Query("select t from TravelStory t order by t.likedBy desc") // public List<TravelStory> findAllByLike(); @Query("select t from TravelStory t order by t.view desc") public List<TravelStory> findAllByViewLimit(); @Query("select t from TravelStory t order by t.createDate desc") public List<TravelStory> findAllLimit(); // public List<TravelStory> findByTags(List tags); }
JavaScript
UTF-8
362
3.453125
3
[]
no_license
function unite(arr1, arr2, arr3) { var masterArray = []; for (var i = 0; i < arguments.length; i++) { masterArray.push(arguments[i]); } return masterArray.reduce(function(a, b) { for (i = 0; i < b.length; i++) { if (a.indexOf(b[i]) == -1) { a.push(b[i]); } } return a; }); } unite([1, 3, 2], [5, 2, 1, 4], [2, 1]);
JavaScript
UTF-8
28,004
2.84375
3
[]
no_license
/** * 结算价格 */ function clearingTab(price, type) { console.info("jiesuanTab") var zongshuTab = parseInt($("#zShu").html()); // 获取购物车菜品总数,购物车上的红数字 var allPrice = parseFloat($(".allprice").html()); // 获取购物车菜品总价,页面下方的合计价格 // 增加按钮 if (type == "add") { zongshuTab++; allPrice += price; } // 减少按钮 else if (type == "mu") { zongshuTab--; allPrice -= price; } // 如果购物车,菜品总数大于0 if (zongshuTab > 0) { // 购物车不为空的样式 gouwucheShow(); } // 如果购物车,菜品总数等于0 else { // 将购物车降落的样式 gouDown(); // 将购物车隐藏的样式 gouwucheHide(); } // 更新购物车的总数和总价 $(".allNum").html(zongshuTab); $(".allprice").html(allPrice.toFixed(2)); } //cookie加菜 剪菜操作 function addDishesToCookie(id, type, number) { var foodArray = localData.get('foodArray'); console.info("addDishesToCookie(), id = " + id + ", foodArray = " + foodArray); var li = $("#li" + id); var numInput = li.find(".caishu"); var num = numInput.val(); if (!$.isNull(number)) { num = number; } var unit = $("#danwei"+id).html(); //正常价 var yuanprice = parseFloat($("#price"+id).html()); var entity = { foodId: id, dishesName: $("#dishName"+id).html(), dishesPrice: yuanprice, realPrice: yuanprice*num, dishesNum: num, unit : unit, dishesRemarks : '' }; // 如果 cookie 中不存在已选的菜品 if (foodArray == undefined || foodArray == null || foodArray.length < 1 || foodArray == 'null') { array = new Array(); array.push(entity); localData.set('foodArray', JSON.stringify(array)); } else { var array = eval('(' + foodArray + ')'); var flag = false; for (var i = 0; i < array.length; i++) { if (array[i].foodId == id) { flag = true; //加 switch (type) { case "add" : console.info("addDishesToCookie() add"); array[i].dishesNum = (parseInt(array[i].dishesNum) + 1); break; case "mu": console.info("addDishesToCookie() mu"); var num = (parseInt(array[i].dishesNum) - 1); if (num == 0) { array.splice(i, 1); } else { array[i].dishesNum = num; } break; } //减 localData.set('foodArray', JSON.stringify(array)); break; } } if (!flag) { if (type != "gg") { array.push(entity); localData.set('foodArray', JSON.stringify(array)); } } } } /** * 菜品数量加一 * id : 菜品id * bol : */ function plus(id, bol, number) { console.info("plus(), id = " + id + ", number = " + number); $("#plushao" + id).hide(); $("#plushao" + id).next().show(); var dishNum = parseInt($("#" + id).val()) + 1; // input 结点 if (!$.isNull(number)) { dishNum = number + 1; // 菜品数量加一 } $("#" + id).val(dishNum); // 修改菜品数量 $("#box"+id).val(dishNum); // 修改购物车中菜品数量 var price = parseFloat($("#price" + id).html()); // 获取菜品总价 clearingTab(price, "add"); // 结算总价 //抛物线特效 var flag = $("#five_texiao").html(); if (bol && flag == 0) { // offset() 方法返回或设置匹配元素相对于文档的偏移(位置) var x = $("#jia" + id).offset().left; var y = $("#jia" + id).offset().top; // 生成抛物线特效 pwxTex(x, y); } addDishesToCookie(id, "add", dishNum); return $("#" + id).val(); } // 增加购物车菜品的数量 function plusCart(id, bol) { console.info("plusCart(), id = " + id); var idStr = ""; var number=parseInt($("#box"+idStr+id).val()); plus(id,bol,number); } // 减按钮(菜品数量减一) function SUB(id, number) { console.info("SUB(), id = " + id + ", number = " + number); var idStr = ""; var v = parseInt($("#" + id).val()) - 1; if (!$.isNull(number)) { v = number - 1; } if (v < 0) { return 0; } $("#" + id).val(v); $("#box" + idStr + id).val(v); var price = parseFloat($("#price" + id).html()); clearingTab(price, "mu"); if (v == 0) { shou(id); $("#bottom" + idStr + id).remove(); } addDishesToCookie(id, "mu", number); return $("#" + id).val(); } function subCart(id) { console.info("subCart(), id = " + id); var idStr = ""; var number = parseInt($("#box" + idStr + id).val()); SUB(id, number); } function openJiaJian(id) { //+-展开 console.info("openJiaJian(), id = " + id); plus(id, true); gouwucheShow(); } function openBro(id) { //+-展开 console.info("openBro(), id = " + id); $("#plushao" + id).hide(); $("#plushao" + id).next().show(); $("#plushao" + id).next(".plusbox").children(".jia").click(); } function shou(id) { //+-收起 console.info("shou(), id = " + id); $("#plusbox" + id).hide(); $("#plushao" + id).show(); } function zhankai(id) { //+-展开 console.info("zhankai(), id = " + id); $("#plusbox" + id).show(); $("#plushao" + id).hide(); } /** * 购物车样式修改函数 begin */ // 购物车不为空的样式 function gouwucheShow() { console.info("gouwucheShow()"); $('.pic_icon').css('display', 'none'); $('.pic_icon1').css('display', 'block'); $('.none').css('display', 'none'); $('.zTotal').css('display', 'block'); $('.ok').css('background', 'red'); } // 购物车为空的样式 function gouwucheHide() { console.info("gouwucheHide()"); $('.pic_icon').css('display', 'block'); $('.pic_icon1').css('display', 'none'); $('.none').css('display', 'block'); $('.zTotal').css('display', 'none'); $('.ok').css('background', '#cccccc'); } // 点击购物车升起 function gouUp() { console.info("gouUp()"); $('.bgUp').fadeIn(300); var iH = $('.toUp').height(); $('.toUp').css({ 'display': 'block', 'bottom': -iH }); $('.b_foot').hide(); $('.toUp').animate({'bottom': 0}, 200) //listfood $("#five_texiao").html(1); initGwc(); } //点击购物车降落 function gouDown() { console.info("gouDown()"); $('.bgUp').fadeOut(300); var iH = $('.toUp').height(); $('.toUp').css({ 'display': 'none', 'bottom': -iH }); $('.b_foot').show(); $('.toUp').animate({'bottom': -iH}, 200, function () { $('.toUp').css({ 'display': 'none' }) }) $("#five_texiao").html(0); } // 清空购物车 function clearDishes() { console.info("clearDishes()"); $("#listfood").html(''); $("#listSur .sur_input").val(0); //加减菜 $(".caishu").val(0); var foodArray = eval('(' + localData.get('foodArray') + ')'); for (i = 0; i < foodArray.length; i++) { shou(foodArray[i].foodId); } localData.set('foodArray', null); $.cookie('surArray', null); $(".allNum").html(0); $(".allprice").html(0); gouwucheHide(); gouDown(); } // 初始化购物车 function initGwc() { console.info("initGwc()"); var foodArray = localData.get('foodArray'); var lihtml = ''; var array = eval('(' + foodArray + ')'); if (array != undefined && array != null && array.length > 0 && array != "null") { for (var i = 0; i < array.length; i++) { var val = array[i]; var dshtml = ""; var idStr = ""; var li = '<li id="bottom' + idStr + val.foodId + '" class="clearfix">' + dshtml + '<span class="caititle">' + val.dishesName + '</span>' + '<div class="pbox">' + ' <div onclick="subCart(' + val.foodId + ',' + val.dishesSpecif + ')" class="upjian">' + ' <i></i>' + ' </div>' + ' <input class="input_txt" id="box' + idStr + val.foodId + '" type="number" value="' + val.dishesNum + '" readonly="readonly">' + ' <div ontouchend="plusCart(' + val.foodId + ',true,' + val.dishesSpecif + ')" class="upjia">' + ' <i></i>' + ' </div>' + '</div>' + '<span class="alert-money"><i>¥</i><b>' + val.dishesPrice + '</b></span>' + '</li>'; lihtml += li; } } $("#listfood").html(lihtml); } /** * 购物车样式修改函数 end */ // 抛物线特效 function pwxTex(x, y) { // 获得购物车图标的偏移量 var offset = $('.pic_icon1').offset(); // document : 文档对象 var div = document.createElement('div'); div.className = 'pao'; div.style.cssText = 'transform: translate3d(0, 0, 0);' + 'width: 0.75rem;' + 'height: 0.75rem;' + 'border-radius: 50%;' + 'background: red; ' + 'position: fixed;' + 'z-index: 99999999;' + 'top:'+x+'px;left:'+y+'px'; // 将生成的 div 写入 body 标签下 $('body').append(div); // 获得生成的抛物线效果对象 var flyer = $('.pao'); flyer.fly({ start: { left: x - 10, top: y - 30 }, end: { left: (offset.left + $('.pic_icon').width() / 2), //结束位置 top: (offset.top + $('.pic_icon').height() / 1) }, speed: 3, // 越大越快,默认1.2 onEnd: function () { // 结束回调 $('.pic_icon1').css({'transform': 'scale(1)'}, 100); this.destory(); // 销毁这个对象 } }); } // 下一步 、 选好了,进入下单页面 function next() { console.info("next()"); var foodArray = localData.get('foodArray'); if (foodArray == undefined || foodArray == null || foodArray == '' || foodArray == '[]' || foodArray == 'null') { $.popu("请选择菜品"); return; } if ($.isNull($.cookie("orderId")) && $("#fj_flag") && $("#fj_flag").val() == 1 && $("#jc_num") && $("#jc_num").val() == 0) { $(".bgUp2").fadeIn(200); $(".toUp2").slideDown(100); gouDown(); return; } window.location = ('orderCon.html'); } //截取名称 function cutDishesName(name) { console.info("cutDishesName(), name = " + name); if ($.isNull(name)) { return ""; } var maxwidth = 11; if (name.length >= maxwidth) { name = name.substring(0, maxwidth); return name + '...'; } return name; } //初始化从cookie中取出的菜品 function initSelectedDishesFromCookie() { console.info("initSelectedDishesFromCookie()"); var foodArray = localData.get('foodArray'); if (foodArray != undefined && foodArray != null && foodArray.length > 0 && foodArray != "null") { var dishesarray = eval('(' + foodArray + ')'); if (dishesarray.length > 0) { var sum = 0; var allprice = 0; for (var i = 0; i < dishesarray.length; i++) { var dishes = dishesarray[i]; var price = dishes.dishesPrice; allprice += (price * dishes.dishesNum); sum += parseInt(dishes.dishesNum); $("#plushao" + dishes.foodId).hide(); $("#plushao" + dishes.foodId).next().show(); $("#" + dishes.foodId).val(dishes.dishesNum); if (dishes.dishesSpecif != undefined) { $("#dishesSpecificationName" + dishes.foodId).val(dishes.dishesSpecif); } } $(".allNum").html(sum); $(".allprice").html(allprice.toFixed(2)); // 初始化购物车 内容 initGwc(); // 初始化购物车 样式 gouwucheShow(); } } } // 菜品初始化 function initDishesClass() { console.info("localData, tableId = " + localData.get('tableId')); // 以下内容是,回调成功后,执行的内容 var successCallback = function (data) { // 菜品信息(菜品分类:[菜品1, 菜品2]) var entity = data; // 菜品分类的个数 var length = entity.length; var liHtml = ""; var dishUL = ''; $("#dishUL").html(""); $("#diffCai").html(""); if (length > 0) { console.info(11111); // 循环的所有菜品分类 for (var j = 0; j < length; j++) { console.info(22222); // 某个分类的所有信息 var objClass = entity[j]; // 某个分类的所有菜品 var dishList = objClass.foodList; // 某个分类的菜品个数 var tableLength = 0; if (dishList != null) { tableLength = dishList.length; } // 添加左侧的导航 if (tableLength != 0) { //左侧导航 liHtml += '<li class="unactive" data="' + objClass.id + '" id="li' + objClass.id + '" >' + objClass.name + '(<a class="show_all">' + tableLength + '</a>)<i class="show_all_hide">' + tableLength + '</i></li>'; } // 循环所有的该分类菜品 if (dishList != null && dishList.length > 0) { for (var i = 0; i < dishList.length; i++) { var dishObj = dishList[i]; //菜品详情start imgurl = '../img/index/order/niurou.png'; // 延迟加载图片 $("#swiper").append('<div class="swiper-slide">' + ' <h4 class="h4">' + dishObj.name + '<span>68</span>元/个</h4>' + ' <div class="content">' + ' <p>' + $.nullToStr(dishObj.detail) + '</p>' + ' </div>' + ' </div>'); //菜品详情end //普通菜价格 var price; // 价格后加 .00(如(1.1).toFixed(),等于 1.10) price = (dishObj.price).toFixed(2); var imgurl = "", imgurl2 = '../img/index/order/niurou.png'; var btnHtml = '<img id="plushao' + dishObj.id + '" onClick="plus(' + dishObj.id + ',true)" class="plushao" style="display:block;" src="../img/index/order/pulsCircle.png" alt="">'; if (dishObj.small_img != null) { imgurl = dishObj.small_img; } if (dishObj.big_img != null) { imgurl2 = dishObj.big_img; } var objDishesName = cutDishesName(dishObj.name); var behindHtml = ""; // 已估清(已售完) if (dishObj.off_stock == 1) { behindHtml = '<img id="guqing' + dishObj.id + '" class="guqing plushao" style="display:block;" onclick="guqing()" src="../img/index/order/guqing.png" alt="">'; } else { behindHtml = (btnHtml + ' <div id="plusbox' + dishObj.id + '" class="plusbox clearfix" style="display:none;">' + ' <div ontouchend="SUB(' + dishObj.id + ')" id="jian' + dishObj.id + '" class="jian"><i></i></div>' + ' <input ontouchstart="numShow(' + dishObj.id + ')" readonly="readonly" id="' + dishObj.id + '" type="number" value="0" class="input caishu">' + ' <div id="jia' + dishObj.id + '" ontouchend="openJiaJian(' + dishObj.id + ')" class="jia">' + ' <i></i>' + ' </div>' + '</div>'); } // 确定菜品的单位,默认为 /份 var uuit = dishObj.unit; if ($.isNull(uuit)) { uuit = "/份"; } // 拼装出一个完整的菜品 html dishUL += ' <li id="li' + dishObj.id + '" data="' + objClass.id + '" class="ab1 pub li' + objClass.id + '"><input type="hidden" class="search_key" value="' + dishObj.name + '_' + dishObj.spell + '" />' + ' <p class="food_infor" style="color:#000;height:1rem;line-height:1rem;">' + ' <s id="dishName' + dishObj.id + '" style="height:1rem;line-height:1rem;width:4rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">' + objDishesName + '</s>&nbsp;<span>¥</span><span id="price' + dishObj.id + '" class="singlePrice" style="font-size:0.7rem;color:#FF1717">' + price + '</span><s class="danwei" id="danwei' + dishObj.id + '">' + uuit + '</s>' + ' </p>' + ' <div class="food_des">' + ' <div class="food_img" style="background:#ededed">' + ' <a id="swip_a" href="' + imgurl2 + '" ><img data-id="' + dishObj.id + '" data-original="' + imgurl + '" alt="' + objDishesName + "(¥" + price + ')"></a></div>' + ' <div class="food_img" style="border:0">' + ' <span >已售<strong>' + (dishObj.sell_num == null ? 0 : dishObj.sell_num) + '</strong>份</span>' + ' </div>' + ' <div style="width:100%;height:0.001rem;clear:both"></div>' + ' </div>' + ' <b class="sport"></b>' + behindHtml + '<p class="food_note">' + $.nullToStr(dishObj.detail) + '</p>' + '</li>' } } } } // 完全拼装好后(菜品、分类等html源码) $("#main").show(); // 分类和分类对应的菜品一起添加 $("#dishUL").html(dishUL); $("#diffCai").html(liHtml); // 取出cookie菜品(之前选好的菜品) initSelectedDishesFromCookie(); $("#right_wrap").trigger('scroll'); // 菜品详情框 (function (window, $, PhotoSwipe) { var options = { enableMouseWheel: false, enableKeyboard: false, captionAndToolbarAutoHideDelay: 0, slideshowDelay: 1500, getToolbar: function () { return "<div class='lfjtdiv ps-toolbar-previous'><img src='http://www.wecaidan.com/systemimg/Jleft.png' class='fimg'/></div><div class='cenjtdiv'><div class='roudOdDiv'><div class='wjiandiv' id='DownDishes'><img src='http://www.wecaidan.com/Images/Writereduce.png' id='DownDishesImg' class='jianIcon'/></div><div id='Num_Text'>0</div><div class='addBuyDiv' id='buyDishes'><img src='http://www.wecaidan.com/Images/Wirteadd.png' id='buyDishesImg' class='jiaIcon'></div></div></div><div class='rijtdiv ps-toolbar-next'><img src='http://www.wecaidan.com/systemimg/Jright.png' class='fimg'/></div>"; } }; rightWrapScroll.refresh(); //菜单详情 var instance = $("#dishUL #swip_a").photoSwipe(options); instance.addEventHandler(PhotoSwipe.EventTypes.onDisplayImage, function (e) { var obj = $(instance.getCurrentImage().refObj.firstElementChild); var id = obj.attr("data-id"); var dishesNum = $("#" + id).val(); var price = $("#price" + id).html(); if (dishesNum) { $("#Num_Text").html(dishesNum) } else { $("#Num_Text").html(0) } }); instance.addEventHandler(PhotoSwipe.EventTypes.onToolbarTap, function (e) { var action = e.tapTarget.id; var obj = $(instance.getCurrentImage().refObj.firstElementChild); var id = obj.attr("data-id"); switch (action) { case "buyDishes": case "buyDishesImg": plus(id) $("#Num_Text").html(parseInt($("#Num_Text").html()) + 1) break; case "DownDishes": case "DownDishesImg": SUB(id) if (parseInt($("#Num_Text").html()) > 0) { $("#Num_Text").html(parseInt($("#Num_Text").html()) - 1) } break; } }); }(window, window.jQuery, window.Code.PhotoSwipe)); $("#diffCai li").eq(0).click(); //跳转顶部 leftWrapScroll.scrollTo(0, 0, 100, IScroll.utils.ease.elastic); rightWrapScroll.scrollTo(0, 0, 100, IScroll.utils.ease.elastic); }; var errorCallback = function (data) { }; var tableId = localData.get('tableId'); var url = "../home"; // POST 请求入参 var data = 'tableId='+tableId; // 执行回调函数 $.jsonpAjaxDaAsync(url, successCallback, errorCallback, data); } var leftWrapScroll; // 左 菜品分类 var rightWrapScroll;// 右 所有菜品 function loaded() { // 左边菜单 leftWrapScroll = new IScroll('#left_wrap', { mouseWheel: true, tap: true, click: true, checkDOMChanges: true } ); // 右边菜单 rightWrapScroll = new IScroll('#right_wrap', { mouseWheel: true, tap: true, click: true, bounce: false, checkDOMChanges: true, hScroll: true } ); } //估清 function guqing() { $('.guq_mark').fadeIn(200); } // 页面初始函数 $(function () { console.info("页面入口,开始初始化。。。"); initSelectedDishesFromCookie(); // 加载菜品分类、所有菜品 loaded(); rightWrapScroll.on('scrollStart', function () { var da_li = $("#dishUL li"); var dataid = ''; for (var d_i = 0; d_i < da_li.length; d_i++) { var top = da_li.eq(d_i).offset().top; if (top > 0) { dataid = da_li.eq(d_i).attr('data') break; } } $("#diffCai li[data=" + dataid + "]").addClass("active"); $("#diffCai li[data=" + dataid + "]").removeClass("unactive"); $("#diffCai li[data=" + dataid + "]").siblings().removeClass("active"); $("#diffCai li[data=" + dataid + "]").siblings().addClass("unactive"); leftWrapScroll.scrollToElement(document.querySelector('#li' + dataid), 200, null, null, IScroll.utils.ease.circular); }); rightWrapScroll.on('scrollEnd', function () { $("#right_wrap").trigger('scroll'); }); $('#right_wrap').trigger('scroll'); $('#head').nextAll().on('touchend', function () { $('input').blur(); }); // 搜索功能 $("#tableName").bind('input propertychange', function () { var tableName = $("#tableName").val(); tableName = tableName.toLowerCase(); var limenu = $("#diffCai li"); for (var j = 0; j < limenu.length; j++) { var sum = 0; var limenuid = limenu.eq(j).attr("id"); var li = $("#dishUL ." + limenuid); for (var i = 0; i < li.length; i++) { var search_key = li.eq(i).find(".search_key").val(); var keys = search_key.split('_'); var pipeiFlag = false; var reg = /^[A-Za-z]+$/; if (reg.test(keys[ki])) { for (var ki = 0; ki < keys.length; ki++) { if (tableName.length <= keys[ki].length) { if (keys[ki].substring(0, tableName.length).toLowerCase() == tableName.toLowerCase()) { pipeiFlag = true; } } } } else { for (var ki = 0; ki < keys.length; ki++) { if (search_key.indexOf(tableName) > -1) { pipeiFlag = true; } } } if (!pipeiFlag) { li.eq(i).hide(); } else { li.eq(i).show(); sum++; } } limenu.eq(j).find(".show_all").html(sum) if (sum == 0) { limenu.eq(j).hide(); } else { limenu.eq(j).show(); } } leftWrapScroll.refresh(); rightWrapScroll.refresh(); //跳转顶部 leftWrapScroll.scrollTo(0, 0, 100, IScroll.utils.ease.elastic); rightWrapScroll.scrollTo(0, 0, 100, IScroll.utils.ease.elastic); }); //没菜和估清 var iH = ($(window).height() - $('.timeDur').innerHeight()) / 2; var iW = ($(window).width() - $('.timeDur').innerWidth()) / 2; $('.timeDur').css({'left': iW, 'top': iH}); $('.guqing').css({'left': iW, 'top': iH}); //导航,左侧的菜品分类 // on() 方法在被选元素及子元素上添加一个或多个事件处理程序。 $('#diffCai').on('click', 'li', function () { var index = $(this).attr('data'); $('#diffCai li').attr('class', 'unactive'); $(this).attr('class', 'active'); leftWrapScroll.refresh(); rightWrapScroll.scrollToElement(document.querySelector('.li' + index), 200, null, null, IScroll.utils.ease.circular); });//左边tab切换右边滑屏效果 $('.bgUp').click(function () { gouDown(); }); // 菜品初始化,Ajax 访问服务器 initDishesClass(); // 菜品图片,延迟加载效果 $("img").lazyload({ placeholder: "../img/dishLoad.png", threshold: 200, effect: 'fadeIn', container: $('#right_wrap'), failurelimit: 50, event: "scroll" }); //自定义键盘 var input2 = document.getElementById('cai_num'); new KeyBoard(input2, {type_length: 2}); $("#cai_num").bind("click", function () { $("#divid").slideDown(400, function () { $("#paydiv").hide() }); }) });
C++
UTF-8
888
2.875
3
[ "MIT" ]
permissive
#pragma once #include "../test_helper.h" #include <sstream> #include "vega/manipulators/signed_long_manipulator.h" #include "vega/dicom/data_element.h" using namespace vega; using namespace vega::manipulators; TEST(SignedLongManipulatorTest, constructor_test) { SignedLongManipulator manipulator{}; manipulator.push_back(10); manipulator.push_back(-1000); EXPECT_EQ(manipulator.str(), "10\\-1000"); SignedLongManipulator manipulator2(manipulator.raw_value()); EXPECT_EQ(manipulator[0], manipulator2[0]); EXPECT_EQ(manipulator[1], manipulator2[1]); } TEST(SignedLongManipulatorTest, data_element_test) { vega::dicom::DataElement data_element{Tag {0x0040, 0xA162}, vr::SL}; auto manipulator = data_element.get_manipulator<SignedLongManipulator>(); manipulator->push_back(33); manipulator->push_back(-65536); EXPECT_EQ(data_element.str(), "33\\-65536"); }
Java
UTF-8
6,751
2.046875
2
[]
no_license
package com.huatek.framework.show; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.huatek.base.tree.HTMLEncoder; import com.huatek.framework.entity.FwAccount; import com.huatek.framework.entity.FwSource; import com.huatek.framework.exception.BusinessRuntimeException; import com.huatek.framework.security.ClientInformationImpl; import com.huatek.framework.security.ThreadLocalClient; import com.huatek.framework.service.GlobalVar; import com.huatek.framework.sso.HttpClientUtil; import com.huatek.framework.sso.SSOServiceManagement; import com.huatek.framework.util.CommonUtil; import com.huatek.framework.util.Constant; import com.huatek.framework.util.Util; @Controller @RequestMapping("/menu.do") public class IndexController { private static final String WELCOME_ACTION = "welcome"; @RequestMapping(params = "actionMethod=getMenu") public String getMenu(final Model model, final HttpServletRequest request,final HttpServletResponse response) throws Exception{ //如果是本地请求,则转发到SSO服务器 if(!SSOServiceManagement.isSSOServer()){ String SSoURL = SSOServiceManagement.getSSOServerURL(request.getServerName(), request.getServerPort()); SSoURL = SSoURL + "/menu.do?"+request.getQueryString(); String token = (String)request.getSession().getAttribute(ClientInformationImpl.SSO_TOKEN); if(token==null){ throw new BusinessRuntimeException("没有获取到SSO服务器登录令牌!"); } request.setAttribute(Constant.AJAX_OUT_DATA, HttpClientUtil.getMethod(SSoURL,token)); return "frame/out_data.jsp"; //如果是SSO服务器自己的请求,使用当前的应用模板 }else{ return getModule(model,request,response); } } public static String getModule(final Model model, final HttpServletRequest request, final HttpServletResponse response) throws Exception { FwAccount user = ThreadLocalClient.get().getOperator(); if(user==null){ return "redirect:sso.show?actionMethod=logout"; } //获取导航条信息 List<FwSource> sourceList = user.getUserMenuTree(); StringBuffer navHtml=new StringBuffer(""); String menuId = request.getParameter("menuId"); for(int i=0;i<sourceList.size();i++){ FwSource source = (FwSource)sourceList.get(i); if(source.getLevel().intValue()==1){ if(source.getId().toString().equals(menuId)){ navHtml.append("<li class='active'><a class='current' "); }else{ navHtml.append("<li><a "); } navHtml.append(" href='"); if(source.getFwSystem().getId()!=1 || source.getFwSystem().getContextPath()!=null){ navHtml.append(source.getFwSystem().getSystemURL(request.getServerName(),request.getServerPort())).append("/"); }else{ navHtml.append("http://").append(request.getServerName()).append(":").append(request.getServerPort()).append(request.getContextPath()).append("/"); } navHtml.append("menu.do?actionMethod=getMenu&menuId="+source.getId()); if(source.getSourceCode()!=null&&!source.getSourceCode().equals("#")){ navHtml.append("&").append(WELCOME_ACTION).append("=").append(java.net.URLEncoder.encode(source.getSourceCode(), GlobalVar.CHARSET_UTF_8)); } navHtml.append("'>"+HTMLEncoder.INSTANCE.encode(source.getTitle())+"</a></li>"); } } model.addAttribute("navHtml", navHtml); if(CommonUtil.isNotZeroLengthTrimString(menuId)){ //获取当前的模块信息 FwSource source = (FwSource)Util.getObject(user.getUserMenuTree(), Long.valueOf(menuId)); model.addAttribute("fwSource",source); //获取当前的二级菜单信息 model.addAttribute("subMenuHtml", getSubMenuStr(source,user)); } //设置布局页面上调用的action if(CommonUtil.isNotZeroLengthTrimString(request.getParameter(WELCOME_ACTION))){ request.setAttribute(WELCOME_ACTION, request.getParameter(WELCOME_ACTION)); } return "layout/common.jsp"; } private static String getSubMenuStr(FwSource fwSource, FwAccount user) { if(fwSource!=null){ StringBuffer menuStr = new StringBuffer(); List<FwSource> sourceList = user.getUserMenuTree(); if(sourceList!=null && sourceList.size()>0){ for(int i=0;i<sourceList.size();i++){ FwSource source = sourceList.get(i); if(source.getLevel()==2 && source.getParent().getId().longValue() == fwSource.getId().longValue()){ menuStr.append("<ul>\n"); if(source.isContainChild()){ FwSource nextNode = (FwSource)source.getNextNode(); if(nextNode.getIsMenu()==1){ menuStr.append("<li class='button'><a href='javascript:;'>"); menuStr.append(source.getName()); menuStr.append("</a></li>\n<li class='dropdown'>\n<ul>\n"); }else{ menuStr.append("<li class='button'> <a href='javascript:;' onclick=\"getInitModule('"+nextNode.getLink()+"','"+fwSource.getName()+" > "+ source.getName() +"');\" >"); menuStr.append(source.getName()+"</a></li></ul>\n"); } }else{ menuStr.append("<li class='button'> <a onclick=\"getInitModule('"+source.getLink()+"','"+fwSource.getName()+" > "+ source.getName() +"');\" >"); menuStr.append(source.getName()+"</a></li></ul>\n"); } }else if(source.getIsMenu()==1 && source.getLevel()==3 && source.getParent().getParent().getId().longValue() == fwSource.getId().longValue()){ FwSource nextNode = (FwSource)source.getNextNode(); if(!source.isContainChild()){ menuStr.append("<li class='button'><a href='javascript:;' onclick=\"getInitModule('"+source.getLink()+"','"+fwSource.getName()+" > "+ source.getParent().getName() +" > "+source.getName()+"');\" >"+source.getName()+"</a></li></ul>\n"); }else{ menuStr.append("<li class='button'><a onclick=\"getInitModule('"+nextNode.getLink()+"','"+fwSource.getName()+" > "+ source.getParent().getName() +" > "+source.getName()+"');\" >"+source.getName()+"</a></li>\n"); while(nextNode!=null&&nextNode.getIsMenu()==2){ nextNode = (FwSource)nextNode.getNextNode(); } } if(nextNode==null || nextNode.getParent()==null || nextNode!=null && nextNode.getParent() != null && nextNode.getParent().getId().longValue() != source.getParent().getId().longValue()){ menuStr.append("</ul>\n"); } } } } if(menuStr.length()>0){ return "<div class='menuTitle'>"+fwSource.getName()+"</div>\n"+menuStr; } return null; }else{ return null; } } }
Markdown
UTF-8
6,376
2.609375
3
[]
no_license
# Feature Extracion ## class Data Class for manipulating the data and extracting characteristics. ### Attributes There are two types of public attributes: 1) __storage attributes__ - their purpose is simply to store data of the matches. To reiterate, we are not only storing the incremental data, that are in the input but the whole frames of data. (`self.today`, `self.bankroll`, `self.matches`) 2) __feature attributes__ - they store the data of the extracted features. The features themselves are meant to be extracted from the storage attributes (`self.LL_data`, `self.SL_data`, `self.match_data`) - `self.today` (`pandas._libs.tslibs.timestamps.Timestamp`): current date [__storage attribute__] - `self.bankroll` (`int`): bankroll from the summary [__storage attribute__] - `self.matches` (`pandas.DataFrame`) [__storage attribute__] | __index__ | `'opps_Date'` | `'Sea'` | `'Date'` | `'Open'` | `'LID'` | `'HID'` | `'AID'` | `'HSC'` | `'ASC'` | `'H'` | `'D'` | `'A'` | `'OddsH'` | `'OddsD'` | `'OddsA'` | `'P(H)'` | `'P(D)'` | `'P(A)'` | `'BetH'` | `'BetD'` | `'BetA'` | | :-- | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | match ID | date of opps occurrence | season | date of play | date of betting possibility | league ID (str) | home team ID | away | home goals scored | away goals scored | home win | draw | away win | odds of home win | odds of draw | odds of | model prob. home win | model prob. draw | model prob. away win | bet home win | bet draw | bet away win away winteam ID | - `self.LL_data` (`pandas.DataFrame`) [__feature attribute__] LL: life-long | __index__ | `'LID'` | `'LL_Goals_Scored'` | `'LL_Goals_Conceded'` | `'LL_Wins'` | `'LL_Draws'` | `'LL_Loses'` | `'LL_Played'` | `'LL_Accu'` | | :- | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | team ID | league ID (list) | goals scored | goals conceded | wins | draws | loses | played matches | model accuracy | - `self.SL_data` (`pandas.DataFrame`) [__feature attribute__] SL: season-long | __index (multi index)__ | `'LID'` | `'SL_Goals_Scored'` | `'SL_Goals_Conceded'` | `'SL_Wins'` | `'SL_Draws'` | `'SL_Loses'` | `'SL_Played'` | `'SL_Accu'` | | :- | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | season,team ID | league ID (list) | goals scored | goals conceded | wins | draws | loses | played matches | model accuracy | - `self.match_data` (`pandas.DataFrame`) [__feature attribute__] | __index__ | `'MatchID'` | `'Sea'` | `'Date'` | `'Oppo'` | `'Home'` | `'Away'` | `'M_Goals_Scored'` | `'M_Goals_Conceded'` | `'M_Win'` | `'M_Draw'` | `'M_Lose'` | `'M_P(Win)'` | `'M_P(Draw)'` | `'M_P(Lose)'` | `'M_Accu'` | | :- | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | team ID | match ID | season | date of play | opponent id | team is home | team is away | goals scored | goals conceded | match win | match draw | match lose | model prob. win | model prob. draw | model prob. lose | model accuracy | ### Methods a) __public__ 1) ```python def update_data(self, opps=None ,summary=None, inc=None, P_dis=None, bets=None): ''' Run the iteration update of the data stored. ! Summary has to be updated first to get the right date! Parameters: All the parameters are supplied by the evaluation loop. opps(pandas.DataFrame): dataframe that includes the opportunities for betting. summary(pandas.DataFrame): includes the `Max_bet`, `Min_bet` and `Bankroll`. inc(pandas.DataFrame): includes the played matches with the scores for the model. ''' ``` Used every time that you want to incrementally update the _storage attributes_. 2) ```python def update_features(self): ''' Update the features for the data stored in `self`. ''' ``` Used every time that the features are to be evaluated from the data in the _storage attributes_ and updated in the _feature attributes_ b) __private__ 1) The evaluation of the passed inputs is handled by the `self._EVAL_***` (where `***` is the input to evaluate) methods using the `self._eval_***` methods (where `***` is generally the field to update). 2) The updating of features from self is handled by the `self._UPDATE_***` (where `***` is the _feature attribute_ to update) methods using the `self._update_***` methods (where `***` is generally the field to update). # Important comments All of this is written with the assumption that the working dir is the git root (`./pm_mode`). ## Interacting with the environment 1) importing ```python from hackathon.src.environment import Environment ``` 2) loading data ```python dataset = pd.read_csv('./hackathon/data/training_data.csv', parse_dates=['Date', 'Open']) ``` 3) initializing (without `model`) ```python env = Environment(dataset, None) ``` 4) some usefull functions examples ```python # returns the same as `data.curr_inc` env.get_incremental_data(pd.to_datetime('2001-12-30')) # returns the same as `data.curr_opps` env.get_opps(pd.to_datetime('2001-12-30')) # returns the same as `data.curr_summary` env.generate_summary(pd.to_datetime('2001-12-30')) ``` ## Parsing dates 1) For testing it is extremely important to parse the data with dates... ```python pd.read_csv('./hackathon/data/training_data.csv', parse_dates=['Date', 'Open']) ``` and not ```python pd.read_csv('./hackathon/data/training_data.csv') ```
Java
UTF-8
563
2.78125
3
[ "Apache-2.0" ]
permissive
package com.wendy.thread.schedule; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; public class ThreadFactoryImpl implements ThreadFactory { private final AtomicLong threadIndex = new AtomicLong(0); private final String threadNamePrefix ; public ThreadFactoryImpl(final String threadNamePrefix) { this.threadNamePrefix = threadNamePrefix; } @Override public Thread newThread(Runnable runnable) { return new Thread(runnable, threadNamePrefix+this.threadIndex.incrementAndGet()); } }
Python
UTF-8
7,108
2.90625
3
[]
no_license
from random import random import gym from entities import * class PokerEnv(gym.Env): metadata = {'render.modes': ['human']} def __init__(self, num_of_chips, lose_punishment, deal_cards=True, randomize_chips=None): self.gm = None self.lp = lose_punishment self.dc = deal_cards self.rc = randomize_chips self.ob = self.reset(num_of_chips) self.fld_pen = 50 self.win_rew = 100 self.los_pen = 0 self.tot_los_pen = 0 self.tot_win_rew = 100 def step(self, action): """Step returns ob, rewards, episode_over, info : tuple ob (list[Player,Player]) : next stage observation [player who is small blind,player who is big blind]. rewards ([float,float]) : amount of reward achieved by the previous action :param action: [small blind action, big blind action] 0 if fold, 1 otherwise """ sb_player = self.gm.sb_player() bb_player = self.gm.bb_player() if action[0] == 1: # Small blind went all in self.gm.player_all_in(sb_player) if action[1] == 1: # BB called self.gm.player_call(bb_player, sb_player.bet) # Need to compare hands for c in range(5): new_card = self.gm.deck.draw_card() for ep in self.gm.p: ep.hand.add_card(new_card) for pl in self.gm.p: pl.hand.sort() # get the absolute score of the hand and the best five cards results = [] for ep in [sb_player, bb_player]: results.append(Game.score(ep.hand)) # select the winner winners = Game.determine_winner(results) # award the pot to the winner if winners.__len__() > 1: # split the pot self.gm.split_the_pot() # Give both players small reward rewards = [self.win_rew, self.win_rew] else: # Actually transfer the chips between players _players = [sb_player, bb_player] wnr = _players[winners[0]] lsr = _players[1 - winners[0]] self.gm.player_won(wnr) rewards = [] # Reward the winner with chips won rewards.insert(winners[0], self.win_rew) # Penalty the loser with chips lost rewards.insert(1 - winners[0], self.los_pen) else: # BB folded # Reward SB with amount won # Transfer chips to SB sb_player.bank += self.gm.pot # Penalty BB by amount lost rewards = [self.win_rew, self.fld_pen] else: # Small blind folded # Reward BB with 0 since their move didn't matter # Penalty SB by amount lost rewards = [self.fld_pen, self.win_rew] # Transfer chips to BB bb_player.bank += self.gm.pot # Change who is SB self.gm.sb = 1 - self.gm.sb self.gm.new_step() self.gm.place_blinds() if self.dc: self.gm.players_draw_cards() if self.gm.a_player().bank <= 0 or self.gm.na_player().bank <= 0: self.gm.done = True # if the game was lost completely, the punishment is different if self.gm.done: for (ind, r) in enumerate(rewards): if (r == self.los_pen) | (r == self.fld_pen): rewards[ind] = self.tot_los_pen self.ob = [sb_player, bb_player] return self.ob, rewards, self.gm.done def reset(self, bank=50): """Initial setup for training :param bank : initial bank size :returns [small blind player, big blind player] """ self.gm = Game("P1", "Qtable", "P2", "Qtable", bank) # Random starting money distribution p=0.4 if self.rc is not None: if random() < self.rc: left = round(random() * ((bank * 2) - 4)) self.gm.sb_player().bank = left + 2 self.gm.bb_player().bank = ((bank * 2) - 4) - left + 2 self.gm.place_blinds() if self.dc: self.gm.players_draw_cards() # Return observation # [ Small Blind Player, Big Blind Player ] self.ob = [self.gm.sb_player(), self.gm.bb_player()] return self.ob def render(self, mode='human'): self.gm.render_game() @staticmethod def encode(hand, small_blind, _num_of_chips, initial_num_of_chips): """Encoding and decoding code was lifted from openAI taxi gym""" # Sort hand and extract cards _sorted_hand = sorted(hand.cards, reverse=True) _card1 = _sorted_hand[0].encode() _card2 = _sorted_hand[1].encode() # Calculate coefficient of number of chips _coef_chips = 2 * _num_of_chips // initial_num_of_chips # Encode encoded = _card2 encoded *= 52 encoded += _card1 encoded *= 2 encoded += small_blind encoded *= 4 encoded += _coef_chips return encoded @staticmethod def decode(_code): """Encoding and decoding code was lifted from openAI taxi gym""" _out = [_code % 4] _code = _code // 4 _out.append(_code % 2) _code = _code // 2 _card1 = Card.decode(_code % 52) _code = _code // 52 _card2 = Card.decode(_code) assert 0 <= _code < 52 _hand = Hand() _hand.add_card(_card1) _hand.add_card(_card2) _out.append(_hand) return _out def test_encoder_decoder(): """Test encoder and decoder""" hand1 = Hand() initial_chips = 10 for chips in range(initial_chips * 2): for sb in range(2): for card1_code in range(52): for card2_code in range(52): if card1_code == card2_code: continue # Create hand card1 = Card.decode(card1_code) card2 = Card.decode(card2_code) hand1.clear_hand() hand1.add_card(card1) hand1.add_card(card2) hand1.cards = sorted(hand1.cards, reverse=True) # Encode and decode code = PokerEnv.encode(hand1, sb, chips, initial_chips) [new_chips, new_small_blind, new_hand] = PokerEnv.decode(code) assert new_chips == 2 * chips // initial_chips assert new_small_blind == sb assert new_hand.cards[0] == hand1.cards[0] assert new_hand.cards[1] == hand1.cards[1] if __name__ == "__main__": # test_encoder_decoder() pass
Markdown
UTF-8
12,807
3.359375
3
[]
no_license
includes ``` // 63: String - `includes()` // To do: make all tests pass, leave the assert lines unchanged! // Follow the hints of the failure messages! describe('`string.includes()` determines if a string can be found inside another one', function() { describe('finding a single character', function() { it('can be done (a character is also a string, in JS)', function() { // const searchString = 'a'; const searchString = 'x'; assert.equal('xyz'.includes(searchString), true); }); it('reports false if character was not found', function() { // const expected = '???'; const expected = false; assert.equal('xyz'.includes('abc'), expected); }); }); describe('find a string', function() { it('that matches exactly', function() { //const findSome = findMe => 'xyz'.includes; const findSome = findMe => 'xyz'.includes(findMe); assert.equal(findSome('xyz'), true); }); }); describe('search for an empty string, is always true', function() { it('in an empty string', function() { // const emptyString = ' '; const emptyString = '' assert.equal(''.includes(emptyString), true); }); it('in `abc`', function() { // const actual =_.includes(''); const actual ='abc'.includes(''); assert.equal(actual, true); }); }); describe('special/corner cases', function() { it('search for `undefined` in a string fails', function() { //const findInAbc = (what) => 'abc'.includes(); const findInAbc = (what) => 'abc'.includes(undefined); assert.equal(findInAbc(undefined), false); }); it('searches are case-sensitive', function() { // const findInAbc = (what) => 'abc'.inkludez(what); const findInAbc = (what) => 'abc'.includes(what); assert.equal(findInAbc('A'), false); }); it('must NOT be a regular expression', function() { //const regExp = ''; const regExp = /.*/; assert.throws(() => {''.includes(regExp)}); }); describe('coerces the searched "thing" into a string', function() { it('e.g. from a number', function() { const actual = '123'.includes(4); // assert.equal(actual, true); assert.equal(actual, false); }); it('e.g. from an array', function() { // const actual = '123'.includes([1,2,3]); const actual = '1,2,3,4'.includes([1,2,3]); assert.equal(actual, true); }); it('e.g. from an object, with a `toString()` method', function() { const objWithToString = {toString: () => ""}; assert.equal('123'.includes(objWithToString), true); }); }); }); describe('takes a position from where to start searching', function() { it('does not find `a` after position 1 in `abc`', function() { // const position = 0; const position = 1; assert.equal('abc'.includes('a', position), false); }); it('even the position gets coerced', function() { // const findAtPosition = position => 'xyz'.includes('x', pos); const findAtPosition = position => 'xyz'.includes('x', position); assert.equal(findAtPosition('2'), false); }); describe('invalid positions get converted to 0', function() { it('e.g. `undefined`', function() { // const findAtPosition = (pos=2) => 'xyz'.includes('x', pos); const findAtPosition = (pos) => 'xyz'.includes('x', pos); assert.equal(findAtPosition(undefined), true); }); it('negative numbers', function() { // const findAtPosition = (pos) => 'xyz'.includes('x', -pos); const findAtPosition = (pos) => 'xyz'.includes('x', pos); assert.equal(findAtPosition(-2), true); }); it('NaN', function() { // const findAtPosition = (pos) => 'xyz'.includes('x', 1); const findAtPosition = (pos) => 'xyz'.includes('x', pos); assert.equal(findAtPosition(NaN), true); }); }); }); }); ``` string.repeat(count) ``` // 71: String - `repeat()` // To do: make all tests pass, leave the assert lines unchanged! // Follow the hints of the failure messages! describe('`str.repeat(x)` concatenates `x` copies of `str` and returns it', function() { describe('the 1st parameter the count', function() { it('if missing, returns an empty string', function() { // const what = 'one'.repeat(23); const what = 'one'.repeat(0); assert.equal(what, ''); }); it('when `1`, the string stays the same', function() { // const what = 'one'.repeat(); const what = 'one'.repeat(1); assert.equal(what, 'one'); }); it('for `3` the string `x` becomes `xxx`', function() { // const actual = 'x'.REPEAT(1); const actual = 'x'.repeat(3); assert.equal(actual, 'xxx'); }); it('for `0` an empty string is returned', function() { // const repeatCount = 1; const repeatCount = 0; assert.equal('shrink'.repeat(repeatCount), ''); }); describe('the count is not a number', () => { it('such as a string "3", it gets converted to an int', function() { // const repeated = 'three'.repeat('2'); const repeated = 'three'.repeat('3'); assert.equal(repeated, 'threethreethree'); }); it('a hex looking number as a string "0xA", it gets converted to an int', function() { // const repeated = 'x'.repeat('0A'); const repeated = 'x'.repeat('0xA'); assert.equal('xxxxxxxxxx', repeated); }); it('and does not look like a number, it behaves like 0', function() { // const repeated = 'x'.repeat('23'); const repeated = 'x'.repeat('0'); assert.equal('', repeated); }); }); }); describe('throws an error for', function() { it('a count of <0', function() { // const belowZero = 1; const belowZero = -1; assert.throws(() => { ''.repeat(belowZero); }, RangeError); }); it('a count of +Infinty', function() { // let infinity = 'infinity'; let infinity = 'Infinity'; assert.throws(() => { ''.repeat(infinity); }, RangeError); }); }); describe('accepts everything that can be coerced to a string', function() { it('e.g. a boolean', function() { // let aBool = true; let aBool = false; assert.equal(String.prototype.repeat.call(aBool, 2), 'falsefalse'); }); it('e.g. a number', function() { // let aNumber;I let aNumber = 1; assert.equal(String.prototype.repeat.call(aNumber, 2), '11'); }); }); describe('for my own (string) class', function() { it('calls `toString()` to make it a string', function() { // class MyString { toString() { return 'my string'; } } class MyString { toString() { return ''; } } const expectedString = ''; assert.equal(String(new MyString()).repeat(1), expectedString); }); it('`toString()` is only called once', function() { let counter = 1; class X { toString() { return counter++; } } // let repeated = new X().repeat(2); let repeated = String(new X()).repeat(2); assert.equal(repeated, 11); }); }); }); ``` starWith ``` // 72: String - `startsWith()` // To do: make all tests pass, leave the assert lines unchanged! // Follow the hints of the failure messages! describe('`str.startsWith(searchString)` determines whether `str` begins with `searchString`.', function() { const s = 'the string s'; describe('the 1st parameter, the string to search for', function() { it('can be just a character', function() { // const actual = s.starts_with('t'); const actual = s.startsWith('t'); assert.equal(actual, true); }); it('can be a string', function() { // const expected = '???'; const expected = true; assert.equal(s.startsWith('the'), expected); }); it('can contain unicode characters', function() { //const nuclear = 'NO ☢ NO'; const nuclear = '☢ NO'; assert.equal(nuclear.startsWith('☢'), true); }); it('a regular expression throws a TypeError', function() { // const aRegExp = ""; const aRegExp = /the/; //startsWith 和正则 出现 TypeError assert.throws(() => {''.startsWith(aRegExp)}, TypeError); }); }); describe('the 2nd parameter, the position where to start searching from', function() { it('e.g. find "str" at position 4', function() { // const position = 3; const position = 4; assert.equal(s.startsWith('str', position), true); }); it('for `undefined` is the same as 0', function() { // const _undefined_ = '1'; const _undefined_ = '0'; assert.equal(s.startsWith('the', _undefined_), true); }); it('the parameter gets converted to an int', function() { // const position = 'four'; const position = '4'; assert.equal(s.startsWith('str', position), true); }); it('a value larger than the string`s length, returns false', function() { // const expected = true; const expected = false; // or // assert.equal(s.startsWith(' ',3), expected) assert.equal(s.startsWith(' ', s.length + 1), expected); }); }); describe('this functionality can be used on non-strings too', function() { it('e.g. a boolean', function() { // let aBool; let aBool = false; assert.equal(String.prototype.startsWith.call(aBool, 'false'), true); }); it('e.g. a number', function() { // let aNumber = 19; let aNumber = '19'; assert.equal(String.prototype.startsWith.call(aNumber + 84, '1984'), true); }); it('also using the position works', function() { // const position = 0; const position = 1; assert.equal(String.prototype.startsWith.call(1994, '99', position), true); }); }); }); ``` endWith ``` // 74: String - `endsWith()` // To do: make all tests pass, leave the assert lines unchanged! // Follow the hints of the failure messages! describe('`str.endsWith(searchString)` determines whether `str` ends with `searchString`', function() { const s = 'el fin'; describe('the 1st parameter the string to search for', function() { it('can be a character', function() { // const doesEndWith = s.doesItReallyEndWith('n'); const doesEndWith = s.endsWith('n'); assert.equal(doesEndWith, true); }); it('can be a string', function() { // const expected = false; const expected = true; assert.equal(s.endsWith('fin'), expected); }); it('can contain unicode characters', function() { // const nuclear = 'NO ☢ Oh NO!'; const nuclear = "NO ☢"; assert.equal(nuclear.endsWith('☢'), true); }); it('a regular expression throws a TypeError', function() { // const aRegExp = '/the/'; const aRegExp = /the/; assert.throws(() => {" ".endsWith(aRegExp)}, TypeError); }); }); describe('the 2nd parameter, the position where the search ends (as if the string was only that long)', function() { it('find "el" at a substring of the length 2', function() { // const endPos = 0; const endPos = 2; assert.equal(s.endsWith('el', endPos), true); }); it('`undefined` uses the entire string', function() { // const _undefined_ = 'i would like to be undefined'; const _undefined_ = undefined; assert.equal(s.endsWith('fin', _undefined_), true); }); it('the parameter gets coerced to an integer (e.g. "5" becomes 5)', function() { // const position = 'five'; const position = '5'; assert.equal(s.endsWith('fi', position), true); }); describe('value less than 0', function() { it('returns `true`, when searching for an empty string', function() { // const emptyString = '??'; const emptyString = '' assert.equal('1'.endsWith(emptyString, -1), true); }); it('return `false`, when searching for a non-empty string', function() { // const notEmpty = ''; const notEmpty = '342'; assert.equal('1'.endsWith(notEmpty, -1), false); }); }); }); describe('this functionality can be used on non-strings too', function() { it('e.g. a boolean', function() { // let aBool = true; let aBool = false; assert.equal(String.prototype.endsWith.call(aBool, 'lse'), true); }); it('e.g. a number', function() { // let aNumber = 0; let aNumber = 84 assert.equal(String.prototype.endsWith.call(aNumber + 1900, 84), true); }); it('also using the position works', function() { // const position = '??'; const position = '3'; assert.equal(String.prototype.endsWith.call(1994, '99', position), true); }); }); }); ```
C++
UTF-8
1,452
2.546875
3
[]
no_license
#pragma once #include "Fonts.h" typedef unsigned char Pixel; /*#define LCD_SIZE (160*43*1) #define LCD_W (160) #define LCD_H (43) #define LCD_P (160)*/ #define PIXEL_ON (128) #define PIXEL_OFF (0) class Surface { int m_Width, m_Height, m_Pitch; Pixel* m_Buffer; lgLcdBitmap160x43x1* m_bmp; public: Surface(); Surface( int a_Width, int a_Height ); ~Surface(); lgLcdBitmapHeader* Get( ) { return m_bmp == 0 ? 0 : &(m_bmp->hdr); }; void Clear( Pixel colour = PIXEL_OFF ) { memset( m_Buffer, colour, m_Width * m_Height ); } void SetPixel(int,int,Pixel); void Print( wchar_t* a_String, int x1, int y1, Font* a_Font, Pixel colour = PIXEL_ON, int max_x = -1 ); void Line( int x1, int y1, int x2, int y2, Pixel c = PIXEL_ON ); void Line( float x1, float y1, float x2, float y2, Pixel c = PIXEL_ON ); void Box( int x1, int y1, int w, int h, Pixel c = PIXEL_ON ); void BoxAbs( int x1, int y1, int x2, int y2, Pixel c = PIXEL_ON ); void Bar( int x1, int y1, int w, int h, Pixel c = PIXEL_ON ); void BarAbs( int x1, int y1, int x2, int y2, Pixel c = PIXEL_ON ); void Plot( int x, int y, Pixel c = PIXEL_ON ); void Save( const wchar_t* file ); Pixel* GetBuffer() { return m_Buffer; } void CopyTo( Surface* a_Dst, int a_X, int a_Y, Pixel* a_AlphaColour = 0 ); int GetWidth() { return m_Width; } int GetHeight() { return m_Height; } int GetPitch() { return m_Pitch; } };
C#
UTF-8
1,480
3.328125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Interviews.OODesign { public class Othello { private SpaceType[,] _grid; public void NewGame(int length) { if (length % 2 != 0) { throw new ArgumentException("Must be even"); } _grid = new SpaceType[length, length]; for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if ((i == (length / 2) && (j == length / 2)) || (i == 1 + (length / 2) && (j == 1 + length / 2))) { _grid[i, j] = SpaceType.White; } else if ((i == (length / 2) && (j == 1 + length / 2)) || (i == 1 + (length / 2) && (j == length / 2))) _grid[i, j] = SpaceType.Black; } } } public bool PlayMove(int i, int j) { if (i >= _grid.Length || j >= _grid.Length) { return false; } if (_grid[i,j] != SpaceType.Unoccupied) { return false; } throw new NotImplementedException(); } } enum SpaceType { Unoccupied, Black, White } }
C#
UTF-8
1,270
2.53125
3
[ "MIT" ]
permissive
// * // * Copyright (C) 2005 Mats Helander : http://www.puzzleframework.com // * // * This library is free software; you can redistribute it and/or modify it // * under the terms of the GNU Lesser General Public License 2.1 or later, as // * published by the Free Software Foundation. See the included license.txt // * or http://www.gnu.org/copyleft/lesser.html for details. // * // * namespace Puzzle.NPersist.Framework.Enumerations { /// <summary> /// This enumeration is used in xml persistence and determines the document partitioning strategy when objects of a class are stored to disk. /// </summary> public enum DocClassMapMode { /// <summary> /// The strategy will be inherited, and finally PerDomain. /// </summary> Default = 0, /// <summary> /// Saves all objects from the domain into one big document. /// </summary> PerDomain = 1, /// <summary> /// Creates a separate document per class where all objects of the class are stored. /// </summary> PerClass = 2, /// <summary> /// Each object gets its own document. /// </summary> PerObject = 3, /// <summary> /// Xml persistence is turned off. /// </summary> None = 4 } }
Java
UTF-8
1,918
1.867188
2
[]
no_license
package com.tinder.api.module; import com.tinder.api.APIHeaderInterceptor; import dagger.internal.C15521i; import dagger.internal.Factory; import javax.inject.Provider; import okhttp3.C17692o; public final class LegacyNetworkModule_ProvideAuthHeadersOkHttpClientFactory implements Factory<C17692o> { private final Provider<APIHeaderInterceptor> apiHeaderInterceptorProvider; private final Provider<C17692o> clientProvider; private final LegacyNetworkModule module; public LegacyNetworkModule_ProvideAuthHeadersOkHttpClientFactory(LegacyNetworkModule legacyNetworkModule, Provider<C17692o> provider, Provider<APIHeaderInterceptor> provider2) { this.module = legacyNetworkModule; this.clientProvider = provider; this.apiHeaderInterceptorProvider = provider2; } public C17692o get() { return provideInstance(this.module, this.clientProvider, this.apiHeaderInterceptorProvider); } public static C17692o provideInstance(LegacyNetworkModule legacyNetworkModule, Provider<C17692o> provider, Provider<APIHeaderInterceptor> provider2) { return proxyProvideAuthHeadersOkHttpClient(legacyNetworkModule, (C17692o) provider.get(), (APIHeaderInterceptor) provider2.get()); } public static LegacyNetworkModule_ProvideAuthHeadersOkHttpClientFactory create(LegacyNetworkModule legacyNetworkModule, Provider<C17692o> provider, Provider<APIHeaderInterceptor> provider2) { return new LegacyNetworkModule_ProvideAuthHeadersOkHttpClientFactory(legacyNetworkModule, provider, provider2); } public static C17692o proxyProvideAuthHeadersOkHttpClient(LegacyNetworkModule legacyNetworkModule, C17692o c17692o, APIHeaderInterceptor aPIHeaderInterceptor) { return (C17692o) C15521i.a(legacyNetworkModule.provideAuthHeadersOkHttpClient(c17692o, aPIHeaderInterceptor), "Cannot return null from a non-@Nullable @Provides method"); } }
Java
UTF-8
2,537
2.640625
3
[]
no_license
package com.boot.example; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.Test; import java.util.List; /** * com.boot.example.CuratorTest1 * * @author lipeng * @date 2019-04-29 14:53 */ public class CuratorTest { @Test public void createNode() throws Exception { CuratorFramework client = CuratorUtils.getClient(); // 创建一个临时结点 client.create() .creatingParentContainersIfNeeded() .forPath("/test", "test".getBytes()); } @Test public void existsNode() throws Exception { CuratorFramework client = CuratorUtils.getClient(); Stat stat = client.checkExists().forPath("/test"); System.out.println("结点/test是否存在:" + stat); } @Test public void getNodeData() throws Exception { CuratorFramework client = CuratorUtils.getClient(); // 读取结点值 System.out.println("结点/test值为:" + new String(client.getData().forPath("/test"), "UTF-8")); } @Test public void modifyNodeData() throws Exception { CuratorFramework client = CuratorUtils.getClient(); // 修改结点值 client.setData().forPath("/test", "curator".getBytes()); System.out.println("更新之后,结点/test值为:" + new String(client.getData().forPath("/test"), "UTF-8")); } @Test public void getChildrenList() throws Exception { CuratorFramework client = CuratorUtils.getClient(); // 获取指定路径下面的所有子节点 List<String> childrenList = client.getChildren().forPath("/"); System.out.println("/base下面的子节点个数:" + childrenList.size()); childrenList.stream().forEach(System.out::println); } @Test public void deleteNode() throws Exception { CuratorFramework client = CuratorUtils.getClient(); // 删除结点 client.delete().forPath("/test"); System.out.println("删除之后,结点/test是否存在:" + client.checkExists().forPath("/test")); } @Test public void transaction() throws Exception { CuratorFramework client = CuratorUtils.getClient(); client.inTransaction() .create().forPath("/transaction", "transaction".getBytes()) .and() .setData().forPath("/transaction", "transaction-test".getBytes()) .and() .commit(); } }
Markdown
UTF-8
905
2.59375
3
[]
no_license
--- title: All Cryptos as API date: 2018-01-22 12:00:00 +0100 subtitle: 22nd January, 2018 style: blue cover: cover.png categories: Tutorials tags: [tutorial, scaping, jquery, crypto, runkit] --- **Update:** it turns out there is a public [API](https://coinmarketcap.com/api/) on Coinmarketcap.com I didn't find out before. Thanks to let me know. Following the [previous article](/blog/welcome-cryptocurrency/) about getting the whole list of the cryptocurrencies from Coinmarketcap.com, here the same scraping code packed in a nice end-point call thanks to [Runkit](https://runkit.com/), of course. I've resurrected a previous and working example that uses Cheerio to transform the HTML source in a JSON array. You can check the source [here](https://runkit.com/abusedmedia/coinmarketcap-all-list-api) or test the API call straight [there](https://coinmarketcap-all-list-api-hki9psot86nl.runkit.sh/).
Markdown
UTF-8
6,122
2.59375
3
[ "Apache-2.0" ]
permissive
--- title: SEO - Mejorar el tiempo de carga de una web description: El tiempo de carga es un factor clave para las estrategias de posicionamiento web image: https://emirodgar.com/cdn/images/og/marketing-digital.png layout: emirodgar_post date: 19/05/2021 author: Emirodgar lang: es_ES sitemap: 1 feed: 1 folder: seo permalink: mejorar-tiempo-carga-web --- Desde el [cambio de algoritmo Mobile First Index](https://emirodgar.com/cambio-algoritmo-google), el tiempo de carga de una página web pasó a ser un [factor SEO](https://emirodgar.com/factores-seo) importante en cualquier estrategia de posicionamiento. Si queremos disponer de una página cuyo tiempo de carga sea rápido y que nos permita mejorar posicionamiento, captación y conversión, estos son los puntos que deberíamos de trabajar. ## 1. Hosting El [hosting afecta al SEO](https://emirodgar.com/hosting-seo) por lo que el servidor donde tengamos alojada nuestra página web es el primer aspecto que debemos trabajar. Un servidor profesional nos ofrecerá buenos tiempos de conexión por lo que antes de contratarlo conviene conocer qué valor de **Time to First Byte** (TTFB) ofrece. >[Web server perfomance test](https://www.dotcom-tools.com/web-server-performance-test.aspx) nos ayudará a validar el tiempo de carga asociado a un hosting. > Si tarda mucho en servir nuestra página web, el resto de carga se verá afectado por lo que garantizar un rápido envío del primer byte es crucial para un correcto tiempo de carga. Si nuestro servidor web no los permite, podemos instalar el [módulo PageSpeed de Google](https://developers.google.com/speed/pagespeed/module/?hl=es-419) que automáticamente configurará una serie de parámetros para optimizar el sitio web. ## 2. Elementos multimedia Tanto imágenes como vídeos pueden provocar que nuestra página sea más lenta de lo necesario. A este respecto hay varias cosas que podemos hacer: 1. [Carga selectiva (lazy load)](https://developers.google.com/web/fundamentals/performance/lazy-loading-guidance/images-and-video/?hl=es) en base a lo que se va mostrando en pantalla. En lugar de cargar todas las imágenes o vídeos de golpe, únicamente cargamos aquellas que entran en el campo de visión del usuario. A medida que hace scroll, vamos cargando las siguientes. 2. Hacer uso de los nuevos formatos de imágenes como [webp](https://developers.google.com/speed/webp/) para mejorar la velocidad. 3. [Comprimir las imágenes](https://web.dev/use-imagemin-to-compress-images) para que ocupen menos espacio. Podemos hacer uso de [ImageOptim](https://imageoptim.com/mac), [Squossh](https://squoosh.app/) o [Compressor.io](https://compressor.io/) 4. Usar [imágenes con las dimensiones adecuadas](https://web.dev/serve-images-with-correct-dimensions). No tiene sentido poner una imagen grande si la vamos a mostrar en pequeño. Para páginas multidispositivo es importante aprender a utilizar las [imágenes adaptativas](https://web.dev/uses-responsive-images/). > También es importante [optimizar las imágenes ](https://emirodgar.com/optimizacion-imagenes-seo) para que aporten valor a la estrategia SEO. Por último, podemos hacer uso de una r**ed de distribución de contenidos** (CDN) como Cloudflare que nos permitirá cachear y servir los ficheros estáticos de forma más rápida y eficiente, mejorando sustancialmente la carga de nuestro web ## 3. Comprimir los recursos Hay ciertos recursos que creamos una vez y no volvemos a utilizar. Por ello se recomiendo comprimirlos al máximo (quitando espacios, comentarios o saltos de línea) para que ocupen el menor tamaño posible. - [Comprimir el código CSS](https://web.dev/unminified-css/). Recomiendo [CSSnano](https://github.com/ben-eb/cssnano) o [CSSO](https://github.com/css/csso). - [Comprimir el código Javascript](https://web.dev/unminified-javascript/). Podemos usar [UglifyJS](https://github.com/mishoo/UglifyJS2). - [Comprimir el código HTML](http://minifycode.com/html-minifier/) > Mucho ojo con [bloquear el acceso de los buscadores a los ficheros CSS y JS](https://emirodgar.com/bloquear-indexacion-js-css) puesto que podría afectar a nuestra estrategia SEO. ## 4. Eliminar aquello que no utilizamos La forma más efectiva de aligerar nuestra web es eliminando aquello que no utilizamos. Es práctica habitual hacer un desarrollo y replicarlo a lo largo de todo el sitio web pero muchas veces, ciertas partes del mismo, son usadas de forma puntual; aún asi, las cargamos de forma transversal. Por ejemplo, si en la home tenemos un banner y en el resto del sitio no, deberíamos tener un CSS/JS común a toda la página que no incluyera nada relacionado con el banner y, únicamente en la home, añadir ese código extra. Podemos hacer uso de [Chrome Dev Tools](https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage) para identificar [el código CSS que no utilizamos en una página](https://web.dev/unused-css-rules/), de esa forma con retirarlo ajustaremos al máximo el tamaño de este fichero. Una aplicación online muy cómoda es [PurifyCSS](https://purifycss.online/). También disponemos de extensiones para el navegador como [UnusedCSS](https://unused-css.com/) o [PurgeCSS](https://www.purgecss.com/) que nos facilitarán la tarea. Adicional a todo esto, existe un punto avanzado que también podemos trabajar. Se trata del [camino crítico para generar nuestra web](https://www.portent.com/blog/design-dev/the-critical-rendering-path-explained.htm). Si conseguimos identificar y separar la estructura crítica de lo demás -para que sea lo primero que cargue- conseguiremos una página realmente rápida. ## Herramientas para validar el tiempo de carga Podemos hacer uso de aplicaciones como [Web.dev](https://web.dev) (basada en [Google Lighthouse](https://emirodgar.com/automatizar-analisis-lighthouse)) o [GTMetrix](https://gtmetrix.com/) para conocer qué puntos debemos otimizar en nuestra web. <!--stackedit_data: eyJoaXN0b3J5IjpbLTEzNzg5MTUyMTgsMTc0OTA4MzU0NCwtMT kwMTkyMTEwMSwxNTc0OTg0NDk1LDE0MTgzODY1NDQsMTE3MDI4 MzExMiwtNTUwNzM0MDc4XX0= -->
Shell
UTF-8
1,110
2.953125
3
[]
no_license
#!/bin/bash set -e -x # copy needed files from pdf.js mkdir -p build/pdf.js if [[ $PRODUCTION = 1 ]]; then cp -r pdf.js/build/minified/* build/pdf.js/; else cp -r pdf.js/build/generic/* build/pdf.js/; fi # copy assets cp -r www/* build/ # download required JS mkdir -p build/static/js pushd . && cd build/static/js if [[ $PRODUCTION = 1 ]]; then curl -sSL https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js -o crypto-js.min.js curl -sSL https://unpkg.com/jquery/dist/jquery.min.js -ojquery.min.js curl -sSL https://unpkg.com/jquery.md5/index.js -ojquery.md5.js curl -sSL https://unpkg.com/vue/dist/vue.min.js -ovue.min.js else curl -sSL https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.js -o crypto-js.js curl -sSL https://unpkg.com/jquery/dist/jquery.js -ojquery.js curl -sSL https://unpkg.com/jquery.md5/index.js -ojquery.md5.js curl -sSL https://unpkg.com/vue/dist/vue.js -ovue.js fi popd # download welcome PDF mkdir -p build/assets curl -sSL https://arxiv.org/pdf/1805.08090.pdf -obuild/assets/welcome.pdf # build webpages python src/build.py
Markdown
UTF-8
2,087
2.875
3
[ "MIT" ]
permissive
# Github-connect Is the app that quantifies your contributions to the open-source world, helps you engage with other projects and bake new project ideas. You can try out the app at [http://github-connect.herokuapp.com](http://github-connect.herokuapp.com/). This is still in beta, so your [feedback](http://github-connect.herokuapp.com/contact) is welcome. ## Setup ### Easy install For a quick setup, just run **make setup** in the root directory. This should work on both Linux and OSX. Then **make run** will start the db and app at [http://localhost:3000](http://localhost:3000). ### Manual setup 1. Install nodejs (preferably from own repo) and npm: add-apt-repository ppa:chris-lea/node.js && apt-get update apt-get install nodejs 2. Install mongodb. Needed for our database: apt-get install mongodb For OSX, I recommand using [MacPorts](http://www.macports.org/) for an easy install: port install mongodb 3. Set node environment ($NODE_ENV): NODE_ENV=development 4. Install all node modules. A list is available further down. npm install 5. Start mongod and import testing database: mongod & mongorestore -d github-connect ghconnect_db/github-connect 6. Run mongod and start the app. Then visit [http://localhost:3000](http://localhost:3000). mongod & node app.js ## Dependencies This is a list of the modules we use (package.json): * [express](https://www.npmjs.org/package/express) - web development framework * [everyauth](https://www.npmjs.org/package/everyauth) - authentication solution * [connect](https://www.npmjs.org/package/connect) - high performance middleware framework * [jade](https://www.npmjs.org/package/jade) - Jade template engine * [mongoose](https://www.npmjs.org/package/mongoose) - MongoDB ODM * [markdown](https://www.npmjs.org/package/markdown) - Markdown parser for javascript * [nodemailer](https://www.npmjs.org/package/nodemailer) - send emails Use package.json to install them all: npm install package.json ### Happy coding !
Go
UTF-8
1,375
2.984375
3
[ "BSD-3-Clause" ]
permissive
package screenshot import ( "fmt" "io/ioutil" "time" "github.com/chromedp/chromedp" "github.com/muraenateam/necrobrowser/action" ) const ( // Name of this action Name = "Screenshot" // Description of this action Description = "Screenshot takes a picture of the screen at the given URL" ) // Screenshot is an action type Screenshot struct { action.Action URL string Selector string SavePath string } // Name returns the action name func (a *Screenshot) Name() string { return Name } // Description returns what the action does func (a *Screenshot) Description() string { return Description } // Take performs the action to take a screenshot func (a *Screenshot) Take() (err error) { var ( buf []byte z = a.Target ) // Define save path if not defined if a.SavePath == "" { a.SavePath = fmt.Sprintf("%s/%s.png", a.LootPath, action.Now()) } z.Info("Taking screenshot of page %s", a.URL) t := chromedp.Tasks{ chromedp.Navigate(a.URL), chromedp.Sleep(2 * time.Second), } if a.Selector != "" { act := chromedp.WaitVisible(a.Selector, chromedp.ByQuery) t = append(t, act) } act := chromedp.CaptureScreenshot(&buf) t = append(t, act) if err = a.Run(t); err != nil { return } err = ioutil.WriteFile(a.SavePath, buf, 0644) if err != nil { return } z.Warning("Screenshot saved to: %s", a.SavePath) return nil }
Python
UTF-8
733
2.859375
3
[]
no_license
import itertools import cipher_common as cc def single_xor_cipher_decode(bytes_): res = bytes() min_chi2 = float('inf') key = None # for byte in bytes(string.printable, encoding='ascii'): for byte in range(256): # xor the string str_xor = cc.bytes_xor(bytes_, [byte]) # count number of alphabet characters letters = cc.count_alphabet_bytes(str_xor) # get chi squared value chi2 = cc.chi_squared( cc.get_freq(str_xor.lower()), letters, cc.LETTER_FREQ) # update min chi2 and appropriate key if chi2 <= min_chi2: min_chi2 = chi2 key = byte return cc.bytes_xor(bytes_, [key]), key
Java
ISO-8859-13
2,847
2.25
2
[]
no_license
package it.unisalento.view.Panels; import it.unisalento.view.Models.ButtonColumn; import it.unisalento.view.Models.LibriTableModel; import javax.swing.JScrollPane; import javax.swing.JTable; public class LibriJPanJTab { private JScrollPane panel; private JTable tab; private static LibriTableModel model; @SuppressWarnings("unused") public LibriJPanJTab(String option){ model=new LibriTableModel(option); tab=new JTable(model); tab.setAutoCreateRowSorter(true); panel= new JScrollPane(tab); switch (option){ //definisco i bottoni case LibriTableModel.CLIENTEOPT:{ ButtonColumn clienteButton= new ButtonColumn(tab, LibriTableModel.getOrdinaAction(), 8); //Definisco il bottone, input: tabella, azione, colonna } break; case LibriTableModel.SCAFFALIOPT:{ ButtonColumn titoloButton= new ButtonColumn(tab, LibriTableModel.getTitoloAction(), 0); //Definisco il bottone, input: tabella, azione, colonna ButtonColumn autoriButton= new ButtonColumn(tab, LibriTableModel.getAutori(), 1); //Definisco il bottone, input: tabella, azione, colonna ButtonColumn casaButton= new ButtonColumn(tab, LibriTableModel.getCasa(), 2); //Definisco il bottone, input: tabella, azione, colonna ButtonColumn genereButton= new ButtonColumn(tab, LibriTableModel.getGenere(), 3); //Definisco il bottone, input: tabella, azione, colonna ButtonColumn costoButton= new ButtonColumn(tab, LibriTableModel.getCosto(), 4); //Definisco il bottone, input: tabella, azione, colonna ButtonColumn pagineButton= new ButtonColumn(tab, LibriTableModel.getPagine(), 5); //Definisco il bottone, input: tabella, azione, colonna ButtonColumn isbnButton= new ButtonColumn(tab, LibriTableModel.getIsbn(), 6); //Definisco il bottone, input: tabella, azione, colonna ButtonColumn dispButton= new ButtonColumn(tab, LibriTableModel.getDisp(), 7); //Definisco il bottone, input: tabella, azione, colonna //Questo bottone non serve pi, lo lascio commentato per delle eventuali versioni successive che possono implementare ordine libro //ButtonColumn ordineButton= new ButtonColumn(tab, LibriTableModel.getOrdine(), 8); //Definisco il bottone, input: tabella, azione, colonna } break; case LibriTableModel.VENDITEOPT:{ ButtonColumn venditeButton= new ButtonColumn(tab, LibriTableModel.getCarrelloAction(), 8); //Definisco il bottone, input: tabella, azione, colonna } } } public static void refresh(){ model.fireTableDataChanged(); } public JScrollPane getPanel() { return panel; } public void setPanel(JScrollPane panel) { this.panel = panel; } public JTable getTab() { return tab; } public void setTab(JTable tab) { this.tab = tab; } public LibriTableModel getModel() { return model; } }
Ruby
UTF-8
332
3.296875
3
[]
no_license
def PermutationStep(num) num_array = num.to_s.split('') permutation_array = num_array.permutation.to_a permutation_array.sort! final_array = [] permutation_array.each do |combo| final_array << combo.join end permutation_array.clear index = final_array.index(num.to_s) p final_array[index + 1] end PermutationStep(41352)
TypeScript
UTF-8
948
2.53125
3
[]
no_license
import { Controller, Post, Body } from '@nestjs/common'; import { CalcProfitabilityDto } from '../dto/calculator.dto'; import { CalculatorService } from '../services/calculator.service'; import { MinerTypesService } from "../../admin/modules/miner-types/services"; import { APISuccess, APIError } from '../../../helpers'; @Controller('calculator') export class CalculatorController { public constructor( private calculatorService: CalculatorService, private minerTypeService: MinerTypesService, ) {} /** * Calculate profit by miner id and crypto currency type */ @Post('calculate') public async calculate(@Body() data: CalcProfitabilityDto) { try { const { id } = data; const minerInfo = await this.minerTypeService.findById(id); const result = await this.calculatorService.calculate(minerInfo); return new APISuccess(result); } catch (error) { return new APIError(error); } } }
C++
UTF-8
1,551
2.765625
3
[]
no_license
// // Feature17.cpp // Created by Claudia Rodriguez-Schroeder on 1/22/20. #include "Feature17.h" Feature17::Feature17() { set_name("\033[1;31mMirror\033[0m"); set_desc("There is a \033[1;31mmirror\033[0m in the bathroom and there is writing on the \033[1;31mmirror\033[0m. "); set_desc_no_obj(get_desc()); set_index_id(16); } int Feature17::read(){ func_togg_count_x(READ); printf("So thirsty. So hungry. So cold. I just want someone to speak to me. "); return 4; } int Feature17::speak(){ if (get_times_toggled(SPEAK)==0){ func_togg_count_x(SPEAK); printf("\"I'm in the \033[0;36mmaster\033[0m bedroom, but I am too weak to speak to anyone except through magic, and this \033[1;31mmirror\033[0m.\nCan I trust you?\nI believe in dreams.\nI dreamt I could trust the human with the beautiful song. Do you have a song for me? Maybe play me some \033[1;35mMusic\033[0m \" "); } else if (get_times_toggled(PLAY)==666){ printf("\"Thank you. I can tell your spirit is good. Please take some blood from the sink; I will be able to be free then. Come to the \033[0;36mmaster bedroom\033[0m.\" "); } else if (get_times_toggled(USE)==666){ printf("\"That song meant a lot to me, thank you.\nTo really know I can trust you, I need you to give me your blood.\nI can tell a person's spirit through their blood.\" Oh god, what can he mean? Your blood? Maybe if you use something sharp..."); } else{ printf("None of the conditions to speak to \033[1;31mmirror\033[0m in a productive way exist at this time. "); } return 4; } Feature17::~Feature17() { }
C++
UTF-8
13,692
2.859375
3
[]
no_license
#include "advent2019.h" // Day 18: Many-Worlds Interpretation /* Use the maze's tree structure to simplify the problem as much * as possible, then solve using heuristic best-first search. * Part 1 and Part 2 have different admissible tree reductions, * and are optimized separately. */ using mask_t = uint32_t; constexpr int N_KEYS = 26; constexpr int HASH_SIZE = 15000; static void assert(bool predicate, const std::string &msg) { if (predicate) return; fprintf(stderr, "%s\n", msg.c_str()); abort(); } namespace { struct node; using tree4 = std::array<node *, 4>; // Disjoint-set structure of keys struct keymap { std::vector<int> M; keymap() : M(N_KEYS) { for (int i = 0; i < N_KEYS; i++) M[i] = i; } int find(int n) { while (M[n] != n) n = M[n] = M[M[n]]; return n; } int join(mask_t key) { int r = find(*bits(key)); for (auto k : ++bits(key)) M[k] = r; return r; } }; struct node { std::vector<node *> C = {}; // children int cost = 0, max_depth = 0; mask_t key = 0, door = 0; mask_t subkey = 0, subdoor = 0; ~node() { for (auto n : C) delete n; } node * clone() const { node *N = new node(*this); for (auto &n : N->C) n = n->clone(); return N; } void rebuild_recursive_stats() { subkey = key; subdoor = door; max_depth = cost; for (auto n : C) { n->rebuild_recursive_stats(); subkey |= n->subkey; subdoor |= n->subdoor; max_depth = std::max(max_depth, cost + n->max_depth); } } // Collapse subtree down to a single node int flatten(keymap &KM) { int base_cost = 0; for (auto n : C) { base_cost += n->flatten(KM); cost += n->cost; key |= n->key; door |= n->door; delete n; } C.clear(); subkey = key = 1 << KM.join(key); base_cost += (cost - max_depth) * 2; cost = max_depth; return base_cost; } // Doors must be renumbered whenever keys might have been joined mask_t renumber_doors(keymap &KM) { mask_t tmp = door; door = 0; for (auto k : bits(tmp)) { door |= 1 << KM.find(k); } subdoor = door; for (auto n : C) subdoor |= n->renumber_doors(KM); return subdoor; } }; struct loader { using grid_t = std::vector<std::string>; // convert a maze quadrant into a tree structure static void dfs(decltype(node::C) &C0, grid_t &G, int x, int y) { auto &c = G[x][y]; if (c == '#') return; mask_t key = (c >= 'a' && c <= 'z') ? 1 << (c - 'a') : 0; mask_t door = (c >= 'A' && c <= 'Z') ? 1 << (c - 'A') : 0; c = '#'; // prevent backtracking decltype(node::C) C; dfs(C, G, x-1, y); dfs(C, G, x+1, y); dfs(C, G, x, y-1); dfs(C, G, x, y+1); node *N; if (key || C.size() > 1) { // key or intersection (N = new node)->C = C; } else if (C.empty()) { // dead end return; } else { // corridor N = C[0]; } N->cost++; N->key |= key; N->door |= door; C0.push_back(N); } static node * dfs(grid_t &G, int x, int y) { decltype(node::C) C; dfs(C, G, x, y); if (C.empty()) return new node; C[0]->cost--; C[0]->rebuild_recursive_stats(); return C[0]; } static tree4 load(input_t in) { grid_t G; for (auto end = in.s + in.len; in.s < end; ) { char *eol = in.s + strcspn(in.s, "\r\n"); G.emplace_back(in.s, eol - in.s); in.s = eol + strspn(eol, "\r\n"); } // Expected coordinate of '@' in center of maze int at = G.size() / 2; // Validate & fixup maze to ensure memory safety assert(G.size() >= 5, "maze too small"); assert(G.size() % 4 == 1, "bad maze dimension"); for (auto &s : G) { assert(s.size() == G.size(), "maze not square"); s.front() = s.back() = '#'; } assert(G[at][at] == '@', "'@' not in center of maze"); // Split the maze into (acyclic for all inputs) quadrants G[at-1][at] = G[at+1][at] = G[at][at-1] = G[at][at+1] = '#'; // Return quadrants in clockwise order; two quadrants // i, j are diagonally opposite iff (i ^ j == 2) return { dfs(G, at-1, at-1), dfs(G, at+1, at-1), dfs(G, at+1, at+1), dfs(G, at-1, at+1) }; } }; // keys collected so far, four robot positions struct state { mask_t key = 0; uint8_t pos[4] = { N_KEYS, N_KEYS, N_KEYS, N_KEYS }; operator uint64_t () const { return *(const uint64_t *)(this); } state(mask_t key) : key(key) { } struct hash { std::size_t operator() (const state &S) const { return std::hash<uint64_t>{}(S); } }; }; // cost, forbidden moves struct metric { int cost = 0; mask_t exclude = 0; metric() { } metric(int cost, mask_t exclude = 0) : cost(cost), exclude(exclude) { } }; using state_map_t = std::unordered_map<state, metric, state::hash>; // priority queue entry struct qentry { state_map_t::iterator state; int heuristic; qentry(decltype(state) state, int heuristic) : state(state), heuristic(heuristic) { } bool operator < (const qentry &o) const { return heuristic > o.heuristic; } }; struct solver_base { tree4 R; // Distance between keys (index N_KEYS is the start position) int Dist[N_KEYS + 1][N_KEYS + 1] = { }; // Which doors are in front of a key mask_t Door[N_KEYS] = { }; // Heuristic minimum cost to collect each key int MinDist[N_KEYS] = { }; // Goal state mask_t goal = 0; solver_base(const decltype(R) &R) : R(R) { for (auto n : R) { door_index(n); pairwise_distance(n); goal |= n->subkey; } } // Populate Door[] array, indexed by key number void door_index(node *N, mask_t door = 0) { door |= N->door; if (N->key) Door[*bits(N->key)] = door; door |= N->key; // ensure parent key is collected first for (auto n : N->C) door_index(n, door); } // Tabulate pairwise distances between keys in separate subtrees of N void pairwise_distance(node *N, int cost = 0) { cost += N->cost; for (auto n : N->C) { pairwise_distance(n, cost); } // Distance from this quadrant's starting position if (N->key) Dist[N_KEYS][*bits(N->key)] = cost; int common = cost * 2; for (auto n : N->C) { for (auto k0 : bits(n->subkey)) { for (auto k1 : bits(N->subkey ^ n->subkey)) { Dist[k0][k1] = Dist[k1][k0] = Dist[N_KEYS][k0] + Dist[N_KEYS][k1] - common; } } } } // Find distances between keys across quadrants void cross_link(mask_t key0, mask_t key1, int dist) { for (auto k0 : bits(key0)) { for (auto k1 : bits(key1)) { Dist[k0][k1] = Dist[k1][k0] = Dist[N_KEYS][k0] + Dist[N_KEYS][k1] + dist; } } } void cross_link() { // Adjacent quadrants cross_link(R[0]->subkey, R[1]->subkey, 2); cross_link(R[1]->subkey, R[2]->subkey, 2); cross_link(R[2]->subkey, R[3]->subkey, 2); cross_link(R[3]->subkey, R[0]->subkey, 2); // Diagonal quadrants cross_link(R[0]->subkey, R[2]->subkey, 4); cross_link(R[1]->subkey, R[3]->subkey, 4); } void compute_heuristic(mask_t key) { for (auto k1 : bits(key)) { // Distance from start position in quadrant MinDist[k1] = Dist[N_KEYS][k1]; for (auto k0 : bits(key ^ (1 << k1))) { // Ignore moves contrary to known precedence if (Door[k0] & (1 << k1)) continue; MinDist[k1] = std::min(MinDist[k1], Dist[k0][k1]); } } } }; template<int PART> struct solver : solver_base { solver(const decltype(R) &R) : solver_base(R) { if (PART == 1) { // Robot can travel between quadrants cross_link(); compute_heuristic(goal); } else { // Robots stay within a single quadrant for (auto n : R) { compute_heuristic(n->subkey); } } } int operator() () { const int r_max = (PART == 1) ? 1 : R.size(); std::unordered_map<state, metric, state::hash> Frontier(HASH_SIZE); std::priority_queue<qentry> Q; Frontier.emplace(goal, metric{}); Q.emplace(Frontier.begin(), 0); while (!Q.empty()) { auto q = Q.top(); Q.pop(); auto& [ S0, M0 ] = *q.state; int cost = std::exchange(M0.cost, -1); mask_t exclude = M0.exclude; if (!S0.key) { // solved return cost; } else if (cost == -1) { // already visited continue; } for (int r = 0; r < r_max; r++) { auto n = R[r]; mask_t todo = S0.key & (n->subkey | -(PART == 1)); for (auto k : bits(todo & ~exclude)) { if (Door[k] & S0.key) continue; auto c = cost + Dist[S0.pos[r]][k]; // If we skip all available moves, don't try again // until this robot has moved elsewhere first if (PART == 2) exclude |= 1 << k; state S = S0; S.key ^= 1 << k; S.pos[r] = k; metric M{c, exclude & ~n->subkey}; auto [ it, ok ] = Frontier.emplace(S, M); if (!ok) { if (c >= it->second.cost) continue; it->second = M; } Q.emplace(it, (q.heuristic - MinDist[k]) + (c - cost)); } // Skipped all moves, but no keys left to uncover if (todo && !(todo & ~exclude)) { break; } } } return -1; } }; struct optimizer { tree4 R; mask_t all_doors = 0; optimizer(tree4 R) : R(R) { } optimizer clone() const { optimizer O = *this; for (auto &n : O.R) n = n->clone(); return O; } ~optimizer() { for (auto n : R) delete(n); } // Optimizations valid for both parts int common() { int cost = 0; all_doors = 0; for (auto n : R) { remove_free_doors(n); all_doors |= n->subdoor; } for (auto n : R) { remove_unused_keys(n, all_doors); cost += merge_free_leaves(n, all_doors); } renumber_doors(); return cost; } // Optimizations valid for Part 1 only: if a key is required to // unlock a door, it cannot be the final key collected int part1_only() { int cost = 0; for (auto n : R) cost += merge_free_door_keys(n, all_doors); renumber_doors(); for (auto n : R) cost += flatten_free_branches(n); renumber_doors(); return cost; } // Optimizations valid for Part 2 only: robots do not // backtrack out of their quadrant int part2_only() { int cost = 0; for (auto n : R) cost += merge_free_branches(n); renumber_doors(); return cost; } private: keymap KM; // Common: If a door is a child of its own key, both can be ignored mask_t remove_free_doors(node *N, mask_t key = 0) { mask_t removed = N->door & key; for (auto n : N->C) removed |= remove_free_doors(n, key | N->key); N->key &= ~removed; N->subkey &= ~removed; N->door &= ~removed; N->subdoor &= ~removed; return removed; } // Common: Keys in internal nodes can be ignored if the door // does not need to be traversed void remove_unused_keys(node *N, mask_t all_doors) { if (N->C.empty()) return; N->key &= all_doors; N->subkey = N->key; for (auto n : N->C) { remove_unused_keys(n, all_doors); N->subkey |= n->subkey; } } // Common: Children may be merged if they meet the following: // - no doors // - the keys don't open any doors int merge_free_leaves(node *N, mask_t all_doors) { int cost = 0; for (auto n : N->C) { cost += merge_free_leaves(n, all_doors); } auto it = N->C.begin(); node *t = NULL; for (auto n : N->C) { if ((n->subkey & all_doors) || n->subdoor) { *it++ = n; } else if (!t) { t = n; } else { t->key |= n->key; t->max_depth = std::max(t->max_depth, n->max_depth); t->cost += n->cost; delete n; } } if (t) { cost += (t->cost - t->max_depth) * 2; t->cost = t->max_depth; if (t->key) t->key = 1 << KM.join(t->key); *it++ = t; } N->C.erase(it, N->C.end()); // Merge upward (a door is allowed on this node) if (N->C.size() == 1 && !(N->subkey & all_doors)) { auto n = N->C[0]; if (!n->subdoor) { N->C.pop_back(); if (n->key) N->key = 1 << KM.join(N->key | n->key); N->cost += n->cost; delete n; } } N->subkey = N->key; for (auto n : N->C) N->subkey |= n->subkey; return cost; } // Part 1: Branches with no doors can be taken all-or-nothing int flatten_free_branches(node *N) { int cost = 0; N->subkey = N->key; for (auto n : N->C) { if (!n->subdoor) { cost += n->flatten(KM); } else { cost += flatten_free_branches(n); } N->subkey |= n->subkey; } return cost; } // Part 1: Keys required for opening doors must backtrack, // so they can be taken greedily int merge_free_door_keys(node *N, mask_t all_doors) { int cost = 0; for (auto n : N->C) { cost += merge_free_door_keys(n, all_doors); } auto it = N->C.begin(); for (auto n : N->C) { if (n->subdoor || (n->subkey & ~all_doors)) { *it++ = n; } else { N->key |= n->key; cost += n->cost * 2; delete n; } } N->C.erase(it, N->C.end()); if (N->key) N->key = 1 << KM.join(N->key); N->subkey = N->key; for (auto n : N->C) N->subkey |= n->subkey; return cost; } // Part 2: Greedily take branches satisfying the following: // - no doors // - no backtracking possible // - not the deepest branch among siblings int merge_free_branches(node *N) { int max_depth = N->max_depth - N->cost; int cost = 0; auto it = N->C.begin(); for (auto n : N->C) { if ((n->max_depth < max_depth) && !n->subdoor) { cost += n->flatten(KM); cost += n->cost * 2; N->key |= n->key; delete n; } else { *it++ = n; } } N->C.erase(it, N->C.end()); // Continue search only if one child (no backtracking) if (N->C.size() == 1) { cost += merge_free_branches(N->C[0]); } if (N->key) N->key = 1 << KM.join(N->key); N->subkey = N->key; for (auto n : N->C) N->subkey |= n->subkey; return cost; } void renumber_doors() { all_doors = 0; for (auto n : R) all_doors |= n->renumber_doors(KM); } }; } output_t day18(input_t in) { optimizer O1{loader::load(in)}; int part1 = O1.common(), part2 = part1; auto O2 = O1.clone(); part1 += O1.part1_only() + 2; part1 += solver<1>{O1.R}(); part2 += O2.part2_only(); part2 += solver<2>{O2.R}(); return { part1, part2 }; }
JavaScript
UTF-8
1,115
2.5625
3
[]
no_license
import { FETCH_SEARCHED_BOOK, DATA_LOADING, FETCH_BOOK_DETAILS, NO_RESULT_FOUND } from "./../actions/types" const initialState = { books: [], book: {}, loading: false, foundResults: null } export const SearchForBooksReducer = (state = initialState, action) => { switch (action.type) { case FETCH_SEARCHED_BOOK: const books = action.payload return { ...state, books, loading: false, foundResults: true } case NO_RESULT_FOUND: return { ...state, foundResults: false, loading: false } case FETCH_BOOK_DETAILS: const book = action.payload return { ...state, book, loading: false } case DATA_LOADING: return { ...state, loading: true, foundResults: null } default: { return state } } }
Markdown
UTF-8
4,986
2.71875
3
[ "Apache-2.0" ]
permissive
PhoneHome ========= Installation ------------- This is an Android library project. To use it: 1. Download the library. 2. [Add it as an existing project](http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Ftasks%2Ftasks-importproject.htm) in Eclipse. 3. In your project settings, select Properties > Android and add the PhoneHome library as an external library. Setup ------------- Configure PhoneHome in the `onCreate()` of your main activity (the one associated with the `android.intent.action.MAIN` intent). PhoneHome must be configured initially, but it can always be changed or turned off later. The most important configuration options are `enable()` and `logSink()`. `enable()` toggles log flushing to the backend, and `logSink()` specifies how the logs are flushed. When a batch of logs is ready to be flushed, it’s passed to the `flushLogs()` method of the PhoneHomeSink object specified in `logSink()`. Here's an example configuration: PhoneHomeConfig.getInstance() // enable or disable log flushing .enabled(false) // wait for this many log events before flushing ... .batchSize(100) // ... or until this many seconds have passed between flushes .flushIntervalSeconds(1800) // when developing, log all messages to logcat, then flush everything to the sink .debugLogLevel(android.util.Log.VERBOSE) // in production, only log INFO messages and above to logcat, then flush everything to the sink .productionLogLevel(android.util.Log.INFO) // specify the sink that receives flushed logs. Required if you enable log flushing .logSink(new PhoneHomeSink() { public void flushLogs(final List<PhoneHomeLogEvent> logEvents) { // flush log events to your backend } }); If you set `enabled(true)`, you must provide a valid `PhoneHomeSink` to `logSink`. The default sink will raise an exception when called. Collection ------------- Using PhoneHome's logger instead of Android's system logger is easy. First, here’s a typical pattern that uses Android’s system logger: public class MyClass { private static final TAG = “MyClass”; MyClass() { Log.d(TAG, “Debug!”); Log.i(TAG, “Info!”); Log.e(TAG, “Oh dear.”); } } PhoneHome’s logger works similarly. First, construct a `PhoneHomeLogger` instance for each `TAG`. (Now, you don’t have to type the first parameter over and over.) Then, use the PhoneHomeLogger instance as you would Android’s system logger: public class MyClass { private static final PhoneHomeLogger Log = PhoneHomeLogger.forClass(MyClass .class); MyClass() { Log.d(“Debug!”); Log.i(“Info!”); Log.e(“Oh dear.”); } } Eligibility ------------- To avoid collecting unnecessary logs (and save your users' batteries and data plans!), we recommend checking if a user matches a particular criteria set before flushing logs. We’ve included an example of this in the [example app and backend](https://github.com/nebulabsnyc/PhoneHome/tree/master/example>). Once you've determined whether a user should phone logs home, enabling, disabling, or re-enabling PhoneHome is as easy as: boolean isEligible =...; // determine eligibility PhoneHomeConfig.getInstance() .enabled(isEligible); Shipment ------------- When a batch of logs is ready, it's passed to your `PhoneHomeSink` object. From there, you choose what to do, though typically, we think you'll want to send it to your backend with a network request. Since there isn’t a standard Android networking library and backend APIs are different, you’ll want to work it in to your existing patterns for network requests and API calls. Here’s an [example](https://github.com/nebulabsnyc/PhoneHome/blob/master/example/PhoneHomeTest/src/com/example/phonehometest/example/ExampleSink.java) of how you might do with this with the AndroidHttpClient. We recommend specifying the device configuration associated with log events to simplify de-duping. One strategy is sending along the Android device model, SDK version, app versionCode, username, and/or other identifying information with the log events. After all, logs from a misbehaving device aren't very helpful if you can't tell from which device they came. Our [example app and backend](https://github.com/nebulabsnyc/PhoneHome/tree/master/example) show one way to send device information with the requests. Display ------------- We built a barebones, Bootstrap’d web dashboard to display logs we collected, but you can just as easily look at the lines, by user and device, in your database. In the sample backend application, the logs are stored in the `logcat_events` table. Similarly, you could set user-log configurations using a simple web form or by editing the database directly.
Java
UTF-8
2,417
3.296875
3
[]
no_license
package sudoku; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; public class Sudoku { private Case[][] grille; private BooleanProperty finished; public Sudoku(String filename) { grille = new Case[9][9]; Scanner scanner = null; finished = new SimpleBooleanProperty(false); try { scanner = new Scanner(new File(filename)); } catch (FileNotFoundException e) { e.printStackTrace(); } for(int i = 0; i < 9; i++) { for(int j = 0; j < 9; j++) { grille[i][j] = new Case(scanner.nextInt()); } } } public BooleanProperty getFinishedProperty() { return finished; } public void checkFinished() { for(int i = 0; i < 27; i++) { if(!getGroup(i).check()) return; } finished.setValue(true); } public void draw() { System.out.println(""); for(int i = 0; i < 9; i++) { System.out.println(""); if(i % 3 == 0) { System.out.println(" -----------------"); } for(int j = 0; j < 9; j++) { if(j % 3 == 0) System.out.print(" | "); System.out.print(grille[i][j].getValue()); } System.out.print(" |"); } System.out.println("\n -----------------"); } public Group9Cases getGroup(int index) { // Ligne if(index < 9) { return new Group9Cases(grille[index]); } else if(index < 18) { // Colonnes Case[] col = new Case[9]; for(int i = 0; i < 9; i++) { col[i] = grille[i][index - 9]; } return new Group9Cases(col); } else { // Carres index = index - 18; Case[] carre = new Case[9]; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { carre[i * 3 + j] = grille[(index / 3)*3 + i][(index % 3)*3 + j]; } } return new Group9Cases(carre); } } public void setFromGroup(int index, Group9Cases group) { if(index < 9) { // Ligne for(int i = 0; i < 9; i++) { grille[index][i].merge(group.getCase(i)); } } else if(index < 18) { // Colonnes for(int i = 0; i < 9; i++) { grille[i][index - 9].merge(group.getCase(i)); } } else { // Carres index = index - 18; for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { grille[(index / 3)*3 + i][(index % 3)*3 + j].merge(group.getCase(i * 3 + j)); } } } checkFinished(); } }
C#
UTF-8
7,674
2.75
3
[]
no_license
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Web.MVC.Infrastructure.Interfaces; namespace Web.MVC.Infrastructure.Implementations { public sealed class RestClientService : IRestClientService { private readonly HttpClient httpClient; private string result = "Error"; public RestClientService(IHttpClientFactory httpClientFactory) { httpClient = httpClientFactory.CreateClient(); } /// <summary> /// Get async /// </summary> /// <param name="requestUri"></param> /// <param name="additionalHeaders"></param> /// <returns></returns> public async Task<string> GetAsync(string requestUri, Dictionary<string, string> additionalHeaders = null) { try { using (HttpClientHandler httpClientHandler = new HttpClientHandler()) { using (HttpClient httpClient = new HttpClient(httpClientHandler)) { AddHeaders(httpClient, additionalHeaders); result = await httpClient.GetStringAsync(requestUri); } } return result; } catch (Exception) { throw; } } /// <summary> /// Post Async /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestUri"></param> /// <param name="request"></param> /// <param name="additionalHeaders"></param> /// <returns></returns> public async Task<string> PostAsync<T>(string requestUri, T request, Dictionary<string, string> additionalHeaders = null) where T : class { try { using (HttpClientHandler httpClientHandler = new HttpClientHandler()) { using (HttpClient httpClient = new HttpClient(httpClientHandler)) { AddHeaders(httpClient, additionalHeaders); result = await httpClient.PostAsync(requestUri, new StringContent(JsonConvert.SerializeObject(request)) { Headers = { ContentType = new MediaTypeHeaderValue("application/json") } }).Result.Content.ReadAsStringAsync(); } } return result; } catch (Exception) { throw; } } /// <summary> /// Delete Async /// </summary> /// <param name="requestUri"></param> /// <param name="additionalHeaders"></param> /// <returns></returns> public async Task<string> DeleteAsync(string requestUri, Dictionary<string, string> additionalHeaders = null) { try { using (HttpClientHandler httpClientHandler = new HttpClientHandler()) { using (HttpClient httpClient = new HttpClient(httpClientHandler)) { AddHeaders(httpClient, additionalHeaders); var httpResponseMessage = await httpClient.DeleteAsync(requestUri); result = await httpResponseMessage.Content.ReadAsStringAsync(); } } return result; } catch (Exception) { throw; } } /// <summary> /// Pust Async /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestUri"></param> /// <param name="request"></param> /// <param name="additionalHeaders"></param> /// <returns></returns> public async Task<string> PutAsync<T>(string requestUri, T request, Dictionary<string, string> additionalHeaders = null) where T : class { try { using (HttpClientHandler httpClientHandler = new HttpClientHandler()) { using (HttpClient httpClient = new HttpClient(httpClientHandler)) { AddHeaders(httpClient, additionalHeaders); var json = JsonConvert.SerializeObject(request, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }); var httpContent = new StringContent(json); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var httpResponseMessage = await httpClient.PutAsync(requestUri, httpContent); result = await httpResponseMessage.Content.ReadAsStringAsync(); } } return result; } catch (Exception) { throw; } } /// <summary> /// Patch Async /// </summary> /// <typeparam name="T"></typeparam> /// <param name="requestUri"></param> /// <param name="request"></param> /// <param name="additionalHeaders"></param> /// <returns></returns> public async Task<string> PatchAsync<T>(string requestUri, T request, Dictionary<string, string> additionalHeaders = null) where T : class { try { using (HttpClientHandler httpClientHandler = new HttpClientHandler()) { using (HttpClient httpClient = new HttpClient(httpClientHandler)) { AddHeaders(httpClient, additionalHeaders); var json = JsonConvert.SerializeObject(request, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }); var httpContent = new StringContent(json); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var httpResponseMessage = await httpClient.PatchAsync(requestUri, httpContent); result = await httpResponseMessage.Content.ReadAsStringAsync(); } } return result; } catch (Exception) { throw; } } /// <summary> /// Add headers /// </summary> /// <param name="httpClient"></param> /// <param name="additionalHeaders"></param> private void AddHeaders(HttpClient httpClient, Dictionary<string, string> additionalHeaders) { httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); if (additionalHeaders == null) return; foreach (KeyValuePair<string, string> current in additionalHeaders) { httpClient.DefaultRequestHeaders.Add(current.Key, current.Value); } } } }
Java
UTF-8
16,436
1.796875
2
[]
no_license
/* * 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 com.sirelab.controller.administrarusuarios; import com.sirelab.bo.interfacebo.usuarios.AdministrarAdministradoresEdificioBOInterface; import com.sirelab.entidades.AdministradorEdificio; import com.sirelab.entidades.Edificio; import com.sirelab.entidades.EncargadoPorEdificio; import com.sirelab.entidades.Sede; import com.sirelab.utilidades.Utilidades; import java.io.Serializable; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; /** * * @author ELECTRONICA */ @ManagedBean @SessionScoped public class ControllerHistorialEdificios implements Serializable { @EJB AdministrarAdministradoresEdificioBOInterface administrarAdministradoresEdificioBO; private AdministradorEdificio administradorEdificio; private BigInteger idAdministrador; private List<Sede> listaSedes; private List<Edificio> listaEdificios; private Sede sedeNuevo; private Edificio edificioNuevo; private boolean activarEdificio; private String colorMensaje, mensajeFormulario; private Logger logger = Logger.getLogger(getClass().getName()); private boolean validacionesSede, validacionesEdificio; private boolean activarNuevoRegistro; private List<EncargadoPorEdificio> listaEncargadosPorEdificio; private List<EncargadoPorEdificio> listaEncargadosPorEdificioTabla; private int posicionEncargadoPorEdificioTabla; private int tamTotalEncargadoPorEdificio; private boolean bloquearPagSigEncargadoPorEdificio, bloquearPagAntEncargadoPorEdificio; public ControllerHistorialEdificios() { } @PostConstruct public void init() { activarNuevoRegistro = true; validacionesEdificio = false; validacionesSede = false; colorMensaje = "black"; mensajeFormulario = "N/A"; activarEdificio = true; BasicConfigurator.configure(); } public void recibirIdAdministradorEdificio(BigInteger id) { this.idAdministrador = id; listaEncargadosPorEdificio = administrarAdministradoresEdificioBO.buscarEncargadosPorEdificioPorIDAdministrador(idAdministrador); listaEncargadosPorEdificioTabla = new ArrayList<EncargadoPorEdificio>(); tamTotalEncargadoPorEdificio = listaEncargadosPorEdificio.size(); posicionEncargadoPorEdificioTabla = 0; cargarDatosTablaEncargadoPorEdificio(); } private void cargarDatosTablaEncargadoPorEdificio() { if (tamTotalEncargadoPorEdificio < 5) { for (int i = 0; i < tamTotalEncargadoPorEdificio; i++) { listaEncargadosPorEdificioTabla.add(listaEncargadosPorEdificio.get(i)); } bloquearPagSigEncargadoPorEdificio = true; bloquearPagAntEncargadoPorEdificio = true; } else { for (int i = 0; i < 5; i++) { listaEncargadosPorEdificioTabla.add(listaEncargadosPorEdificio.get(i)); } bloquearPagSigEncargadoPorEdificio = false; bloquearPagAntEncargadoPorEdificio = true; } } public void cargarPaginaSiguienteEncargadoPorEdificio() { listaEncargadosPorEdificioTabla = new ArrayList<EncargadoPorEdificio>(); posicionEncargadoPorEdificioTabla = posicionEncargadoPorEdificioTabla + 5; listaEncargadosPorEdificio = listaEncargadosPorEdificioTabla; int diferencia = tamTotalEncargadoPorEdificio - posicionEncargadoPorEdificioTabla; if (diferencia > 5) { for (int i = posicionEncargadoPorEdificioTabla; i < (posicionEncargadoPorEdificioTabla + 5); i++) { listaEncargadosPorEdificioTabla.add(listaEncargadosPorEdificio.get(i)); } bloquearPagSigEncargadoPorEdificio = false; bloquearPagAntEncargadoPorEdificio = false; } else { for (int i = posicionEncargadoPorEdificioTabla; i < (posicionEncargadoPorEdificioTabla + diferencia); i++) { listaEncargadosPorEdificioTabla.add(listaEncargadosPorEdificio.get(i)); } bloquearPagSigEncargadoPorEdificio = true; bloquearPagAntEncargadoPorEdificio = false; } } public void cargarPaginaAnteriorEncargadoPorEdificio() { listaEncargadosPorEdificioTabla = new ArrayList<EncargadoPorEdificio>(); posicionEncargadoPorEdificioTabla = posicionEncargadoPorEdificioTabla - 5; listaEncargadosPorEdificio = listaEncargadosPorEdificioTabla; int diferencia = tamTotalEncargadoPorEdificio - posicionEncargadoPorEdificioTabla; if (diferencia == tamTotalEncargadoPorEdificio) { for (int i = posicionEncargadoPorEdificioTabla; i < (posicionEncargadoPorEdificioTabla + 5); i++) { listaEncargadosPorEdificioTabla.add(listaEncargadosPorEdificio.get(i)); } bloquearPagSigEncargadoPorEdificio = false; bloquearPagAntEncargadoPorEdificio = true; } else { for (int i = posicionEncargadoPorEdificioTabla; i < (posicionEncargadoPorEdificioTabla + 5); i++) { listaEncargadosPorEdificioTabla.add(listaEncargadosPorEdificio.get(i)); } bloquearPagSigEncargadoPorEdificio = false; bloquearPagAntEncargadoPorEdificio = false; } } public void actualizarNuevoRegistro() { if (activarNuevoRegistro == true) { listaEdificios = null; listaSedes = null; edificioNuevo = null; sedeNuevo = null; activarEdificio = true; validacionesEdificio = true; validacionesSede = true; } else { listaEdificios = null; listaSedes = administrarAdministradoresEdificioBO.obtenerListaSedesActivos(); edificioNuevo = null; sedeNuevo = null; activarEdificio = true; validacionesEdificio = false; validacionesSede = false; } } public void actualizarSedes() { try { if (Utilidades.validarNulo(sedeNuevo)) { activarEdificio = false; edificioNuevo = null; listaEdificios = administrarAdministradoresEdificioBO.obtenerEdificiosActivosPorIDSede(sedeNuevo.getIdsede()); validacionesSede = true; eliminarEdificiosRegistrados(); } else { validacionesEdificio = false; validacionesSede = false; activarEdificio = true; edificioNuevo = null; listaEdificios = null; FacesContext.getCurrentInstance().addMessage("form:sedeAdministradorEdificio", new FacesMessage("El campo Sede es obligatorio.")); } } catch (Exception e) { logger.error("Error ControllerHistorialEdificios actualizarSedes : " + e.toString(), e); } } private void eliminarEdificiosRegistrados() { if (Utilidades.validarNulo(listaEncargadosPorEdificio)) { for (int i = 0; i < listaEncargadosPorEdificio.size(); i++) { if (Utilidades.validarNulo(listaEdificios)) { for (int j = 0; j < listaEdificios.size(); j++) { if (listaEncargadosPorEdificio.get(i).getEdificio().getIdedificio().equals(listaEdificios.get(j).getIdedificio())) { listaEdificios.remove(j); } } } } } } /** * Metodo encargado de actualizar los edificios y obtener la informacion de * las carreras relacionadas */ public void actualizarEdificios() { try { if (Utilidades.validarNulo(edificioNuevo)) { validacionesEdificio = true; } else { validacionesEdificio = false; FacesContext.getCurrentInstance().addMessage("form:edificioNuevo", new FacesMessage("El campo Edificio es obligatorio.")); } } catch (Exception e) { logger.error("Error ControllerHistorialEdificios actualizarEdificios: " + e.toString(), e); } } public void cancelarRegistro() { idAdministrador = null; administradorEdificio = null; listaSedes = null; listaEdificios = null; activarNuevoRegistro = true; validacionesEdificio = false; validacionesSede = false; sedeNuevo = null; edificioNuevo = null; activarEdificio = true; listaEncargadosPorEdificio = null; listaEncargadosPorEdificio = null; listaEncargadosPorEdificioTabla = null; tamTotalEncargadoPorEdificio = 0; posicionEncargadoPorEdificioTabla = 0; bloquearPagAntEncargadoPorEdificio = true; bloquearPagSigEncargadoPorEdificio = true; } public void limpiarDatos() { listaEncargadosPorEdificio = null; listaEncargadosPorEdificioTabla = null; tamTotalEncargadoPorEdificio = 0; posicionEncargadoPorEdificioTabla = 0; bloquearPagAntEncargadoPorEdificio = true; bloquearPagSigEncargadoPorEdificio = true; listaSedes = null; listaEdificios = null; activarNuevoRegistro = true; validacionesEdificio = false; validacionesSede = false; sedeNuevo = null; edificioNuevo = null; activarEdificio = true; colorMensaje = "black"; mensajeFormulario = "N/A"; listaEncargadosPorEdificio = null; recibirIdAdministradorEdificio(this.idAdministrador); } public void guardarCambiosPagina() { if (cantidadRegistrosAntiguos() == true) { if (validarRegistros() == true) { almacenarModificacionHistorial(); limpiarDatos(); colorMensaje = "green"; mensajeFormulario = "El formulario ha sido ingresado con exito."; } else { colorMensaje = "#FF0000"; mensajeFormulario = "El formulario de nuevo registro presenta errores."; } } else { colorMensaje = "#FF0000"; mensajeFormulario = "Debe existir al menos un edificio asociado al personal."; } } private void almacenarModificacionHistorial() { if (activarNuevoRegistro == true) { for (int i = 0; i < listaEncargadosPorEdificio.size(); i++) { administrarAdministradoresEdificioBO.editarAsocioEncargadoEdificio(listaEncargadosPorEdificio.get(i)); } } else { for (int i = 0; i < listaEncargadosPorEdificio.size(); i++) { listaEncargadosPorEdificio.get(i).setEstado(false); administrarAdministradoresEdificioBO.editarAsocioEncargadoEdificio(listaEncargadosPorEdificio.get(i)); } administrarAdministradoresEdificioBO.registrarAsocioEncargadoEdificio(administradorEdificio, edificioNuevo); } } private boolean validarRegistros() { boolean retorno = true; if (validacionesEdificio == false) { retorno = false; } if (validacionesSede == false) { retorno = false; } return retorno; } private boolean cantidadRegistrosAntiguos() { boolean retorno = false; int contador = 0; for (int i = 0; i < listaEncargadosPorEdificio.size(); i++) { if (listaEncargadosPorEdificio.get(i).getEstado() == true) { contador++; } } if (contador == 1) { retorno = true; } return retorno; } //GET-SET public AdministradorEdificio getAdministradorEdificio() { return administradorEdificio; } public void setAdministradorEdificio(AdministradorEdificio administradorEdificio) { this.administradorEdificio = administradorEdificio; } public BigInteger getIdAdministrador() { return idAdministrador; } public void setIdAdministrador(BigInteger idAdministrador) { this.idAdministrador = idAdministrador; } public List<Sede> getListaSedes() { return listaSedes; } public void setListaSedes(List<Sede> listaSedes) { this.listaSedes = listaSedes; } public List<Edificio> getListaEdificios() { return listaEdificios; } public void setListaEdificios(List<Edificio> listaEdificios) { this.listaEdificios = listaEdificios; } public Sede getSedeNuevo() { return sedeNuevo; } public void setSedeNuevo(Sede sedeNuevo) { this.sedeNuevo = sedeNuevo; } public Edificio getEdificioNuevo() { return edificioNuevo; } public void setEdificioNuevo(Edificio edificioNuevo) { this.edificioNuevo = edificioNuevo; } public boolean isActivarEdificio() { return activarEdificio; } public void setActivarEdificio(boolean activarEdificio) { this.activarEdificio = activarEdificio; } public String getColorMensaje() { return colorMensaje; } public void setColorMensaje(String colorMensaje) { this.colorMensaje = colorMensaje; } public String getMensajeFormulario() { return mensajeFormulario; } public void setMensajeFormulario(String mensajeFormulario) { this.mensajeFormulario = mensajeFormulario; } public boolean isActivarNuevoRegistro() { return activarNuevoRegistro; } public void setActivarNuevoRegistro(boolean activarNuevoRegistro) { this.activarNuevoRegistro = activarNuevoRegistro; } public List<EncargadoPorEdificio> getListaEncargadosPorEdificio() { return listaEncargadosPorEdificio; } public void setListaEncargadosPorEdificio(List<EncargadoPorEdificio> listaEncargadosPorEdificio) { this.listaEncargadosPorEdificio = listaEncargadosPorEdificio; } public List<EncargadoPorEdificio> getListaEncargadosPorEdificioTabla() { return listaEncargadosPorEdificioTabla; } public void setListaEncargadosPorEdificioTabla(List<EncargadoPorEdificio> listaEncargadosPorEdificioTabla) { this.listaEncargadosPorEdificioTabla = listaEncargadosPorEdificioTabla; } public int getPosicionEncargadoPorEdificioTabla() { return posicionEncargadoPorEdificioTabla; } public void setPosicionEncargadoPorEdificioTabla(int posicionEncargadoPorEdificioTabla) { this.posicionEncargadoPorEdificioTabla = posicionEncargadoPorEdificioTabla; } public int getTamTotalEncargadoPorEdificio() { return tamTotalEncargadoPorEdificio; } public void setTamTotalEncargadoPorEdificio(int tamTotalEncargadoPorEdificio) { this.tamTotalEncargadoPorEdificio = tamTotalEncargadoPorEdificio; } public boolean isBloquearPagSigEncargadoPorEdificio() { return bloquearPagSigEncargadoPorEdificio; } public void setBloquearPagSigEncargadoPorEdificio(boolean bloquearPagSigEncargadoPorEdificio) { this.bloquearPagSigEncargadoPorEdificio = bloquearPagSigEncargadoPorEdificio; } public boolean isBloquearPagAntEncargadoPorEdificio() { return bloquearPagAntEncargadoPorEdificio; } public void setBloquearPagAntEncargadoPorEdificio(boolean bloquearPagAntEncargadoPorEdificio) { this.bloquearPagAntEncargadoPorEdificio = bloquearPagAntEncargadoPorEdificio; } }
C++
UTF-8
2,130
3.3125
3
[]
no_license
#include "HuffmanCode.h" #include <fstream> #include <iostream> using namespace std; /** * Title : Heaps and AVL Trees * Author : Munib Emre Sevilgen * ID: 21602416 * Section : 1 * Assignment : 3 * Description : Main function */ int main(){ char* characters = new char[100]; int* freqs = new int[100]; int maxNumberOfCharacters = 100; int numberOfCharacters = 0; string line; string inputName; string outputName; cout << "Enter the name of the input file: "; cin >> inputName; cout << "Enter the name of the output file: "; cin >> outputName; ifstream inputFile; inputFile.open(inputName.c_str()); // Reads from the file if (inputFile.is_open()){ while(!inputFile.eof()){ if (numberOfCharacters + 1 > maxNumberOfCharacters){ int maxSize = maxNumberOfCharacters*2; char* temp = new char[maxSize]; int* temp2 = new int[maxSize]; for (int i = 0; i< numberOfCharacters; i++){ temp[i] = characters[i]; temp2[i] = freqs[i]; delete [] characters; characters = temp; delete [] freqs; freqs = temp2; } } inputFile >> characters[numberOfCharacters] >> freqs[numberOfCharacters]; numberOfCharacters++; } } // Generates the shemes HuffmanCode* huffman = new HuffmanCode(characters, freqs, numberOfCharacters); string* schemes; char* chars; huffman->getHuffmanSchemes(chars, schemes); // for (int i = 0; i < 6; i++) // cout << chars[i] << " - " << schemes[i] << endl; // Writes to the file ofstream outputFile; outputFile.open(outputName.c_str()); if(outputFile.is_open()){ for(int i = 0; i < numberOfCharacters; i++){ outputFile << chars[i] << " " << schemes[i] << endl; } outputFile.close(); } delete [] characters; delete [] freqs; delete [] schemes; delete [] chars; delete huffman; return 0; }
JavaScript
UTF-8
2,240
2.578125
3
[]
no_license
/******************************************************************************\ * @file api/controllers/controller.premise.js * @description premise controller * @author Tyler Yasaka \******************************************************************************/ var ASYNC = require('async'); var LIB = require('../lib/lib.js'); var DB = require('../database/connect.js'); /******************************************************************************\ * @function create * @desc add a premise to an argument (using a new or existing statement) * @param premise => premise object * @param author => author of argument * @param callback => function to call (with result parameter) when done \******************************************************************************/ exports.create = (premise, author, callback) => { var argKey = premise.argKey; var statement = premise.statement; ASYNC.waterfall([ // Create new statement or get the specified id function(next) { if(typeof statement._key == 'undefined') { DB.v.statement.save(statement) .then( result => { next(null, result.vertex._key); }); } else { next(null, statement._key); } }, // Connect statement to argument as premise function(stmtKey) { var argId = 'argument/' + argKey; var stmtId = 'statement/' + stmtKey; DB.e.premise.save({author: author}, stmtId, argId) .then( result => { callback( LIB.successMsg({_id: stmtId}) ); }); } ]); } /******************************************************************************\ * @function remove * @desc remove a premise from an argument, and delete the statement if not * otherwise referenced by the user's arguments * @param argKey => argument identifier * @param premiseKey => premise statement identifier * @param author => author of argument * @param callback => function to call (with result parameter) when done \******************************************************************************/ exports.remove = (argKey, premiseKey, author, callback) => { var argId = 'argument/' + argKey; var premiseId = 'statement/' + premiseKey; LIB.removeEdge('premise', premiseId, argId, author, () => { callback( LIB.successMsg({}) ); }); }
Markdown
UTF-8
2,778
3.3125
3
[ "MIT" ]
permissive
--- title: "PrysmJs Syntax Highlighter" date: "12-29-2019" order: 1 --- Install the following ```js npm install --save gatsby-transformer-remark gatsby-remark-prismjs prismjs ``` <br> <br> Include gatsby styles in gatsby-browser.js ```js //in gatsby-browser.js require("prismjs/themes/prism-okaidia.css") require("prismjs/plugins/line-numbers/prism-line-numbers.css") ``` <br> <br> ## Adding Syntax Highlighting to a page manually Import useEffect and PrismJs ```js //import useEffect and Prism on whatever page/template you will use Prism import { useEffect } from "react" import Prism from "prismjs" ``` <br> <br> Define a const variable with your code example ```js const code = `<!-- html --> <div className="container"> <h1>This is an h1</h1> <p>This is a paragraph</p> </div>` ``` <br> <br> Add useEffect before your return which is used for code highlighting ```js useEffect(() => { Prism.highlightAll() }) ``` <br> <br> Add your html inside your return using the const variable for the code ```html <!--HTML--> <pre className="language-html line-numbers"> <code> {code}<!-- const variable above, or just add code inside curly braces with single backticks --> </code> <!-- Add line numbers here if you want to show them --> </pre> ``` <br> <br> ## Add Line Numbers To show line numbers, add the following before the closing pre tag. Each empty span tag is a line number ```html <span className="line-numbers-rows"><span></span></span> <!-- would show 1 line number etc --> <span className="line-numbers-rows"><span></span><span></span></span> <!-- would show 2 line numbers etc --> ``` <br> <br> Add this CSS to fix Line Numbers, adjust if needed desired ```css /** * CSS for line numbers */ pre.line-numbers code { padding: 0px; } .line-numbers .line-numbers-rows { left: 0; padding: 1em; width: 3em !important; } ``` <br> <br> ## Final Code Example using this inside a page e.g `/src/pages/index.js` ```js import React from "react" import Layout from "../components/layout" //import the Prism package import { useEffect } from "react" import Prism from "prismjs" // The code snippet you want to highlight, as a string const codeExample = `< !--html --> <div className="container"> <h1>This is an h1</h1> <p>This is a paragraph</p> </div>` const IndexPage = () => { useEffect(() => { Prism.highlightAll() }) return ( <Layout> <pre className="language-html line-numbers"> <code> {codeExample} </code> <span className="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span> </pre> </Layout> ) } export default IndexPage ```
Java
UTF-8
329
1.960938
2
[]
no_license
package com.mk.shoppingbackend.dao; import java.util.List; import com.mk.shoppingbackend.dto.Products; public interface ProductsDAO { Products get(int id); List<Products> list(); boolean add(Products products); boolean update(Products products); void delete(int id); Products getProduct(int id); }
Java
UTF-8
1,233
2.21875
2
[]
no_license
package hznj.com.zhongcexiangjiao.doman; import java.util.List; /** * Description: * Copyright : Copyright (c) 2016 * Company : 传智播客 * Author : 隔壁小张 * Date : 2017/4/13 16:29 */ public class zhaopianBean { /** * list : [{"PICURL":"http://171.188.42.56:8081/app/XrayImages/XrayPic.bmp"}] * msg : 请求成功 * result : 1 */ private String msg; private String result; private List<ListBean> list; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public List<ListBean> getList() { return list; } public void setList(List<ListBean> list) { this.list = list; } public static class ListBean { /** * PICURL : http://171.188.42.56:8081/app/XrayImages/XrayPic.bmp */ private String PICURL; public String getPICURL() { return PICURL; } public void setPICURL(String PICURL) { this.PICURL = PICURL; } } }
Markdown
UTF-8
651
2.53125
3
[ "BSD-3-Clause" ]
permissive
# Climate Index Download and visulize climate indices from NOAA website http://www.esrl.noaa.gov/psd/gcos_wgsp/Timeseries/ ## Major APIs: * `print_database()`: print information of the available climate indices (e.g. long_name, url). * `get_climate_index(climate_index_name=None)`: get the climate index as a pandas Series instance (if None, print the database). * `plot_climate_index(climate_index_name)`: plot the climate index time series. ## Notebook Examples http://nbviewer.ipython.org/github/wy2136/climate_index/blob/master/climate_index.ipynb ## Documentation https://dl.dropboxusercontent.com/u/16364556/climate_index_doc/html/index.html
Shell
UTF-8
208
2.59375
3
[]
no_license
echo ########repace for android 4.43############# for file in `find -name "project.properties"` do mv $file $file.bak more $file.bak | sed 's@target=android-15@target=android-18@g' > $file rm $file.bak done
Markdown
UTF-8
1,417
2.53125
3
[ "Apache-2.0" ]
permissive
文件同步是 Nocalhost 进入`开发模式`的一项重要功能,只有在启用`开发模式`时才会启用,他是实现本地和远程文件自动同步的关键。它将根据配置或命令建立从本地到开发容器的隧道,并传输文件。 您可以通过`ntctl`使用它: ``` nhctl sync [application_name]] [参数] ``` 参数: ``` -m,-daemon 布尔值,默认为 true,文件同步作为守护程序运行 -d,--deployment 字符串,进入开发环境的工作负载名称 -b,--double 布尔值,默认为 false,单向同步 全局参数: --debug 启用调试级别日志 --kubeconfig 字符串,指定 kubeconfig 文件的路径 ``` 在使用IDE 插件进入`开发模式`时会自动启用文件同步,同步目录由配置项 `syncDirs` 决定,其路径代表相对于源码的目录,并同步到配置项 `workDir` 指定改的目录。 >注意:由于平台差异,当从 Windows 同步文件到 devContainer 时将丢失执行位,例如 Shell 脚本和其他无法在 Windows 下作为可执行的文件。您可以在 devContainer 中手动执行 `chmod + x filename' 来解决该问题。 文件同步使用 [Syncthing](https://github.com/syncthing/syncthing) 工具,Syncthing 控制台默认用户名和密码均为 “nocalhost”,您可以使用 `nhctl list [application_name]` 命令获取登陆控制台的端口。
Java
UTF-8
8,650
2.40625
2
[]
no_license
package ai.libs.jaicore.search.algorithms.standard.uncertainty.explorationexploitationsearch; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ai.libs.jaicore.search.algorithms.standard.uncertainty.ISolutionDistanceMetric; import ai.libs.jaicore.search.model.travesaltree.DefaultNodeComparator; import ai.libs.jaicore.search.model.travesaltree.Node; public class UncertaintyExplorationOpenSelection<T, V extends Comparable<V>> implements Queue<Node<T, V>> { private static final Logger logger = LoggerFactory.getLogger(UncertaintyExplorationOpenSelection.class); private final Queue<Node<T, V>> exploitationOpen = new PriorityQueue<>(new DefaultNodeComparator<>()); private final PriorityQueue<Node<T, V>> explorationOpen = new PriorityQueue<>(new DefaultNodeComparator<>()); private final ISolutionDistanceMetric<T> solutionDistanceMetric; private final IPhaseLengthAdjuster phaseLengthAdjuster; private final IExplorationCandidateSelector<T, V> candidateSelector; private int explorationPhaseLength; private int exploitationPhaseLength; private double exploitationScoreThreshold; private double explorationUncertaintyThreshold; private int selectedNodes = 0; private int exploredNodes = 0; private long timeout; private long startTime; private boolean exploring = true; public UncertaintyExplorationOpenSelection(final long timeout, final int phaseInterval, final double exploitationScoreThreshold, final double explorationUncertaintyThreshold, final IPhaseLengthAdjuster phaseLengthAdjuster, final ISolutionDistanceMetric<T> solutionDistanceMetric, final IExplorationCandidateSelector<T, V> candidateSelector) { super(); this.timeout = timeout; this.startTime = System.currentTimeMillis(); int[] phaseLenghts = phaseLengthAdjuster.getInitialPhaseLengths(phaseInterval); assert phaseLenghts.length == 2; this.explorationPhaseLength = phaseLenghts[0]; this.exploitationPhaseLength = phaseLenghts[1]; this.exploitationScoreThreshold = exploitationScoreThreshold; this.explorationUncertaintyThreshold = explorationUncertaintyThreshold; this.phaseLengthAdjuster = phaseLengthAdjuster; this.solutionDistanceMetric = solutionDistanceMetric; this.candidateSelector = candidateSelector; } @Override public Node<T, V> peek() { return this.selectCandidate(this.exploring); } private synchronized Node<T, V> selectCandidate(final boolean isExploring) { Comparator<Node<T, V>> comparator = (n1, n2) -> { try { Double u1 = (Double) n1.getAnnotation("uncertainty"); Double u2 = (Double) n2.getAnnotation("uncertainty"); V v1 = n1.getInternalLabel(); V v2 = n2.getInternalLabel(); if (isExploring) { if (Math.abs(u1 - u2) <= this.explorationUncertaintyThreshold) { return -1 * v1.compareTo(v2); } else { return Double.compare(u1, u2); } } else { if (v1 instanceof Double && v2 instanceof Double) { Double s1 = (Double) v1; Double s2 = (Double) v2; if (Math.abs(s1 - s2) <= this.exploitationScoreThreshold) { return Double.compare(u1, u2); } else { return Double.compare(s1, s2); } } else { if (v1 instanceof Double && v2 instanceof Double) { Double s1 = (Double) v1; Double s2 = (Double) v2; if (Math.abs(s1 - s2) <= this.exploitationScoreThreshold) { return Double.compare(u1, u2); } else { return v1.compareTo(v2); } } else { return v1.compareTo(v2); } } } } catch (Exception e) { logger.error(e.getMessage()); return 0; } }; if (isExploring) { return this.explorationOpen.stream().max(comparator).orElse(this.explorationOpen.peek()); } else { return this.exploitationOpen.stream().min(comparator).orElse(this.exploitationOpen.peek()); } } private void adjustPhaseLengths(final long passedTime) { int[] newPhaseLengths = this.phaseLengthAdjuster.adjustPhaseLength(this.explorationPhaseLength, this.exploitationPhaseLength, passedTime, this.timeout); assert newPhaseLengths.length == 2; this.explorationPhaseLength = newPhaseLengths[0]; this.exploitationPhaseLength = newPhaseLengths[1]; } @Override public synchronized boolean add(final Node<T, V> node) { if (node == null) { throw new IllegalArgumentException("Cannot add node NULL to OPEN"); } if (!this.contains(node)) { throw new IllegalArgumentException("Node " + node + " is already there!"); } if (this.exploring) { return this.explorationOpen.add(node); } else { return this.exploitationOpen.add(node); } } @Override public synchronized boolean remove(final Object node) { if (this.exploitationOpen.contains(node) && this.explorationOpen.contains(node)) { throw new IllegalStateException("A node (" + node + ") that is to be removed is in BOTH open lists!"); } if (this.exploring) { return this.explorationOpen.remove(node) || this.exploitationOpen.remove(node); } else { return this.exploitationOpen.remove(node) || this.explorationOpen.remove(node); } } @Override public synchronized boolean addAll(final Collection<? extends Node<T, V>> arg0) { assert this.exploitationOpen != null : "Primary OPEN is NULL!"; if (arg0 == null) { throw new IllegalArgumentException("Cannot add NULL collection"); } if (this.exploring) { return this.explorationOpen.addAll(arg0); } else { return this.exploitationOpen.addAll(arg0); } } @Override public synchronized void clear() { this.exploitationOpen.clear(); this.explorationOpen.clear(); } @Override public synchronized boolean contains(final Object arg0) { return this.exploitationOpen.contains(arg0) || this.explorationOpen.contains(arg0); } @Override public boolean containsAll(final Collection<?> arg0) { for (Object o : arg0) { if (!this.contains(o)) { return false; } } return true; } @Override public synchronized boolean isEmpty() { return this.exploitationOpen.isEmpty() && this.explorationOpen.isEmpty(); } @Override public Iterator<Node<T, V>> iterator() { return this.exploring ? this.explorationOpen.iterator() : this.exploitationOpen.iterator(); } @Override public synchronized boolean removeAll(final Collection<?> arg0) { return this.exploitationOpen.removeAll(arg0) && this.explorationOpen.removeAll(arg0); } @Override public synchronized boolean retainAll(final Collection<?> arg0) { return this.exploitationOpen.retainAll(arg0) && this.explorationOpen.retainAll(arg0); } @Override public synchronized int size() { return this.exploitationOpen.size() + this.explorationOpen.size(); } @Override public Object[] toArray() { return this.exploitationOpen.toArray(); } @SuppressWarnings("unchecked") @Override public <X> X[] toArray(final X[] arg0) { return (X[]) this.exploitationOpen.toArray(); } @Override public Node<T, V> element() { return this.peek(); } @Override public boolean offer(final Node<T, V> e) { return this.add(e); } @Override public Node<T, V> poll() { return this.remove(); } @Override public synchronized Node<T, V> remove() { /* determine element to be returned and remove it from the respective list */ Node<T, V> peek = this.peek(); this.remove(peek); /* update internal state */ if (!this.exploring) { this.selectedNodes++; if (this.selectedNodes % this.exploitationPhaseLength == 0) { List<Node<T, V>> explorationCandidates = this.candidateSelector.selectExplorationCandidates(this.exploitationOpen, this.exploitationOpen.peek(), this.solutionDistanceMetric); /* enable exploration with the node selected by the explorer evaluator */ try { logger.info("Entering exploration phase under {}", explorationCandidates); } catch (Exception e) { logger.error(e.getMessage()); } this.exploring = true; this.exploredNodes = 0; this.exploitationOpen.removeAll(explorationCandidates); this.explorationOpen.clear(); this.explorationOpen.addAll(explorationCandidates); } } else { this.exploredNodes++; if (this.exploredNodes > this.explorationPhaseLength || this.explorationOpen.isEmpty()) { this.adjustPhaseLengths(System.currentTimeMillis() - this.startTime); this.exploring = false; this.exploitationOpen.addAll(this.explorationOpen); this.explorationOpen.clear(); logger.info("Entering exploitation phase"); } } /* return the peeked element */ return peek; } }
PHP
UTF-8
13,812
2.609375
3
[ "Apache-2.0" ]
permissive
<?php namespace Svea\WebPay\HostedService\Helper; use Svea\WebPay\Helper\Helper; use Svea\WebPay\BuildOrder\CreateOrderBuilder; use Svea\WebPay\HostedService\Payment\HostedPayment; use XMLWriter; /** * Formats request xml in preparation of sending request to hosted webservice. * * These methods writes requests to hosted payment & hosted admin services * as detailed in "Technical Specification Svea\WebPay\WebPay v 2.6.8" as of 140403. * * @author Kristian Grossman-Madsen */ class HostedXmlBuilder { /** * @var XMLWriter $XMLWriter */ private $XMLWriter; private $isCompany = "FALSE"; // set to true by serializeCustomer if needed. /** * Returns the webservice payment request message xml * * @deprecated 2.0.0 use @see getPaymentXML instead * @param type $request * @param CreateOrderBuilder $order * This method expect UTF-8 input * @return string */ public function getOrderXML($request, $order) { return $this->getPaymentXML($request, $order); } /** * Returns the webservice payment request message xml * payment request structure as in "Technical Specification Svea\WebPay\WebPay v 2.6.8" * * @param HostedPayment $request * @param CreateOrderBuilder $order * @return string * This method expect UTF-8 input */ public function getPaymentXML($request, $order) { $this->setBaseXML($order->conf); $this->XMLWriter->startElement("payment"); //paymentmethod -- optional if (isset($request['paymentMethod'])) { $this->XMLWriter->writeElement("paymentmethod", $request['paymentMethod']); // paymentmethod -- if not set, goes to paypage } //lang -- optional $this->XMLWriter->writeElement("lang", $request['langCode']); // currency $this->XMLWriter->writeElement("currency", $request['currency']); // amount $this->XMLWriter->writeElement("amount", Helper::bround($request['amount'])); // vat -- optional if ($request['totalVat'] != null) { $this->XMLWriter->writeElement("vat", Helper::bround($request['totalVat'])); } // customerrefno -- optional $this->XMLWriter->writeElement("customerrefno", $request['clientOrderNumber']); // returnurl -- optional $this->XMLWriter->writeElement("returnurl", $request['returnUrl']); // cancelurl -- optional $this->XMLWriter->writeElement("cancelurl", $request['cancelUrl']); // callbackurl -- optional if ($request['callbackUrl'] != null) { $this->XMLWriter->writeElement("callbackurl", $request['callbackUrl']); } // subscriptiontype -- optional if (isset($request['subscriptionType'])) { $this->XMLWriter->writeElement("subscriptiontype", $request['subscriptionType']); // subscriptiontype } // simulatorcode // excludepaymentmethods -- in exclude element if (isset($request['excludePaymentMethods'])) { $this->serializeExcludePayments($request['excludePaymentMethods']); // excludepaymentmethods } // orderrows -- in row element $this->serializeOrderRows($request['rows']); // orderrows // customer -- optional if(isset($request['paymentMethod'])) { $this->serializeCustomer($order, $request['paymentMethod']); // customer // -- used by Invoice payment } else { $this->serializeCustomer($order); // customer // -- used by Invoice payment } $this->XMLWriter->writeElement("iscompany", $this->isCompany); // -- used by invoice payment $this->XMLWriter->writeElement("addinvoicefee", "FALSE"); // -- used by invoice payment // iscompany -- optional // addinvoicefee -- optional // addressid -- optional // -- used by invoice payment // not in specification, but seems legit if (isset($request['ipAddress'])) { $this->XMLWriter->writeElement("ipaddress", $request['ipAddress']); } if(isset($request['payerAlias'])) { $this->XMLWriter->writeElement("payeralias", $request['payerAlias']); } $this->XMLWriter->endElement(); $this->XMLWriter->endDocument(); return $this->XMLWriter->flush(); } private function setBaseXML($config) { $this->XMLWriter = new XMLWriter(); $this->XMLWriter->openMemory(); $this->XMLWriter->setIndent(true); $this->XMLWriter->startDocument("1.0", "UTF-8"); $this->XMLWriter->writeComment(Helper::getLibraryAndPlatformPropertiesAsJson($config)); } private function serializeExcludePayments($payMethods) { if (count($payMethods) > 0) { $this->XMLWriter->startElement("excludepaymentmethods"); foreach ($payMethods as $payMethod) { $this->XMLWriter->writeElement('exclude', $payMethod); } $this->XMLWriter->endElement(); } } private function serializeOrderRows($orderRows) { if (count($orderRows) > 0) { $this->XMLWriter->startElement("orderrows"); foreach ($orderRows as $orderRow) { $this->serializeOrderRow($orderRow); } $this->XMLWriter->endElement(); } } private function serializeOrderRow($orderRow) { $this->XMLWriter->startElement("row"); if (!empty($orderRow->sku) && $orderRow->sku != null) { $this->XMLWriter->writeElement("sku", $orderRow->sku); } else { $this->XMLWriter->writeElement("sku", ""); } if (!empty($orderRow->name) && $orderRow->name != null) { $this->XMLWriter->writeElement("name", $orderRow->name); } else { $this->XMLWriter->writeElement("name", ""); } if (!empty($orderRow->description) && $orderRow->description != null) { $this->XMLWriter->writeElement("description", $orderRow->description); } else { $this->XMLWriter->writeElement("description", ""); } if (!empty($orderRow->amount) && $orderRow->amount != null) { $this->XMLWriter->writeElement("amount", Helper::bround($orderRow->amount)); } else { $this->XMLWriter->writeElement("amount", "0"); } if (!empty($orderRow->vat) && $orderRow->vat != null) { $this->XMLWriter->writeElement("vat", Helper::bround($orderRow->vat)); } else { $this->XMLWriter->writeElement("vat", "0"); } if (!empty($orderRow->quantity) && $orderRow->quantity != null) { $this->XMLWriter->writeElement("quantity", $orderRow->quantity); } if (!empty($orderRow->unit) && $orderRow->unit != null) { $this->XMLWriter->writeElement("unit", $orderRow->unit); } $this->XMLWriter->endElement(); } private function serializeCustomer($order, $paymentMethod = NULL) { $this->XMLWriter->startElement("customer"); if(isset($paymentMethod) && $paymentMethod == "SVEACARDPAY_PF") { $this->XMLWriter->writeElement("unknowncustomer", "true"); $this->XMLWriter->writeElement("country", $order->countryCode); } else { //nordic country individual if (isset($order->customerIdentity->ssn)) { $this->XMLWriter->writeElement("ssn", $order->customerIdentity->ssn); } elseif (isset($order->customerIdentity->birthDate)) { $this->XMLWriter->writeElement("ssn", $order->customerIdentity->birthDate); } //customer identity for NL and DE when choosing invoice or paymentplan if (isset($order->customerIdentity->firstname)) { $this->XMLWriter->writeElement("firstname", $order->customerIdentity->firstname); } if (isset($order->customerIdentity->lastname)) { $this->XMLWriter->writeElement("lastname", $order->customerIdentity->lastname); } if (isset($order->customerIdentity->initials)) { $this->XMLWriter->writeElement("initials", $order->customerIdentity->initials); } if (isset($order->customerIdentity->street)) { $this->XMLWriter->writeElement("address", $order->customerIdentity->street); } if (isset($order->customerIdentity->coAddress)) { $this->XMLWriter->writeElement("address2", $order->customerIdentity->coAddress); } if (isset($order->customerIdentity->housenumber)) { $this->XMLWriter->writeElement("housenumber", $order->customerIdentity->housenumber); } if (isset($order->customerIdentity->zipCode)) { $this->XMLWriter->writeElement("zip", $order->customerIdentity->zipCode); } if (isset($order->customerIdentity->locality)) { $this->XMLWriter->writeElement("city", $order->customerIdentity->locality); } if (isset($order->countryCode)) { $this->XMLWriter->writeElement("country", $order->countryCode); } if (isset($order->customerIdentity->phonenumber)) { $this->XMLWriter->writeElement("phone", $order->customerIdentity->phonenumber); } if (isset($order->customerIdentity->email)) { $this->XMLWriter->writeElement("email", $order->customerIdentity->email); } if (isset($order->customerIdentity->orgNumber) || isset($order->customerIdentity->companyVatNumber)) { if (isset($order->customerIdentity->orgNumber)) { $this->XMLWriter->writeElement("ssn", $order->customerIdentity->orgNumber); } else { $this->XMLWriter->writeElement("vatnumber", $order->customerIdentity->companyVatNumber); // -- used by Invoice payment } // companyname // -- used by Invoice payment // companyid // -- used by Invoice payment $this->isCompany = "TRUE"; } $this->XMLWriter->endElement(); if (isset($order->customerIdentity->addressSelector)) { $this->XMLWriter->writeElement("addressid", $order->customerIdentity->addressSelector); // -- used by Invoice payment } } } /** * Returns the webservice preparepayment request message xml * uses the same code as getPaymentXML above, with the addition of the lang and ipaddress fields * * @param type $request * @param CreateOrderBuilder $order * @return type * This method expect UTF-8 input */ public function getPreparePaymentXML($request, $order) { $this->setBaseXML($order->conf); $this->XMLWriter->startElement("payment"); if (isset($request['paymentMethod'])) { $this->XMLWriter->writeElement("paymentmethod", $request['paymentMethod']); // paymentmethod -- if not set, goes to paypage } $this->XMLWriter->writeElement("lang", $request['langCode']); // required in preparepayment $this->XMLWriter->writeElement("currency", $request['currency']); $this->XMLWriter->writeElement("amount", Helper::bround($request['amount'])); if ($request['totalVat'] != null) { $this->XMLWriter->writeElement("vat", Helper::bround($request['totalVat'])); } $this->XMLWriter->writeElement("customerrefno", $request['clientOrderNumber']); $this->XMLWriter->writeElement("returnurl", $request['returnUrl']); $this->XMLWriter->writeElement("cancelurl", $request['cancelUrl']); if ($request['callbackUrl'] != null) { $this->XMLWriter->writeElement("callbackurl", $request['callbackUrl']); } // subscriptiontype -- optional if (isset($request['subscriptionType'])) { $this->XMLWriter->writeElement("subscriptiontype", $request['subscriptionType']); // subscriptiontype } // simulatorcode if (isset($request['excludePaymentMethods'])) { $this->serializeExcludePayments($request['excludePaymentMethods']); // excludepaymentmethods } $this->serializeOrderRows($request['rows']); // orderrows $this->XMLWriter->writeElement("ipaddress", $request['ipAddress']); // required in preparepayment $this->serializeCustomer($order); // customer // -- used by Invoice payment $this->XMLWriter->writeElement("iscompany", $this->isCompany); // -- used by invoice payment $this->XMLWriter->writeElement("addinvoicefee", "FALSE"); // -- used by invoice payment // addressid // -- used by invoice payment $this->XMLWriter->endElement(); $this->XMLWriter->endDocument(); return $this->XMLWriter->flush(); } /** * write xml for webservice getpaymentmethods * @param $merchantId * @return mixed */ public function getPaymentMethodsXML($merchantId) { $this->setBaseXML(); $this->XMLWriter->startElement("getpaymentmethods"); $this->XMLWriter->writeElement("merchantid", $merchantId); $this->XMLWriter->endElement(); $this->XMLWriter->endDocument(); return $this->XMLWriter->flush(); } }
Java
UTF-8
7,231
1.710938
2
[]
no_license
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot; import java.security.acl.Group; import java.util.ResourceBundle.Control; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.can.VictorSPX; import com.ctre.phoenix.motorcontrol.can.WPI_VictorSPX; import com.kauailabs.navx.frc.AHRS; import com.revrobotics.ColorMatch; import com.revrobotics.ColorMatchResult; import com.revrobotics.ColorSensorV3; import edu.wpi.first.wpilibj.I2C; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.SpeedControllerGroup; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.SerialPort.Port; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.util.Color; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the TimedRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the build.gradle file in the * project. */ public class Robot extends TimedRobot { private static final String kDefaultAuto = "Default"; private static final String kCustomAuto = "My Auto"; private String m_autoSelected; private final SendableChooser<String> m_chooser = new SendableChooser<>(); boolean stage1; String colorString; AHRS ahrs = new AHRS(Port.kMXP); Joystick j = new Joystick(0); I2C.Port rioI2C = I2C.Port.kOnboard; ColorSensorV3 colorSensor = new ColorSensorV3(rioI2C); ColorMatch colorMatcher = new ColorMatch(); private final Color kBlueTarget = ColorMatch.makeColor(0.143, 0.427, 0.429); private final Color kGreenTarget = ColorMatch.makeColor(0.197, 0.561, 0.240); private final Color kRedTarget = ColorMatch.makeColor(0.561, 0.232, 0.114); private final Color kYellowTarget = ColorMatch.makeColor(0.361, 0.524, 0.113); Color detectedColor; WPI_VictorSPX frontLeft = new WPI_VictorSPX(2); WPI_VictorSPX backLeft = new WPI_VictorSPX(4); SpeedControllerGroup left = new SpeedControllerGroup(frontLeft, backLeft); WPI_VictorSPX frontRight = new WPI_VictorSPX(3); WPI_VictorSPX backRight = new WPI_VictorSPX(5); SpeedControllerGroup right = new SpeedControllerGroup(frontRight, backRight); WPI_VictorSPX shooter = new WPI_VictorSPX(6); WPI_VictorSPX setter = new WPI_VictorSPX(7); WPI_VictorSPX intake = new WPI_VictorSPX(8); WPI_VictorSPX revolver = new WPI_VictorSPX(9); /** * This function is run when the robot is first started up and should be used * for any initialization code. */ @Override public void robotInit() { m_chooser.setDefaultOption("Default Auto", kDefaultAuto); m_chooser.addOption("My Auto", kCustomAuto); SmartDashboard.putData("Auto choices", m_chooser); revolver.setNeutralMode(NeutralMode.Brake); colorMatcher.addColorMatch(kBlueTarget); colorMatcher.addColorMatch(kGreenTarget); colorMatcher.addColorMatch(kRedTarget); colorMatcher.addColorMatch(kYellowTarget); } /** * This function is called every robot packet, no matter the mode. Use this for * items like diagnostics that you want ran during disabled, autonomous, * teleoperated and test. * * <p> * This runs after the mode specific periodic functions, but before LiveWindow * and SmartDashboard integrated updating. */ @Override public void robotPeriodic() { } /** * This autonomous (along with the chooser code above) shows how to select * between different autonomous modes using the dashboard. The sendable chooser * code works with the Java SmartDashboard. If you prefer the LabVIEW Dashboard, * remove all of the chooser code and uncomment the getString line to get the * auto name from the text box below the Gyro * * <p> * You can add additional auto modes by adding additional comparisons to the * switch structure below with additional strings. If using the SendableChooser * make sure to add them to the chooser code above as well. */ @Override public void autonomousInit() { m_autoSelected = m_chooser.getSelected(); // m_autoSelected = SmartDashboard.getString("Auto Selector", kDefaultAuto); System.out.println("Auto selected: " + m_autoSelected); } /** * This function is called periodically during autonomous. */ @Override public void autonomousPeriodic() { switch (m_autoSelected) { case kCustomAuto: // Put custom auto code here break; case kDefaultAuto: default: // Put default auto code here break; } } /** * This function is called periodically during operator control. */ @Override public void teleopPeriodic() { detectedColor = colorSensor.getColor(); ColorMatchResult match = colorMatcher.matchClosestColor(detectedColor); if(j.getRawButton(2)) { revolver.set(ControlMode.PercentOutput, -0.2); } else if (match.color == kRedTarget) { revolver.set(ControlMode.PercentOutput, 0); } /**if (stage1) { if (match.color == red) { revolver.set(ControlMode.PercentOutput, 0); stage1 = false; } else { revolver.set(ControlMode.PercentOutput, -0.15); } } else if (j.getRawButton(2)) { revolver.set(ControlMode.PercentOutput, -0.15); stage1 = true; } else { revolver.set(ControlMode.PercentOutput, 0); }**/ if(j.getRawButton(1)) { setter.set(ControlMode.PercentOutput, 1); shooter.set(ControlMode.PercentOutput, 1); } else{ setter.set(ControlMode.PercentOutput, 0); shooter.set(ControlMode.PercentOutput, 0); } if(j.getRawButton(3)) { intake.set(ControlMode.PercentOutput, -0.75); } else{ intake.set(ControlMode.PercentOutput, 0); } left.set(-j.getY() + j.getZ()*0.25); right.set(j.getY() + j.getZ()*0.25); if (match.color == kBlueTarget) { colorString = "Blue"; } else if (match.color == kRedTarget) { colorString = "Red"; } else if (match.color == kGreenTarget) { colorString = "Green"; } else if (match.color == kYellowTarget) { colorString = "Yellow"; } else { colorString = "Unknown"; } SmartDashboard.putNumber("Red", detectedColor.red); SmartDashboard.putNumber("Green", detectedColor.green); SmartDashboard.putNumber("Blue", detectedColor.blue); SmartDashboard.putNumber("Confidence", match.confidence); SmartDashboard.putString("Detected Color", colorString); } /** * This function is called periodically during test mode. */ @Override public void testPeriodic() { } }
Rust
UTF-8
1,990
3.015625
3
[]
no_license
// Speeds achieved on my machine: // Building lookup table: 3.8m/s // Searching for collision: 9.6m/s // Eventually finds, after ~1,050,000,000 attempts: // COLLISION! // Encrypting 'weakhash' with A425CEC20 then with 6EECEC66A gives DA99D1EA64144F3E use std::sync::Arc; use weakhash_rs::mitm; fn main() { let lookup = mitm::build_lookup_table(/*show_progress_every=*/10000000); let lookup = Arc::new(lookup); let targets = vec![0xDA99D1EA64144F3E, 0x59A3442D8BABCF84]; let collision = mitm::find_collision(&lookup, targets, /*show_progress_every=*/50000000, /*num_threads=*/5); println!("COLLISION! Encrypting 'weakhash' with {:X} then with {:X} gives {:X}", collision.encryption_key, collision.decryption_key, collision.output); } #[cfg(test)] mod tests { use super::*; use weakhash_rs::des; #[test] fn test_counter_to_key() { assert_eq!(mitm::counter_to_key(0x1FFu64), 0b110_11111110); } #[test] fn test_encrypt_decrypt() { let plaintext = u64::from_be_bytes(*b"weakhash"); let key = 0x84BC0CF41Cu64; let ciphertext = des::encrypt(key, plaintext); assert_eq!(ciphertext, 0x4d8fd5d169e1ecb9u64); assert_eq!(des::decrypt(key, ciphertext), plaintext); } #[test] fn test_cpp_solution() { // Goal: find these via mitm :) // Values from C++ solution. let plaintext = u64::from_be_bytes(*b"weakhash"); let key1 = 0x5e0414f206000000u64; let block = des::encrypt(key1, plaintext); assert_eq!(block, 0x32da4c17852dbcdcu64); let key2 = 0xa89020a200000000u64; assert_eq!(des::encrypt(key2, block), 0xda99d1ea64144f3eu64); } #[test] fn test_rust_solution() { // Based on: // Encrypting 'weakhash' with A425CEC20 then with 6EECEC66A gives DA99D1EA64144F3E let block = mitm::encrypt_iv(0xA425CEC20u64); assert_eq!(des::encrypt(0x6EECEC66Au64, block), 0xDA99D1EA64144F3Eu64); } }
JavaScript
UTF-8
1,079
3.625
4
[]
no_license
// Notes: // 1) Parsing time would be much easier and well-done with // something like moment.js. const {askUser, handleError} = require('../helpers'); const questions = ['Que horas são? (ex.: 14 horas e 37 minutos)']; const hoursAndMinutes = /(0\d|1\d|2[0-3]) horas e (0\d|[12345]\d) minutos/; const millisecondsToMinutes = ms => parseInt((ms / 1000) / 60, 10); const parseHours = userInput => { const [_, hours, minutes] = userInput.match(hoursAndMinutes); return {hours: Number(hours), minutes: Number(minutes)}; }; const calcElapsedTime = ({hours, minutes}) => { const start = new Date(); start.setHours(0, 0, 0, 0); const end = new Date(); end.setHours(hours, minutes, 0, 0); const elapsedTime = end.getTime() - start.getTime(); return millisecondsToMinutes(elapsedTime); }; const printResult = answers => { const [currentTime] = answers; const elapsedTime = calcElapsedTime(parseHours(currentTime)); console.log(`\nPassaram-se ${elapsedTime} minutos desde o início do dia. \n`); }; askUser(questions) .then(printResult) .catch(handleError);
Python
UTF-8
1,118
3.34375
3
[ "MIT" ]
permissive
""" Contains the definition of Line. """ from xdtools.utils import Point from xdtools.artwork import Artwork class Line(Artwork): """ A Line. === Attributes === name - The name of this Line as it appears in the Layers panel. uid - The unique id of this Line. position - The position of this Line. start - The starting Point of this Line. end - The ending Point of this Line. === Operations === """ def __init__(self, uid, start_x, start_y, end_x, end_y, name='Line', x=0, y=0): """ Instantiate a new Line. """ super().__init__(uid, 'line', name) self.position = Point(x, y) self.start = Point(start_x, start_y) self.end = Point(end_x, end_y) def __repr__(self): """ Return a constructor-style representation of this Line. """ return str.format( "Line(uid={}, type={}, name={}, position={}, start={}, end={}, styles={})", repr(self.uid), repr(self.type), repr(self.name), repr(self.position), repr(self.start), repr(self.end), repr(self.styles))
TypeScript
UTF-8
786
2.75
3
[ "Apache-2.0" ]
permissive
/* eslint-disable no-unused-expressions */ // @ts-nocheck import { expect } from 'chai' import { P_TYPE, P_VALUE } from './constants' import { NBTTypes, tagLong } from '../src' describe('l2nbt.js - tagLong', () => { it('basic', () => { const tag = tagLong(1) expect(tag).to.have.property(P_TYPE, NBTTypes.TAG_LONG) expect(tag).to.have.property(P_VALUE).to.be.eq(BigInt(1)) }) it('empty value or undefined, the value is 0', () => { expect(tagLong()) .to.have.property(P_VALUE) .that.is.eq(BigInt(0)) expect(tagLong(undefined)) .to.have.property(P_VALUE) .that.is.eq(BigInt(0)) }) it('illegal value then throw error', () => { expect(() => tagLong(null)).to.throw(Error) expect(() => tagLong([])).to.throw(Error) }) })
C++
UTF-8
8,301
2.90625
3
[]
no_license
/* * convert.hh * * Created on: 25 juin 2010 * Author: rnouacer */ #ifndef CONVERT_HH_ #define CONVERT_HH_ #include <stdint.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <string> #include <vector> #include <typeinfo> #include <stdexcept> #include <map> #include <unisim/util/endian/endian.hh> class BadConversion : public std::runtime_error { public: BadConversion(std::string const& s) : std::runtime_error(s) { } }; template<typename T> inline std::string stringify(T const& x) { std::ostringstream o; if (!(o << x)) { throw BadConversion(std::string("stringify(") + typeid(x).name() + ")"); } return (o.str()); } template<typename T> inline void convert(std::string const& s, T& x, bool failIfLeftoverChars = true) { std::istringstream i(s); char c; if (!(i >> x) || (failIfLeftoverChars && i.get(c))) { throw BadConversion(s); } } template<typename T> inline T convertTo(std::string const& s, bool failIfLeftoverChars = true) { T x; convert(s, x, failIfLeftoverChars); return (x); } inline bool isHexChar(char ch) { if(ch >= 'a' && ch <= 'f') return (true); if(ch >= '0' && ch <= '9') return (true); if(ch >= 'A' && ch <= 'F') return (true); return (false); } inline char nibble2HexChar(uint8_t v) { v = v & 0xf; // keep only 4-bits return (v < 10 ? '0' + v : 'a' + v - 10); } inline uint8_t hexChar2Nibble(char ch) { if(ch >= 'a' && ch <= 'f') return (ch - 'a' + 10); if(ch >= '0' && ch <= '9') return (ch - '0'); if(ch >= 'A' && ch <= 'F') return (ch - 'A' + 10); return (0); } inline void number2HexString(uint8_t* value, size_t size, std::string& hex, std::string endian) { ssize_t i; char c[2]; c[1] = 0; hex.erase(); if(endian == "big") { //#if BYTE_ORDER == BIG_ENDIAN // for(i = 0; i < size; i++) //#else // for(i = size - 1; i >= 0; i--) //#endif #if BYTE_ORDER == BIG_ENDIAN i = 0; #else i = size - 1; #endif for (size_t j=0; j<size; j++) { c[0] = nibble2HexChar(value[i] >> 4); hex += c; c[0] = nibble2HexChar(value[i] & 0xf); hex += c; #if BYTE_ORDER == BIG_ENDIAN i = i + 1; #else i = i - 1; #endif } } else { //#if BYTE_ORDER == LITTLE_ENDIAN // for(i = 0; i < size; i++) //#else // for(i = size - 1; i >= 0; i--) //#endif #if BYTE_ORDER == LITTLE_ENDIAN i = 0; #else i = size - 1; #endif for (size_t j=0; j<size; j++) { c[0] = nibble2HexChar(value[i] >> 4); hex += c; c[0] = nibble2HexChar(value[i] & 0xf); hex += c; #if BYTE_ORDER == LITTLE_ENDIAN i = i + 1; #else i = i - 1; #endif } } } inline bool hexString2Number(const std::string& hex, void* value, size_t size, std::string endian) { ssize_t i; size_t len = hex.length(); size_t pos = 0; if(endian == "big") { //#if BYTE_ORDER == BIG_ENDIAN // for(i = 0; i < size && pos < len; i++, pos += 2) //#else // for(i = size - 1; i >= 0 && pos < len; i--, pos += 2) //#endif #if BYTE_ORDER == BIG_ENDIAN i = 0; #else i = size - 1; #endif for (size_t j = 0; j < size && pos < len; j++, pos += 2) { if(!isHexChar(hex[pos]) || !isHexChar(hex[pos + 1])) return (false); ((uint8_t*) value)[i] = (hexChar2Nibble(hex[pos]) << 4) | hexChar2Nibble(hex[pos + 1]); #if BYTE_ORDER == BIG_ENDIAN i = i + 1; #else i = i - 1; #endif } } else { //#if BYTE_ORDER == LITTLE_ENDIAN // for(i = 0; i < size && pos < len; i++, pos += 2) //#else // for(i = size - 1; i >= 0 && pos < len; i--, pos += 2) //#endif #if BYTE_ORDER == LITTLE_ENDIAN i = 0; #else i = size - 1; #endif for(size_t j = 0; j < size && pos < len; j++, pos += 2) { if(!isHexChar(hex[pos]) || !isHexChar(hex[pos + 1])) return (false); ((uint8_t*) value)[i] = (hexChar2Nibble(hex[pos]) << 4) | hexChar2Nibble(hex[pos + 1]); #if BYTE_ORDER == LITTLE_ENDIAN i = i + 1; #else i = i - 1; #endif } } return (true); } inline void textToHex(const char *s, size_t count, std::string& packet) { size_t i; std::stringstream strm; for(i = 0; (i<count); i++) { strm << nibble2HexChar((uint8_t) s[i] >> 4); strm << nibble2HexChar((uint8_t) s[i] & 0xf); } packet = strm.str(); strm.str(std::string()); } inline void hexToText(const char *s, size_t count, std::string& packet) { size_t i; std::stringstream strm; uint8_t c; for (i = 0; i < count; i=i+2) { c = (hexChar2Nibble((uint8_t) s[i]) << 4) | hexChar2Nibble((uint8_t) s[i+1]); strm << c; } packet = strm.str(); strm.str(std::string()); } inline void stringSplit(std::string str, const std::string delim, std::vector<std::string>& results) { size_t cutAt = 0; while ((cutAt != str.npos) && !str.empty()) { cutAt = str.find_first_of(delim); if (cutAt == str.npos) { results.push_back(str); } else { results.push_back(str.substr(0,cutAt)); str = str.substr(cutAt+1); } } } inline void splitCharStr2Array(char* str, const char * delimiters, int *count, char** *res) { char * p = strtok (str, delimiters); int n_spaces = 0; /* split string and append tokens to 'res' */ while (p) { (*res) = (char**) realloc ((*res), sizeof (char*) * ++n_spaces); if ((*res) == NULL) exit (-1); /* memory allocation failed */ (*res)[n_spaces-1] = p; p = strtok (NULL, " "); } // /* print the result */ // // for (i = 0; i < (n_spaces); ++i) // printf ("res[%d] = %s\n", i, (*res)[i]); *count = n_spaces; } /* Function to get parity of number n. It returns 1 if n has odd parity, and returns 0 if n has even parity */ template <typename T> inline bool getParity(T n) { bool parity = false; while (n) { parity = !parity; n = n & (n - 1); } return parity; } template <typename T> inline bool ParseHex(const std::string& s, size_t& pos, T& value) { size_t len = s.length(); size_t n = 0; value = 0; while(pos < len && n < 2 * sizeof(T)) { uint8_t nibble; if(!isHexChar(s[pos])) break; nibble = hexChar2Nibble(s[pos]); value <<= 4; value |= nibble; pos++; n++; } return (n > 0); } inline const char* getOsName() { #ifndef __OSNAME__ #if defined(_WIN32) || defined(_WIN64) const char* osName = "Windows"; #else #ifdef __linux const char* osName = "Linux"; #else const char* osName = "Unknown"; #endif #endif #endif return (osName); } /* * Expand environment variables * Windows: * - ExpandEnvironmentStrings(%PATH%): Expands environment-variable strings and replaces them with the values defined for the current user * - PathUnExpandEnvStrings: To replace folder names in a fully qualified path with their associated environment-variable strings * - Example Get system informations : * url: http://msdn.microsoft.com/en-us/library/ms724426%28v=vs.85%29.aspx * * Linux/Posix: * url: http://stackoverflow.com/questions/1902681/expand-file-names-that-have-environment-variables-in-their-path * */ #include <cstdlib> #include <string> inline std::string expand_environment_variables( std::string s ) { if( s.find( "$(" ) == std::string::npos ) return s; std::string pre = s.substr( 0, s.find( "$(" ) ); std::string post = s.substr( s.find( "$(" ) + 2 ); if( post.find( ')' ) == std::string::npos ) return s; std::string variable = post.substr( 0, post.find( ')' ) ); std::string value = ""; post = post.substr( post.find( ')' ) + 1 ); if( getenv( variable.c_str() ) != NULL ) value = std::string( getenv( variable.c_str() ) ); return expand_environment_variables( pre + value + post ); } inline std::string expand_path_variables( std::string s , std::map<std::string, std::string> env_vars) { if( s.find( "$(" ) == std::string::npos ) return s; std::string pre = s.substr( 0, s.find( "$(" ) ); std::string post = s.substr( s.find( "$(" ) + 2 ); if( post.find( ')' ) == std::string::npos ) return s; std::string variable = post.substr( 0, post.find( ')' ) ); std::string value = ""; post = post.substr( post.find( ')' ) + 1 ); std::map<std::string, std::string>::iterator it = env_vars.find(variable); if (it == env_vars.end()) { if( getenv( variable.c_str() ) != NULL ) value = std::string( getenv( variable.c_str() ) ); } else { value = it->second; } return expand_environment_variables( pre + value + post ); } #endif /* CONVERT_HH_ */
Java
UTF-8
229
2.25
2
[]
no_license
package voorbeelden; public class Oef5 { public static void main(String[] args) { int getal1, getal2; getal1 = 2147483645; getal2 = 2147483642; long getal3 = (long)getal1 * getal2; System.out.println(getal3); } }
Markdown
UTF-8
3,206
3.125
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
Jaxon Library for CodeIgniter ============================= This package integrates the [Jaxon library](https://github.com/jaxon-php/jaxon-core) into the CodeIgniter 3 framework. Features -------- - Read Jaxon options from a file in CodeIgniter config format. - Automatically register Jaxon classes from a preset directory. Installation ------------ First install CodeIgniter version 3. Create the `composer.json` file into the installation dir with the following content. ```json { "require": { "jaxon-php/jaxon-codeigniter": "1.0.*", } } ``` Copy the content of the `app/` directory of this repo to the `application/` dir of the CodeIgniter application. This will install the Jaxon library for CodeIgniter, as well as the controller to process Jaxon requests and a default config file. Configuration ------------ The settings in the jaxon.php config file are separated into two sections. The options in the `lib` section are those of the Jaxon core library, while the options in the `app` sections are those of the CodeIgniter application. The following options can be defined in the `app` section of the config file. | Name | Default value | Description | |------|---------------|-------------| | dir | APPPATH . 'jaxon' | The directory of the Jaxon classes | | namespace | \Jaxon\App | The namespace of the Jaxon classes | | excluded | empty array | Prevent Jaxon from exporting some methods | | | | | Usage ----- This is an example of a CodeIgniter controller using the Jaxon library. ```php require(__DIR__ . '/Jaxon_Controller.php'); class Demo extends Jaxon_Controller { public function __construct() { parent::__construct(); } public function index() { // Register the Jaxon classes $this->jaxon->register(); // Print the page $this->load->library('parser'); $this->parser->parse('index', array( 'JaxonCss' => $this->jaxon->css(), 'JaxonJs' => $this->jaxon->js(), 'JaxonScript' => $this->jaxon->script() )); } } ``` The controller must inherit from the `Jaxon_Controller` provided in this package, and call its contructor. Before it prints the page, the controller makes a call to `$this->jaxon->register()` to export the Jaxon classes. Then it calls the `$this->jaxon->css()`, `$this->jaxon->js()` and `$this->jaxon->script()` functions to get the CSS and javascript codes generated by Jaxon, which it inserts in the page. ### The Jaxon classes The Jaxon classes of the application must all be located in the directory indicated by the `app.dir` option in the `jaxon.php` config file. If there is a namespace associated, the `app.namespace` option should be set accordingly. The `app.namespace` option must be explicitely set to `null`, `false` or an empty string if there is no namespace. By default, the Jaxon classes are located in the `APPPATH/jaxon` dir of the CodeIgniter application, and the associated namespace is `\Jaxon\App`. Contribute ---------- - Issue Tracker: github.com/jaxon-php/jaxon-codeigniter/issues - Source Code: github.com/jaxon-php/jaxon-codeigniter License ------- The project is licensed under the BSD license.
Swift
UTF-8
4,111
4.59375
5
[]
no_license
//: Playground - noun: a place where people can play import UIKit // 常量 字符串 let label = "the width is" let width = 94 let widthLabel = label + String(width) let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit." // 数组 var shoppingList = ["catfish", "water", "tulips", "blue paint"] print(shoppingList[1]) shoppingList[1] = "bottle of water" print(shoppingList) let emptyArray = [String]() // 字典 var occupations = [ "Nature":"男", ] print(occupations) occupations = [:] let emptyDic = [String : Float]() ////////// 控制流 // 使用if和switch来进行条件操作,使用for in、for、while、repeat-while 进行循环,包裹条件的()可以省略 let individualScores = [74, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } print(teamScore) // if语句 条件必须是一个bool表达式,不能直接用其他值来做判断 var optionalString: String? = "Hello" print(optionalString == nil) var optionalName : String? = "John" var greeting = "Hello!" if let name = optionalName { // 这个地方什么意思呢?没有看懂 greeting = "Hello, \(name)" } // 一种处理可选值的方法是通过 ?? 操作符来提供一个默认值 let nickName : String? = nil let fullName : String = "John Appleseed" let infomalGreeting = "Hi \(nickName ?? fullName )" let interestingNumbers = [ "Prime":[2, 3, 5, 7, 11, 13], "Fibonacci":[1, 1, 2, 3, 5, 8], "Square":[1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number; } } } print(largest) var n = 2 while n < 100 { n = n * 2 } print(n) var m = 2 repeat { m = m * 2; } while m < 100 print(m) var total = 0 // ..< 创建的范围不包含上界,... 创建的范围包含上界 for i in 0...4 { total += i } print(total) // 函数和闭包 // 使用func 来声明一个函数,使用名字和参数来调用函数。使用 -> 来指定函数返回值的类型 func greet(person:String, day:String) -> String { return "Hello \(person), today is \(day)." } greet(person: "Bob", day: "Tuesday") // 使用元组来让一个函数返回多个值,该元组的元素可以用名称或数字来表示 func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0] var max = scores[0] var sum = 0 for score in scores { if score > max { max = score } else if score < min { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9]) print(statistics.min) print(statistics.2) // 可变个数的参数,这些参数在函数内表现为数组的形式 func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum; } sumOf() sumOf(numbers: 42, 456, 12) // 函数可以嵌套。被嵌套的函数可以访问外侧函数的变量,可以使用嵌套函数来重构一个太长或者太复杂的函数 (ps: 感觉类似于OC中的block) func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() // 函数可以作为一个函数的返回值 let a = 10 func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) // 函数可以作为一个函数的参数 func hasAnyMatches(list: [Int], condition:(Int)->Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(list: numbers, condition: lessThanTen) // 类 //:
Java
UTF-8
1,533
2.078125
2
[]
no_license
package com.michael.qrcode.qrcode.camera; import android.graphics.Point; import android.graphics.Rect; import android.hardware.Camera; import android.util.Log; import com.michael.qrcode.qrcode.decode.Decoder; import com.michael.qrcode.qrcode.scan.BarcodeScanner; /** * Created with IntelliJ IDEA. * User: di.zhang * Date: 13-12-9 * Time: 下午2:38 * To change this template use File | Settings | File Templates. */ final class PreviewCallback implements Camera.PreviewCallback { private static final String TAG = PreviewCallback.class.getSimpleName(); private static final boolean DEBUG = true & BarcodeScanner.DEBUG; private CameraManager mCameraManager; private CameraConfiguration mConfigManager; private Decoder mDecoder; PreviewCallback(CameraManager cameraManager, CameraConfiguration configManager, Decoder decodeThread) { mCameraManager = cameraManager; mConfigManager = configManager; mDecoder = decodeThread; } @Override public void onPreviewFrame(byte[] bytes, Camera camera) { Point cameraResolution = mConfigManager.getCameraResolution(); Rect rectInPreview = mCameraManager.getFramingRectInPreview(); if (cameraResolution != null && mDecoder != null && rectInPreview != null) { mDecoder.decode(bytes, cameraResolution.x, cameraResolution.y, rectInPreview); } else { if (DEBUG) Log.d(TAG, "Got preview callback, but no handler or resolution available"); } } }
Markdown
UTF-8
3,305
2.796875
3
[]
no_license
--- layout: post title: november meeting news date: 2021-11-29 19:00:00 description: news from our November 2021 Meeting. --- A simple evening for us, and the last of the year/season. Having had the presentation, a couple of competitions, the results of the years competition winners will be announced in the January Meeting. With the new restrictions and a new variant, the face to face meetings are still up in the air. Again we will need to play it by ear, we shall review in the New Year and see how it pans out figures and if we end up in lock down again... I hope not and can't wait for face to face meetings. On this we will keep you posted. Focus point for the evening was - 'Look for Details'. This is a subject we have covered previously, however it doesn't hurt to go over these things again. Looking at 5 tips to help you look into the details, what to look for, I hope these help you to bring more focus to your images, rather than normal holiday snaps. Full details of this will be in the members newsletter. *Members receive a copy of the presentation in the club newsletter.* <br> <hr> <br> The ‘Monthly Competition’ entitled *'Fireworks and Sparklers'* was held. The winners were:- <ul> <li>1st - 'Lighting up the Sky' by Joan Banks</li> <li>2nd - 'Pour Me a Glass of Sparkle' - by Julie Beddow</li> <li>3rd - 'The Triple' by Graham Welsby</li> </ul> <br> <div class="img_row"> <img class="col three" src="{{ site.baseurl }}/assets/img/Nov21 - Monthly/01 - Lighting up the sky.jpg"> </div> <div class="col three caption"> 'Lighting up the Sky' by Joan Banks </div> <br> <br> <div class="img_row"> <img class="col two" src="{{ site.baseurl }}/assets/img/Nov21 - Monthly/02 - pour me a glass of sparkle.jpg"> <img class="col one" src="{{ site.baseurl }}/assets/img/Nov21 - Monthly/07 - The Triple.jpg"> </div> <!-- <div class="img_row_sm"> <img class="col three" src="{{ site.baseurl }}/assets/img/May21_Monthly/16 - Tree Lines.jpg"> </div> --> <div class="col three caption"> Some of these images have been cropped for a better fit for the website. </div> <br> <hr> <br> The 'Lancaster Memorial Competition’ entitled *'People at Large'* was held. <ul> <li>1st - 'It's been a Hard Day' by John Horton</li> <li>2nd - 'Christmas Market' - by Judy Moore</li> <li>3rd - 'P1040693' - by Marg Hazeldine</li> </ul> <br> <div class="img_row"> <img class="col three" src="{{ site.baseurl }}/assets/img/Nov21 - Lancaster/11 - Its been a hard day.jpg"> </div> <div class="col three caption"> 'It's been a Hard Day' by John Horton </div> <br> <br> <div class="img_row"> <img class="col two" src="{{ site.baseurl }}/assets/img/Nov21 - Lancaster/06 - Christmas Market.jpg"> <img class="col one" src="{{ site.baseurl }}/assets/img/Nov21 - Lancaster/03 - P1040693.jpg"> </div> <!-- <div class="img_row_sm"> <img class="col three" src="{{ site.baseurl }}/assets/img/May21_Monthly/16 - Tree Lines.jpg"> </div> --> <div class="col three caption"> Some of these images have been cropped for a better fit for the website. </div> <br> <hr> <br> ### NEXT MEETING <br> The Programme is still being constructed, and we will get it published ASAP. This will include the full years activities and competitions. <br> #### Members receive full details via Email and BEFORE they are posted here...
C++
UTF-8
1,347
3.09375
3
[]
no_license
#include <iostream> #include <string> #include <stdio.h> using namespace std; int main() { //freopen("input.txt", "r", stdin); char word[25], empty[25]; string s = ""; scanf("%[^A-Za-z]", empty); while(scanf("%[A-Za-z]", word) != EOF) { scanf("%[^A-Za-z]", empty); //printf("%s\n", word); s = string(word) + " " + s; } cout << s.substr(0, s.length() - 1) << endl; return 0; } /* // 解法2 #include <iostream> #include <string> #include <vector> #include <stdio.h> using namespace std; int main() { //freopen("input.txt", "r", stdin); char word[25], empty[25]; string s = ""; while(getline(cin, s)) { string temp = ""; vector<string> vec_w; for(int i = 0; i < s.length(); i ++) { if((s[i] <= 'Z' && s[i] >= 'A') || (s[i] <= 'z' && s[i] >= 'a')) temp += s[i]; else { if(temp.length() > 0) { vec_w.push_back(temp); temp = ""; } } } if(temp.length() > 0) vec_w.push_back(temp); if(vec_w.size() == 0) continue; for(int i = vec_w.size() - 1; i > 0; i --) cout << vec_w[i] << " "; cout << vec_w[0] << endl; } return 0; } */
Java
UTF-8
833
2.34375
2
[]
no_license
package org.sirius.transport.api.channel; import java.util.List; import org.sirius.transport.api.UnresolvedAddress; /* * 管理具有相同地址的{@link Channel} */ public interface ChannelGroup { UnresolvedAddress remoteAddress(); UnresolvedAddress localAddress(); void setLocalAddress(UnresolvedAddress local); List<Channel> channels(); Channel next(); boolean add(Channel c); boolean isEmpty(); int getWeight(); void setWeight(int weight); public int getEffectiveWeight(); public void setEffectiveWeight(int effectiveWeight); public int getCurrentWeight(); public void setCurrentWeight(int currentWeight) ; boolean remove(Channel c); int size(); int getCapacity(); void setCapacity(int capacity); }
TypeScript
UTF-8
1,549
2.5625
3
[]
no_license
import jwt from "jsonwebtoken"; import errHandler from "./errHandler"; import fs from 'fs' export async function jwtSignIn(objPayload, objOption) { try { /**Dev mode */ //let strKey = await fs.readFileSync(__dirname + '/config/private.key', 'utf-8'); /**Prod Mode */ let strKey = await fs.readFileSync('./config/private.key', 'utf-8'); let objOptions = await { issuer: objOption["issuer"], subject: objOption["subject"], audience: objOption["audience"], algorithm: "RS256" }; let strToken = await jwt.sign(objPayload, strKey, objOptions); return strToken; } catch (error) { throw new errHandler(error); } } export async function jwtVerify(strToken, objOption) { try { /**Dev mode */ //let strKey = await fs.readFileSync(__dirname + '/config/public.key', 'utf-8'); /**Prod Mode */ let strKey = await fs.readFileSync('./config/public.key', 'utf-8'); let objOptions = { issuer: objOption["issuer"], subject: objOption["subject"], audience: objOption["audience"], algorithm: 'RS256', expiresIn: '300d' }; return jwt.verify(strToken, strKey, objOptions) } catch (error) { if (error["name"] == "JsonWebTokenError") { throw new errHandler("INVALID_TOKEN") } throw new errHandler(error); } } /** * @param token jwt token passing */ export async function jwtDecode(strToken) { try { return jwt.decode(strToken, { complete: true }); } catch (error) { throw new errHandler(error); } }
Python
UTF-8
2,213
2.53125
3
[]
no_license
from flask import request from flask_restx import Resource from app.main.service.menu_service import MenuService from app.main.util.decorator import owner_token_required from app.main.util.dto import MenuDto api = MenuDto.api _create_menu = MenuDto.add_menu _update_menu = MenuDto.update_menu _get_menu = MenuDto.get_menu @api.route('/') class MenuList(Resource): @owner_token_required @api.doc('add_menu') @api.response(201, 'Menu successfully added') @api.expect(_create_menu, validate=True) def post(self): """ Add a restaurant menu """ return MenuService.add_menu(data=request.json) @api.route('/<id>') @api.doc(params={'id': 'An ID'}) class Menu(Resource): @owner_token_required @api.doc('get_an_existing_menu') @api.marshal_with(_get_menu) def get(self, id): """ Get an existing restaurant menu """ print('I was executed') return MenuService.get_menu(id=id) @owner_token_required @api.doc('update_an_existing_menu') @api.response(200, 'Menu successfully updated') @api.response(404, 'Menu not found') @api.expect(_update_menu, validate=True) def put(self, id): """ Update an existing restaurant menu """ return MenuService.update_menu(id=id, data=request.json) @owner_token_required @api.doc('delete_an_existing_menu') @api.response(200, 'Menu successfully deleted') @api.response(404, 'Menu not found') def delete(self, id): """ Delete an existing restaurant menu """ return MenuService.delete_menu(id=id) @api.route('/multiple') class AddMultipleMenu(Resource): @api.doc('app_multiple_menus') @api.response(201, 'Menu successfully added') @api.expect([_create_menu], validate=True) def post(self): """ Add multiple menu items """ return MenuService.add_multiple_menu(data=request.json) @api.route('/check/<menu_name>') class CheckMenu(Resource): @owner_token_required @api.doc('check_menu') def get(self, menu_name): """ Check if menu exists """ return MenuService.check_menu(menu_name)
C++
UTF-8
3,919
2.703125
3
[]
no_license
#include "include/Model/ConsoleModel.h" ConsoleModel::ConsoleModel(QSettings *settings, QObject *parent): QAbstractTableModel(parent), m_settings(settings){ this->reload(); if(m_consoles.size() == 0){ this->defaultInit(); } } ConsoleModel::~ConsoleModel(){ for(QList<Console*>::iterator i=m_consoles.begin();i != m_consoles.end();++i){ delete *i; } } int ConsoleModel::rowCount(const QModelIndex &parent) const{ if(parent.isValid()){ return 0; } return m_consoles.size(); } int ConsoleModel::columnCount(const QModelIndex &parent) const{ if(parent.isValid()){ return 0; } return 2; } QVariant ConsoleModel::data(const QModelIndex &index, int role) const{ if(!index.isValid()){ return QVariant(); } QString *c = (QString*)index.internalPointer(); if(role == Qt::DisplayRole){ if(index.column() == 0){ return QVariant(*c); }else if(index.column() == 1){ return QVariant(*c); } } return QVariant(); } void ConsoleModel::defaultInit(){ #ifdef _WIN32 Console *c = new Console("cmd", "cmd.exe"); m_consoles.append(c); #elif __linux__ qDebug() << "linux"; m_consoles.append(new Console("terminal", "terminal")); #endif this->valider(); } QModelIndex ConsoleModel::index(int row, int column, const QModelIndex &parent) const{ if(!(row < m_consoles.size())){ return QModelIndex(); } if(!parent.isValid()){ if(column == 0){ return createIndex(row,column,&m_consoles[row]->name); }else if (column == 1){ return createIndex(row,column,&m_consoles[row]->cmd); } } return QModelIndex(); } QVariant ConsoleModel::headerData(int section, Qt::Orientation orientation, int role) const{ if(orientation == Qt::Horizontal && role == Qt::DisplayRole){ if(section == 0){ return QVariant("nom"); }else if(section == 1){ return QVariant("commande de lancement"); } } return QVariant(); } bool ConsoleModel::addConsole(QString name, QString cmd){ QList<Console*>::iterator it; for(it = m_consoles.begin();it != m_consoles.end();++it){ if((*it)->name == name){ return false; } } emit beginInsertRows(QModelIndex(),m_consoles.size(),m_consoles.size()); m_consoles.append(new Console(name,cmd)); emit endInsertRows(); return true; } bool ConsoleModel::modify(int row, QString name, QString cmd){ for(int i = 0; i < m_consoles.size(); i++){ Console *c = m_consoles[i]; if(c->name == name && row != i){ return false; } } Console *c = m_consoles[row]; c->cmd = cmd; c->name = name; emit dataChanged(this->index(row,0),this->index(row,1)); return true; } void ConsoleModel::removeConsole(int row){ emit beginRemoveRows(QModelIndex(),row,row); Console *tmp = m_consoles[row]; this->m_consoles.removeAt(row); delete tmp; emit endRemoveRows(); } void ConsoleModel::valider(){ m_settings->beginGroup("Consoles"); QList<Console*>::iterator it; for(it = m_consoles.begin();it != m_consoles.end();++it){ m_settings->setValue((*it)->name,(*it)->cmd); } m_settings->endGroup(); } void ConsoleModel::reload(){ for(QList<Console*>::iterator i=m_consoles.begin();i != m_consoles.end();++i){ delete *i; } m_consoles.clear(); m_settings->beginGroup("Consoles"); QStringList keys = m_settings->allKeys(); for(int i = 0; i < keys.size(); i++){ m_consoles.append(new Console(keys[i], m_settings->value(keys[i],"noname").toString())); } m_settings->endGroup(); }
C++
UTF-8
3,413
2.5625
3
[ "MIT" ]
permissive
#include "jsonreader.h" #include "ifile.h" #include <boost/assert.hpp> #include "boost/algorithm/string/predicate.hpp" // namespace platform { namespace Json { bool GetStr( Json::Value const& V, std::string& O ) { if( !V.isString() ) { return false; } O = V.asString(); return !O.empty(); } bool GetUInt( Json::Value const& V, uint32_t& O ) { if( !V.isNumeric() ) { return false; } O = V.asUInt(); return true; } bool GetInt( Json::Value const& V, int32_t& O ) { if( !V.isNumeric() ) { return false; } O = V.asInt(); return true; } bool GetDouble( Json::Value const& V, double& O ) { if( !V.isNumeric() ) { return false; } O = V.asDouble(); return true; } bool GetFloat( Json::Value const& V, float& O ) { if( !V.isNumeric() ) { return false; } O = V.asDouble(); return true; } bool GetColor( Json::Value const& Color, int32_t& O ) { if( Json::GetInt( Color, O ) ) { return true; } std::string s; if( Json::GetStr( Color, s ) && ( O = strtoul( s.c_str(), NULL, 16 ) ) ) { size_t const h = s.find( 'x' ); if( ( s.size() <= 6 && h == std::string::npos ) || ( s.size() <= 8 && h == 1 ) ) { // make it rgba O = ( O << 8 ) | 0xff; } return true; } return false; } bool GetColor( Json::Value const& Color, glm::vec4& O ) { int32_t c; if( !GetColor( Color, c ) ) { return false; } O = glm::vec4( ( ( c & 0xff000000 ) >> 24 ) / 255., ( ( c & 0x00ff0000 ) >> 16 ) / 255., ( ( c & 0x0000ff00 ) >> 8 ) / 255., ( ( c & 0x000000ff ) ) / 255. ); return true; } bool GetBool( Json::Value const &V, bool& O) { int32_t i = 0; if (Json::GetInt( V, i )) { O = i != 0; return true; } std::string s = ""; if (Json::GetStr( V, s )) { O = !(boost::iequals( s, "false" ) || boost::iequals( s, "f" ) || boost::iequals( s, "0" ) || boost::iequals( s, "n" ) || boost::iequals( s, "no" )); return true; } return false; } bool Get( Value const& V, std::string& O ) { return GetStr( V, O ); } bool Get( Value const& V, uint32_t& O ) { return GetUInt( V, O ); } bool Get( Value const& V, int32_t& O ) { return GetInt( V, O ); } bool Get( Value const& V, double& O ) { return GetDouble( V, O ); } bool Get( Value const& V, float& O ) { return GetFloat( V, O ); } bool Get( Value const& V, bool& O ) { return GetBool( V, O ); } bool Get( Value const& V, glm::vec4& O ) { return GetColor( V, O ); } } // namespace Json namespace platform { JsonReader::JsonReader( File& F ) : mValid( false ) { Json::Reader Reader; std::string Contents; if( !F.ReadAll( Contents ) ) { return; } try { Json::Value target; if( !Reader.parse( Contents, target, false ) ) { BOOST_ASSERT( false ); } using namespace std; swap( target, mRoot ); mValid = true; } catch( std::runtime_error const& ) { } } bool JsonReader::IsValid() const { return mValid; } Json::Value& JsonReader::GetRoot() { return mRoot; } } // namespace platform
Java
UTF-8
4,784
2.09375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.lastaflute.core.json.adapter; import java.io.IOException; import java.util.function.Predicate; import org.lastaflute.core.json.JsonMappingOption; import org.lastaflute.core.json.filter.JsonUnifiedTextReadingFilter; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.internal.bind.TypeAdapters; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** * @author jflute */ public interface StringGsonAdaptable { // to show property path in exception message // =================================================================================== // Type Adapter // ============ class TypeAdapterString extends TypeAdapter<String> { protected final TypeAdapter<String> realAdapter = TypeAdapters.STRING; protected final Class<?> yourType; // not null protected final JsonMappingOption gsonOption; protected final JsonUnifiedTextReadingFilter readingFilter; // null allowed protected final Predicate<Class<?>> emptyToNullReadingDeterminer; // null allowed protected final Predicate<Class<?>> nullToEmptyWritingDeterminer; // null allowed public TypeAdapterString(JsonMappingOption gsonOption) { this.yourType = String.class; this.gsonOption = gsonOption; this.readingFilter = JsonUnifiedTextReadingFilter.unify(gsonOption); // cache as plain for performance this.emptyToNullReadingDeterminer = gsonOption.getEmptyToNullReadingDeterminer().orElse(null); // me too this.nullToEmptyWritingDeterminer = gsonOption.getNullToEmptyWritingDeterminer().orElse(null); // me too } @Override public String read(JsonReader in) throws IOException { final String read = filterReading(realAdapter.read(in)); if (read == null) { // filter makes it null return null; } if ("".equals(read) && isEmptyToNullReading()) { // option return null; } else { // mainly here return read; } } protected String filterReading(String text) { if (text == null) { return null; } return readingFilter != null ? readingFilter.filter(String.class, text) : text; } protected boolean isEmptyToNullReading() { return emptyToNullReadingDeterminer != null && emptyToNullReadingDeterminer.test(yourType); } @Override public void write(JsonWriter out, String value) throws IOException { if (value == null && isNullToEmptyWriting()) { // option out.value(""); } else { // mainly here realAdapter.write(out, value); } } protected boolean isNullToEmptyWriting() { return nullToEmptyWritingDeterminer != null && nullToEmptyWritingDeterminer.test(yourType); } } // =================================================================================== // Creator // ======= default TypeAdapterFactory createStringTypeAdapterFactory() { return TypeAdapters.newFactory(String.class, createTypeAdapterString()); } default TypeAdapterString createTypeAdapterString() { return newTypeAdapterString(getGsonOption()); } default TypeAdapterString newTypeAdapterString(JsonMappingOption gsonOption) { return new TypeAdapterString(gsonOption); } // =================================================================================== // Accessor // ======== JsonMappingOption getGsonOption(); }
Python
UTF-8
737
4.03125
4
[]
no_license
class Solution: def isPalindrome(self, x): a = [] if x < 0: return False else: while (x > 0): remainder = x % 10 x = x // 10 a.append(remainder) if a == a[::-1]: return True else: return False # 既然不能转化为String,1234那么千位上为1,百位上为2 这样切分一下 # 那么就需要取整和取余的操作 # # 123 / 10 = 12...3 # 那么个位数就有了 # # 12 / 10 = 1...2 # 那么百位数就有了 # # 1 / 10 = 0...1 # 那么千位数就有了 if __name__ == '__main__': sol = Solution() res = sol.isPalindrome(-121) print(res)
JavaScript
UTF-8
366
2.640625
3
[]
no_license
class Chain{ constructor(bodyA,bodyB){ var options={ bodyA: bodyA, bodyB:bodyB, stiffness:0.04, length:10 } this.chain=Constraint.create(options) World.add(world,chain) } display(){ var pointA=this.chain.bodyA.position var pointB=this.chain.bodyB.position strokeWeight(3) line(pointA.x,pointA.y,pointB.x,pointB.y) } }
C++
UTF-8
777
3.40625
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; class MyObj { int width; int height; float price; public: MyObj() { set(0, 0, 0); } MyObj(int w, int h, float p) { set(w, h, p); } void set(int w, int h, float p) { width = w; height = h; price = p; } void show() { cout << width << " " << height << " " << price << endl; } ~MyObj() { cout << "bye bye\n"; } }; int main() { MyObj *y[3] = { new MyObj, new MyObj(2, 3, 100.5), new MyObj(5, 6, 750.0)}; for (int i = 0; i < 3; i++) y[i]->show(); for (int i = 0; i < 3; i++) delete y[i]; }
Java
UTF-8
3,719
2.75
3
[]
no_license
/* * 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 model.dao.mySQLJDBCImpl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import model.mo.Admin; import model.dao.AdminDAO; import model.dao.exception.DuplicatedObjectException; import java.util.Random; /** * * @author Filippo */ public class AdminDAOMySQLJDBCImpl implements AdminDAO{ Connection conn; public AdminDAOMySQLJDBCImpl(Connection conn){ this.conn = conn; } Admin read(ResultSet rs){ Admin admin = new Admin(); try { admin.setId(rs.getLong("id")); } catch (SQLException sqle) { } try { admin.setFirstname(rs.getString("firstname")); } catch (SQLException sqle) { } try { admin.setLastname(rs.getString("lastname")); } catch (SQLException sqle) { } try { admin.setPassword(rs.getString("password")); } catch (SQLException sqle) { } try { admin.setDeleted(rs.getBoolean("deleted")); } catch (SQLException sqle) { } return admin; } @Override public Admin insert(String firstname, String lastname){ throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void update(Admin admin){ throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void delete(Admin admin){ throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public Admin findAdminById(Long id){ PreparedStatement ps; Admin admin = null; try { String sql = "SELECT * " + "FROM admin " + "WHERE " + "id = ? AND " + "deleted = '0' "; ps = conn.prepareStatement(sql); ps.setLong(1, id); ResultSet resultSet = ps.executeQuery(); if (resultSet.next()) { admin = read(resultSet); } resultSet.close(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } return admin; } @Override public Admin findAdminByIdAndName(String firstname, String lastname, Long id) { PreparedStatement ps; Admin admin = null; try { String sql = "SELECT * " + "FROM admin " + "WHERE " + "id = ? AND " + "firstname = ? AND " + "lastname = ? AND " + "deleted = '0' "; ps = conn.prepareStatement(sql); ps.setLong(1, id); ps.setString(2, firstname); ps.setString(3, lastname); ResultSet resultSet = ps.executeQuery(); if (resultSet.next()) { admin = read(resultSet); } resultSet.close(); ps.close(); } catch (SQLException e) { throw new RuntimeException(e); } return admin; } }
Rust
UTF-8
1,975
2.71875
3
[ "MIT", "NCSA" ]
permissive
use std::fmt; use libc; use llvm_sys::prelude::*; use llvm_sys::core as llvm; use super::*; // No `Drop` impl is needed as this is disposed of when the associated context is disposed #[derive(Debug)] pub struct Module { pub ptr: LLVMModuleRef } impl_llvm_ref!(Module, LLVMModuleRef); impl Module { pub fn dump(&self) { unsafe { llvm::LLVMDumpModule(self.ptr) } } pub fn add_function(&mut self, func_ty: LLVMTypeRef, name: &str) -> Function { let c_name = CString::new(name).unwrap(); let p = unsafe { llvm::LLVMAddFunction(self.ptr, c_name.as_ptr(), func_ty) }; Function { ptr: p } } pub fn get_named_function(&mut self, name: &str) -> Option<Function> { let c_name = CString::new(name).unwrap(); let res = unsafe { llvm::LLVMGetNamedFunction(self.ptr, c_name.as_ptr()) }; if res.is_null() { None } else { Some(Function::from_value_ref(res)) } } pub fn print_to_file(&self, path: &str) -> Result<(), &'static str> { let c_path = CString::new(path).unwrap(); let mut em: usize = 0; let em_ptr: *mut usize = &mut em; unsafe { llvm::LLVMPrintModuleToFile(self.ptr, c_path.as_ptr(), em_ptr as *mut *mut i8); if em == 0 { // no error message was set Ok(()) } else { Err(c_str_to_str!(em as *const i8)) } } } } impl fmt::Display for Module { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { let c_str = llvm::LLVMPrintModuleToString(self.ptr); let len = libc::strlen(c_str); let s = String::from_raw_parts( c_str as *mut u8, (len + 1) as usize, (len + 1) as usize ); write!(f, "{}", s) } } }