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
TypeScript
UTF-8
539
2.625
3
[]
no_license
import { useState, useEffect } from 'react' export function useDimensions() { function getWindowDimensions() { return { width: window.innerWidth, height: window.innerHeight } } const [dimensions, setDimensions] = useState(getWindowDimensions()) useEffect(() => { function updateWindowDimensions() { setDimensions(getWindowDimensions()) } window.addEventListener('resize', updateWindowDimensions) return () => window.removeEventListener('resize', updateWindowDimensions) }, []) return dimensions }
JavaScript
UTF-8
300
3.8125
4
[]
no_license
/** * Write a JavaScript program to * replace every character in a given string * with the character following it in the alphabet */ const moveChars = (str) => str .split("") .map((char) => String.fromCharCode(char.charCodeAt(0) + 1)) .join(""); console.log(moveChars("amdfj"));
C#
UTF-8
442
2.546875
3
[ "MIT" ]
permissive
using System; using System.Reflection; namespace Explosuress { internal class FieldAdapter : FieldOrPropertyAdapter { private readonly FieldInfo _field; public FieldAdapter(FieldInfo field) { _field = field ?? throw new ArgumentNullException(nameof(field)); } public override object? GetValue(object? obj) { return _field!.GetValue(obj); } } }
Swift
UTF-8
1,799
2.78125
3
[]
no_license
// // Database.swift // DailyHub // // Created by Joe Salter on 4/3/17. // Copyright © 2017 Luke Petruzzi. All rights reserved. // import Foundation import AWSS3 import AWSDynamoDB import AWSSQS import AWSSNS import AWSCognito class Database { class func getDatabaseInfo(completionHandler:@escaping (String?, NSError?) -> ()) { let dynamodb = AWSDynamoDB.default() let req = AWSDynamoDBGetItemInput() req?.tableName = "MainStorageFeed" let value:AWSDynamoDBAttributeValue = AWSDynamoDBAttributeValue() // this needs to be the current date in ISO value.s = getFormattedESTDate() req?.key = ["Date":value] dynamodb.getItem(req!).continueWith { (task) -> Any? in if task.error != nil { completionHandler(nil, task.error as NSError?) return nil } let output = task.result!.item completionHandler(output?.values.first?.s, nil) return nil } } class func getFormattedESTDate() -> String{ let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "yyyy-MM-dd" return formatter.string(from: Date()) } class func getFormattedESTDateAndTime() -> String{ let formatter = DateFormatter() formatter.calendar = Calendar(identifier: .iso8601) formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.dateFormat = "yyyy-MM-dd HH:mm:ss:SSSS" return formatter.string(from: Date()) } }
Python
UTF-8
2,030
2.90625
3
[]
no_license
#Text Extractor Service By Ganesh Ghag import re import nltk from nltk.corpus import stopwords stop = stopwords.words('english') def extract_phone_numbers(string): r = re.compile(r'(\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4})') phone_numbers = r.findall(string) return [re.sub(r'\D', '', number) for number in phone_numbers] def extract_email_addresses(string): r = re.compile(r'[\w\.-]+@[\w\.-]+') return r.findall(string) def extract_dates(in1): r1 = re.compile(r'\d{4}[- /.]\d{2}[- /.]\d{2}') r2 = re.compile(r'\d{2}[- /.]\d{2}[- /.]\d{4}') return r1.findall(in1) + r2.findall(in1) def extract_DecimalAmounts(in1): r = re.compile(r'[0-9]\d*,?\d*,?\d*,?\d*.?\d*') return r.findall(in1) def ie_preprocess(document): document = ' '.join([i for i in document.split() if i not in stop]) sentences = nltk.sent_tokenize(document) sentences = [nltk.word_tokenize(sent) for sent in sentences] sentences = [nltk.pos_tag(sent) for sent in sentences] return sentences def extract_names(document): names = [] sentences = ie_preprocess(document) for tagged_sentence in sentences: for chunk in nltk.ne_chunk(tagged_sentence): if type(chunk) == nltk.tree.Tree: if chunk.label() == 'PERSON': names.append(' '.join([c[0] for c in chunk])) return names def extract_all(input): return [extract_email_addresses(input), extract_phone_numbers(input),extract_dates(input),extract_DecimalAmounts(input), extract_names(input)] #Web app Flask related code starts here >>>>>>>>>>>>>>>>>>>>>>> import json from flask import jsonify from flask import Flask from flask import request app = Flask(__name__) #Sample CURL command as input: curl -X POST --data-binary "@sampletext1.txt" http://127.0.0.1:5000/ @app.route('/',methods = ['POST']) def index(): s = extract_all(request.get_data(as_text=True)) return jsonify(s) if __name__ == '__main__': app.run(debug=True)
Java
UTF-8
426
3.359375
3
[]
no_license
public class CarLambda{ public static void main(String [] args){ Car basicCar = () -> { return " Adding features of "; }; Car sportsCar = () -> basicCar.assemble() + "Sports Car."; System.out.println(sportsCar.assemble()); System.out.println("\n*****"); Car sportsLuxuryCar = () -> basicCar.assemble() + " Luxury Car." + sportsCar.assemble() ; System.out.println(sportsLuxuryCar.assemble()); } }
Java
UTF-8
305
1.984375
2
[]
no_license
package it.solvingteam.course.olimpiadinfinite.dto.messages; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; public class SportDto { @NotNull(message = "The id doesn't exist!") private Long id; @NotEmpty(message = "Required field") private String name; }
Python
UTF-8
2,099
2.8125
3
[]
no_license
import sys import cv2 import numpy as np def cropBorder(srcLength, dstLength): center = srcLength//2 half = divmod(dstLength, 2) begin = center - half[0] end = center + half[0] if half[1]: end += 1 return begin, end def isOut(radius, thickness, limit): graphBorder = radius + thickness/2 if graphBorder > limit or graphBorder < 0: return True else: return False # Zoom in increment fastIncrement = lambda v, t: np.tan(v*t) slowIncrement = lambda v, t: np.tan(v*t)/3 videoParam = {"size": (1024, 1024), "outSize": (512, 512),"time": 15, "fps": 30} outFileName = str( sys.argv[1] ) fourcc = cv2.VideoWriter_fourcc(*'MJPG') out = cv2.VideoWriter(outFileName, fourcc, videoParam["fps"], videoParam["outSize"]) verticalCropPoint = cropBorder(videoParam["size"][0], videoParam["outSize"][0]) horizontalCropPoint = cropBorder(videoParam["size"][1], videoParam["outSize"][1]) # Increment velocity here marker = {"type": cv2.MARKER_SQUARE, "position": (512, 512), "initialSize": 51, "initialThickness": 2, "brigntness": 250, "velocity": 0.012} shortestLenhth2border = min(videoParam["size"][0]-marker["position"][0], marker["position"][0], videoParam["size"][1]-marker["position"][1], marker["position"][1]) for t in range(0, videoParam["time"]*videoParam["fps"]): img = np.zeros(videoParam["size"], dtype=np.uint8) if t == 0: size = marker["initialSize"] thic = marker["initialThickness"] else: # Increase tan(v*t) size += fastIncrement(marker["velocity"], t) thic += slowIncrement(marker["velocity"], t) if isOut(size, thic, shortestLenhth2border): print("Warning: Graph is out of border. Interrupted.") break cv2.drawMarker(img, marker["position"], marker["brigntness"], marker["type"], int(size), int(thic)) outImg = img[verticalCropPoint[0]:verticalCropPoint[1], horizontalCropPoint[0]:horizontalCropPoint[1]] out.write(cv2.cvtColor(outImg, cv2.COLOR_GRAY2BGR)) cv2.imshow("test", outImg) cv2.waitKey(100) out.release() cv2.destroyAllWindows()
Java
UTF-8
74
1.679688
2
[]
no_license
package com.haubui.common; public enum Operator { SUM,SUB,MUL,DIV,MOD }
Python
UTF-8
8,059
2.828125
3
[]
no_license
import math import os import random import string script_dir = os.path.dirname(__file__) def get_max_hp(class_name): if class_name in ['Berserker']: return(12) elif class_name in ['Fighter', 'Paladin', 'Dark Knight', 'Battlemaster']: return(10) elif class_name in ['Barbarian', 'Cleric', 'Ranger', 'Monk', 'Hunter', 'Vampire', 'Skirmisher', 'Slayer']: return(8) elif class_name in ['Bard', 'Druid', 'Thief', 'Trickster', 'Shaman']: return(6) else: return(4) def get_damage_die(class_name): if class_name in ['Barbarian', 'Fighter', 'Paladin', 'Dark Knight', 'Berserker', 'Channeler', 'Slayer']: return('d10') elif class_name in ['Immolator', 'Ranger', 'Thief', 'Monk', 'Hunter', 'Vampire', 'Battlemaster']: return('d8') elif class_name in ['Bard', 'Cleric', 'Druid', 'Trickster', 'Shaman', 'Skirmisher']: return('d6') else: #wizard, necromancer return('d4') class character: def __init__(self, id = "", name = "Jim", class_name = "Wizard", level = 1, attribute = {'str': 10, 'dex': 10, 'con': 10, 'int': 10, 'wis': 10, 'cha': 10}): self.name = name self.class_name = class_name self.level = level self.attribute = attribute self.id = id self.max_hp = get_max_hp(class_name) self.damage_die = get_damage_die(class_name) self.advanced_moves = [] self.level_1_spells = "" self.level_3_spells = "" self.level_5_spells = "" self.level_7_spells = "" self.level_9_spells = "" def skill_use(self, governing_attribute): return(roll('2d6', get_modifier(self.attribute[governing_attribute]))) def damage_roll(self): return(roll(self.damage_die)) def update(self, new_data): parsable_data = new_data.splitlines() self.name = parsable_data[0].split(" the ")[0] self.class_name = (parsable_data[0].split(" the ")[1]).split(", ")[0] self.level = int(parsable_data[0].split(" Level ")[1]) # will clean these up eventually, hopefully, anyway self.attribute['str'] = int((parsable_data[2][5:7]).strip()) self.attribute['dex'] = int((parsable_data[3][5:7]).strip()) self.attribute['con'] = int((parsable_data[4][5:7]).strip()) self.attribute['int'] = int((parsable_data[5][5:7]).strip()) self.attribute['wis'] = int((parsable_data[6][5:7]).strip()) self.attribute['cha'] = int((parsable_data[7][5:7]).strip()) self.max_hp = get_max_hp(self.class_name) + self.attribute['con'] self.damage_die = get_damage_die(self.class_name) self.advanced_moves = parsable_data[10][15:].split(", ") if self.class_name in ['Wizard']: self.level_1_spells = parsable_data[14][9:] try: self.level_3_spells = parsable_data[15][9:] self.level_5_spells = parsable_data[16][9:] self.level_7_spells = parsable_data[17][9:] self.level_9_spells = parsable_data[18][9:] except: pass def pull_attributes(self): return([self.attribute['str'], self.attribute['dex'], self.attribute['con'], self.attribute['int'], self.attribute['wis'], self.attribute['cha']]) def full_output(self): full_text_output = str(self.name + " the " + self.class_name + ", Level " + str(self.level) + "\n----------------------------------" + "\nSTR: " + str(self.attribute['str']) + " (" + str(get_modifier(self.attribute['str'])) + ")" + "\nDEX: " + str(self.attribute['dex']) + " (" + str(get_modifier(self.attribute['dex'])) + ")" + "\nCON: " + str(self.attribute['con']) + " (" + str(get_modifier(self.attribute['con'])) + ")" + "\nINT: " + str(self.attribute['int']) + " (" + str(get_modifier(self.attribute['int'])) + ")" + "\nWIS: " + str(self.attribute['wis']) + " (" + str(get_modifier(self.attribute['wis'])) + ")" + "\nCHA: " + str(self.attribute['cha']) + " (" + str(get_modifier(self.attribute['cha'])) + ")" + "\n----------------------------------" + "\nMax HP: " + str(self.max_hp) + " | Damage Die: " + self.damage_die + "\nAdvanced Moves: " + ", ".join(self.advanced_moves) ) if self.class_name in ['Wizard']: full_text_output += ("\n----------------------------------" + "\nLEARNED SPELL LIST" + "\nCantrips: Light, Prestidigitation, Unseen Servant" "\nLevel 1: " + self.level_1_spells ) if self.level >= 3: full_text_output += "\nLevel 3: " + self.level_3_spells if self.level >= 5: full_text_output += "\nLevel 5: " + self.level_5_spells if self.level >= 7: full_text_output += "\nLevel 7: " + self.level_7_spells if self.level >= 9: full_text_output += "\nLevel 9: " + self.level_9_spells return(full_text_output) def roll(dice = '2d6', modifier = 0): try: # gonna be for throwing just 'd8' or whatever in there number_of_dice = int(dice.split("d")[0]) sides_of_dice = int(dice.split("d")[1]) except: number_of_dice = 1 sides_of_dice = int(dice[1:]) rolls = random.sample(range(1, sides_of_dice+1), number_of_dice) result = sum(rolls) + modifier return(result) def get_modifier(attribute): if attribute <= 3: return(-3) elif attribute <= 5: return(-2) elif attribute <= 8: return(-1) elif attribute <= 11: return(0) elif attribute <= 15: return(1) elif attribute <= 17: return(2) else: return(3) def create(id = "", random_creation = False, attributes = {'str': 16, 'dex': 15, 'con': 13, 'int': 12, 'wis': 9, 'cha': 8}, name = 'Jim', class_name = 'Fighter', level = 1): if random_creation == True: attributes = {'str': roll('3d6'), 'dex': roll('3d6'), 'con': roll('3d6'), 'int': roll('3d6'), 'wis': roll('3d6'), 'cha': roll('3d6')} else: pass if id == "": #for whenever nothing is passing an ID to it, it'll instead generate one string_junk = string.ascii_letters + string.digits for _ in range(6): id += random.choice(string_junk) new_character = character(id, name, class_name, level, attributes) print(new_character.full_output()) save(new_character) def load(id="", name="Jim", class_name="Wizard"): #loads from text file pc_list = os.listdir('pc/') if id != "": for i, elem in enumerate(pc_list): if id in elem: index_id = i elif (name + class_name != ""): for i, elem in enumerate(pc_list): if (name + class_name) in elem: index_id = i else: return("broken missing etc") with open("pc/" + pc_list[index_id], "r") as file: loaded_char = character() loaded_char.update(file.read()) return(loaded_char) def save(char): #saves to text file savedir = "pc" # if playercharacter == True else "npc" fileFull = os.path.join(script_dir, savedir, char.name + char.class_name + '-' + char.id + ".txt") full_save_output = char.full_output() with open(fileFull, "w+") as file: file.write(full_save_output) def main(): # test_file = open("testchar.txt", "r").read() # current_character = character() # current_character.update(test_file) # save(current_character) current_char = load() if __name__ == "__main__": main()
PHP
UTF-8
297
2.65625
3
[ "MIT" ]
permissive
<?php class slink { public static function to($link) { $locale = slang::get(); $string = $locale."/".$link; if (Request::secure()) { return secure_asset($string); } else { return asset($string); } } public static function path($link) { return asset($link); } }
Java
UTF-8
1,573
2.0625
2
[]
no_license
package com.frankgreen.apdu.command; import com.acs.smartcard.Reader; import com.acs.smartcard.ReaderException; import com.frankgreen.NFCReader; import com.frankgreen.apdu.OnGetResultListener; import com.frankgreen.apdu.Result; import com.frankgreen.task.BaseParams; /** * Created by kevin on 5/27/15. */ public class UID extends Base<BaseParams> { private boolean sendPlugin = true; public boolean isSendPlugin() { return sendPlugin; } public void setSendPlugin(boolean sendPlugin) { this.sendPlugin = sendPlugin; } public UID(BaseParams params) { super(params); } public boolean run() { byte[] sendBuffer = new byte[]{(byte) 0xFF, (byte) 0xCA, (byte) 0x0, (byte) 0x0, (byte) 0x0}; byte[] receiveBuffer = new byte[16]; Result result = Result.buildSuccessInstance("UID"); NFCReader reader = this.getParams().getReader(); int byteCount = 0; try { byteCount = reader.getReader().transmit(this.getParams().getSlotNumber(), sendBuffer, sendBuffer.length, receiveBuffer, receiveBuffer.length); result = new Result("UID", byteCount, receiveBuffer); reader.getChipMeta().setUID(result.getData()); } catch (ReaderException e) { result = new Result("UID", e); } result.setSendPlugin(this.isSendPlugin()); if (this.getParams().getOnGetResultListener() != null) { this.getParams().getOnGetResultListener().onResult(result); } return result.isSuccess(); } }
Java
UTF-8
840
3.578125
4
[ "MIT" ]
permissive
package recursionProblems; import java.util.Scanner; public class MaxofAnArray { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter n"); int n=sc.nextInt(); int index; int[] arr=new int[n]; for(index=0;index<n;index++) { arr[index]=sc.nextInt(); } int max=maxElement(arr,0); System.out.println(max); } private static int maxElement(int[] arr, int i) { int max=0; int prev=0; if(arr.length==1) { return arr[0]; } if(i==arr.length) { return max; } max=maxElement(arr,i+1); if(i>0) prev=arr[i-1]; if(max>prev&&max>arr[arr.length-1]) { //System.out.print(arr[arr.length-1]); return max; } else { if(prev>arr[arr.length-1]) { return prev; } else { return arr[arr.length-1]; } } } }
PHP
UTF-8
1,454
2.90625
3
[]
no_license
<?php /** * Created by IntelliJ IDEA. * User: luthfi * Date: 2/23/16 * Time: 12:09 AM */ namespace Model; use Exception; use DateTime; class Comment extends Model { private $table = "comments"; private $userModel; public function __construct() { parent::__construct(); $this->userModel = new User(); } public function addComment($comment) { $id = $this->database->insert($this->table,$comment); if ($id) { return $this->getById($id); } else { throw new Exception("failed"); } } public function getById($id) { $comment = $this->database->get($this->table,"*",["id"=>$id]); $dateTime = new DateTime($comment["time"]); $comment["time"] = $dateTime->getTimestamp()*1000; $comment['user'] = $this->userModel->getById($comment['user_id']); unset($comment['user_id']); return $comment; } public function getByPost($post_id) { $comments = []; foreach ($this->database->select($this->table, "*", ["post_id" => $post_id, "ORDER" => "id DESC"]) as $comment) { $dateTime = new DateTime($comment["time"]); $comment["time"] = $dateTime->getTimestamp()*1000; $comment['user'] = $this->userModel->getById($comment['user_id']); unset($comment['user_id']); $comments[] = $comment; } return $comments; } }
C++
UTF-8
709
3.0625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int main(int argc, char *argv[]) { char str[300]; cin >> str; int len = strlen(str); bool flag = false; for (int i = 0; i < len; ++ i) { if (i + 2 < len) { if (str[i] == 'W' && str[i+1] == 'U' && str[i+2] == 'B') { i += 2; if (flag) cout << " "; flag = false; } else { flag = true; cout << str[i]; } } else { flag = true; cout << str[i]; } } cout << endl; return 0; }
Java
UTF-8
6,009
2.875
3
[ "Apache-2.0" ]
permissive
package org.g4.certificate.utilities; import org.junit.Test; import org.junit.Before; import org.junit.After; import java.io.*; import java.util.List; import static org.junit.Assert.*; /** * Unit test for FileUtil * * @author Johnson Jiang * @version 1.0 * @since 1.0 */ public class FileUtilTest { String rootFolder; String helloWorldFile = "helloworld.txt"; @Before public void setUp() { rootFolder = FileUtil.getJarCurrentPath() + "CGA_TEST\\"; String helloWorld = "Hello World"; try { File dir = new File(rootFolder); if (!dir.exists()) { dir.mkdir(); } File f = new File(rootFolder + helloWorldFile); if (!f.exists()) f.createNewFile(); FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter(fw); pw.append(helloWorld); pw.flush(); pw.close(); } catch (Exception e) { fail("Errors happen when trying to create folders and files"); } } @Test public void createFile() { String tempStr = "test create file"; FileUtil.createFile(new ByteArrayInputStream(tempStr.getBytes()), rootFolder + "myTemp.txt"); File f = new File(rootFolder + "myTemp.txt"); assertTrue(f.exists() && f.isFile()); assertEquals("test create file", readFile(rootFolder + "myTemp.txt")); String myFile1 = rootFolder + "myFile1.txt"; boolean rtn = FileUtil.createFile(rootFolder + helloWorldFile, myFile1); assertTrue(rtn); File ff = new File(myFile1); assertTrue(ff.exists() && ff.isFile()); assertEquals("Hello World", readFile(myFile1)); } @Test public void createDir() { String dir = rootFolder + "testFolder1"; boolean rtn = FileUtil.createDir(dir); assertTrue(rtn); File f = new File(dir); assertTrue(f.exists() && f.isDirectory()); rtn = FileUtil.createDir(rootFolder + File.separator + "aaa" + File.separator + "bbb"); assertFalse(rtn); } @Test public void deleteDir() { String folder2 = rootFolder + "testFolder2"; String folder3 = rootFolder + "testFolder2" + File.separator + "testFolder3"; String folder4 = rootFolder + "testFolder2" + File.separator + "testFolder4"; FileUtil.createDir(folder2); FileUtil.createDir(folder3); FileUtil.createDir(folder4); boolean rtn = FileUtil.deleteDir(folder2); assertTrue(rtn); File f = new File(folder2); assertFalse(f.exists()); } @Test public void deleteFile() { String tempStr = "test create file"; String myDelFile = rootFolder + "myDelFile.txt"; FileUtil.createFile(new ByteArrayInputStream(tempStr.getBytes()), myDelFile); File f = new File(myDelFile); assertTrue(f.exists()); boolean rtn = FileUtil.deleteFile(myDelFile); assertTrue(rtn); File delFile = new File(myDelFile); assertFalse(delFile.exists()); } @Test public void getFileNameList() { String testFolder = rootFolder + "fileNameList"; FileUtil.createDir(testFolder); FileUtil.createFile(rootFolder + helloWorldFile, testFolder + File.separator + "a.txt"); FileUtil.createFile(rootFolder + helloWorldFile, testFolder + File.separator + "b.txt"); List<String> fileNameList = FileUtil.getFileNameList(testFolder); int count = 0; for (String fileName : fileNameList) { if (fileName.equals("a.txt")) { count++; } else if (fileName.equals("b.txt")) { count++; } } if (count != 2) { fail("No get the correct file name list"); } } @Test public void getDirNameList() { String testFolder = rootFolder + "dirNameList"; FileUtil.createDir(testFolder); FileUtil.createDir(testFolder + File.separator + "dirNameFolder1"); FileUtil.createDir(testFolder + File.separator + "dirNameFolder2"); List<String> dirNameList = FileUtil.getDirNameList(testFolder); int count = 0; for (String dirName : dirNameList) { if (dirName.equals("dirNameFolder1")) { count++; } else if (dirName.equals("dirNameFolder2")) { count++; } } if (count != 2) { fail("No get the correct folder name list"); } } @Test public void isFile() { assertTrue(FileUtil.isFile(rootFolder + helloWorldFile)); assertFalse(FileUtil.isFile(rootFolder + "aaabbbcccddd.txt")); } @Test public void isDir() { assertTrue(FileUtil.isDir(rootFolder)); assertFalse(FileUtil.isDir(rootFolder + "aaabbbccccddd")); } @Test public void getFileName() { assertEquals(helloWorldFile, FileUtil.getFileName(rootFolder + helloWorldFile)); } @After public void tearDown() { FileUtil.deleteDir(rootFolder); } private String readFile(String file) { FileReader fr = null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { fr = new FileReader(file); br = new BufferedReader(fr); String s = null; while ((s = br.readLine()) != null) { sb.append(s); } } catch (Exception e) { fail("Error happens when reading file"); } finally { try { if (br != null) { br.close(); } if (fr != null) { fr.close(); } } catch (Exception e) { fail("Error happens when closing bufferedReader and FileReader"); } } return sb.toString(); } }
TypeScript
UTF-8
3,903
2.6875
3
[]
no_license
module egret3d { /** * @private * 粒子初始化的尺寸大小 */ export class ParticleScale extends AnimationNode { private _scaleValue: ConstRandomValueShape; private _animationState: ParticleAnimationState; private _node: ParticleDataScaleBirth; constructor() { super(); this.name = "ParticleScale"; } /** * @language zh_CN * 填充粒子尺寸缩放数据 * @param data ParticleDataNode 粒子数据来源 * @version Egret 3.0 * @platform Web,Native */ public initNode(data: ParticleDataNode): void { //##FilterBegin## ##Particle## var node: ParticleDataScaleBirth = this._node = <ParticleDataScaleBirth>data; this._scaleValue = new ConstRandomValueShape(); this._scaleValue.max = node.max; this._scaleValue.min = node.min; //##FilterEnd## } /** * @language zh_CN * 填充顶点数据 * @param geometry 网格数据 * @param count 粒子数量 * @version Egret 3.0 * @platform Web,Native */ public build(geometry: Geometry, count: number) { //##FilterBegin## ##Particle## this._animationState = <ParticleAnimationState>this.state; var scaleArray: number[] = this._scaleValue.calculate(count); var vertices: number = geometry.vertexCount / count; var index: number = 0; var progress: number = 0; var duration: number = this._animationState.emitter.data.life.duration; var timeOffsetIndex: number = this._animationState.emitter.timeNode.offsetIndex; var particleIndex: number = 0; var timeIndex: number; var bornTime: number; var scale: number = 0; for (var i: number = 0; i < count; ++i) { // if (this._node.type == ParticleValueType.OneBezier || this._node.type == ParticleValueType.TwoBezier) { timeIndex = particleIndex * geometry.vertexAttLength + timeOffsetIndex; bornTime = geometry.vertexArray[timeIndex + 0]; //出生时间 progress = bornTime / duration; progress = progress - Math.floor(progress); //取小数部分 scale = this._node.bezier1.calc(progress); if (this._node.type == ParticleValueType.TwoBezier) { var random: number = Math.random(); scale *= random; scale += this._node.bezier2.calc(progress) * (1 - random); } } else { scale = scaleArray[i]; } if (scale == 1) { continue; } for (var j: number = 0; j < vertices; ++j) { index = i * vertices + j; index = index * geometry.vertexAttLength; geometry.vertexArray[index + 0] *= scale; geometry.vertexArray[index + 1] *= scale; geometry.vertexArray[index + 2] *= scale; } } //##FilterEnd## } /** * @private * 构建结束后需要清理掉临时数据 */ public afterBuild(): void { //##FilterBegin## ##Particle## this._scaleValue.dispose(); this._scaleValue = null; //##FilterEnd## } /** * @private */ public dispose(): void { super.dispose(); this._animationState = null; this._node = null; this._scaleValue = null; } } }
SQL
UTF-8
266
3.25
3
[]
no_license
Select First_Name, Last_name, Title, EpName from Actors AS a join Casting AS b on b.ActorId = a.Id join Episodes AS c on c.EpNumber = b.EpisodeId and c.Season = b.Season join Programs AS d on d.Id = c.ProgramId Where c.Season = 2 and c.EpNumber = 1
JavaScript
UTF-8
3,652
3.15625
3
[]
no_license
var questions = [ { question: "What is 8 * 9?", answers: { a: "17", b: "71", c: "72", d: "27"}, correctAnswer: "c"}, { question: "What is 15 / 3?", answers: { a: "5", b: "-5", c: "3", d: "-3"}, correctAnswer: "a"}, { question: "What is 3 + 4?", answers: { a: "43", b: "34", c: "-7", d: "7"}, correctAnswer: "d"}, { question: "How do you spell code?", answers: { a: "doec", b: "odec", c: "code", d: "coed"}, correctAnswer: "c"} ] var timerEl = document.getElementById("timer"); var qSpace = document.getElementById("question"); var choices = document.getElementById("choices"); var choiceA = document.getElementById("a"); var choiceB = document.getElementById("b"); var choiceC = document.getElementById("c"); var choiceD = document.getElementById("d"); var startBtn = document.getElementById("start"); var rightWrong = document.getElementById("rightWrong"); var quizTitle = document.getElementById("quizTitle"); var instructions = document.getElementById("directions"); var mainDiv = document.getElementById("mainDiv"); var highscoresInput = document.getElementById("highscoresInput"); var submitIn = document.getElementById("submitInitials"); var highScores = []; var i = 0; var secondsLeft = 75; var timerInterval; function showInstructions () { qSpace.style.display = "none"; choices.style.display = "none"; mainDiv.style.display = "inline-grid"; highscoresInput.style.display = "none"; } function timer() { timerInterval = setInterval(function() { secondsLeft--; timerEl.textContent = " " + secondsLeft; if(secondsLeft <= 0) { endGame(); } }, 1000); } function showQuestion(qnum) { if (qnum < 4){ choices.setAttribute("data-ans", questions[qnum].correctAnswer) question[qnum]; qSpace.textContent = questions[qnum].question; choiceA.textContent = "A: " + questions[qnum].answers.a; choiceB.textContent = "B: " + questions[qnum].answers.b; choiceC.textContent = "C: " + questions[qnum].answers.c; choiceD.textContent = "D: " + questions[qnum].answers.d; } else { endGame(); } } function getHs () { var storedHs = JSON.parse(localStorage.getItem("highScores")); if (storedHs !== null){ highScores = storedHs; } } function resetQ () { i++; showQuestion(i); } function storeHs () { localStorage.setItem("highScores", JSON.stringify(highScores)); } function startGame() { qSpace.style.display = "inline-grid"; choices.style.display = ""; startBtn.style.display = "none"; instructions.style.display = "none"; quizTitle.style.display = "none"; } function endGame() { highscoresInput.style.display = "inline-grid"; qSpace.style.display = "none"; choices.style.display = "none"; rightWrong.textContent = ""; clearInterval(timerInterval); } function start() { startGame(); timer(); showQuestion(i); } choices.addEventListener("click", function(event) { var element = event.target; var correct = choices.getAttribute("data-ans"); if (element.getAttribute("id") === correct) { rightWrong.textContent = "Correct!"; } else { rightWrong.textContent = "Incorrect"; secondsLeft -= 5; } resetQ(); }); startBtn.addEventListener("click", start); submitIn.addEventListener("click", function(){ var initials = document.getElementById("initials"); var initialsInput = initials.value.trim(); if (initialsInput === "") { return; } var gameInfo = { score: secondsLeft, initials: initialsInput } highScores.push(gameInfo); initialsInput.value = ""; storeHs(); location.href = "highscores.html"; }); getHs(); showInstructions();
Markdown
UTF-8
1,707
2.9375
3
[]
no_license
# Slack AD Checker A Python/Powershell util script for checking to see that everyone in a Slack group has a corresponding email in Active Directory ### Why? This is a little utility script you could use to remind admins to remove people from slack (basically if you don't wanna pay for full AD sync) ### Install/Setup Assuming you're on a Windows machine, you'll need something with Powershell and Python installed. For some versions of Windows (just Windows 10 at the moment), you may need to install the Get-ADUser module. See under the setup/ directory. Here's the source for the module installer: https://blogs.technet.microsoft.com/ashleymcglone/2016/02/26/install-the-active-directory-powershell-module-on-windows-10/ Once you have that module set up, you can query your current Active Directory domain for users. The Python script is going to invoke the powershell script to check everybody. Now all you need is a Python environment with the slackclient package installed (pip install slackclient). You'll need a Slack API token to make queries. You can get one from here: https://api.slack.com/custom-integrations/legacy-tokens Enter the token in the config file and then you should be all set. ### Usage For now the script just spits out which emails for slack users don't seem to exist in AD. ### Notes This is just a quick utility I cooked up. An even better idea would be to auto-populate/control slack accounts based on AD users. Erik Kalkoken makes some interesting suggestions here: http://stackoverflow.com/questions/33420052/populate-slack-user-profiles-using-external-directory-data Here's his info on Slack's undocumented API methods: https://github.com/ErikKalkoken/slackApiDoc
C++
UTF-8
633
2.65625
3
[]
no_license
#include<string> #include<iostream> #include<algorithm> using namespace std; int str[100]; bool cmp(const int&A,const int&B){ return A<B?true:false; } int main() { int n,sum,tmp1,tmp2; scanf("%d",&n); while(~scanf("%d",&n)){ for(int i=1;i<=n;i++){ scanf("%d",&str[i]); } sort(&str[1],str+n+1,cmp); sum=0; while(1){ if(n>=4){ tmp1=(str[2]<<1)+str[1]+str[n]; tmp2=(str[1]<<1)+str[n-1]+str[n]; sum+=(tmp1>tmp2?tmp2:tmp1); n-=2; }else if(n==3){ sum+=(str[1]+str[2]+str[3]); break; }else if(n==2){ sum+=str[2]; break; }else{ sum+=str[1]; break; } } printf("%d\n",sum); } return 0; }
Java
UTF-8
550
2.265625
2
[]
no_license
package com.habbib.customer.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.stereotype.Component; @Component public class Utilities { public Date convertDateFormate(Date date) { SimpleDateFormat formate = new SimpleDateFormat("yyyy-dd-MM"); try { String newDate = formate.format(date); return formate.parse(newDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
Java
UTF-8
627
3.015625
3
[]
no_license
public class Sort012{ public static void sort012(int[] arr){ int indexOf0 = 0; int IndexOf2 = arr.length -1; int i = 1; int temp = 0; while(i < arr.length ) { if(arr[i] == 0 && i > indexOf0) { temp = arr[i]; arr[i] = arr[indexOf0]; arr[indexOf0] = temp; indexOf0++; } else if(arr[i] == 2 && i < IndexOf2) { temp = arr[i]; arr[i] = arr[IndexOf2]; arr[IndexOf2] = temp; IndexOf2--; } else i++; } } }
Markdown
UTF-8
642
2.796875
3
[]
no_license
--- title: Preload types: - string --- # Preload Adds a string to the preload buffer. ## Declaration ```jass native Preload takes string filename returns nothing ``` ## Parameters `string filename`{!language=jass} : The string to be added to the buffer.Should probably not be named`filename`. ## Notes The data will be put into the file like this:````call Preload("<data here>")````So to put any executable code in the file you have to close the string and thenput your code onto a new line, like this:````call Preload("\")\n call your_stuff_here()")```` Also see the documentation for`Preloader`for more info on the generated files.
C#
UTF-8
721
4.34375
4
[]
no_license
using System; class PerimeterAndAreaOfCircle { static void Main() { //Write a program that reads the radius r of a circle and prints its perimeter and area. Console.Write("Please insert the radius of the circle - "); double radius = double.Parse(Console.ReadLine()); // Reads the number that you have entered and converts it from string to double double perimeter = 2 * radius * Math.PI; // calculates the perimeter, Math.PI is a function from the Math library of C# double area = radius * radius * Math.PI; // calculates the area of the circle Console.WriteLine("The perimeter of the circle is : {0}\nThe are of the circle is : {1}", perimeter, area); } }
Shell
UTF-8
302
3.546875
4
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash # Written by: Bilal Jooma for d in */ ; do cd $d BRANCH=$( git branch | grep \* | cut -d ' ' -f2 ) echo "##== Updating: $d ==##" if [ "$BRANCH" != "master" ] then echo "Only supported for Master Branch: $d" else git pull fi echo cd .. done
Java
UTF-8
1,756
2.671875
3
[]
no_license
package test; import org.junit.Test; import static org.junit.Assert.*; import static.org.junit.Assert.assertTrue; import static.org.junit.Assert.assertFalse; import static.org.junit.Assert.add; import org.junit.Before; import static.org.junit.Assert.assertEquals; public class BalancedBracketsTest { //TODO: add tests here @Test public void emptyTest() { assertEquals(true, true); } @Test public void onlyBracketsReturnsTrue() { BalancedBrackets test_Class = new BalancedBrackets(); assertTrue(test_Class.hasBalancedBrackets("[]")); } @Test public void onlyBracketsReturnFalse() { BalancedBrackets test_Class = new BalancedBrackets(); assertFalse(test_Class.hasBalancedBrackets("[]")); } //for normal addition @Test public void testAdd1Plus1() { int x = 1 ; int y = 1; assertEquals(2, test_Class.hasBalancedBrackets.add(x,y)); } //if you are using 0 as default for null, make sure your class works in that case. @Test public void testBracketsAdd1Plus1() { int y = 1; assertEquals(0, test_Class.hasBalancedBrackets.add(null,y)); } @Test public void testSimpleAddition() { } @Test public void testPositiveNegativeAddition() { } @Test public void testNegativePositiveAddition() { } @Test public void testNegativeAddition() { } @Test public void testOverflow() { } @Before public void createBalancedBrackets() { test_Class.newBalancedBrackets(); } @Test public void onlyBracketsExpected() { assertEquals(test_Class.actualBalancedBrackets("[]")); } }
Python
UTF-8
395
3.140625
3
[]
no_license
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10, 4), index = pd.date_range('1/1/2000', periods=10), columns = ['A', 'B', 'C', 'D']) print (df) r = df.rolling(window=3,min_periods=1) print (r.aggregate(np.sum)) print (r['A'].aggregate(np.sum)) print (r['A','B'].aggregate([np.sum,np.mean])) print (r.aggregate({'A' : np.sum,'B' : np.mean}))
C++
UTF-8
279
2.8125
3
[]
no_license
#include <algorithm> #include <string> #include <iostream> int main() { std::string s = "acb"; // что переставляем std::sort(s.begin(), s.end()); do { std::cout << s << std::endl; } while(std::next_permutation(s.begin(), s.end())); }
C++
UTF-8
2,925
2.828125
3
[]
no_license
#include "simpleArbiter.h" namespace manifold { namespace iris { //#################################################################### // SimpleArbiter //#################################################################### SimpleArbiter::SimpleArbiter(unsigned nch) : no_channels(nch), requested(nch) { for ( unsigned i=0; i<no_channels; i++) requested[i] = false; } SimpleArbiter::~SimpleArbiter() { } //! @param \c ch The index of virtual channel //! @return The request status for a given virtual channel bool SimpleArbiter::is_requested ( unsigned ch ) { assert( ch < requested.size() ); return requested[ch]; } /* //! @return True if no channel is requesting. bool SimpleArbiter::is_empty ( void ) { for ( uint i=0 ; i<no_channels; i++ ) if ( requested[i] ) return false; return true; } */ //! Make a request for the given channel. //! @param \c ch The index of virtual channel void SimpleArbiter::request ( unsigned ch ) { assert(ch < no_channels); requested[ch] = true; } //! Clear request for the given channel. //! @param \c ch The index of virtual channel. void SimpleArbiter :: clear_request ( unsigned ch ) { assert(ch < no_channels); requested[ch] = false; } //#################################################################### // RRSimpleArbiter //#################################################################### RRSimpleArbiter :: RRSimpleArbiter(unsigned nch) : SimpleArbiter(nch), last_winner(-1) { } //! Pick a winner using round-robin priority, i.e., the last winner //! would have the lowest priority. //! @return The winning VC, or no_channels if there's no requester. unsigned RRSimpleArbiter::pick_winner () { for ( uint i=last_winner+1; i<requested.size() ; i++ ) if ( requested[i] ) { last_winner = i; return last_winner; } for ( uint i=0; i<=last_winner ; i++ ) if ( requested[i] ) { last_winner = i; return last_winner; } return no_channels; } //#################################################################### // FCFSSimpleArbiter //#################################################################### FCFSSimpleArbiter :: FCFSSimpleArbiter(unsigned nch) : SimpleArbiter(nch) { } void FCFSSimpleArbiter::request( unsigned ch ) { assert(ch < no_channels && requested[ch] == false); requested[ch] = true; m_requesters.push_back(ch); } //! Pick a winner using first-come-first-serve priority. //! Return the winner, which is the earliest of the current requesters; or no_channels if //! there are no requesters. unsigned FCFSSimpleArbiter::pick_winner () { unsigned winner = no_channels; if(m_requesters.size() > 0) { winner = m_requesters.front(); m_requesters.pop_front(); } return winner; } } //iris } //manifold
C++
UTF-8
10,152
2.59375
3
[]
no_license
/* Diffie-Hellman key exchange (without HMAC) aka ECDH_anon in RFC4492 1. Alice picks a (secret) random natural number 'a', calculates P = a * G and sends P to Bob. 'a' is Alice's private key. 'P' is Alice's public key. 2. Bob picks a (secret) random natural number 'b', calculates Q = b * G and sends Q to Alice. 'b' is Bob's private key. 'Q' is Bob's public key. 3. Alice calculates S = a * Q = a * (b * G). 4. Bob calculates T = b * P = b * (a * G). .. which are the same two values since multiplication in the field is commutative and associative. T = S = the new shared secret. Pseudo-random number generator inspired / stolen from: http://burtleburtle.net/bob/rand/smallprng.html */ // aes #include "aes.h" #include <string.h> #include <stdint.h> // ecdh #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "ecdh.h" // client-server #include <stdio.h> #include <WinSock2.h> #include <WS2tcpip.h> #define SERVER_PORT 8080 #define SERVER_ADDR "127.0.0.1" #define BUFF_SIZE 2048 #pragma comment(lib, "Ws2_32.lib") /* pseudo random number generator with 128 bit internal state... probably not suited for cryptographical usage */ typedef struct { uint32_t a; uint32_t b; uint32_t c; uint32_t d; } prng_t; static prng_t prng_ctx; static uint32_t prng_rotate(uint32_t x, uint32_t k) { return (x << k) | (x >> (32 - k)); } static uint32_t prng_next(void) { uint32_t e = prng_ctx.a - prng_rotate(prng_ctx.b, 27); prng_ctx.a = prng_ctx.b ^ prng_rotate(prng_ctx.c, 17); prng_ctx.b = prng_ctx.c + prng_ctx.d; prng_ctx.c = prng_ctx.d + e; prng_ctx.d = e + prng_ctx.a; return prng_ctx.d; } static void prng_init(uint32_t seed) { uint32_t i; prng_ctx.a = 0xf1ea5eed; prng_ctx.b = prng_ctx.c = prng_ctx.d = seed; for (i = 0; i < 31; ++i) { (void)prng_next(); } } uint8_t* gen_Key_ECDH(SOCKET conn) { static uint8_t puba[ECC_PUB_KEY_SIZE]; static uint8_t prva[ECC_PRV_KEY_SIZE]; static uint8_t seca[ECC_PUB_KEY_SIZE]; static uint8_t pubb[ECC_PUB_KEY_SIZE]; static uint8_t prvb[ECC_PRV_KEY_SIZE]; static uint8_t secb[ECC_PUB_KEY_SIZE]; uint32_t i; int ret; /* 0. Initialize and seed random number generator */ static int initialized = 0; if (!initialized) { srand(time(0)); // srand(42); // prng_init((0xbad ^ 0xc0ffee ^ 42) | 0xcafebabe | 666); prng_init(rand()); initialized = 1; } /* 2. Bob picks a (secret) random natural number 'b', calculates Q = b * g and sends Q to Alice. */ for (i = 0; i < ECC_PRV_KEY_SIZE; ++i) { prvb[i] = prng_next(); } ecdh_generate_keys(pubb, prvb); printf("private key of Bob: "); for (int i = 0; i < ECC_PRV_KEY_SIZE; i++) printf("%2X", prvb[i]); printf("\n"); printf("public key of Bob: "); for (int i = 0; i < ECC_PRV_KEY_SIZE; i++) printf("%2X", pubb[i]); printf("\n"); // receive pubKey from Alice ret = recv(conn, (char*)puba, ECC_PUB_KEY_SIZE, NULL); if (ret == SOCKET_ERROR) { printf("Error %d: cannot receive pubKey from Alice\n", WSAGetLastError()); return NULL; } // send pubkey to Alice ret = send(conn, (char*)pubb, ECC_PUB_KEY_SIZE, NULL); if (ret == SOCKET_ERROR) { printf("Error %d: cannot send pubKey to Bob\n", WSAGetLastError()); return NULL; } /* 4. Bob calculates T = b * P = b * (a * g). */ ecdh_shared_secret(prvb, puba, secb); printf("Shared secret: "); for (i = 0; i < ECC_PUB_KEY_SIZE; i++) printf("%2X", secb[i]); printf("\n"); printf("Size of shared secret: %d\n", ECC_PUB_KEY_SIZE); return secb; } /* WARNING: This is not working correctly. ECDSA is not working... */ void ecdsa_broken() { static uint8_t prv[ECC_PRV_KEY_SIZE]; static uint8_t pub[ECC_PUB_KEY_SIZE]; static uint8_t msg[ECC_PRV_KEY_SIZE]; static uint8_t signature[ECC_PUB_KEY_SIZE]; static uint8_t k[ECC_PRV_KEY_SIZE]; uint32_t i; srand(time(0)); srand(42); for (i = 0; i < ECC_PRV_KEY_SIZE; ++i) { prv[i] = rand(); msg[i] = prv[i] ^ rand(); k[i] = rand(); } /* int ecdsa_sign(const uint8_t* private, const uint8_t* hash, uint8_t* random_k, uint8_t* signature); int ecdsa_verify(const uint8_t* public, const uint8_t* hash, uint8_t* signature); */ ecdh_generate_keys(pub, prv); /* No asserts - ECDSA functionality is broken... */ ecdsa_sign((const uint8_t*)prv, msg, k, signature); ecdsa_verify((const uint8_t*)pub, msg, (const uint8_t*)signature); /* fails... */ } // use AES_ECB to encrypt data int send_data_encrypt(uint8_t keyAES[32], SOCKET conn, char* msg, int lenMsg) { struct AES_ctx ctx; int pad_size, ret; printf("Plaintext: "); for (int i = 0; i < lenMsg; i++) printf("%c", msg[i]); printf("\n"); if (lenMsg % 16 != 0) { pad_size = lenMsg + 16 - (lenMsg % 16); } else pad_size = lenMsg; printf("Pad size: %d\n", pad_size); // convert data uint8_t ct[BUFF_SIZE]; memset(ct, 0, BUFF_SIZE); memcpy(ct, msg, lenMsg); AES_init_ctx(&ctx, keyAES); AES_ECB_encrypt(&ctx, ct); printf("ECB Encrypt: "); for (int i = 0; i < pad_size; i++) printf("%2X", ct[i]); printf("\n------------------------------------------------------\n"); ret = send(conn, (char*)&ct, pad_size, NULL); return ret; } // use AES_ char* recv_data_decrypt(uint8_t keyAES[32], SOCKET conn) { struct AES_ctx ctx; char ct[BUFF_SIZE]; int ret; memset(ct, 0, BUFF_SIZE); ret = recv(conn, ct, BUFF_SIZE, NULL); if (ret == SOCKET_ERROR) { // printf("Error %d: cannot receive data\n", WSAGetLastError()); return NULL; } else if (ret == 0) { char result[22] = "Client disconnected!\n"; return result; } uint8_t pt[BUFF_SIZE]; memset(pt, 0, BUFF_SIZE); printf("Ciphertext: "); for (int i = 0; i < ret; i++) printf("%2X", ct[i]); printf("\n"); memset(pt, 0, ret); memcpy(pt, ct, ret); AES_init_ctx(&ctx, keyAES); AES_ECB_decrypt(&ctx, pt); printf("ECB decrypt: "); for (int i = 0; i < ret; i++) printf("%2X", pt[i]); printf("\n------------------------------------------------------\n"); return (char*)pt; } int main(int argc, char* argv[]) { // initiate winsock WSADATA wsaData; WORD wVersion = MAKEWORD(2, 2); if (WSAStartup(wVersion, &wsaData)) { printf("winsock 2.2 not supported!\n"); return 0; } // construct socket SOCKET listenSock; listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSock == INVALID_SOCKET) { printf("Error %d: cannot create server socket\n", WSAGetLastError()); return 0; } // bind address to socket sockaddr_in serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(SERVER_PORT); inet_pton(AF_INET, SERVER_ADDR, &serverAddr.sin_addr); if (bind(listenSock, (sockaddr*)&serverAddr, sizeof(serverAddr))) { printf("Error: %d cannot associate a local address with server socket\n", WSAGetLastError()); return 0; } // communicate with client sockaddr_in clientAddr; char buff[BUFF_SIZE], clientIP[INET_ADDRSTRLEN]; int ret, clientAddrLen = sizeof(clientAddr), clientPort; SOCKET connSock; while (1) { // listen request from client if (listen(listenSock, 10)) { printf("Error %d cannot place server socket in state listen\n", WSAGetLastError()); return 0; } printf("Server started!\n"); // accept request connSock = accept(listenSock, (sockaddr*)&clientAddr, &clientAddrLen); if (connSock == SOCKET_ERROR) { printf("Error %d: Cannot permit incoming connection\n", WSAGetLastError()); return 0; } else { inet_ntop(AF_INET, &clientAddr.sin_addr, clientIP, sizeof(clientIP)); clientPort = ntohs(clientAddr.sin_port); printf("Accept incoming connection from %s:%d\n", clientIP, clientPort); } uint8_t key[32]; uint8_t* pKey; char* recv_data; // gen key in curve pKey = gen_Key_ECDH(connSock); if (pKey == NULL) { printf("Create key fron ECDH faild\n"); } else { memcpy(key, pKey, 32); printf("Key use for AES: "); for (int i = 0; i < 32; i++) printf("%2X", key[i]); printf("\n------------------------------------------------------\n"); } while (1) { // receive message from client recv_data = recv_data_decrypt(key, connSock); if (recv_data == NULL) { printf("Error %d: cannot receive data\n", WSAGetLastError()); break; } else if (memcmp(recv_data, "Client disconnected!\n", 22) == 0) { printf("Client [%s:%d] disconnected!\n", clientIP, clientPort); break; } else { printf("receive from client [%s:%d] %s\n", clientIP, clientPort, recv_data); // echo to client ret = send_data_encrypt(key, connSock, recv_data, strlen(recv_data)); if (ret == SOCKET_ERROR) { printf("Error %d: cannot send data\n", WSAGetLastError()); break; } } } } // end communicating // close socket closesocket(connSock); closesocket(listenSock); WSACleanup(); return 0; }
PHP
UTF-8
5,796
2.828125
3
[]
no_license
<?php require_once( "pagination.php"); require_once("session.php"); require_once("nice.php"); $status_msg = array(10 => "Created: entry record created in database", 20 => "Uploaded: ready to be unzipped and compiled", 30 => "Compiling: compiling and running tests", 40 => "Success: ready to play", 50 => "Download Error: error receiving submission zip file", 60 => "Unpack Error: error while unzipping submission file", 70 => "Compile Error: error while compiling submission", 80 => "Test Error: compiled, but failed test cases", 90 => "Upload Error: server failed to retrieve uploaded file correctly", 100 =>"Deactivated: not in queue to play game", 0 => "Unknown Error"); /* * getSubmissionTableString * * Returns Submission Table as a string, * if viewmore is true (default), it outputs viewresults rows and has an underlink to page given * if viewmore is false, it uses pagination with viewresults rows per page * */ function getSubmissionTableString($user_id, $viewmore = true, $viewresults = 10, $viewlink, $page=0) { global $status_msg; // Avoid SQL injections if(!filter_var($user_id, FILTER_VALIDATE_INT)) { return ""; } else { $user_id = intval($user_id); } if (!filter_var($page, FILTER_VALIDATE_INT)) { $page = 0; } else { $page = intval($page); } // Fetch row count $rowcount_query = <<<EOT select count(*) from submission where user_id = $user_id EOT; $rowcount_data = mysql_query($rowcount_query); if ($rowcount_data) { list($rowcount) = mysql_fetch_row($rowcount_data); } else { $rowcount = 0; } // Fetch submission data $submission_query = <<<EOT select s.submission_id, s.status, s.errors, s.timestamp, s.version, s.mu - 3 * s.sigma as skill, s.mu, s.sigma, l.name as language, s.game_count, timestampdiff(second, gmin.timestamp, gmax.timestamp)/60/s.game_count as game_rate from submission s left outer join game gmin on gmin.game_id = s.min_game_id left outer join game gmax on gmax.game_id = s.max_game_id inner join user u on u.user_id = s.user_id left outer join language l on l.language_id = s.language_id where u.user_id = $user_id order by s.submission_id desc EOT; if ($viewmore) { $submission_query .= " limit $viewresults"; } else if ($page != 0) { $submission_query .= " limit $viewresults OFFSET " . ($viewresults * ($page-1)); } $submission_results = mysql_query($submission_query); // If query fails if (!$submission_results || $rowcount == 0) { return "<p>No submissions available at this time.</p>"; } // Build table $table = ""; if (!$viewmore) { $table .= getPaginationString($page, ceil($rowcount/$viewresults), $viewresults, $viewlink); } $table .= "<table class=\"submissions\"> <thead><tr> <th>Version</th> <th>Submission Time</th> <th>Status</th> <th>Skill</th> <th>Games</th> <th><span title=\"average minutes between games\">Game Rate</span></th> <th>Language</th> </tr></thead><tbody>"; for ($i = 1; $row = mysql_fetch_assoc($submission_results); $i += 1) { $status = $row["status"]; $status_class = (($status == 40 || $status == 100) ? "success": (($status == 30 || ($status > 40 || $status < 100))? "fail" : "inprogress")); if (isset($status_msg[$status])) { $status = $status_msg[$status]; } else { $status = $status_msg[0]; } $version = $row["version"]; $submission_id = $row["submission_id"]; $timestamp = $row["timestamp"]; $language = $row["language"]; $language_link = urlencode($language); $row_class = $i % 2 == 0 ? "even" : "odd"; $errors = $row["errors"]; $skill = $status_class == "success" ? nice_skill($row['skill'], $row['mu'], $row['sigma']) : "-"; // trueskill formula $games = $row["game_count"]; $game_rate = "".($row['game_rate'] == NULL ? "" : round($row["game_rate"],0)); $table .= "<tr class=\"$row_class\">"; $table .= " <td>".nice_version($version, $timestamp, $submission_id)."</td>"; $table .= " <td>". nice_datetime_span($timestamp) ."</td>"; $table .= " <td class=\"$status_class\">$status</td>"; $table .= " <td>$skill</td>"; $table .= " <td>$games</td>"; $table .= " <td>$game_rate</td>"; $table .= " <td><a href=\"language_profile.php?language=$language_link\"> $language</a></td>"; $table .= "</tr>"; if ($errors and $status_class == "fail" and ($user_id == current_user_id() or logged_in_as_admin())) { $errors = json_decode($errors); $error_msg = "<pre class=\"error\">"; if (isset($errors->errors)) { for ($i = 0; $i < count($errors->errors); $i++) { $error_msg .= str_replace('\n', "\n", $errors->errors[$i])."\n"; } } elseif (gettype($errors) == "array") { foreach ($errors as $error) { $error_msg .= str_replace('\n', "\n", $error)."\n"; } } $error_msg .= "</pre>"; $table .= "<tr><td colspan=\"7\">$error_msg</td></tr>"; } } $table .= "</tbody></table>"; if ($viewmore && $rowcount > $viewresults) { $table .= "<a href=\"$viewlink\">View More</a>"; } return $table; } ?>
C#
UTF-8
1,406
3.5625
4
[ "MIT" ]
permissive
namespace ValidUsernames { using System; using System.Linq; using System.Text; class Program { static void Main() { string[] userName = Console.ReadLine() .Split(", ") .ToArray(); StringBuilder validUserName = new StringBuilder(); for (int i = 0; i < userName.Length; i++) { bool isLength = false; bool isCorectSymbol = true; if (userName[i].Length >= 3 && userName[i].Length <= 16) { isLength = true; } else { continue; } for (int j = 0; j < userName[i].Length; j++) { if (Char.IsLetterOrDigit(userName[i][j]) || userName[i][j] == '-' || userName[i][j] == '_') { continue; } else { isCorectSymbol = false; break; } } if (isLength && isCorectSymbol) { validUserName = validUserName.AppendLine(userName[i]); } } Console.WriteLine(string.Join("", validUserName)); } } }
Java
UTF-8
1,593
2.359375
2
[ "Apache-2.0" ]
permissive
package com.eclubprague.iot.android.weissmydeweiss.cloud.sensors; import com.eclubprague.iot.android.weissmydeweiss.cloud.hubs.Hub; import com.eclubprague.iot.android.weissmydeweiss.cloud.sensors.supports.NameValuePair; import com.eclubprague.iot.android.weissmydeweiss.cloud.sensors.supports.SensorType; import com.eclubprague.iot.android.weissmydeweiss.cloud.sensors.supports.cloud_entities.SensorEntity; import com.google.gson.Gson; import java.util.List; /** * Created by Dat on 6.8.2015. */ public class HumiditySensor extends Sensor { protected String unit = "%"; protected float humidity = 0; public HumiditySensor(SensorEntity entity) { super(entity); } public HumiditySensor(String uuid, String secret, Hub hub, String name) { super(uuid, SensorType.HUMIDITY, secret, hub, name, null); } @Override public void readPayload(byte[] payload) { //TODO } @Override public String printData() { return ("humidity = " + humidity + " %"); } public float getHumidity() { return humidity; } public String getUnit() { return unit; } @Override public String toString() { return new Gson().toJson(this); } @Override public List<NameValuePair> getDataList() { measured.clear(); measured.add(new NameValuePair("humidity", Float.toString(humidity))); measured.add(new NameValuePair("unit", unit)); return measured; } @Override public void setData(float[] values) { humidity = values[0]; } }
Java
UTF-8
1,523
3.25
3
[ "MIT" ]
permissive
/* * 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 am_utils; /** * * @author NThering */ public final class CUtils { /** If we're allowing debug messages and features */ private static final boolean DEBUGMODE = true; private CUtils() { } /** Prints a standard message to the console. */ public static void msg( String msg ) { System.out.println( msg ); } /** Prints a standard message to the console only if debug mode is on. */ public static void debugMsg( String msg ) { if ( DEBUGMODE ) System.out.println( "[DEBUG] " + msg ); } /** Prints a warning to the console. Should only be used to reflect something going wrong. */ public static void warning( String warningString ) { System.out.println( "[WARNING] " + warningString ); } /** Print out a nice list of all categories and subcategories.*/ public static void printOutCategories() { CUtils.msg("Printing categories!\n"); MainCategory mainCatList[] = new DefaultCategories().getDefaultCategories(); for( MainCategory mainCat: mainCatList ) { CUtils.msg(mainCat.printName()); for( SubCategory subCat: mainCat.children() ) CUtils.msg( "\t" + subCat.printName() ); } } }
PHP
UTF-8
1,084
2.8125
3
[ "MIT" ]
permissive
<?php namespace App\Libraries; use App\Libraries\Crud_core; use CodeIgniter\HTTP\RequestInterface; class Crud extends Crud_core { function __construct($params, RequestInterface $request) { parent::__construct($params, $request); } function form() { return $this->parent_form(); } public function callback_days_left($item){ $days = $this->days($item->p_end_date); if($days < 0){ $out = '<span class="text-success">Completed</span>'; }else{ $out = '<span>' . $days . ' days left</span>'; } return $out; } private function days($date) { $now = time(); // or your date as well $your_date = strtotime($date); $datediff = $your_date - $now; return round($datediff / (60 * 60 * 24)); } public function callback_featured_image($item){ $src = $item->p_image ? '/uploads/images/'.$item->p_image : '/admin/assets/img/profile.png'; return '<img src="'.$src.'" style="width:54px;" class="img-circle">'; } }
Python
UTF-8
98
2.6875
3
[ "MIT-Modern-Variant", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
def from_monad(m): """ Returns the value of a monad """ return m >> (lambda x: x)
Python
UTF-8
428
3.125
3
[]
no_license
from tkinter import* import webbrowser win=Tk() win.title('Search Bar') def bt_on(): url=entry.get() webbrowser.open(url) label= Label(win,text='Enter url: ',font=('arial',14,'bold')) label.grid(row=0,column=0) entry = Entry(win,width=35) entry.grid(row=0,column=1) button =Button(win,text='Search',width = 10,height=1,command=bt_on) button.grid(row=1,column=1,pady=5) win.mainloop()
Python
UTF-8
70
3.03125
3
[]
no_license
a,b,c=input().split() x=int(a) y=int(b) z=int(c) m=((x*y)%z) print(m)
Shell
UTF-8
756
3.78125
4
[ "MIT" ]
permissive
#!/bin/sh # wait until nginx is running while [ ! -f /run/nginx/nginx.pid ]; do sleep 1 done # make sure the /services key is set in etcd before we start for ETCD_URL in ${ETCD_PEERS//,/ }; do curl -s -f $ETCD_URL/v2/keys/services -XPUT -d dir=true if [ "$?" = "0" ]; then break fi done # attempt to generate a first configuration ETCD_NODES="-node ${ETCD_PEERS//,/ -node }" ./confd -onetime $ETCD_NODES -config-file /etc/confd/conf.d/nginx.toml if [ "$?" != "0" ]; then echo confd cannot generate initial configuration, exiting. nginx -s stop exit 1 fi # start the watch cycle while [ true ]; do ./confd -interval 10 $ETCD_NODES -config-file /etc/confd/conf.d/nginx.toml echo confd exited, restarting. done
Java
UTF-8
1,647
4.125
4
[]
no_license
/** * TP01Q03 PALINDROMO * * @author Thiago Henrique de Castro Oliveira * @version 1 08/2019 Este algoritmo testa se uma string é um palindromo */ class TP01Q03Palindromo { public static void main(String[] args) { String[] input = new String[1000]; int inputIndex = 0; MyIO.setCharset("UTF-8"); do { input[inputIndex] = MyIO.readLine(); } while (isFim(input[inputIndex++]) == false); inputIndex--; for (int i = 0; i < inputIndex; i++) { if (isPalindromo(input[i]) == true) { MyIO.println("SIM"); } else { MyIO.println("NAO"); } } } /** * * @param line string que devera ser verificada * @return true se 'FIM' for encontrado */ public static boolean isFim(String line) { boolean boolValue = false; if (line.length() == 3 && line.charAt(0) == 'F' && line.charAt(1) == 'I' && line.charAt(2) == 'M') { boolValue = true; } return boolValue; } /** * * @param line string que deve ser analizada * @return true se as metadas da palavra forem identicas inversamente */ public static boolean isPalindromo(String line) { int j = line.length() - 1; boolean result = true; // roda a palavra de traz pra frente e de frente ate ao meio // verifica se esses inversos sao iguais for (int i = 0; i < (line.length() / 2); i++) { if (line.charAt(i) != line.charAt(j)) { result = false; } j--; } return result; } }
Python
UTF-8
1,109
2.734375
3
[]
no_license
#! /usr/bin/env python3 import sys import os import logging from traceback import format_exc from argparse import ArgumentParser from reporting.report import who_in_space logging.basicConfig(filename='profusion.log', level=logging.INFO) def main(argv=None): """ Main function that calls who_in_space function. """ program_name = os.path.basename(sys.argv[0]) if argv is None: argv = sys.argv else: sys.argv.extend(argv) try: parser = ArgumentParser(description='Parse the link for api') parser.add_argument('apilink', help='Api link with info on whos in space', nargs = '*',type=str, default='http://api.open-notify.org/astros.json') args = parser.parse_args() logging.info("Beginning parse api and see who is in space!") who_in_space(args.apilink) logging.info("Done, look at csv for tabular info of who in space") return 0 except Exception as e: sys.stderr.write(program_name + ": " + repr(e) + '\n' + format_exc() + '\n') raise e if __name__ == "__main__": sys.exit(main())
Markdown
UTF-8
1,612
2.5625
3
[ "MIT" ]
permissive
--- layout: post title: "Representation Balancing MDPs for Off-Policy Policy Evaluation" date: 2018-05-23 10:43:16 categories: arXiv_AI tags: arXiv_AI author: Yao Liu, Omer Gottesman, Aniruddh Raghu, Matthieu Komorowski, Aldo Faisal, Finale Doshi-Velez, Emma Brunskill mathjax: true --- * content {:toc} ##### Abstract We study the problem of off-policy policy evaluation (OPPE) in RL. In contrast to prior work, we consider how to estimate both the individual policy value and average policy value accurately. We draw inspiration from recent work in causal reasoning, and propose a new finite sample generalization error bound for value estimates from MDP models. Using this upper bound as an objective, we develop a learning algorithm of an MDP model with a balanced representation, and show that our approach can yield substantially lower MSE in a common synthetic domain and on a challenging real-world sepsis management problem. ##### Abstract (translated by Google) 我们研究RL中的非政策性政策评估(OPPE)问题。与之前的工作相比,我们考虑如何准确估计个别政策价值和平均政策价值。我们从最近的因果推理工作中汲取灵感,并提出了一个新的有限样本泛化误差界,用于MDP模型的估计值。以这个上限为目标,我们开发了一个具有平衡表示的MDP模型的学习算法,并且表明我们的方法可以在常见合成领域和具有挑战性的现实世界败血症管理问题中产生显着较低的MSE。 ##### URL [http://arxiv.org/abs/1805.09044](http://arxiv.org/abs/1805.09044) ##### PDF [http://arxiv.org/pdf/1805.09044](http://arxiv.org/pdf/1805.09044)
Java
UTF-8
1,044
3.03125
3
[]
no_license
package net.rayfall.TankAI; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Map { private Number mapSizeX; private Number mapSizeY; private ArrayList<Terrain> terrainList; public Map(JSONObject map) { try{ JSONArray hold = map.getJSONArray("size"); for(int i = 0; i < 2; i++){ if(i == 0){ this.mapSizeX = hold.getDouble(i); } else if(i == 1){ this.mapSizeY = hold.getDouble(i); } } JSONArray Terrain = map.getJSONArray("terrain"); terrainList = new ArrayList<Terrain>(); for(int i = 0; i < Terrain.length(); i++){ terrainList.add(new Terrain(Terrain.getJSONObject(i))); } } catch(JSONException e) { System.err.println("[Building Map] JSON Error " + e + ". Raw JSON: " + map.toString()); } } public Number getMapSizeX(){ return this.mapSizeX; } public Number getMapSizeY(){ return this.mapSizeY; } public ArrayList<Terrain> getTerrainList(){ return this.terrainList; } }
C++
UTF-8
492
3.109375
3
[]
no_license
#include <iostream> using namespace std; int main() { string hajjName, hajjFullName; int caseNo = 1; while(1) { cin>>hajjName; if(hajjName == "*") { break; } else if(hajjName == "Hajj") { hajjFullName = "Hajj-e-Akbar"; } else if(hajjName == "Umrah") { hajjFullName = "Hajj-e-Asghar"; } cout<<"Case "<<caseNo<<": " <<hajjFullName<<endl; caseNo++; } return 0; }
Java
UTF-8
499
1.992188
2
[]
no_license
package com.hemeiyue.common; import java.util.Map; public class ResultCount extends ResultBean{ private Map<String, Long> count; public ResultCount() { super(); // TODO Auto-generated constructor stub } public ResultCount(boolean result, String code, String message) { super(result, code, message); // TODO Auto-generated constructor stub } public Map<String, Long> getCount() { return count; } public void setCount(Map<String, Long> count) { this.count = count; } }
Java
UTF-8
1,304
1.976563
2
[]
no_license
package com.wondersgroup.scxj.portal.modules.sys.web.mobile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.wondersgroup.scxj.portal.common.config.Global; import com.wondersgroup.scxj.portal.modules.sys.entity.Updater; /** * A controller class to process the user related requests. * * @author Li RiChen */ @Controller @RequestMapping("${frontPath}/sys") public class SysMobileController { protected final Log logger = LogFactory.getLog(getClass()); public SysMobileController() { // userService = ServiceLocator.getUserService(); } @RequestMapping(value = "/validateversion", method = RequestMethod.GET, produces = "application/json") public @ResponseBody Updater getSysemVersion( HttpServletRequest request, HttpServletResponse response) { Updater updater = new Updater(); updater.setVersion(Global.getMobileClientVersion()); updater.setUpdateUrl("/static/app/scxj.apk"); return updater; } }
C
UTF-8
1,045
2.875
3
[]
no_license
#include<stdio.h> #include<fcntl.h> #include<stdlib.h> #include<unistd.h> #include<sys/stat.h> #include<semaphore.h> #include<sys/mman.h> int main(void) { int fd; int *mmap_addr; int *ptr; int ptr1 = 0; int pid; int i = 0; int zero = 0; sem_t *sem_addr; int sem_count; fd = shm_open("/shmq",O_RDWR|O_CREAT,0777); sem_addr = sem_open("/sem_phr12",O_CREAT,0777,2); printf("address of semaphore = %p\n",sem_addr); if(fd == -1){ printf("fail to open:\n"); exit(0); } ftruncate(fd,4096); sem_getvalue(sem_addr,&sem_count); printf("semaphore count = %d\n",sem_count); write(fd,&zero,4); mmap_addr = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(off_t)0); ptr = mmap_addr; pid = fork(); if(pid > 0){ printf("in parent process :\n"); for(i= 0; i <= 50 ; i++){ printf("parent : %d\n",(*ptr)++); printf("parent1 : %d\n",ptr1++); } } else if(pid == 0){ printf("in child process :\n"); for(i = 0;i <= 50;i++){ printf("child : %d\n",(*ptr)++); printf("child1 : %d\n",ptr1++); } } }
JavaScript
UTF-8
892
3.203125
3
[]
no_license
/* Treehouse Techdegree: FSJS Project 2 - Data Pagination and Filtering */ /* Create the `showPage` function This function will create and insert/append the elements needed to display a "page" of nine students */ function createElement(elementName, appendTo) { const element = document.createElement(elementName); appendTo.appendChild(element); } function showPage(list, page) { const startIndex = (page * 9) - 9; const endIndex = page * 9; const ul = document.querySelector(".student-list"); ul.innerHTML = ""; for (let i = 0; i < list.length; i++) { if (i >= startIndex && i < endIndex) { createElement(li,ul); createElement(div, li) } } } /* Create the `addPagination` function This function will create and insert/append the elements needed for the pagination buttons */ // Call functions
Java
UTF-8
4,741
1.789063
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2014 Fernando Rincon Martin <frm.rincon@gmail.com> * * 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.openeos.erp.core.ui; import org.openeos.erp.core.ui.actions.ChangeProfileAction; import org.openeos.services.ui.menu.AbstractMenuProvider; import org.openeos.services.ui.model.IMenuDefinition; import org.openeos.services.ui.model.IMenuDefinition.MenuType; public class CoreMenus extends AbstractMenuProvider { public static final String MENU_FINANCIAL_MANAGEMENT_ID = CoreMenus.class.getName() + ".MENU_FINANCIAL_MANAGEMENT_ID"; public static final String MENU_ACCOUNTING_ID = CoreMenus.class.getName() + ".MENU_ACCOUNTING_ID"; public static final String MENU_ACCOUNTING_SETUP_ID = CoreMenus.class.getName() + ".MENU_ACCOUNTING_SETUP_ID"; public static final String MENU_GENERAL_SETUP_ID = CoreMenus.class.getName() + ".MENU_GENERAL_SETUP"; public static final String MENU_CLIENT_GROUP_ID = CoreMenus.class.getName() + ".MENU_CLIENT_GROUP_ID"; public static final String MENU_CLIENT_ID = CoreMenus.class.getName() + ".MENU_CLIENT_ID"; public static final String MENU_ORGANIZATION_ID = CoreMenus.class.getName() + ".MENU_ORGANIZATION_ID"; public static final String MENU_SECURITY_ID = CoreMenus.class.getName() + ".MENU_SECURITY"; public static final String MENU_USERS_ID = CoreMenus.class.getName() + ".MENU_USERS"; public static final String MENU_MASTER_DATA_ID = CoreMenus.class.getName() + ".MENU_MASTER_DATA_ID"; public static final String MENU_BUSINESS_PARTNER_ID = CoreMenus.class.getName() + ".MENU_BUSINESS_PARTNER_ID"; public static final String MENU_CHANGE_PROFILE_ID = CoreMenus.class.getName() + ".MENU_BUSINESS_PARTNER_ID"; public IMenuDefinition MENU_FINANCIAL_MANAGEMENT = newMenu().id(MENU_FINANCIAL_MANAGEMENT_ID).action(MenuType.MENU) .name("Financial Management").description("Financial Management Menu").order(2000).build(); public IMenuDefinition MENU_ACCOUNTING = newMenu().id(MENU_ACCOUNTING_ID).parent(MENU_FINANCIAL_MANAGEMENT) .action(MenuType.MENU).name("Accounting").description("Accounting").order(100).build(); public IMenuDefinition MENU_ACCOUNTING_SETUP = newMenu().id(MENU_ACCOUNTING_SETUP_ID).parent(MENU_ACCOUNTING) .action(MenuType.MENU).name("Setup").description("Accounting Setup Menu").order(100).build(); public IMenuDefinition MENU_GENERAL_SETUP = newMenu().id(MENU_GENERAL_SETUP_ID).order(0).action(MenuType.MENU) .name("General Setup").description("General Setup Menu").build(); public IMenuDefinition MENU_CLIENT_GROUP = newMenu().id(MENU_CLIENT_GROUP_ID).order(0).action(MenuType.MENU).name("Client") .description("Client Setup").parent(MENU_GENERAL_SETUP).build(); public IMenuDefinition MENU_CLIENT = newMenu().id(MENU_CLIENT_ID).order(0).action(MenuType.WINDOW).name("Client") .description("Client Menu").parent(MENU_CLIENT_GROUP).window(CoreWindows.ClientWindow.ID).build(); public IMenuDefinition MENU_ORGANIZATION = newMenu().id(MENU_ORGANIZATION_ID).order(1000).action(MenuType.WINDOW) .name("Organization").description("Organization Menu").parent(MENU_CLIENT_GROUP) .window(CoreWindows.OrganizationWindow.ID).build(); public IMenuDefinition MENU_SECURITU = newMenu().id(MENU_SECURITY_ID).order(1000).action(MenuType.MENU).name("Security") .description("Security Menu").parent(MENU_GENERAL_SETUP).build(); public IMenuDefinition MENU_USERS = newMenu().id(MENU_USERS_ID).order(0).action(MenuType.WINDOW).name("Users") .description("Users Menu").parent(MENU_SECURITU).window(CoreWindows.UserWindow.ID).build(); public IMenuDefinition MENU_MASTER_DATA = newMenu().id(MENU_MASTER_DATA_ID).order(1000).action(MenuType.MENU) .name("Mater Data").description("Master Data Menu").build(); public IMenuDefinition MENU_BUSINESS_PARTNER = newMenu().id(MENU_BUSINESS_PARTNER_ID).order(0).action(MenuType.WINDOW) .name("Business Partner").description("Business Partner Menu").parent(MENU_MASTER_DATA) .window(CoreWindows.BusinessPartnerWindow.ID).build(); public IMenuDefinition MENU_CHANGE_PROFILE = newMenu().id(MENU_CHANGE_PROFILE_ID).parent(MENU_GENERAL_SETUP).order(-5000) .action(MenuType.CUSTOM).name("Change Profile").description("Change Profile Menu").customAction(ChangeProfileAction.ID) .build(); }
PHP
UTF-8
1,025
2.515625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class Locations extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('customer_locations', function (Blueprint $table) { $table->increments('id'); $table->integer('customer_id'); $table->date('created_at'); $table->date('updated_at'); $table->string('location_name', 150); $table->string('address', 400); $table->string('country', 30); $table->string('city', 30); $table->string('state', 30); $table->integer('zip'); $table->string('phone', 15); $table->tinyInteger('default'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('customer_locations'); } }
Markdown
UTF-8
2,903
2.6875
3
[]
no_license
2431 - STUDENT ACTIVITIES DURING HOLIDAY PERIODS ================================================ The Board of Education recognizes the importance of family unity during holiday periods, the educational value of family vacations and the importance of religious services. It is, therefore, the policy of the Board that a student's participation in athletics, extra-curricular or co-curricular activities not be limited on the basis of missed practices or competitions during holiday periods or during a family approved vacation, trip, or due to attending a religious service. For the purposes of this policy the following definitions will apply: Holiday Periods shall be defined as Labor Day, Thanksgiving day, and the associated non-student days, Christmas Eve, Christmas Day, and the associated non-student days, New Years Eve, New Years Day, Martin Luther King Day, Presidents Day, Good Friday, Easter Sunday, Spring Break, and the associated non-student days, Memorial Day, Independence Day, all Sundays, and Summer Break, but just the associated non-student days from August 1^st^ to the first day of school or Labor Day, whichever occurs first. The High School Athletic Director and/or building principal in the case of non-athletic activities may schedule for students in grades nine through twelve, competitions and events as appropriate, during the holiday period's associated non-student days described above. Participation by students in such events is not required, but shall be optional. The Junior High Athletic Director and/or building principal, in the case of non-athletic activities, shall not schedule for students in grades seven and eight any competitions or events during the Holiday Periods described above. The only events, which may be scheduled on any of those days, are those, which are scheduled by our athletic league or governing/controlling body of that competition without any local option to not schedule the event. Participation by students in such events is not required, but shall be optional. Should it be necessary and/or appropriate for a coach, director, or advisor to schedule a practice during a holiday period described above due to extenuating circumstances such as the timing of a tournament game, competition, or season opener, such practices must be approved in advance by the Superintendent of Schools. Participation by students in such practices is not required, but shall be optional. However, the coach, director, or advisor may limit participation after the student's return if the student's absence, in fact, resulted in a lack of material preparedness or physical condition. If any such limitation is imposed, the coach, director, or advisor shall immediately advise the student of the nature of and reason(s) for such limits, and shall assist the student in normalizing his/her level of participation as quickly as possible. Adopted 5/14/02
C#
UTF-8
1,591
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class UpdateBookForm : Form { private int BookId; private LogicLayer Business; public UpdateBookForm(int id) { InitializeComponent(); this.BookId = id; this.Business = new LogicLayer(); this.Load += UpdateBookForm_Load; this.btnSave.Click += btnSave_Click; this.btnCancel.Click += btnCancel_Click; } void btnCancel_Click(object sender, EventArgs e) { this.Close(); } void btnSave_Click(object sender, EventArgs e) { var namebook = this.txtNamebook.Text; var author = this.txtAuthor.Text; var topic = this.txtTopic.Text; var type = this.txtType.Text; this.Business.UpdateBook(this.BookId, namebook, author, topic, type); MessageBox.Show("Update Book successfuly"); this.Close(); } void UpdateBookForm_Load(object sender, EventArgs e) { var book = this.Business.GetBook(this.BookId); this.txtNamebook.Text = book.NameBook; this.txtAuthor.Text = book.Author; this.txtTopic.Text = book.Topic; this.txtType.Text = book.TypeExchange; } } }
JavaScript
UTF-8
2,962
3.390625
3
[]
no_license
import './App.css'; import {useState, useEffect} from 'react' import Square from './Components/Square' import { Patterns } from './Components/patterns' function App() { // STATES const [board, setBoard] = useState(["","","","","","","","",""]) // GAME BOARD const [player, setPlayer] = useState('X') // PLAYER TURN const [result, setResult] = useState( {winner:'none', state:'none'}); // THE WINNER // USEFFECTS // FOR ANY CHANGE ON THE BOARD, WE PERFORME CHECKS useEffect(()=>{ checkWin(); checkTied(); },[board]) // FOR ANY CHANGE ON RESULT, WE ALERT THE WINNER useEffect(()=>{ if (result.state !== 'none'){ alert(`Partie finie, le gagant est ${result.winner}`) restartGame(); } },[result]) // HANDLERS // HANDLE CLICK / FOR EACH CLICK, WE CHECK IF THE SQUARE IS EMPTY, WE SET THE VALUE, CHANGE THE PLAYER const handleSquare = (index) => { setBoard(board.map( (squareValue, squareIndex) => { if (squareIndex === index && squareValue === "") { return player; } return squareValue; } )); if (player === 'X'){ setPlayer('O')} else{ setPlayer('X')} } // FUNCTIONS // CHECK IF THE PLAYER HAS WON BASED THE KNOWN PATTERNS const checkWin = ()=> { Patterns.map((pattern)=>{ if (board[pattern[0]] === '') return; let win = true; pattern.forEach((index)=> { if (board[index] !== board[pattern[0]]) { win = false; } }) if ( win ) { setResult({winner:board[pattern[0]], state: 'Gagné' }); } }) } // CHECK IF GAME IS TIED, NO ONE HAS WON const checkTied =()=>{ let filled = true; board.forEach((square)=>{ if (square == ''){ filled = false; } }) filled && setResult({winner:'Personne', state:'partie finie' }) } // INITIALISE THE GAME IF GAME FINISHED OR CLICK ON RESTART BUTTON const restartGame = () => { setBoard(["","","","","","","","",""]) setPlayer('X') } return ( <div className="App"> <h1>JEU DE MORPION</h1> <p>Cliquer pour commencer</p> <div className="board"> <div className="row"> <Square val={board[0]} handleSquare={() => handleSquare(0)} /> <Square val={board[1]} handleSquare={() => handleSquare(1)}/> <Square val={board[2]} handleSquare={() => handleSquare(2)}/> </div> <div className="row"> <Square val={board[3]} handleSquare={() => handleSquare(3)} /> <Square val={board[4]} handleSquare={() => handleSquare(4)}/> <Square val={board[5]} handleSquare={() => handleSquare(5)}/> </div> <div className="row"> <Square val={board[6]} handleSquare={() => handleSquare(6)} /> <Square val={board[7]} handleSquare={() => handleSquare(7)}/> <Square val={board[8]} handleSquare={() => handleSquare(8)}/> </div> </div> <button className='btn-restart' onClick={()=>restartGame()}>Rejouer la partie</button> </div> ); } export default App;
Markdown
UTF-8
2,497
2.984375
3
[ "MIT" ]
permissive
--- title: Nick Davis awarded Honorary Life Membership of Liffey Valley Athletics Club location: Phoenix Park, Dublin --- Tonight, we presented an Honorary Life Membership of Liffey Valley Athletics Club Award to Nick Davis to officially recognise the long-term commitment, dedication, support and the significant contribution that Nick has made to LVAC over the years – Nick has been central and at the heart of many of the athletics success the club has had over the years. While many of us know the many achievements that Nick has had as an athlete and also with the club and indeed nationally and internationally, we would like to highlight a few: <b>Nick as an Athlete<b/> Nick started his athletic career with South Dublin Harriers where his main events were 200 and 400 meters and he medalled in the Leinster Senior championships over 200 metres. He also has the unusual claim to fame for a sprinter to have also won Dublin and Leinster Medals over the cross country when he was part of the Avondale team that won the Leinster Intermediate. He also ran one marathon. <b>Nick as a Coach<b/> Nick is a founding member of Liffey Valley and was appointed club coach upon the club’s inception. The club had immediate success and won many team titles at Regional and National Senior Level In the club’s first year he also coached Tom Brennan to win the National Senior Male Cross Country championships He also coached Kathryn Davis to win the Women’s National Senior title during those years. When the club revived the Women’s section in the early 2000's, Nick became coach and we have enjoyed many successes at Dublin, Leinster & National Level since then. <b>Athletics Ireland<b/> Nick is a founding member of the Athletics Association of Ireland in 1999 and was elected it's first President upon its inception. Nick has also been a council member of European Athletics for over 30 years and has attended meetings throughout Europe in that role. Nick has also been Team Manager of Irish teams at Olympic Games, World Championships and European Championships. RTE Radio Sport have relied on Nick as an Athletics Correspondent for many years, reporting on all the major athletics events throughout the country. Nick has also been heard throughout all major athletics events held in Ireland as the official announcer, including the World and European Cross Country Championships. <a href="https://www.instagram.com/p/CqXJ-57MnZ6/" target="_blank" rel="noopener noreferrer">Instagram</a>
JavaScript
UTF-8
4,815
3.171875
3
[]
no_license
var experience_array = ["None",">= 6 months",">= 1 years",">= 2 years",">= 5 years",">= 10 years"]; var qualification_array = ["10th","12th","B.C.A","M.sc(IT)","Ph.D."]; function Friend(name,isEnabled){ this.name=name; this.isEnabled=isEnabled; } var languages = [ new Friend("C/C++",false), new Friend("Java",true), new Friend("C#",true), new Friend("PHP",false), new Friend("Python",false) ]; function Create_Dynamic_Content(){ Create_Qual_DropDownList(); Create_expe_DropDownList(); Create_Lang_Checkbox(); } function Create_Qual_DropDownList(){ var qualification_dropdown = document.getElementById("qualification_dropdown"); // get qualification dropdown div reference var select_ = document.createElement("select"); // create Select select_.id = "qualification"; // assign select id select_.name = "qualification"; // assign select name qualification_dropdown.appendChild(select_); // append seelct to qualification dropdown div for (var i = 0; i < qualification_array.length; i++) { var option_ = document.createElement("option"); //create option option_.value = qualification_array[i]; // assign option value option_.text = qualification_array[i]; // asign option text select_.appendChild(option_); // append option to select } } function Create_expe_DropDownList(){ var experience_dropdown = document.getElementById("experience_dropdown"); // get experience dropdown div reference var select_ = document.createElement("select"); // create Select select_.id = "experience"; // assign select id select_.name = "experience"; // assign select name experience_dropdown.appendChild(select_); // append seelct to experience dropdown div for (var i = 0; i < experience_array.length; i++) { var option_ = document.createElement("option"); //create option option_.value = experience_array[i]; // assign option value option_.text = experience_array[i]; // asign option text select_.appendChild(option_); // append option to select } } function Create_Lang_Checkbox() { for(var i=0 ; i<languages.length ; i++){ var chk = document.createElement('input'); // create input chk.setAttribute('type', 'checkbox'); // define input type chk.setAttribute('id', languages[i].name); // assign checkbox id chk.setAttribute('value', languages[i].name); // assign checkbox value chk.setAttribute('name', 'languages'); // assign checkbox name if(languages[i].isEnabled===true)// check for default checked attribute { chk.setAttribute('checked', 'true'); } var lbl = document.createElement('label'); // create label. lbl.setAttribute('for', languages[i]); // attach label to checkbox lbl.appendChild(document.createTextNode(languages[i].name)); // create textnode for label and attach it container.appendChild(chk); // append checkbox to checkbox_div container.appendChild(lbl); // append checkbox to checkbox_div container.appendChild(document.createElement('br')); // create <br> and append it to checkbox_div } } var user; // use to store registratoni details function display(){ var form_ = document.getElementById("registration_form"); user = new user_details(form_.firstname.value,form_.lastname.value,form_.email.value,form_.contact.value,form_.address.value,form_.username.value,form_.pass.value,form_.gender.value,form_.qualification.value,form_.experience.value,form_.languages); /*alert(user.firstname); alert(user.lastname); alert(user.email); alert(user.contact); alert(user.address); alert(user.username); alert(user.pass); alert(user.gender); alert(user.qualification); alert(user.experience);*/ console.log("Firstname : "+user.firstname); console.log("lastName : "+user.lastname); console.log("Email : "+user.email); console.log("Contact Number : " +user.contact); console.log("Address : "+user.address); console.log("Username : "+user.username); console.log("Password : "+user.pass); console.log("Gender : "+user.gender); console.log("Qualification : "+user.qualification); console.log("Experience : "+user.experience); console.log("Coding Languages : "); for(var j=0;j<languages.length;j++) { console.log(languages[j]); } } function user_details(fname,lname,email,contact,address,uname,pass,gender,qual,expe,lang){ var i; this.firstname=fname; this.lastname=lname; this.email=email; this.contact=contact; this.address=address; this.username=uname; this.pass=pass; this.gender=gender; this.qualification=qual; this.experience=expe; this.languages = []; for(i=0;i<lang.length;i++) { if(lang[i].checked) { languages.push(lang[i].value); } } }
Python
UTF-8
3,423
3.734375
4
[]
no_license
#!/usr/local/bin/python3 ''' Title: malaria.py Date: 2020-10-11 Author: Linnea Olsson Description: This program will appended protein descriptions from a blast file to the end of the fasta id line in. The program puts the output in a file designated by the user. If there is no protein name indicated in the blast file (null), this fasta file will not be included in the output file. List of user defined functions (if any): List of modules used that are not explained in the course material: sys - module for using system specific parameters and functions. In this case for getting command line parameters Procedure: 1. Create an empty dictionary. 2. From a blast file, add id numbers as keys and hitDescriptions (protein description) as values into the dictionary. 3. Look for matching ids in the fasta file and the dictionary. 4. If a proper match (where the description is not null) is found, the hitDescription of that id in the dictionary is appended to the fasta header line and written into an output file along with the corresponding DNA sequence from the fasta file. Usage: python3 malaria.py malaria.blastx.tab malaria.fna output.txt ''' protDict = dict() #create empty dictionary import sys #to be able to insert command line arguments (the files) into the code with open(sys.argv[1], 'r') as f: #opens the file to read it and names it 'f' (and don't have to close it, by using with open()). [1] will be blast file headers = f.readline() #headers are first line for lines in f: #loops through the rest of the lines in f info = lines.split('\t') #split line by tabs and call the resulting list info protDict[info[0]] = info[9] # id is on column zero and the protein description is in column 9, save id as key and description as value with open(sys.argv[2], 'r') as t: #opens and reads command line argument[2] the fasta file open(sys.argv[3], 'w').write("") #opens command line argument [3] the output file, and writes nothing "", making sure the with command always starts in an empty output.txt, in case you run it several times. file = open(sys.argv[3], 'a') #opens the output file as "file" and appending information to it. to easily use this in the following loops for lines in t: #loops through lines in fasta file info = lines.split('\t') #lines are tab delimited, info is list of all objects in fasta file if ">" in info[0]: #info is a list, therefor looks for a '>' in the first object of the list info[3] = info[3].strip() #strip whitespace from list column in fastafile key = info[0][1:].strip() #id without '>' and removes the white space behind the id, and puts in 'key' name = protDict[key] #looks for id in dictionary and gets matching hitDescription if name != "null": #if the id is not value 'null' in the dictionary, then: info.append(name) #append the hitDescription to info in fasta file file.write("\t".join(info) + "\n") #opens output file and joins objects in info with tab as delimiter and adds new line at the end. writes this in output file else: #if line doesn't have a '>': if name != "null": #and if hitDescrption isn't 'null': file.write(info[0]) #write object one in info, seq, as next line. since info is list, we define the seq as the first object
PHP
UTF-8
1,679
2.78125
3
[ "PHP-3.0", "Apache-2.0" ]
permissive
<?php /** * 时间工具类 */ namespace app\common\utils; use app\common\bean\ListMap; class TimeUtil extends BaseUtil { static $_self = null; public static function getInstance(){ if(empty(self::$_self)){ self::$_self = new TimeUtil(); } return self::$_self; } /** 获取时间 * @param string $format * @return false|string */ public function getTimeNow($format = "Y-m-d H:i:s"){ return date($format); } /** 处理后台搜索时间间隔 * @param ListMap $listMap * @return array|bool */ public function dealBetweenTime(ListMap $listMap){ if($this->getParamBool($listMap,"beginTime")){ if($this->getParamBool($listMap,"endTime")){ $timeArray = array("between time",[$listMap->getParameter("beginTime"),$listMap->getParameter("endTime")]); }else{ $timeArray = array(">",$listMap->getParameter("beginTime")); } }else{ if($this->getParamBool($listMap,"endTime")){ $timeArray = array("<",$listMap->getParameter("endTime")); } } if(isset($timeArray)){ //array_unshift($timeArray,$field); return $timeArray; } return false; } /** 获取搜索的参数是否参与/存在 * @param ListMap $listMap * @param $param * @return bool */ private function getParamBool(ListMap $listMap,$param){ $data = $listMap->getData(); if(!isset($data[$param]) || $data[$param] == ''){ return false; } return true; } }
PHP
UTF-8
363
2.546875
3
[ "MIT" ]
permissive
<?php namespace Concrete\Core\User\Group\Command\Traits; trait ExistingGroupTrait { protected $groupID; /** * @return mixed */ public function getGroupID() { return $this->groupID; } /** * @param mixed $groupID */ public function setGroupID($groupID) { $this->groupID = $groupID; } }
Java
UTF-8
1,586
2.09375
2
[]
no_license
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import sun.applet.Main; public class LoginPage { private By loginLink = By.cssSelector("[tabindex='5']"); private By usernameLocator = By.name("login_username"); private By passwordLocator = By.name("login_password"); private By sslLocator = By.className("login-ssl"); private final WebDriver driver; public LoginPage(WebDriver driver) { this.driver = driver; } public MainPage login(String login, String password) { WebElement link = driver.findElement(loginLink); link.click(); WebElement loginElement = driver.findElement(usernameLocator); loginElement.sendKeys(login); WebElement passwordElement = driver.findElement(passwordLocator); passwordElement.sendKeys(password); WebElement sslElement = driver.findElement(sslLocator); sslElement.click(); passwordElement.submit(); (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith("rutracker.org"); } }); WebElement loginButton = driver.findElement(By.xpath("//*[@id=\"login-form-full\"]/table/tbody/tr[2]/td/div/table/tbody/tr[4]/td/input")); loginButton.click(); return new MainPage(driver); } }
C++
UTF-8
1,087
3.171875
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; const int maxn = 10005; int n, g, k; struct Stu { int rank{}; string username; int grade{}; } stu[10005]; bool cmp(const Stu& a, const Stu& b) { if (a.grade == b.grade) { return a.username < b.username; } return a.grade > b.grade; } int money; int main() { cin >> n >> g >> k; for (int i = 0; i < n; i++) { cin >> stu[i].username >> stu[i].grade; if (stu[i].grade >= 60 && stu[i].grade < g) { money += 20; } if (stu[i].grade >= g && stu[i].grade <= 100) { money += 50; } } sort(stu, stu + n, cmp); stu[0].rank = 1; for (int i = 1; i < n; i++) { if (stu[i].grade == stu[i - 1].grade) { stu[i].rank = stu[i - 1].rank; } else { stu[i].rank = i + 1; } } cout << money << endl; for (int i = 0; i < n; i++) { if (stu[i].rank > k) break; cout << stu[i].rank << " " << stu[i].username << " " << stu[i].grade << endl; } }
Go
UTF-8
701
3.25
3
[ "MIT" ]
permissive
package ntlmv2hash import ( "encoding/binary" "fmt" "golang.org/x/crypto/md4" "unicode/utf16" ) // NTPasswordHash computes the NTLM v2 password hash. // // The output is password-equivalent and easy to reverse. It must be // guarded just as well as the original password. func NTPasswordHash(password string) string { input := utf16.Encode([]rune(password)) h := md4.New() if err := binary.Write(h, binary.LittleEndian, input); err != nil { // these are all in-memory operations with no error modes, // but just in case panic(fmt.Errorf("impossible error hashing password: %w", err)) } output := h.Sum(nil) // encode to conventional uppercase hex return fmt.Sprintf("%X", output) }
TypeScript
UTF-8
689
3.765625
4
[]
no_license
'use strict'; enum Colors { Orange, Yellow, Brown, Red } let selectedColor = Colors.Red; //regular if, else if, else statement if (selectedColor == Colors.Yellow) { console.log('Yellow'); } else if (selectedColor == Colors.Orange) { console.log('Orange'); } else if (selectedColor == Colors.Brown) { console.log('Brown'); } else (selectedColor == Colors.Red) console.log('Red'); //ternary if statement example console.log( selectedColor == Colors.Yellow ? 'Yellow' : selectedColor == Colors.Orange ? 'Orange' : selectedColor == Colors.Brown ? 'Brown' : 'Red');
Python
UTF-8
234
2.53125
3
[]
no_license
import abc class FormatterInterface: """ Interface ot implement different formatter types depending on requirements """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def __call__(self, state): pass
Markdown
UTF-8
2,093
3.09375
3
[]
no_license
--- layout: post title: "Using CSS to hide evil things" style: csshack date: 2020-07-21 --- ## Topic Good evening neighbors, <br /> Quickie: Today I'd like to talk to you about a thing everyone does but no one pays a lot of attention to it. > __Copy/Pasting things from the internet into your terminal__ One would think what could possibly happen if I just copy this code from some website I've found to fix my issue on the server. Well lets see... ## What you see isn't what you get Let's take the following example: <br /> Please use the textarea below to copy/paste the example into. {% include csshack.html %} <img src="/assets/images/pikachu.jpg" style="max-width:20%" class="center"> <br /> While this attack isn't highly sophisticated I can think of multiple sysadmins off the top of my head who would own their own server if they would be targeted by this attack. ## Craft __HTML__ ``` <span id="select"> Copy/Paste to fix your <p id="danger"> <br /> rm -rf / # all your base are belong to us <br /> </p> server </span> ``` __CSS__ ``` span#select{ color: blue; user-select: all; } p#danger{ display: inline-block; font-size:0px; } ``` "display:inline-block" is used that the <br/> tags don't create a newline in html but act as newline in a bash terminal which is equivalent as hitting the enter key. (doesn't work with zsh) "font-site:0px" is used to hide the text. "user-select: all" was just added for convenience and could even be suspicious to the trained eye. ## Why not JS/HTML5? Of course it would be easier to copy any content to the user clipboard with HTML5/JS. But I've wanted to share some CSS tricks with you guys. There's also the CSS keylogger which I may share somewhere down the line. ## Conclusion I've just wanted to share this piece of unlikely tech which could prevent you from executing malicious code on your servers. :) Also don't run around and just copy/paste stuff in your terminal. ### Likelihood Highly unlikely ヽ(゚_゚)ノ <br /> Thanks for reading.
Python
UTF-8
635
3.1875
3
[]
no_license
import pygame # create list of buttons class buttons: buttonlist = [] # add buttons to list def add(self, bt): self.buttonlist.append(bt) # draw all buttons def draw(self, win): for bt in self.buttonlist: bt.draw(win, (0, 0, 0)) # process events for all buttons def proc_event(self, event): pos = pygame.mouse.get_pos() for bt in self.buttonlist: if event.type == pygame.MOUSEBUTTONDOWN: if bt.isOver(pos): bt.clicked(pos) if event.type == pygame.MOUSEMOTION: bt.mouseover(bt.isOver(pos))
Java
UTF-8
7,270
3.015625
3
[]
no_license
package model; import java.util.ArrayList; public class Animal{ //Constantes public static final String GATO = "Gato"; public static final String PERRO = "Perro"; public static final String AVE = "Ave"; public static final String OTRO = "Otro"; //Attributes private String name; private double height; private double weight; private String type; private int age; private String breed; //Relations private ClinicHistory cH; private HRoom room; private ArrayList<ClinicHistory> clientH; //Methods public Animal(String name, double height, double weight, String type, int age, String breed, ClinicHistory cH){ this.name = name; this.height = height; this.weight = weight; this.type = type; this.age = age; this.breed = breed; this.cH = cH; clientH = new ArrayList<ClinicHistory>(); } //name /** * Description This method allows to get the name of the pet. <br> * <b>post:</b> The name of the pet is given. * @return The name of the pet. */ public String getName(){ return name; } /** * Description This method allows to change the name of the pet. <br> * <b>post:</b> The name of the pet is changed. * @param The new name of the pet. */ public void setName(String name){ this.name = name; } //height /** * Description This method allows to get the height of the pet. <br> * <b>post:</b> The height of the pet is given. * @return The height of the pet. */ public double getHeight(){ return height; } /** * Description This method allows to change the height of the pet. <br> * <b>post:</b> The height of the pet is changed. * @param The new height of the pet. */ public void setHeight(double height){ this.height = height; } //weight /** * Description This method allows to get the weight of the pet. <br> * <b>post:</b> The weight of the pet is given. * @return The weight of the pet. */ public double getWeight(){ return weight; } /** * Description This method allows to change the weight of the pet. <br> * <b>post:</b> The weight of the pet is changed. * @param The new weight of the pet. */ public void setWeight(double weight){ this.weight = weight; } //type /** * Description This method allows to get the type of the pet. <br> * <b>post:</b> The type of the pet is given. * @return The type of the pet. */ public String getType(){ return type; } /** * Description This method allows to change the type of the pet. <br> * <b>post:</b> The type of the pet is changed. * @param The new type of the pet. */ public void setType(String type){ this.type = type; } //age /** * Description This method allows to get the age of the pet. <br> * <b>post:</b> The age of the pet is given. * @return The age of the pet. */ public int getAge(){ return age; } /** * Description This method allows to change the age of the pet. <br> * <b>post:</b> The age of the pet is changed. * @param The new age of the pet. */ public void setAge(int age){ this.age = age; } //breed /** * Description This method allows to get the breed of the pet. <br> * <b>post:</b> The breed of the pet is given. * @return The breed of the pet. */ public String getBreed(){ return breed; } /** * Description This method allows to change the breed of the pet. <br> * <b>post:</b> The breed of the pet is changed. * @param The new breed of the pet. */ public void setBreed(String breed){ this.breed = breed; } //room /** * Description This method allows to get the whole object. <br> * <b>post:</b> The whole object is given. * @return The object room. */ public HRoom getRoom(){ return room; } /** * Description This method allows to change the object room. <br> * <b>post:</b> The object room is changed. * @param The new object room. */ public void setRoom(HRoom room){ this.room = room; } /** * Description This method allows to make a list with the pet information. <br> * <b>pre:</b> The pet was created before and its attributes are not null. * @return The information of the animal. */ //infoPet public String infoPet(){ String msj = ""; msj += "Mi nombre es:" + name + "\n"; msj += "Su edad es:" + age + "\n"; msj += "Su altura es:" + height + "\n"; msj += "Mi peso es:" + weight + "\n"; msj +="Mi tipo es:" + type + "\n"; msj +="Mi indice de masa corporal es: "+ calculateBMI() + "\n\n"; return msj; } /** * Description This method allows to get symptom of the animal in the room and allows to do another method. <br> * @return The symptom of the pet in the room. */ public String symptomPet(){ return cH.getSymptom(); } /** * Description This method allows to get diagnosis of the animal in the room and allows to do another method. <br> * @return The diagnosis of the pet in the room. */ public String diagnosisPet(){ return cH.getDiagnosis(); } //calculateBMI /** *Description This method allows to calculate the body mass index for a pet. *pre: The pet was created before and its attributes height and weight are not null neither height must be zero. *post: The BMI is calculated. *@return The pet body mass index. Returns -1 if the height is zero due to the division on zero does not exist. */ public double calculateBMI(){ double bmi = 0.0; if(height == 0){ bmi = -1.0; }else{ bmi += (weight / (height * height)); } return bmi; } /** *Description This method allows to add new medicines that were prescription during the hospitalization at the patient stories. *pre: The patient clinic story must be not null. *post: New medicines were added to the patient clinic story. *@param The medicine name. This param must be not null. *@param The medicine dose, this param refers to the amount of medicine supplied to the pet each time according the frequence assigned. *@param The medicine cost by each dose. This param could be empty. *@param The frequency of medicine application. This param could be empty. *@return A message that indiques if medicine was added to the patient clinic story */ public String addNewMedicine(String mName, double mDose, double mDP, String mFreq){ String msj = "El medicamento ha sido agregado"; cH.addNewMedicine(mName, mDose, mDP, mFreq); return msj; } /** *Description This method allows to add new notes to the possible diagnostic during the hospitalization at the patient stories. *pre: The patient clinic story must be not null. *post: New notes were added to the possible diagnostic in the patient clinic story. *@param The notes of possible diagnostic. This param must be not null. */ public void addNewDiagnosis(String nDiagnosis){ cH.addNewDiagnosis(nDiagnosis); } /** *Description This method allows to add new notes to the possible diagnostic during the hospitalization at the patient stories. *pre: The patient clinic story must be not null. *post: New notes were added to the possible diagnostic in the patient clinic story. *@param The notes of possible diagnostic. This param must be not null. */ public void addNewSymptom(String nSymptom){ cH.addNewSymptom(nSymptom); } }//final
Java
UTF-8
1,586
3.796875
4
[]
no_license
import java.io.*; import java.util.*; public class KDifference { public static void main(String[] args) throws Exception { Reader rd; if(args.length == 0) rd = new InputStreamReader(System.in); else rd = new FileReader(args[0]); new KDifference().run(rd); } private void run(Reader r) throws Exception { BufferedReader br = new BufferedReader(r); // Read first line of N and K StringTokenizer st = new StringTokenizer(br.readLine()); // Store the values of N and K int N = Integer.parseInt(st.nextToken()); int K = Integer.parseInt(st.nextToken()); Set<Integer> set = new HashSet<Integer>(N); int count = 0; // Now read the second line for getting N integers st = new StringTokenizer(br.readLine()); for(int i = 0; i < N; i++) { // Get a number from line int x = Integer.parseInt(st.nextToken()); // Generate two numbers, one smaller than it by K digits and another greater int a = x - K; int b = x + K; // Check whether these numbers exist in the set or not if(set.contains(a)) count++; if(set.contains(b)) count++; // Add the current integer to the set set.add(x); } // Emit the count System.out.println(count); } }
Java
UTF-8
1,431
1.9375
2
[]
no_license
package com.ys.idatrix.metacube.metamanage.service; import com.ys.idatrix.metacube.metamanage.domain.*; import com.ys.idatrix.metacube.metamanage.vo.request.AlterSqlVO; import com.ys.idatrix.metacube.metamanage.vo.request.DBViewVO; import com.ys.idatrix.metacube.metamanage.vo.request.MySqlTableVO; import java.util.ArrayList; import java.util.List; /** * @ClassName MySqlDDLService * @Description mysql ddl 语句生成api * @Author ouyang * @Date */ public interface MySqlDDLService { // 获取创建表的sql ArrayList<String> getCreateTableSql(Metadata table, List<TableColumn> columnList, List<TableIdxMysql> tableIndexList, List<TableFkMysql> tableFkMysqlList); // 获取修改表的sql AlterSqlVO getAlterTableSql(MySqlTableVO newTable, MySqlTableVO snapshotTable); // 获取删除表的sql List<String> getDeleteTableSql(List<String> removeTableNames); // 获取创建视图的sql String getCreateOrUpdateViewSql(String name, ViewDetail viewDetail); // 获取修改视图的sql AlterSqlVO getAlterViewSql(DBViewVO snapshotMySqlView, DBViewVO newMySqlView); // 获取删除视图的sql List<String> getDropViewSql(List<String> viewNames); // 将操作生效到数据库中 void goToDatabase(Metadata metadata, List<String> commands); // 将操作生效到数据库中 void goToDatabase(String user, Metadata metadata, List<String> commands); }
Java
UTF-8
617
2.0625
2
[ "MIT" ]
permissive
package es.upm.miw.apaw_ep_jesus_garceran.sponsor_resource; import es.upm.miw.apaw_ep_jesus_garceran.exceptions.NotFoundException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @Controller public class SponsorBusinessController { private SponsorDao sponsorDao; @Autowired public SponsorBusinessController(SponsorDao sponsorDao) { this.sponsorDao = sponsorDao; } public void delete(String id) { sponsorDao.delete(sponsorDao.findById(id).orElseThrow(() -> new NotFoundException("Sponsor id: " + id))); } }
Python
UTF-8
2,210
2.53125
3
[]
no_license
from django.db import models # Add description for Submissions and Comments in the 2nd phase class Subreddit(models.Model): id = models.CharField(primary_key=True, max_length=20) display_name = models.CharField(max_length=30, blank=False, default="") title = models.CharField(max_length=100, blank=False, default="") def __str__(self): return self.display_name class Redditor(models.Model): id = models.CharField(primary_key=True, max_length=20) name = models.CharField(max_length=50, blank=False, default="") def __str__(self): return self.name class Submission(models.Model): id = models.CharField(primary_key=True, max_length=20) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) redditor = models.ForeignKey(Redditor, on_delete=models.CASCADE) karma = models.IntegerField() upvote_ratio = models.DecimalField(max_digits=10, decimal_places=2) num_comments = models.IntegerField() created_utc = models.DateTimeField() def __str__(self): return self.id class Comment(models.Model): id = models.CharField(primary_key=True, max_length=20) subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) redditor = models.ForeignKey(Redditor, on_delete=models.CASCADE) submission = models.ForeignKey(Submission, on_delete=models.CASCADE) karma = models.IntegerField() created_utc = models.DateTimeField() def __str__(self): return self.id # Top 5 submitters and commenters per week class WeeklyRedditorScore(models.Model): class ScoreType(models.TextChoices): SUBMISSION = "SUB", "Submission" COMMENT = "COM", "Comment" subreddit = models.ForeignKey(Subreddit, on_delete=models.CASCADE) redditor = models.ForeignKey(Redditor, on_delete=models.CASCADE) score_type = models.CharField(max_length=3, choices=ScoreType.choices, blank=False) score = models.DecimalField(max_digits=10, decimal_places=2) rank = models.PositiveIntegerField() week_number = models.PositiveIntegerField() created_utc = models.DateTimeField() def __str__(self): return f"Score type: {self.score_type} with rank: {self.rank}"
Java
UTF-8
2,088
1.703125
2
[]
no_license
// isComment package org.wheelmap.android.fragment; import org.wheelmap.android.app.WheelmapApp; import org.wheelmap.android.model.Extra; import org.wheelmap.android.online.R; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; public class isClassOrIsInterface extends SearchDialogFragment implements OnCheckedChangeListener { WheelmapApp isVariable; private String isVariable = null; public static final SearchDialogCombinedFragment isMethod() { SearchDialogCombinedFragment isVariable = new SearchDialogCombinedFragment(); Bundle isVariable = new Bundle(); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, true); isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, true); isNameExpr.isMethod(isNameExpr); return isNameExpr; } protected View isMethod() { isNameExpr = (WheelmapApp) this.isMethod().isMethod(); try { isNameExpr = isNameExpr.isMethod(); } catch (Exception isParameter) { } LayoutInflater isVariable = isNameExpr.isMethod(isMethod()); View isVariable = isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr, null); if (isNameExpr != null) { ((EditText) isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr)).isMethod(isNameExpr); isNameExpr.isMethod(null); } isNameExpr.isMethod(isNameExpr.isFieldAccessExpr.isFieldAccessExpr).isMethod(new View.OnClickListener() { @Override public void isMethod(View isParameter) { isNameExpr.isMethod(true); isMethod(); isMethod(); } }); return isNameExpr; } protected void isMethod(final View isParameter) { super.isMethod(isNameExpr); // isComment } @Override public void isMethod(RadioGroup isParameter, int isParameter) { } }
Markdown
UTF-8
7,727
2.546875
3
[]
no_license
# Download Song of Angels (Kei Yadosh) Video and Lyrics | Dunsin Oyekan [Music](https://estheradeniyi.com/category/music/) # Download Song of Angels (Kei Yadosh) Video and Lyrics | Dunsin Oyekan by [Esther Adeniyi](https://estheradeniyi.com/author/esther-adeniyi/)on [October 17, 2018October 17, 2018](https://estheradeniyi.com/song-of-angels-kei-yadosh-dunsin-oyekan/)[Leave a Comment on Download Song of Angels (Kei Yadosh) Video and Lyrics | Dunsin Oyekan](https://estheradeniyi.com/song-of-angels-kei-yadosh-dunsin-oyekan/#respond) ![Kei Yadosh by Dunsin Oyekan](images\Kei-Yadosh-by-Dunsin-Oyekan.jpg) Sharing is caring! - [0](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Festheradeniyi.com%2Fsong-of-angels-kei-yadosh-dunsin-oyekan%2F&amp;t=Download%20Song%20of%20Angels%20%28Kei%20Yadosh%29%20Video%20and%20Lyrics%20%7C%20Dunsin%20Oyekan) - [0](https://twitter.com/intent/tweet?text=Download%20Song%20of%20Angels%20%28Kei%20Yadosh%29%20Video%20and%20Lyrics%20%7C%20Dunsin%20Oyekan&amp;url=https%3A%2F%2Festheradeniyi.com%2Fsong-of-angels-kei-yadosh-dunsin-oyekan%2F) - [0](#) 0shares ## Song of Angels (Kei Yadosh) Lyrics Kei Yadosh Kalamba Yandei Kei Yadosh Kalamba Yandei Related: [My tomorrow must be greater than today](https://estheradeniyi.com/download-my-tomorrow-must-be-greater-than-today-by-david-ekene-lyrics/) Sometimes You need to confuse the enemy and go in tongues Kei Yadosh Kalamba Yandei Kei Yadosh Kalamba Yandei Hey Hey Hey Hey Hey Hey Hey Hey Hey Hey Hey Hey Say Hey Hey Hey Hey Hey Hey Anybody ready for war Hey Hey Hey I&#x2019;m ready for war (Drums and other instruments playing) Everybody say Hey Hey Hey Look at your neighbour and say You are war Hey Hey Hey Hey Hey Hey Hey Hey Hey Related: [You made a way by Travis Greene](https://estheradeniyi.com/download-travis-greene-made-a-way/) Hey Hey Hey Hey Hey Hey Everybody lift your voice and say Hey Hey Hey Kei Yadosh Kalamba Yandei Kei Yadosh Kalamba Yandei Kei Yadosh Kalamba Yandei Kei Yadosh Kalamba Yandei Kei Yadosh Kalamba Yandei Kei Yadosh Kalamba Yandei Say Hey Hey Hey Hey Hey Hey Kei Yadosh Kalamba Yandei Say Kei Yadosh Kei Yadosh Kalamba Yandei Say Kei Yadosh Kei Yadosh Kalamba Yandei Say Hey Hey Hey Hey Hey Hey You alone are worthy of praise You alone are worthy of praise You alone You alone are worthy of praise Say You You alone are worthy of praise Say Hey Hey hey Hey hey hey You alone are worthy of praise You alone are worthy of praise Related : [Nobody like Jesus by Neville](https://estheradeniyi.com/nobody-like-jesus-by-neville-d-ft-cjay/) You alone You alone are worthy of praise You alone You alone are worthy of praise Alagbara bi ara o! (The One that Has power like thunder) Eya Judah (From the tribe of Judah) Kinium de eya Judah (The Lion of the tribe of Judah has come) Alagbara bi ara o! (The One that Has power like thunder) Eya Judah (From the tribe of Judah) Kinium de eya Judah (The Lion of the tribe of Judah has come) Call and Response Resp: Kinium de eya Judah (The Lion of the tribe of Judah has come) Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Resp: Kinium de eya Judah (The Lion of the tribe of Judah has come) Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Resp: Kinium de eya Judah (The Lion of the tribe of Judah has come) Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Resp: Kinium de eya Judah (The Lion of the tribe of Judah has come) Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Resp: Kinium de eya Judah (The Lion of the tribe of Judah has come) Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Ode (He&#x2019;s here) Resp: Ode Resp: Kinium de eya Judah (The Lion of the tribe of Judah has come) Ode (He&#x2019;s here) Ode (He&#x2019;s here) Ajagun ma fi ti bon se&#x2026; Ode (A warrior who doesn&#x2019;t need a gun) Ode (He&#x2019;s here) (In Yoruba, there is an adage) Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju It means what is scaring me Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju And this is what you do to the enemy Hey!!!&#x2026;, Hey Hey Hey Call and Response Resp: Hey Hey Hey Resp: Hey Hey Hey Lift your voice, Lift your soul Lift your heart and say Hey Hey Hey Resp: Hey Hey Hey One more time say Ki lon dun mahuru mahuru&#x2026; say! Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Hey Hey Hey Resp: Hey Hey Hey Hey Hey Hey Resp: Hey Hey Hey Resp: Hey Hey Hey Resp: Hey Hey Hey Lift Your voice and say Related: [Amaghimo by Password](https://estheradeniyi.com/amaghimo-by-password-lyrics/) (All) Resp: Hey Hey Hey Resp: Hey Hey Hey Resp: Hey Hey Hey Resp: Hey Hey Hey Resp: Hey Hey Hey (Prayers and exaltation) Resp: Hey Hey Hey Resp: Hey Hey Hey Call: Hey Hey Hey Resp: Hey Hey Hey Resp: Hey Hey Hey Call: Hey Hey Hey Resp: Hey Hey Hey Call: Say Hey Hey Hey Resp: Hey Hey Hey (Prayers and exaltation) Call: Say Hey Hey Hey Resp: Hey Hey Hey Call: Hey Hey Hey Resp: Hey Hey Hey Call: Say Hey Hey Hey Resp: Hey Hey Hey Call: Say Hey Hey Hey Resp: Hey Hey Hey Call: Hey Resp: Hey Hey Hey Ki lon dun mahuru mahuru&#x2026; say! Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Resp: Ki lon dun mahuru mahuru mahuru mahuru mahuru mahuru mahuru momi loju Resp: Hey Hey Hey Resp: Hey Hey Hey Call: Hey Hey Hey Resp: Hey Hey Hey (Prayers and exaltation) Lyrics source: [Gospelsongsng](https://gospelsongsng.com/kei-yadosh-download-video-and-lyrics-dunsin-oyekan/) ## [Song of Angels (Kei Yadosh) Download](https://gospelsongsng.com/kei-yadosh-download-video-and-lyrics-dunsin-oyekan/) Sharing is caring! - [0](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Festheradeniyi.com%2Fsong-of-angels-kei-yadosh-dunsin-oyekan%2F&amp;t=Download%20Song%20of%20Angels%20%28Kei%20Yadosh%29%20Video%20and%20Lyrics%20%7C%20Dunsin%20Oyekan) - [0](https://twitter.com/intent/tweet?text=Download%20Song%20of%20Angels%20%28Kei%20Yadosh%29%20Video%20and%20Lyrics%20%7C%20Dunsin%20Oyekan&amp;url=https%3A%2F%2Festheradeniyi.com%2Fsong-of-angels-kei-yadosh-dunsin-oyekan%2F) - [0](#) 0shares Tags:[Download Song of Angels (Kei Yadosh) by Dunsin Oyekan](https://estheradeniyi.com/tag/download-song-of-angels-kei-yadosh-by-dunsin-oyekan/)[Dunsin Oyekan](https://estheradeniyi.com/tag/dunsin-oyekan/)[Song of Angels (Kei Yadosh) Video and Lyrics](https://estheradeniyi.com/tag/song-of-angels-kei-yadosh-video-and-lyrics/)[song of angels by Dunsin Oyekan](https://estheradeniyi.com/tag/song-of-angels-by-dunsin-oyekan/)[song of angels mp3 download](https://estheradeniyi.com/tag/song-of-angels-mp3-download/)[Song of angels video](https://estheradeniyi.com/tag/song-of-angels-video/)
Markdown
UTF-8
1,598
2.796875
3
[]
no_license
#Radio_Performance.py ## A tool for monitoring radio performance using NMEA Messages ### Usage >Radio_Performance.py [-h] [--version] [-T] [-c] [-d DURATION] [-v] host port [name [name ...]] ####positional arguments: > host: GNSS Receiver IP or name > port: GNSS TCP Port that the NMEA GGA Messages are available on > name: Test Name ####optional arguments: >-h, --help > show this help message and exit >--version > show program's version number and exit >-T, --tell > Tell the settings for the run >-c, --csv > Output in a CSV Format >-d DURATION, --duration DURATION > Test Time, in seconds >-v, --verbose > increase output verbosity (use up to 3 times) ### Usage Details * Duration: The length of the time the test wil run for * CSV: Output the information in CSV Format * Tell: Report the arguments that are in use ### CSV Format The CSV Format has a fixed number of standard columns followed by details 1. Host 2. Port 3. Test Name, with "" 4. Start Time of Test 5. End Time of Test 6. Test Time 7. RTK Epochs 8. Non RTK Epochs 9. Packet Received this epoch 10. Packet Received this epoch, % 11. Packet Received this epoch 12. Packet missed for 1 epoch 13. Packet missed for 1 epoch, % Next Columns are repeating, 2 second, 3 second etc.... 1. Number of Epochs of this age 2. % of Total Epochs of this age ## Requirements pynmea2 >*pip install pynmea2*
Java
UTF-8
1,522
4.28125
4
[]
no_license
package LeetCode; /** * LeetCode 191 * 题意: * 编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。 * 输入:00000000000000000000000000001011 * 输出:3 * 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 * 输入:11111111111111111111111111111101 * 输出:31 * 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 * 提示: * 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。 * 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数 -3。 * 思路:统计1的个数,有个操作 n & (n - 1),将最后面的1置为0,只要n != 0,就继续把尾部1置为0,统计次数,即为1的个数 * 99.19% , 5.26% */ public class NumberOf1Bits191 { public static void main(String[] args) { int n = -3; int res = hammingWeight(n); System.out.println(res); } public static int hammingWeight(int n){ int count = 0; while(n != 0){ n = n & (n - 1); count ++ ; } return count; } }
Java
UTF-8
1,278
2.140625
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 telus.test.voting.serviceImpl; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.List; import telus.test.voting.entity.User; import telus.test.voting.repository.UserRepository; @Service("userDetailsServiceImpl") public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findByUser(username); List<GrantedAuthority> authorities = new ArrayList<>(); return new org.springframework.security.core.userdetails.User(user.getUser(), user.getPassword(), authorities); } }
Java
UTF-8
8,412
1.679688
2
[]
no_license
package hba; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import common.FormatDateText; import layout.MenuModel; import model.CustomerContact; import model.QbListsModel; import model.VendorModel; import org.apache.log4j.Logger; import org.zkoss.bind.BindUtils; import org.zkoss.bind.Form; import org.zkoss.bind.ValidationContext; import org.zkoss.bind.Validator; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.ContextParam; import org.zkoss.bind.annotation.ContextType; import org.zkoss.bind.validator.AbstractValidator; import org.zkoss.lang.Strings; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Path; import org.zkoss.zk.ui.Session; import org.zkoss.zk.ui.Sessions; import org.zkoss.zk.ui.util.Clients; import org.zkoss.zul.Messagebox; import org.zkoss.zul.Window; import setup.users.WebusersModel; public class EditVendorViewModel { private Logger logger = Logger.getLogger(this.getClass()); VendorsData data=new VendorsData(); HBAData dataHba=new HBAData(); private VendorModel selectedVendor; private boolean activeVendor; private boolean canSave; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Calendar c = Calendar.getInstance(); Date creationdate; private MenuModel companyRole; private CustomerContact compSetting; public EditVendorViewModel() { try { Execution exec = Executions.getCurrent(); Map map = exec.getArg(); int vendKey=(Integer)map.get("vendKey"); String type=(String)map.get("type"); Window win = (Window)Path.getComponent("/vendorModalDialog"); if(type.equals("edit")) { canSave=true; win.setTitle("Edit Vendor Info"); } else if(type.equalsIgnoreCase("Add")) { canSave=true; win.setTitle("Add New Vendor Info"); } else { win.setTitle("View Vendor Info"); } Session sess = Sessions.getCurrent(); WebusersModel dbUser=(WebusersModel)sess.getAttribute("Authentication"); getCompanyRolePermessions(dbUser.getCompanyroleid(),4); CustomerData cdata=new CustomerData(); compSetting = cdata.getCOMPANYSETTINGS(); if(vendKey>0) { selectedVendor=data.getVendorByKey(vendKey); activeVendor=selectedVendor.getIsActive().equals("Y"); if(selectedVendor.getIsActive().equals("N")) { activeVendor=true; } else { activeVendor=false; } } else { selectedVendor=new VendorModel(); selectedVendor.setName(""); selectedVendor.setArName(""); selectedVendor.setPhone(""); selectedVendor.setCompanyName(""); selectedVendor.setBillAddress1(""); selectedVendor.setPhone(""); selectedVendor.setFax(""); selectedVendor.setEmail(""); selectedVendor.setWebSite(""); selectedVendor.setContact(""); selectedVendor.setPrintChequeAs(""); selectedVendor.setBankName(""); selectedVendor.setBranchName(""); selectedVendor.setIbanNo(""); selectedVendor.setAltContact(""); selectedVendor.setAltPhone(""); selectedVendor.setSkypeId(""); selectedVendor.setMiddleName(""); selectedVendor.setFirstName(""); selectedVendor.setAccountName(""); selectedVendor.setAccountNumber(""); selectedVendor.setSalutation(""); selectedVendor.setLastName(""); selectedVendor.setNote(""); selectedVendor.setcC(""); selectedVendor.setIsActive("false"); activeVendor=false; } } catch (Exception ex) { logger.error("ERROR in EditVendorViewModel ----> init", ex); } } public Validator getTodoValidator(){ return new AbstractValidator() { public void validate(ValidationContext ctx) { //get the form that will be applied to todo VendorModel fx = (VendorModel)ctx.getProperty().getValue(); String name = fx.getName(); if(Strings.isBlank(name)) { Clients.showNotification("Please fill all the required fields (*) !!"); //mark the validation is invalid, so the data will not update to bean //and the further command will be skipped. ctx.setInvalid(); } } }; } @Command public void updateVendor(@ContextParam(ContextType.VIEW) Window comp) throws ParseException { int result=0; if(FormatDateText.isEmpty(selectedVendor.getName())) { Messagebox.show("Please Enter the Vendor Name.","Vendor List",Messagebox.OK , Messagebox.INFORMATION); return; } List<QbListsModel> QbListNames=dataHba.getNameFromQbListForValidation(); if(activeVendor) { selectedVendor.setIsActive("N"); } else { selectedVendor.setIsActive("Y"); } if(selectedVendor.getVend_Key()>0) { for(QbListsModel ValidationName:QbListNames) { if(selectedVendor.getName().replaceAll("\\s","").equalsIgnoreCase(ValidationName.getName().replaceAll("\\s","")) && (selectedVendor.getVend_Key()!=ValidationName.getRecNo())) { Messagebox.show("The name already exist.","Vendor List",Messagebox.OK , Messagebox.INFORMATION); return; } } creationdate=df.parse(sdf.format(c.getTime())); selectedVendor.setTimeModified(creationdate); result=data.UpdateVendorData(selectedVendor); } else { for(QbListsModel ValidationName:QbListNames) { if(selectedVendor.getName().replaceAll("\\s","").equalsIgnoreCase(ValidationName.getName().replaceAll("\\s",""))) { Messagebox.show("The name already exist.","Vendor List",Messagebox.OK , Messagebox.INFORMATION); return; } } result=data.addVendorData(selectedVendor); } if(result==1) { if(selectedVendor.getVend_Key()>0) { Clients.showNotification("The Vendor Has Been Updated Successfully.", Clients.NOTIFICATION_TYPE_INFO, null, "middle_center", 10000,true); }else { Clients.showNotification("The Vendor Has Been Saved Successfully.", Clients.NOTIFICATION_TYPE_INFO, null, "middle_center", 10000,true); } Map args = new HashMap(); args.put("type", "vendor"); BindUtils.postGlobalCommand(null, null, "refreshParentVendor", args); comp.detach(); } else Clients.showNotification("Erro at save Vendor.",Clients.NOTIFICATION_TYPE_INFO, null, "middle_center", 10000,true); comp.detach(); } public VendorModel getSelectedVendor() { return selectedVendor; } public void setSelectedVendor(VendorModel selectedVendor) { this.selectedVendor = selectedVendor; } public boolean isCanSave() { return canSave; } public void setCanSave(boolean canSave) { this.canSave = canSave; } public boolean isActiveVendor() { return activeVendor; } public void setActiveVendor(boolean activeVendor) { if(!companyRole.isAllowToActive() && !companyRole.isAllowToInActive()) { Clients.showNotification("You are not allowed to Active or In-Active the status.",Clients.NOTIFICATION_TYPE_INFO, null, "middle_center", 10000,true); return; } else if(!companyRole.isAllowToActive() && activeVendor==false) { Clients.showNotification("You are not allowed to Active the status.",Clients.NOTIFICATION_TYPE_INFO, null, "middle_center", 10000,true); return; } else if(!companyRole.isAllowToInActive() && activeVendor==true) { Clients.showNotification("You are not allowed to In-Active the status.",Clients.NOTIFICATION_TYPE_INFO, null, "middle_center", 10000,true); return; } else { this.activeVendor = activeVendor; } } private void getCompanyRolePermessions(int companyRoleId,int parentId) { companyRole=new MenuModel(); List<MenuModel> lstRoles= dataHba.getMenuRoles(companyRoleId,parentId); for (MenuModel item : lstRoles) { if(item.getMenuid()==74) { companyRole=item; break; } } } /** * @return the companyRole */ public MenuModel getCompanyRole() { return companyRole; } /** * @param companyRole the companyRole to set */ public void setCompanyRole(MenuModel companyRole) { this.companyRole = companyRole; } public CustomerContact getCompSetting() { return compSetting; } public void setCompSetting(CustomerContact compSetting) { this.compSetting = compSetting; } }
Java
UTF-8
2,925
2.515625
3
[]
no_license
package com.buu.se.s55160026.mysqlite_student; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; public class DetailActivity extends Activity { private StudentOperations studentDBoperation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); studentDBoperation = new StudentOperations(this); studentDBoperation.open(); Intent data = getIntent(); Student student = (Student) data.getSerializableExtra("student"); EditText textviewName = (EditText) findViewById(R.id.editTextName); EditText textviewMail = (EditText) findViewById(R.id.editTextMail); EditText textviewPhone = (EditText) findViewById(R.id.editTextPhone); EditText textviewMemo = (EditText) findViewById(R.id.editTextMemo); textviewName.setText(student.getName()); textviewMail.setText(student.getMail()); textviewPhone.setText(student.getPhone()); textviewMemo.setText(student.getMemo()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_detail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public void onButtonBackClick(View v){ finish(); } public void onButtonDeleteClick(View v){ Intent data = getIntent(); Student student = (Student) data.getSerializableExtra("student"); studentDBoperation.deleteStudent(student); finish(); } public void onButtonSaveClick(View v){ Intent data = getIntent(); Student student = (Student) data.getSerializableExtra("student"); EditText textName = (EditText) findViewById(R.id.editTextName); EditText textMail = (EditText) findViewById(R.id.editTextMail); EditText textPhone = (EditText) findViewById(R.id.editTextPhone); EditText textMemo = (EditText) findViewById(R.id.editTextMemo); studentDBoperation.editStudent(student.getId(),textName.getText().toString(), textMail.getText().toString(), textPhone.getText().toString(), textMemo.getText().toString()); finish(); } }
Python
UTF-8
2,747
2.828125
3
[]
no_license
import torch import torch.nn as nn import torch.nn.functional as F class DCGAN(nn.Module): ''' DCGAN model based on Pytorch DCGAN tutorial. Modules: Generator (z -> x), Distriminator (x, x_rec -> {0,1}) ''' def __init__(self, device, g, d, size_z, lr_g=0.0002, lr_d=0.0002, smoothing=0.0): super().__init__() self.device = device self.g = g.to(device) self.d = d.to(device) self.size_z = size_z self.smoothing = smoothing self.optim_g = torch.optim.Adam(self.g.parameters(), lr=lr_g, betas=(0.5, 0.999), weight_decay=0) self.optim_d = torch.optim.Adam(self.d.parameters(), lr=lr_d, betas=(0.5, 0.999), weight_decay=0) self.criterion = nn.BCELoss() self.scheduler_g = None self.scheduler_d = None self.apply(self.weights_init) def epoch_end(self): if self.scheduler_g is not None: self.scheduler_g.step() if self.scheduler_d is not None: self.scheduler_d.step() @staticmethod def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find('BatchNorm') != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) def decode(self, batch): ''' Decodes batch of random normal vector to image space. Tensor dimensions: (B, Z-size, 1, 1) -> (B, C, H, W) ''' return self.g(batch) def train_step(self, batch): batch = batch.to(self.device) noise = torch.randn(batch.shape[0], self.size_z, 1, 1, device=self.device) label_fake = torch.full((batch.shape[0],), 0.0 + self.smoothing, device=self.device) label_real = torch.full((batch.shape[0],), 1.0 + self.smoothing, device=self.device) # 1. Update D network: maximize log(D(x)) + log(1 - D(G(z))) self.d.zero_grad() # 1.1 Train with all-real batch output = self.d(batch) error_real = self.criterion(output, label_real) error_real.backward() # 1.2 Train with all-fake batch fake = self.g(noise) output = self.d(fake.detach()) error_fake = self.criterion(output, label_fake) error_fake.backward() # 1.3 Update discriminator error_d = error_real + error_fake self.optim_d.step() # 2. Update G network: maximize log(D(G(z))) self.g.zero_grad() output = self.d(fake) error_g = self.criterion(output, label_real) error_g.backward() self.optim_g.step() return {'loss_d': error_d.data, 'loss_g': error_g.data}
Markdown
UTF-8
2,782
3.328125
3
[ "Apache-2.0" ]
permissive
--- title: 並べ替えによるGraphQLクエリ description: GraphQL クエリでソートを実装する方法 --- このガイドでは、GraphQL 変換ライブラリを使用してGraphQL APIでソートを実装する方法を説明します。 ### 概要 始めるには、Todo アプリの基本的なGraphQLスキーマから始めましょう。 ```graphql type Todo @model { id: ID! title: String! } ``` API が `@model` ディレクティブで作成されると、次のクエリが自動的に作成されます。 ```graphql type Query { getTodo(id: ID!): Todo listTodos(filter: ModelTodoFilterInput, limit: Int, nextToken: String): ModelTodoConnection } ``` 次に、 `ModelTodoConnection` 型を見て、 `listTodos` クエリが実行されたときに返されるデータのアイデアを取得します。 ```graphql type ModelTodoConnection { items: [Todo] nextToken: String } ``` デフォルトでは、 `listTodos` クエリは `items` array __を順序なしで__を返します。 何度も、タイトル、作成日、またはいくつかの他の方法で順序付けられるこれらの項目が必要になります。 To enable this, you can use the [@key](~/cli/graphql-transformer/key.md) directive. This directive will allow you to set a custom `sortKey` on any field in your API. ### 実装 In this example, you will enable sorting by the `createdAt` field. By default, Amplify will populate this `createdAt` field with a timestamp if none is passed in. これを有効にするには、以下のスキーマを更新してください: ```graphql type Todo @model @key(name: "todosByDate", fields: ["type", "createdAt"], queryField: "todosByDate") { id: ID! title: String! type: String! createdAt: String! } ``` <amplify-callout> Todo を作成する際には、 `タイプ` フィールドを正常に動作させる必要があります。 </amplify-callout> 次に、 `タイプ` フィールドを確実に取り込むために、いくつかの ToDo を作成します。 ```graphql mutation createTodo { createTodo(input: { title: "Todo 1" type: "Todo" }) { id title } } ``` これで、新しい `todosByDate` クエリを使用して、日付ごとに昇順または降順でタスクをクエリできます。 ```graphql query todosByDate { todosByDate( type: "Todo" sortDirection: ASC ) { items { id title createdAt } } } query todosByDateDescending { todosByDate( type: "Todo" sortDirection: DESC ) { items { id title createdAt } } } ``` `@key` ディレクティブの詳細については、こちらのドキュメント [をご覧ください](~/cli/graphql-transformer/key.md)
Java
UTF-8
322
2.109375
2
[]
no_license
package cartesianplane.engine; import javafx.scene.shape.Shape; /** * User: hugo_<br/> * Date: 18/10/2017<br/> * Time: 23:40<br/> */ public class RelativeShape { Shape shape; Coord coord; public RelativeShape(Shape shape, Coord coord) { this.shape = shape; this.coord = coord; } }
Python
UTF-8
480
3.140625
3
[]
no_license
class Solution(object): def clumsy(self, N): """ :type N: int :rtype: int """ n = N infix = "" c = 0 ops = ["*", "//", "+", "-"] while n > 1: infix += str(n) n -= 1 k = c % 4 infix += ops[k] c += 1 infix += str(1) return eval(infix) if __name__ == "__main__": obj = Solution() N = 10 r = obj.clumsy(N) print(r)
Python
UTF-8
218
3.984375
4
[]
no_license
#ELI PRUSHANSKY 151019 import turtle #This turtle moves forward 200 units, then turns left 144 degrees 5 times each to make a five pointed star star=turtle.Turtle() for x in range(5): star.forward(200) star.left(144)
Java
UTF-8
1,902
2.203125
2
[]
no_license
package com.task; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricTestRunner; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @RunWith(RobolectricTestRunner.class) public class MainActivityTest { MainActivity activity; UserFragment userFragment; @Before public void setUp() throws Exception { activity = Robolectric.buildActivity(MainActivity.class).create().get(); userFragment = new UserFragment(); activity.getSupportFragmentManager().beginTransaction().add(userFragment, null).commit(); } @Test public void justSimpleTest() throws Exception { assertThat(activity.getString(R.string.app_name), equalTo("TestTask")); TestApplication app = (TestApplication) activity.getApplicationContext(); } @Test public void hasPictureTest(){ View userPic = userFragment.getView().findViewById(R.id.default_user_pic); assertTrue(userPic instanceof ImageView); } @Test public void hasNeededTextViewsTest() { View userView = userFragment.getView(); View nameView = userView.findViewById(R.id.name); View surnameView = userView.findViewById(R.id.surname); View birthdateView = userView.findViewById(R.id.birthdate); View bioView = userView.findViewById(R.id.bio); View emailView = userView.findViewById(R.id.email); assert (nameView instanceof TextView && surnameView instanceof TextView && birthdateView instanceof TextView && bioView instanceof TextView && emailView instanceof TextView); } }
Markdown
UTF-8
2,623
3.171875
3
[]
no_license
# 动态变量 运行时才能决定的变量 ##### 申请 ```C++ int * ptr = new int ``` ptr本身在展空间,但是同时申请了一个它指向的空间 ```c++ (int *)malloc(sizeof(int) * 10) new int[10] ``` 函数只知道空间,不知道类型 ##### 差别 * 强制类型转换 * 如果是对于OO,new自动调用构造函数。 * new作为操作符,可以进行重载。 new的时候可能不成功,要做有效性判断,要看返回的是不是null。失败了要做异常处理。申请资源可能失败 new_handler() 代替系统处理,要注意能退出去 ##### 归还 free delete [] 归还的时候为什么不需要长度? 每次分配的时候用符号表记录,不过不太好,表效率低且不知道大小 在分配空间的时候,在初始位置记住size。 当new 指针之后,不要去动指针,否则free的时候size有问题,无法正确free空间。 所有申请的空间都必须要归还 PAII delete[],会依次调用析构函数。对象的撤销不仅是本身的内存空间还掉。打开的文件、连接的socket,等等。不调用则很多对象的删除没有清干净。方括号申请一定要方括号归还 #### 动态变量的管理 链表管理 FAT 前面加一个dummy节点,链永远不空,永远不在头上插入,比较方便。 # OOP ##### OOP的引入 * 初始化的安全隐患,职责问题 * 访问权限 构造函数,强制执行,保证安全性 访问控制 实际上,内存空间的结构并不会变化。各种关键字只给Cfront看,由它进行检查。 ##### 十个问题 1. 为什么编译器提供默认构造函数?它做了什么事情? 它不仅完成赋值的初始化。但是父类的数据有赋值操作。empty class,compiler里有什么? 默认构造函数,析构函数,虚函数表(?) 2. 构造函数 private时什么情况? 单例模式。static成员 友元 3. 为什么引入成员初始化表? ref成员只能用这种方式初始化。 4. why 引入copy构造函数和 =操作符重载? 有的东西挂在外面 5. Late Binding。virtual 静态绑定的方式实现了动态绑定 6. 什么时候用virtual? 只定义了接口 能干但是子类干得更好。动态绑定。定义接口和实现。 不准许字类改变,non-virtual。 7. public 继承和non-public 继承 8. 不能作为全局函数重载 9. 什么时候成员函数能够返回& 10. 什么情况下、怎么进行重载new delete 对自己的类有更好的掌控。
Markdown
UTF-8
960
4.03125
4
[]
no_license
# Inorder List ## Motivation Algorithm Inorder(tree) 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree) # Problem Description Given the following Binary tree definition: ''' class Node: def __init__(self,key,left=None,right=None): self.left = left self.right = right self.key = key ''' Define a function `Inorder` which consumes one argument `root`. The function returns the inorder traversal of a given binary tree. # Example ``` Input: 6 / \ 4 7 / \ 3 5 items = Node(6) items.left = Node(4) items.right = Node(7) items.left.left = Node(3) items.left.right = Node(5) Inorder(items) == [3, 4, 5, 6, 7] ``` ## Testing * To test your solution, type 'pytest' within the **solution** subdirectory ## Submission * Submit your answers in the *solution.py* file within the *Solutions* subdirectory within this directory
Java
UTF-8
1,142
3.640625
4
[]
no_license
import java.lang.Math; import java.util.Scanner; class CompletingSquare { public static void main(String[] args) { System.out.println("Welcome to the CompletingSquare Finder !! :: "); Scanner sc1 = new Scanner(System.in); Scanner sc2 = new Scanner(System.in); Scanner sc3 = new Scanner(System.in); System.out.println("Please put a-value ::"); double avalue= sc1.nextDouble(); System.out.println("Please put b-value ::"); double bvalue= sc2.nextDouble(); System.out.println("Please put c-value ::"); double cvalue= sc3.nextDouble(); System.out.print("The answer is :: "); calc(avalue, bvalue, cvalue); } public static String calc(double a, double b, double c){ double d = b/(2*a); //System.out.println(d); Check double d1 = b*b/(4*a); //System.out.println(d1); Check double e = c - d1; //System.out.println(e); //Check String ans = "( x + "+d+" )^2 + "+e+" = 0 ::"; System.out.println(ans); //output result return ans; } }
Python
UTF-8
5,530
3.21875
3
[]
no_license
# from bs4 import BeautifulSoup # # html = ''' # <html><head><title>The Dormouse's story</title></head> # <body> # <p class="title"><b>The Dormouse's story</b></p> # # <p class="story">Once upon a time there were three little sisters; and their names were # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; # and they lived at the bottom of a well.</p> # <p class="story">...</p> # ''' # soup = BeautifulSoup(html,'lxml') # # # print(soup.prettify()) # print("1:",soup.title) # print("2:",soup.title.name) # print("3:",soup.title.string) # print("4:",soup.title.parent.name) # print("5:",soup.p) # print("6:",soup.p["class"]) # print("7:",soup.a) # print("8:",soup.find_all('a')) # print("9:",soup.find(id='link3')) # 通过select()直接传入CSS选择器就可以完成选择 熟悉前端的人对CSS可能更加了解,其实用法也是一样的 .表示class #表示id 标签1,标签2 # 找到所有的标签1和标签2 标签1 标签2 找到标签1内部的所有的标签2 [attr] 可以通过这种方法找到具有某个属性的所有标签 [atrr=value] 例子[target=_blank]表示查找所有target=_blank的标签 # html=''' # <div class="panel"> # <div class="panel-heading"> # <h4>Hello</h4> # </div> # <div class="panel-body"> # <ul class="list" id="list-1"> # <li class="element">Foo</li> # <li class="element">Bar</li> # <li class="element">Jay</li> # </ul> # <ul class="list list-small" id="list-2"> # <li class="element">Foo</li> # <li class="element">Bar</li> # </ul> # </div> # </div> # ''' # from bs4 import BeautifulSoup # soup = BeautifulSoup(html, 'lxml') # print('1:',soup.select('.panel .panel-heading')) # print('2:',soup.select('ul li')) # print('3:',soup.select('#list-2 .element')) # print('4:',type(soup.select('ul')[0])) # print("5:",soup.select('li')) # for content in soup.select('li'): # print(content.get_text()) # print(content['class']) # print(content.attrs['class']) # # print(content.get) # import requests # # response = requests.get("https://www.baidu.com") # print('1:',response) # print('2:',type(response)) # print('3:',response.status_code) # print('4:',type(response.text)) # print('5:',response.text) # print('6:',response.cookies) # print('7:',response.content) # print('8:',response.content.decode("utf-8")) # import time # from selenium import webdriver # driver = webdriver.Firefox() # driver.maximize_window() # driver.implicitly_wait(8) # driver.get("https://www.baidu.com") # driver.find_element_by_xpath("//*[@id='kw']").send_keys("selenium") # driver.find_element_by_xpath("//*[@id='su']").click() # time.sleep(2) # # 第二个判断方法 # # //*[@id="20"]/h3/a #\32 0 > h3 > a # ele_string = driver.find_element_by_xpath("//div/h3/a[text()='官网']/../a").text # if (ele_string == "Selenium - Web Browser Automation"): # print("测试成功,结果和预期结果匹配!" ) # driver.quit() # coding:utf-8 # from bs4 import BeautifulSoup # import requests # import os # r = requests.get("http://699pic.com/sousuo-218808-13-1.html") # fengjing = r.content # soup = BeautifulSoup(fengjing, "html.parser") # # print("soup content:",soup.contents) # # 找出所有的标签 # images = soup.find_all(class_="lazy") # # print images # 返回list对象 # # print("images:",images) # for i in images: # jpg_rl = i["data-original"] # 获取url地址 # title = i["title"] # 返回title名称 # print(title) # print(jpg_rl) # print("") # import requests # # # 先打开登录首页,获取部分cookie # url = "https://passport.cnblogs.com/user/signin" # headers = { # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0" # } # get方法其它加个ser-Agent就可以了 # # s = requests.session() # r = s.get(url, headers=headers,verify=False) # print(s.cookies) # coding:utf-8 # import yaml # import os # # cur = os.path.dirname(os.path.realpath(__file__)) # # def get_token(yamlName="token.yaml"): # ''' # 从token.yaml读取token值 # :param yamlName: 配置文件名称 # :return: token值 # ''' # p = os.path.join(cur, yamlName) # print('p:',p) # f = open(p,'rb') # print("f:",f) # a = f.read() # t = yaml.load(a) # f.close() # return t["token"] # # if __name__ =="__main__": # print(get_token()) import unittest import os # # class test_group(unittest.TestCase): # case_path = os.path.join(os.getcwd(),"test_case") # def testMinus(self): # self.assertEqual(6 - 5,9 - 8) # print("减法 is success") # def testDivide(self): # d = 9/4 # e = 2.25 # self.assertEqual(d,e) # print("除法 is success") # # def all_case(self): # discase=unittest.defaultTestLoader.discover(self,case_path,pattern='test*.py',top_level_dir=None) # return discase # # # if __name__ == "__main__": # # unittest.main() # # if __name__ =="_main__": # unittest.TextTestRunner().run(all_case) # # # import random seed = ["1","2","3","4","5","6","7a"] print("hahah:",seed[random.randrange(0,len(seed), 1, int)]) idx = 0 while True: if idx > 10: break idx += 1 seed[random.randrange(0,len(seed), 1, int)]
Python
UTF-8
1,687
2.640625
3
[]
no_license
import analyser as als import sys import os import subprocess import traceback os_logo = " @@@ @@@@@@ @@@ @@@ @@@ @@@@@@ @@@ @@@ @@@ @@@@@@\n @@@ @@@@@@@@ @@@@ @@@ @@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@\n @@! @@! @@@ @@!@!@@@ @@! !@@ @@! @@! @@! @@! @@@\n !@! !@! @!@ !@!!@!@! !@! !@! !@! !@! !@! !@! @!@\n !!@ @!@!@!@! @!@ !!@! !!@ !!@@!! @!! !!@ @!@ @!@ !@!\n !!! !!!@!!!! !@! !!! !!! !!@!!! !@! !!! !@! !@! !!!\n !!: !!: !!! !!: !!! !!: !:! !!: !!: !!: !!: !!!\n !!: :!: :!: !:! :!: !:! :!: !:! :!: :!: :!: :!: !:!\n ::: : :: :: ::: :: :: :: :::: :: :::: :: ::: ::::: ::\n : ::: : : : :: : : :: : : :: : : : : : : " def post_mortem(exc_type, exc_val, exc_tb): os.system('cls') #BSoD à la windows 9x os.system("color 9f") print(os_logo + "\n") message_err = ["Une erreur fatale est surevenue.", "", ""] for i in message_err: print("\t\t" + i) #on affiche l'exception histoire de savoir ce qu'on debug print("\n" + str(exc_type) + " :: " + str(exc_val) + "\n" * 2) print(traceback.format_exception(exc_type, exc_val, exc_tb)[-2]) input("\n\nAppuyez sur Entrer pour relancer Janiswö ...") os.system('cls') subprocess.Popen(['py', '-3.4', 'janiswo.py']) #on dit à python de lancer cette fonction quand il plante sys.excepthook = post_mortem def go(): os.system("color 0f") #on démarre l'analyser analyse_stx = als.Speaker(os_logo) #on démarre le noyau analyse_stx.start() if __name__ == '__main__': go()
C++
UTF-8
1,999
3.03125
3
[]
no_license
// Rational Sum (20) // 时间限制 1000 ms 内存限制 65536 KB 代码长度限制 100 KB 判断程序 Standard (来自 小小) // 题目描述 // Given N rational numbers in the form "numerator/denominator", you are supposed to calculate their sum. // 输入描述: // Each input file contains one test case. Each case starts with a positive integer N (<=100), // followed in the next line N rational numbers "a1/b1 a2/b2 ..." where all the numerators and denominators // are in the range of "long int". If there is a negative number, then the sign must appear in front of the numerator. // 输出描述: // For each test case, output the sum in the simplest form "integer numerator/denominator" where "integer" is // the integer part of the sum, "numerator" < "denominator", and the numerator and the denominator have no common factor. // You must output only the fractional part if the integer part is 0. // 输入例子: // 5 // 2/5 4/15 1/30 -2/60 8/3 // 输出例子: // 3 1/3 #include<cstdio> #include<cmath> typedef long long ll; ll gcd(ll a, ll b){ return b==0?std::abs(a):gcd(b,a%b); } int main(){ ll cnt; scanf("%lld",&cnt); ll res_nume=0, res_deno = 1; for(ll i=0;i<cnt;i++){ ll nume=0,deno=0; scanf("%lld/%lld",&nume,&deno); ll curgcd = gcd(nume,deno); nume /= curgcd; deno /= curgcd; res_nume = res_nume * deno + nume * res_deno; res_deno = deno * res_deno; ll res_gcd = (gcd(res_nume,res_deno)); res_deno /= res_gcd; res_nume /= res_gcd; //printf("%lld",res_gcd); } // printf("%lld/%lld",res_nume,res_deno); ll integer=res_nume/res_deno; res_nume = res_nume - (integer * res_deno) ; if(integer!=0){ printf("%lld",integer); if(res_nume!=0)printf(" "); } if(res_nume!=0){ printf("%lld/%lld",res_nume,res_deno); } if(integer==0 && res_nume==0){ printf("0"); } return 0; }
Markdown
UTF-8
481
2.515625
3
[]
no_license
# Infinite Scroll Blog Posts This little project made with by **Vanilla Javascript**. # Files Inside of my repository, I have created and used it the two folder which is **js & css!** > As a matter of fact, this little project is in order to use in my some others project such as travel blogging which is one of my quite a bit project so far. # Demo Screenshot ![Demo: What I did so! ](https://i.imgur.com/8PtNOqo.jpg) - I will try to live on my server if I have much time.
C++
UTF-8
948
2.90625
3
[]
no_license
#include "IDataIO.h" #include "../BotException.h" unsigned int IDataIO::getPos() const { return pos; } unsigned int IDataIO::getSize() const { return size; } void IDataIO::setPos(unsigned int position) { isPosOK(position); pos = position; } void IDataIO::advancePos(int amount) { isPosOK(pos + amount); pos += amount; } void IDataIO::isPosOK(unsigned int position) const { if (position < 0 || position > size) { throw BotException(0); } } void IDataIO::copyData(const char *origin, char *destination, unsigned int len) { for (int i = 0; i < len; i++) { destination[i] = origin[i]; } } void IDataIO::copyAndInvertData(const char *origin, char *destination, unsigned int len) { for (int i = 0; i < len; i++) { destination[i] = origin[len - i - 1]; } } char *IDataIO::getBuffer() const { return &buffer[pos]; } bool IDataIO::isEnd() const { return pos == size; }
Java
UTF-8
2,247
2.109375
2
[]
no_license
package org.consume.com.user.service; import com.github.pagehelper.Page; import org.apache.ibatis.annotations.Param; import org.consume.com.user.model.UserModel; import java.util.List; /** * @name 人员资料接口 */ public interface UserService { /** * add * * @param model UserModel * @return int */ int add(@Param("model") UserModel model); /** * put * * @param k String 需要修改的键 * @param v String 需要修改的值 * @param wk String 条件键 * @param wv String 条件值 * @return int */ int put(String k, String v, String wk, String wv); /** * put * * @param model UserModel * @return int */ int put(UserModel model); /** * put2 * * @param model UserModel * @return int */ int put2(UserModel model); /** * getById * 单表查询 * * @param id String * @return UserModel */ UserModel getById(String id); /** * 多表联查 * * @param id String * @return UserModel */ UserModel getById2(String id); /** * 获取当前登陆人的信息,主要用于shiro * * @return UserModel */ UserModel getLanders(); /** * getByAccount * * @param account String * @return UserModel */ UserModel getByAccount(String account); Page<UserModel> findAllPage(int pageNow, int pageSize); /** * 根据单位和部门查找人员 * * @param id String * @return List<UserModel> */ List<UserModel> getByCD(String id); /** * upPWD * * @param pwd String * @param account String * @return int */ int upPWD(String pwd, String account); /** * del * * @param id String * @return int */ int del(String id); /** * 重置密码 * * @param id String * @param pwd String * @return int */ int resetting(String id, String pwd); boolean resetting2(String account, String pwd); void delGL(String account); /** * 查询所有 * * @return UserModel */ List<UserModel> findAll(); }
SQL
UTF-8
3,472
3.484375
3
[]
no_license
/***** Database QuanLyHoaDon *****/ CREATE DATABASE QuanLyHoaDon USE QuanLyHoaDon CREATE TABLE KHACHHANG ( MAKH char(10) PRIMARY KEY, HO nvarchar(20) NOT NULL, TEN nvarchar(20) NOT NULL, NGSINH SMALLDATETIME NOT NULL, DUONG nvarchar(40) NOT NULL, QUAN nvarchar(40) NOT NULL, TPHO nvarchar(40) NOT NULL, DTHOAI nvarchar(12) ) INSERT INTO KHACHHANG(MAKH, HO, TEN, NGSINH, DUONG, QUAN, TPHO, DTHOAI) VALUES ('KH01', 'HA', 'LAM', '01/01/2001', 'Dlieya', 'Quan 5', 'HCM', '0123') INSERT INTO KHACHHANG(MAKH, HO, TEN, NGSINH, DUONG, QUAN, TPHO, DTHOAI) VALUES ('KH02', 'NGUYEN', 'MAI', '01/01/2001', 'Dliey0', 'Quan 6', 'HCM', '0123') INSERT INTO KHACHHANG(MAKH, HO, TEN, NGSINH, DUONG, QUAN, TPHO, DTHOAI) VALUES ('KH03', 'BA', 'LAN', '01/01/2001', 'Dlieya', 'Quan 7', 'HCM', '0123') INSERT INTO KHACHHANG(MAKH, HO, TEN, NGSINH, DUONG, QUAN, TPHO, DTHOAI) VALUES ('KH04', 'HAI', 'MINH', '01/01/2001', 'Dlieya', 'Quan 8', 'HCM', '0123') SELECT * FROM KHACHHANG CREATE TABLE HOADON ( MAHD char(10) PRIMARY KEY, MAKH char(10) NOT NULL, NGAYLAP SMALLDATETIME NOT NULL, TONGTIEN MONEY NULL, CONSTRAINT FK_MaKH_HOADON_KHACHHANG FOREIGN KEY (MAKH) REFERENCES KHACHHANG(MAKH) ) INSERT INTO HOADON(MAHD, MAKH, NGAYLAP) VALUES ('HD01', 'KH01', '01/01/2001') INSERT INTO HOADON(MAHD, MAKH, NGAYLAP) VALUES ('HD02', 'KH01', '01/03/2001') INSERT INTO HOADON(MAHD, MAKH, NGAYLAP) VALUES ('HD03', 'KH01', '01/05/2001') INSERT INTO HOADON(MAHD, MAKH, NGAYLAP) VALUES ('HD04', 'KH01', '01/04/2001') SELECT *FROM HOADON DROP TABLE HOADON CREATE TABLE SANPHAM ( MASP char(10) PRIMARY KEY, TENSP varchar(40) NOT NULL, SL int NOT NULL, MOTA varchar(100) , GIA int NOT NULL ) INSERT INTO SANPHAM(MASP, TENSP, SL, MOTA, GIA) VALUES ('SP01', 'RAU', 5 , '', 200) INSERT INTO SANPHAM(MASP, TENSP, SL, MOTA, GIA) VALUES ('SP02', 'XA LACH', 10 , 'KHONG DU', 200) INSERT INTO SANPHAM(MASP, TENSP, SL, MOTA, GIA) VALUES ('SP03', 'BAPSU', 30 , '', 300) SELECT *FROM SANPHAM CREATE TABLE CT_HOADON ( MAHD char(10) NOT NULL, MASP char(10) NOT NULL, SOLUONG INT NOT NULL, GIABAN MONEY NOT NULL, GIAGIAM MONEY NULL, THANHTIEN MONEY NULL CONSTRAINT PK_CTHD PRIMARY KEY (MAHD, MASP), CONSTRAINT FK_Mahd_CTHD_HOADON FOREIGN KEY (MAHD) REFERENCES HOADON(MAHD), CONSTRAINT FK_Masp_CTHD_SANPHAM FOREIGN KEY (MASP) REFERENCES SANPHAM(MASP) ) INSERT INTO CT_HOADON(MAHD, MASP, SOLUONG, GIABAN, GIAGIAM) VALUES ('HD01', 'SP01', 3, 3000, 200) INSERT INTO CT_HOADON(MAHD, MASP, SOLUONG, GIABAN, GIAGIAM) VALUES ('HD02', 'SP01', 5, 3000, 200) INSERT INTO CT_HOADON(MAHD, MASP, SOLUONG, GIABAN, GIAGIAM) VALUES ('HD01', 'SP03', 5, 3000, 200) INSERT INTO CT_HOADON(MAHD, MASP, SOLUONG, GIABAN, GIAGIAM) VALUES ('HD01', 'SP02', 8, 3000, 200) INSERT INTO CT_HOADON(MAHD, MASP, SOLUONG, GIABAN, GIAGIAM) VALUES ('HD02', 'SP02', 10, 5000, 200) DROP TABLE CT_HOADON SELECT *FROM CT_HOADON ---trigger 1 CREATE TRIGGER trg_CTDH ON CT_HOADON AFTER INSERT AS BEGIN UPDATE CT_HOADON SET THANHTIEN = (inserted.GIABAN - inserted.GIAGIAM) * inserted.SOLUONG FROM inserted, CT_HOADON WHERE inserted.MAHD = CT_HOADON.MAHD and inserted.MASP = CT_HOADON.MASP END DROP TRIGGER trg_CTDH ----trigger 2 CREATE TRIGGER trg_CTDH_HD ON CT_HOADON AFTER INSERT AS BEGIN UPDATE HOADON SET TONGTIEN = (SELECT SUM(CT_HOADON.THANHTIEN) FROM CT_HOADON inner join inserted on CT_HOADON.MAHD = inserted.MAHD) FROM HOADON JOIN inserted ON HOADON.MAHD = inserted.MAHD END DROP TRIGGER trg_CTDH_HD
C++
UTF-8
413
2.71875
3
[]
no_license
// // ListNode.cpp // Assignment 8 // // Created by zane saul on 12/9/17. // Copyright © 2017 zane saul. All rights reserved. // #include "ListNode.h" ListNode::ListNode( ) { next= nullptr; } ListNode *ListNode::getNext( ){ return next; } void ListNode::setNext( ListNode *newnode ){ next = newnode; } int ListNode::compare( ListNode *newnode ){ return 0; } ListNode::~ListNode(){ delete next; }
Python
UTF-8
4,539
3.34375
3
[]
no_license
# -*- coding: utf-8 -*- ######################## # Phylogenetic Trees # ######################## class PhylNode: def __init__(self, distance = None, ch=[]): self.children = ch self.distance = distance def get_children(self): ch=[] for i in self.children: ch.append(str(i)) return ch def get_distance(self): return self.distance def set_distance(self, distance): self.distance = distance def __call__(self): ch="[" if len(self.children) != 0: for c in self.children: ch += c.__str__() + ", " ch= ch[: len(ch)-2] ch+="]" return "PhylNode = (" + str(self.distance) + ", " + ch +")" def __str__(self): ch="[" if len(self.get_children())!= 0: for c in self.children: ch += c.__str__() + ", " ch= ch[: len(ch)-2] ch+="]" return "PhylNode = (" + str(self.distance) + ", " + ch +")" def max_leaf(self, maxi = 0, a = 0): a += self.distance if len(self.children) != 0: for i in self.children: maxi = i.max_leaf(maxi, a) a -= self.distance return maxi else: if a > maxi: maxi= a a -= self.distance return maxi def min_leaf(self, mini=float("inf") , a=0): a += self.distance if len(self.children) != 0: for i in self.children: mini = i.min_leaf(mini, a) a-=self.distance return mini else: if mini > a: mini = a a -= self.distance return mini def truncate(self, mini): if len(self.children) != 0: h= mini - min( self.sum_path(self.distance, paths = [])) if h<0: h=0 self.set_distance(h) for ch in self.children: ch.truncate(mini) else: self.set_distance(mini) def elongate( self, maxi ): if len(self.children) != 0: print maxi h = maxi - max( self.sum_path(self.distance, paths = [])) if h > self.distance: self.set_distance(h) maxi -= self.distance if maxi != 0: for ch in self.children: ch.elongate(maxi) maxi+= self.distance else: self.set_distance(maxi) def unify(self, avrg): if len(self.children) != 0: x = self.sum_path(0, 0, paths=[]) a = self.distance + avrg - float(sum(x)) / len(x) a= max(a, 0) self.set_distance(a) avrg -= self.get_distance() for ch in self.children: ch.unify(avrg) avrg+=self.distance else: self.set_distance(avrg) def sum_path(self, info= 0, dist = 0, paths = []): dist += self.distance if len(self.children) != 0: for ch in self.children: paths=ch.sum_path(info, dist, paths) dist-=self.distance else: paths.append(dist - info) return paths class PhylTree: def __init__(self, node=None): self.root = node def get_children(self): ch=[] if self.root!=None: ch=self.root.get_children() return ch def root(self): return self.root def max_leaf_distance(self): if self.root!=None: return self.root.max_leaf() - self.root.distance def __str__(self): tree = "PhylTree= (" if self.root != None: tree += str(self.root()) tree += ")" return tree def __call__(self): tree = "PhylTree= (" if self.root != None: tree += self.root() tree += ")" return tree def min_leaf_distance(self): if self.root!=None: return self.root.min_leaf() - self.root.distance def elongate_distances(self): if self.root != None: if self.root.children != None: for child in self.root.children: child.elongate(self.max_leaf_distance()) def truncate_distances(self): ro=self.root.distance if self.root != None: self.root.truncate(self.min_leaf_distance()) self.root.set_distance(ro) def unify_distances(self): avrg= self.average_leaf_distance() if self.root != None: if self.root.children != None: for ch in self.root.children: ch.unify(avrg) def average_leaf_distance(self): leaf_dist = self.root.sum_path(self.root.distance, paths = []) return float(sum(leaf_dist))/ len(leaf_dist)
C#
UTF-8
3,553
2.6875
3
[]
no_license
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using St_Dogmaels.Models; using Xamarin.Forms; namespace St_Dogmaels.Services { class AzureDataStore : IDataStore<Place> { private static AzureDataStore singleton = null; public static AzureDataStore Store { get { if (singleton == null) singleton = new AzureDataStore(); return singleton; } } private AzureDataStore() { } private Places cache; private HttpClient client = new HttpClient(); public async Task<bool> AddItemAsync(Place item) { throw new NotImplementedException(); } public async Task<bool> DeleteItemAsync(string id) { throw new NotImplementedException(); } private async Task SetCache() { cache = new Places(); client.Timeout = TimeSpan.FromSeconds(30); var response = await client.GetAsync("https://moylgrove-history.azurewebsites.net/api/places"); if (response.IsSuccessStatusCode) { var js = await response.Content.ReadAsStringAsync(); cache.AddJson(js); DependencyService.Get<ILocalFile>().WriteAll("houseCache.js", js); } else { var fileString = DependencyService.Get<ILocalFile>().ReadAll("houseCache.js"); if (String.IsNullOrWhiteSpace(fileString)) { cache.AddJson(fileString); } } } public async Task<Place> GetItemAsync(string id) { if (cache == null) await SetCache(); if (!cache.KeyDict.ContainsKey(id)) { var js = await client.GetStringAsync("https://moylgrove-history.azurewebsites.net/api/place?id=" + Place.Row(id)); cache.Add1Json(js); } return cache.KeyDict[id]; } public async Task<IEnumerable<Place>> GetItemsAsync(bool forceRefresh = false) { if (cache == null || forceRefresh) { await SetCache(); } return new List<Place>(cache); } public Task<bool> UpdateItemAsync(Place item) { throw new NotImplementedException(); } } class Places : IEnumerable<Place> { public Dictionary<String, Place> KeyDict { get; set; } public Places() { KeyDict = new Dictionary<string, Place>(); } public Places AddJson(string js) { var placeList = JsonConvert.DeserializeObject<List<Place>>(js); foreach (var place in placeList) { KeyDict[place.Id] = place; } return this; } public Place Add1Json(string js) { var place = JsonConvert.DeserializeObject<Place>(js); KeyDict[place.Id] = place; return place; } public string Json() { return JsonConvert.SerializeObject(new List<Place>(KeyDict.Values)); } IEnumerator<Place> IEnumerable<Place>.GetEnumerator() { return KeyDict.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return KeyDict.Values.GetEnumerator(); } } }
Java
UTF-8
9,443
2.015625
2
[]
no_license
package de.tomsplayground.peanuts.client.editors.security; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ITableColorProvider; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import de.tomsplayground.peanuts.client.app.Activator; import de.tomsplayground.peanuts.domain.base.Security; import de.tomsplayground.peanuts.domain.process.IPrice; import de.tomsplayground.peanuts.domain.process.IPriceProvider; import de.tomsplayground.peanuts.domain.process.Price; import de.tomsplayground.peanuts.domain.process.PriceProviderFactory; import de.tomsplayground.peanuts.domain.process.StopLoss; import de.tomsplayground.peanuts.util.Day; import de.tomsplayground.peanuts.util.PeanutsUtil; public class DevelopmentEditorPart extends EditorPart { private TableViewer tableViewer; private final int colWidth[] = new int[5]; private static class StringTableLabelProvider extends LabelProvider implements ITableLabelProvider, ITableColorProvider { private final Color red; public StringTableLabelProvider(Color red) { this.red = red; } @Override public Image getColumnImage(Object element, int columnIndex) { return null; } @Override public String getColumnText(Object element, int columnIndex) { String[] strings = (String[]) element; if (columnIndex < strings.length) { return strings[columnIndex]; } else { return ""; } } @Override public Color getBackground(Object element, int columnIndex) { return null; } @Override public Color getForeground(Object element, int columnIndex) { String[] strings = (String[]) element; if (columnIndex < strings.length) { String v = strings[columnIndex]; if (columnIndex > 0 && v.startsWith("-")) { return red; } } return null; } } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { if (!(input instanceof SecurityEditorInput)) { throw new PartInitException("Invalid Input: Must be SecurityEditorInput"); } setSite(site); setInput(input); setPartName(input.getName()); } @Override public void createPartControl(Composite parent) { restoreState(); Composite top = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.marginHeight = 0; layout.marginWidth = 0; top.setLayout(layout); tableViewer = new TableViewer(top, SWT.NONE); Table table = tableViewer.getTable(); table.setHeaderVisible(true); table.setLinesVisible(true); table.setFont(Activator.getDefault().getNormalFont()); ControlListener saveSizeOnResize = new ControlListener() { @Override public void controlResized(ControlEvent e) { saveState(); } @Override public void controlMoved(ControlEvent e) { } }; TableColumn col = new TableColumn(table, SWT.LEFT); col.setText("Text"); col.setWidth((colWidth[0] > 0) ? colWidth[0] : 100); col.setResizable(true); col.addControlListener(saveSizeOnResize); col = new TableColumn(table, SWT.RIGHT); col.setText("Start"); col.setWidth((colWidth[1] > 0) ? colWidth[1] : 100); col.setResizable(true); col.addControlListener(saveSizeOnResize); col = new TableColumn(table, SWT.RIGHT); col.setText("Change"); col.setWidth((colWidth[2] > 0) ? colWidth[2] : 100); col.setResizable(true); col.addControlListener(saveSizeOnResize); col = new TableColumn(table, SWT.RIGHT); col.setText("Change %"); col.setWidth((colWidth[3] > 0) ? colWidth[3] : 100); col.setResizable(true); col.addControlListener(saveSizeOnResize); col = new TableColumn(table, SWT.RIGHT); col.setText("Anual change %"); col.setWidth((colWidth[4] > 0) ? colWidth[4] : 100); col.setResizable(true); col.addControlListener(saveSizeOnResize); Color red = Activator.getDefault().getColorProvider().get(Activator.RED); tableViewer.setLabelProvider(new StringTableLabelProvider(red)); tableViewer.setContentProvider(new ArrayContentProvider()); table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); tableViewer.setInput(generateValues()); } protected List<String[]> generateValues() { List<String[]> result = new ArrayList<String[]>(); Security security = ((SecurityEditorInput) getEditorInput()).getSecurity(); IPriceProvider prices = PriceProviderFactory.getInstance().getSplitAdjustedPriceProvider(security, Activator.getDefault().getAccountManager().getStockSplits(security)); development(result, prices, ChronoUnit.DAYS, -7, "One week"); development(result, prices, ChronoUnit.MONTHS, -1, "One month"); development(result, prices, ChronoUnit.MONTHS, -3, "Three months"); development(result, prices, ChronoUnit.MONTHS, -6, "Six months"); development(result, prices, ChronoUnit.DAYS, -LocalDate.now().getDayOfYear(), "This year"); development(result, prices, ChronoUnit.YEARS, -1, "One year"); development(result, prices, ChronoUnit.YEARS, -3, "Three years"); development(result, prices, ChronoUnit.YEARS, -5, "Five years"); development(result, prices, ChronoUnit.YEARS, -7, "Seven years"); development(result, prices, ChronoUnit.YEARS, -10, "Ten years"); ImmutableSet<StopLoss> stopLosses = Activator.getDefault().getAccountManager().getStopLosses(security); if (! stopLosses.isEmpty()) { ImmutableList<Price> stopPrices = stopLosses.iterator().next().getPrices(prices); if (! stopPrices.isEmpty()) { BigDecimal stopLoss = stopPrices.get(stopPrices.size()-1).getValue(); IPrice price = prices.getPrice(prices.getMaxDate()); if (price.getValue().compareTo(BigDecimal.ZERO) != 0) { BigDecimal delta = price.getValue().subtract(stopLoss); BigDecimal percent = delta.divide(price.getValue(), PeanutsUtil.MC); percent = percent.movePointRight(2); percent = percent.setScale(2, RoundingMode.HALF_UP); result.add(new String[]{"Stop Loss", PeanutsUtil.formatCurrency(stopLoss, null), PeanutsUtil.formatCurrency(delta, null), percent.toString()+" %"}); } else { result.add(new String[]{"Stop Loss", PeanutsUtil.formatCurrency(stopLoss, null)}); } } } return result; } private void development(List<String[]> result, IPriceProvider prices, TemporalUnit field, int delta, String text) { LocalDate date = LocalDate.now(); Day to = Day.from(date); date = date.plus(delta, field); Day from = Day.from(date); IPrice price1 = prices.getPrice(from); IPrice price2 = prices.getPrice(to); BigDecimal diff = price2.getValue().subtract(price1.getValue()); if (price1.getValue().compareTo(BigDecimal.ZERO) != 0 && from.delta(to) > 0) { BigDecimal anualDiff = price2.getValue().divide(price1.getValue(), PeanutsUtil.MC); anualDiff = new BigDecimal(Math.pow(anualDiff.doubleValue(), 360.0 / from.delta(to))).subtract(BigDecimal.ONE); anualDiff = anualDiff.movePointRight(2).setScale(2, RoundingMode.HALF_UP); BigDecimal diffPercent = diff.divide(price1.getValue(), PeanutsUtil.MC); diffPercent = diffPercent.movePointRight(2).setScale(2, RoundingMode.HALF_UP); result.add(new String[]{text, PeanutsUtil.formatCurrency(price1.getValue(), null), PeanutsUtil.formatCurrency(diff, null), diffPercent.toString()+" %", anualDiff.toString()+" %"}); } else { result.add(new String[]{text, PeanutsUtil.formatCurrency(price1.getValue(), null), PeanutsUtil.formatCurrency(diff, null), "-", "-"}); } } @Override public void setFocus() { tableViewer.getTable().setFocus(); } public void restoreState() { Security security = ((SecurityEditorInput) getEditorInput()).getSecurity(); for (int i = 0; i < colWidth.length; i++ ) { String width = security.getConfigurationValue(getClass().getSimpleName()+".col" + i); if (width != null) { colWidth[i] = Integer.valueOf(width).intValue(); } } } public void saveState() { Security security = ((SecurityEditorInput) getEditorInput()).getSecurity(); TableColumn[] columns = tableViewer.getTable().getColumns(); for (int i = 0; i < columns.length; i++ ) { TableColumn tableColumn = columns[i]; security.putConfigurationValue(getClass().getSimpleName()+".col" + i, String.valueOf(tableColumn.getWidth())); } } @Override public void doSave(IProgressMonitor monitor) { // nothing to do } @Override public void doSaveAs() { // nothing to do } @Override public boolean isDirty() { return false; } @Override public boolean isSaveAsAllowed() { return false; } }
PHP
UTF-8
1,451
2.8125
3
[]
no_license
<?php namespace App\Services\Employees; use App\Services\Companies\CompanyService; use App\Repositories\Employees\EmployeeRepository; use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException; class EmployeeService { private $employeeRepository; private $companyService; public function __construct(EmployeeRepository $employeeRepository, CompanyService $companyService) { $this->employeeRepository = $employeeRepository; $this->companyService = $companyService; } public function paginate() { return $this->employeeRepository->paginate(); } public function getById($id) { return $this->employeeRepository->getById($id); } public function create($data) { $company = $this->companyService->getById($data['company_id']); if (is_null($company)) { throw new UnprocessableEntityHttpException('Selected company is invalid.'); } $employee = $this->employeeRepository->create($data); return $employee; } public function update($id, $data) { $employee = $this->employeeRepository->getById($id); return $this->employeeRepository->update($employee, $data); } public function delete($id) { $employee = $this->employeeRepository->getById($id); $employeeDeleted = $this->employeeRepository->delete($employee); return true; } }
JavaScript
UTF-8
5,060
2.578125
3
[]
no_license
/* **** For create a new Scene **** * * @step 1 Copy the content of this file in a new .js document. * ---------------------------------------------------------------------------------------------------------------------------- * @step 2 Save the new file in Assets/Javascript/Scenes/NameOfYourScene.js . * ---------------------------------------------------------------------------------------------------------------------------- * @step 3 In the index.html add below this comment <!-- Scene --> the line: * "<script type="text/javascript" src="Assets/Scripts/Javascript/Scenes/NameOfYourGameObject.js"></script>" * ---------------------------------------------------------------------------------------------------------------------------- * @step 4 For create a new scene, use this instruction: "new Scene()". */ /* **** How to make the setup of a Scene **** * * @property name {string} * The name of the scene. * -------------------------------------------------------------------------------------------------------------------------------- * @property GameObjects {array[GameObject1, ...]} * All the GameObject of the scene * */ /* **** Method of the scene **** * * @method Awake() * Called at the instruction new Scene(). * -------------------------------------------------------------------------------------------------------------------------------- * @method Start() * Called at the first use of scene in game. * -------------------------------------------------------------------------------------------------------------------------------- * @method Update() * Called each frame,code game is here. * -------------------------------------------------------------------------------------------------------------------------------- * @method LateUpdate() * Called each frame, code all the GUI here. */ /* **** For launch Scene **** * * To load your scene, use this instruction: "Application.LoadLevel(LevelName)". */ function SceneRoof () { this.name = "Toit"; this.Started = false; this.step = 0; this.GameObjects = []; this.Awake = function() { //codez l'awake avant le console.log console.clear(); console.log(" %c System: Scene " + this.name + " created!", 'background: #222; color: #bada55'); }; this.Start = function() { if(!this.Started) { this.Started = true; Time.LevelLoaded(); console.log(" %c System: Scene " + this.name + " have started!", 'background: #222; color: #bada55'); } this.Update(); }; this.OnLoadLevel = function() { this.step = 0; }; this.Update = function() { if(!Application.GamePaused) { ctx.drawImage(Images.toitBackground ,0,0, canvas.width, canvas.height); if(this.step == 0 || this.step == 1 || this.step == 2){ ctx.drawImage(Images.cop, 0, 150, 400, 800); ctx.drawImage(Images.cop, 300, 290, 400, 800); ctx.drawImage(Images.cop, 600, 100, 400, 800); } switch(this.step){ case 0: GUI.Availaible = false; Dialogue.Begin("Aucune issue [short] . [short] . [short] . [short]", 0.10, {x:30, y:570}, "white", "30px Georgia"); this.step++; break; case 1: if(Dialogue.finished){ Dialogue.Begin("“RECULEZ ! NE VOUS APPROCHEZ PAS !”", 0.10, {x:30, y:570}, "white", "30px Georgia"); this.step++; } break; case 2: if(Dialogue.finished){ this.GameObjects.push( new CursorTarget(Images.toitBackground, [ {sprite: Images.cop, x: 0, y: 150, w: 400, h: 800, speed: 5, Life: 15}, {sprite: Images.cop, x: 300, y: 290, w: 400, h: 800, speed: 5, Life: 15}, {sprite: Images.cop, x: 600, y: 100, w: 400, h: 800, speed: 5, Life: 15} ], this)); this.step++; } break; case 3: break; case 4: this.GameObjects = []; if(Dialogue.finished){ Dialogue.Begin("Je... [short] C’était donc moi...", 0.10, {x:30, y:570}, "white", "30px Georgia"); this.step++; } break; case 5: if(Dialogue.finished){ Dialogue.Begin("Depuis le début ...... [short] Qu’ai-je fait...", 0.10, {x:30, y:570}, "white", "30px Georgia"); this.step++; } break; case 6: if(Dialogue.finished){ GUI.Availaible = true; this.step++; } break; case 7: Application.LoadLevel("Outro"); break; } for(var i = 0; i < this.GameObjects.length; i++) { if(this.GameObjects[i].enabled) { this.GameObjects[i].Start(); } } if(!Dialogue.finished) { ctx.drawImage(Images.dialogueBox, 0, 470); Dialogue.Continue(); } this.LateUpdate(); } }; this.LateUpdate = function() { if(!Application.GamePaused) { //Codez la GUI ici pour que la pause soit prise en compte } if(Application.DebugMode) { Debug.ShowStats(); } }; this.BattleResult = function(str) { this.step++; } // lance l'awake a la creation de la scene this.Awake(); }