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
Shell
UTF-8
684
3.203125
3
[ "MIT" ]
permissive
#!/bin/bash -l rvm use 2.5.8 rvm --force gemset delete cfn_model rvm gemset use cfn_model --create gem uninstall cfn-model -x gem build cfn-model.gemspec gem install cfn-model-0.0.0.gem --no-ri --no-rdoc mkdir aws_sample_templates || true pushd aws_sample_templates wget https://s3-eu-west-1.amazonaws.com/cloudformation-examples-eu-west-1/AWSCloudFormation-samples.zip rm *.template rm -rf aws-cloudformation-templates unzip AWSCloudFormation-samples.zip git clone https://github.com/awslabs/aws-cloudformation-templates.git templates=$(find . -name \*.template -o -name \*.yml -o -name \*.json -o -name \*.yaml) for template in ${templates} do cfn_parse ${template} done popd
JavaScript
UTF-8
7,892
2.59375
3
[]
no_license
var width = window.innerWidth; var height = window.innerHeight; var wm = new WeakMap(); var context; var analyser; class MusicManager { constructor(foxes,rabbits) { this.MEDIA_ELEMENT_NODES = new WeakMap(); this.foxes = foxes; this.rabbits = rabbits; this.audio = null; this.context = null; this.src = null; this.analyser = null; this.fft = 2048; this.bufferLength = 0; this.dataArray = null; this.time = 0; this.deltaTime = 0.1; this.processor = null; this.speed = 0; this.totalTime = 0; this.initialized = false; } initAudioContext(){ context = new (AudioContext || webkitAudioContext)(); analyser = context.createAnalyser(); } init() { if (!this.initialized){ this.initAudioContext(); this.initialized = true; } this.audio.load(); this.audio.play(); // this.src = this.context.createMediaElementSource(this.audio); if (wm.has(this.audio)) { // if (this.oldsrc != null){ // this.oldsrc.disconnect(); // } this.src = wm.get(this.audio); // if(this.src != this.oldsrc){ // // // this.analyser.connect(this.context.destination); // console.log("on est la"); // this.src.connect(this.analyser); // } // this.src.connect(this.analyser); // this.analyser.connect(this.context.destination); } else { this.src = context.createMediaElementSource(this.audio); wm.set(this.audio, this.src); } this.src.connect(analyser); analyser.connect(context.destination); analyser.fftSize = this.fft; this.bufferLength = analyser.frequencyBinCount; this.dataArray = new Uint8Array(this.bufferLength); this.totalTime = Math.ceil(this.audio.duration); } switchAudio(newAudio){ // if(this.src){ // this.src.disconnect(); // } // this.audio.load(); // this.audio.play(); // // this.src = this.context.createMediaElementSource(this.audio); // if (wm.has(this.audio)) { // this.src = wm.get(this.audio); // } else { // this.src = this.context.createMediaElementSource(this.audio); // wm.set(this.audio, this.src); // } // // this.analyser = this.context.createAnalyser(); // // this.src.connect(this.analyser); // this.analyser.connect(this.context.destination); // // this.analyser.fftSize = this.fft; // // this.bufferLength = this.analyser.frequencyBinCount; // this.dataArray = new Uint8Array(this.bufferLength); // this.audio.play(); // this.totalTime = Math.ceil(this.audio.duration); } //update de Samuel update() { this.time += this.deltaTime; if(this.dataArray != null){ analyser.getByteFrequencyData(this.dataArray); this.foxes.all.forEach(particule => { var new_deltaTime = this.deltaTime + (( average(this.dataArray))/200); var v_x_new = particule.velocity.x; var v_y_new = particule.velocity.y; var x_new = particule.position.x + v_x_new * new_deltaTime; var y_new = particule.position.y + v_y_new * new_deltaTime; particule.motion(x_new,y_new,v_x_new,v_y_new); }) } } updateFoxAndRabbit() { this.time += this.deltaTime; if(this.dataArray != null) { analyser.getByteFrequencyData(this.dataArray); var i = 0; this.rabbits.rabbits.forEach(rabbit => { if(i >= this.bufferLength) { i = 0; } rabbit.dimension.width = this.dataArray[i]/10; // rabbit.color = "rgb("+this.dataArray[i]+","+this.dataArray[i]+","+this.dataArray[i]+")"; rabbit.color = "rgb("+Math.abs(this.dataArray[i]-255)+","+Math.abs(this.dataArray[i]-255)+","+Math.abs(this.dataArray[i]-255)+")"; if(!rabbit.alive){ rabbit.color = "#FFF"; } // rabbit.velocity.x = randInt((-average(this.dataArray)/10)+1,average(this.dataArray)/10); // rabbit.velocity.y = randInt((-average(this.dataArray)/10)+1,average(this.dataArray)/10); // rabbit.color = "rgb("+(this.dataArray[i]%255)+","+(this.dataArray[i]%255)+","+(this.dataArray[i]%255)+")"; if(rabbit.dimension.width < 5) { rabbit.dimension.width = 5 } i++; }) this.foxes.foxes.forEach(fox => { fox.bonus.velocity = average(this.dataArray)/10; fox.bonus.attack = average(this.dataArray)/1; }) } } updateAtom(){ this.time += this.deltaTime; if(this.dataArray != null) { analyser.getByteFrequencyData(this.dataArray); this.foxes.atoms.forEach(atom => { var new_deltaTime = this.deltaTime + ((average(this.dataArray)+1)/30) var v_x_new = atom.dirx; var v_y_new = atom.diry; var xnew = atom.position.x + v_x_new * new_deltaTime; var ynew = atom.position.y + v_y_new * new_deltaTime; atom.motion(xnew, ynew, v_x_new, v_y_new); }); } } // Draw de Samuel draw() { this.time += this.deltaTime; if(this.dataArray != null){ analyser.getByteFrequencyData(this.dataArray); var circleRadius = canvas.height/10; var frequencyWidth = ((2*Math.PI)/this.bufferLength); var frequencyHeight = 0; var x = 0; for(var increment = 0; increment < this.bufferLength; increment+=4){ // ou increment+=10 frequencyHeight = this.dataArray[increment] * (canvas.height * 0.0008); if(this.dataArray[increment] >0 && this.dataArray[increment] < 40){ //violet var r = 162; var g = 0; var b = 255; } if(this.dataArray[increment] >39 && this.dataArray[increment] < 80){ //indigo var r = 0; var g = 0; var b = 255; } if(this.dataArray[increment] >79 && this.dataArray[increment] < 120){ //bleu var r = 0; var g = 232; var b = 255; } if(this.dataArray[increment] >119 && this.dataArray[increment] < 160){ //vert var r = 203; var g = 245; var b = 13; } if(this.dataArray[increment] >159 && this.dataArray[increment] < 200){ // jaune var r = 255; var g = 243; var b = 0; } if(this.dataArray[increment] >199 && this.dataArray[increment] < 240){ // orange var r = 255; var g = 151; var b = 0; } if(this.dataArray[increment] >239){ // rouge var r = 255; var g = 19; var b = 0; } ctx.beginPath(); var ax = canvas.width/2 + (circleRadius*Math.cos(x*1000)); var ay = canvas.height/2 + (circleRadius*Math.sin(x*1000)); var bx = canvas.width/2 + ((circleRadius+frequencyHeight)*Math.cos(x*1000)); var by = canvas.height/2 + ((circleRadius+frequencyHeight)*Math.sin(x*1000)); ctx.moveTo(ax,ay); ctx.lineTo(bx,by); //ctx.lineWidth = 5; ctx.strokeStyle ="rgb(" + r + "," + g + "," + b + ")"; ctx.stroke(); var currentTime = Math.ceil(document.getElementById('audio').currentTime); ctx.beginPath(); ctx.arc(canvas.width/2, canvas.height/2, circleRadius-10, -0.5*Math.PI, -0.5*Math.PI+(((2*Math.PI)/this.totalTime)*currentTime),false); // ctx.lineWidth = 10; ctx.stroke(); x += (2*Math.PI)/(this.bufferLength); } } } }
Markdown
UTF-8
1,359
2.5625
3
[]
no_license
<a href="https://truyentiki.com/nu-than-toi-cua-cuong-te.33785/" title="Nữ Thần Tới Cửa Cuồng Tế"><h1>Nữ Thần Tới Cửa Cuồng Tế</h1></a><div style="display:table"><img align="right" style="float: left; padding: 10px;" src="https://truyentiki.com/a/img/str/src/33785.jpg" alt="Nữ Thần Tới Cửa Cuồng Tế">Ông trở về nhà như một đứa con trai-trong-pháp luật và đã bị bỏ rơi bởi những người khác cho đến khi ông nội của ông tìm thấy anh ta. Từ đó trở đi, số phận của mình tăng như một cơn gió, và anh lái xe lên đến 90.000 dặm. Ngay cả ông nội của ông đã được phục vụ, và hỏi anh ta đến hàng trăm kế thừa của hàng triệu tính!</div><p><br><b>Truyện Hay Khác :</b></p><a href="https://truyentiki.com/nghich-tap.33784/" alt="Nghịch Tập">Nghịch Tập</a><br/><a href="https://github.com/nownovels/top500/tree/master/truyenhay/33621/" alt="Tuyệt Thế Đan Thần">Tuyệt Thế Đan Thần</a><br/><a href="https://github.com/nownovels/top500/tree/master/truyenhay/33923/" alt="Trọng Sinh Đại Phú Hào">Trọng Sinh Đại Phú Hào</a><br/><a href="https://truyentiki.wordpress.com/2020/06/08/nu-than-toi-cua-cuong-te/" alt="Nữ Thần Tới Cửa Cuồng Tế">Nữ Thần Tới Cửa Cuồng Tế</a><br/>
Java
UTF-8
1,468
3.078125
3
[]
no_license
package org.wcy123.rxjava1; import org.junit.Test; import rx.Observable; import rx.Observer; import rx.observers.Observers; public class JustTest { @Test public void main1() throws Exception { final Observable<String> observable = Observable.just("hello world"); final Observer<Object> observer = Observers.create(System.out::println); observable.subscribe(observer); } @Test public void main2() throws Exception { final Observable<Integer> observable = Observable.range(1, 10); final Observer<Integer> observer = Observers.create(System.out::println); observable.subscribe(observer); } @Test public void main3() throws Exception { final Observable<Integer> observable = Observable.range(1, 10); final Observer<Integer> observer = Observers.create(System.out::println); observable.subscribe(observer); } @Test public void main4() throws Exception { final Observable<String> observable = Observable.empty(); final Observer<String> observer = new SimpleObserver(); observable.subscribe(observer); System.out.println("hi"); } @SuppressWarnings("WeakerAccess") static class SimpleObserver implements Observer<String> { @Override public void onCompleted() {} @Override public void onError(Throwable e) {} @Override public void onNext(String s) {} } }
Python
UTF-8
1,961
3.890625
4
[]
no_license
""" The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. Example 1: Input: n = 4 Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above Example 2: Input: n = 1 Output: [["Q"]] Constraints: 1 <= n <= 9 """ # Approach: DFS backtrack class Solution: def solveNQueens(self, n: int) -> List[List[str]]: board = [["."]*n for i in range(n)] res = [] self.backtrack(res, board, n, 0) return res def backtrack(self, res, board, n, row): if row == n: res.append(["".join(row) for row in board]) return for col in range(n): if not self.checkValid(board, row, col, n): continue board[row][col] = "Q" self.backtrack(res, board, n, row+1) board[row][col] = "." def checkValid(self, board, row, col, n): # check same column attack for r in range(n): if board[r][col] == "Q": return False # check top left diagnoal attack srow, scol = row, col while srow-1 >= 0 and srow < n and scol-1 >= 0 and scol < n: srow = srow-1 scol = scol-1 if board[srow][scol] == 'Q': return False # check top right diagnoal attack srow, scol = row, col while srow-1 >= 0 and srow < n and scol >= 0 and scol < n-1: srow = srow-1 scol = scol+1 if board[srow][scol] == 'Q': return False return True
PHP
UTF-8
901
2.890625
3
[]
no_license
<?php class Csoport { private $azonosito; private $nev; private $admin_felhasznalo; /** * @return mixed */ public function getAzonosito() { return $this->azonosito; } /** * @param mixed $azonosito */ public function setAzonosito($azonosito) { $this->azonosito = $azonosito; } /** * @return mixed */ public function getNev() { return $this->nev; } /** * @param mixed $nev */ public function setNev($nev) { $this->nev = $nev; } /** * @return mixed */ public function getAdminFelhasznalo() { return $this->admin_felhasznalo; } /** * @param mixed $admin_felhasznalo */ public function setAdminFelhasznalo($admin_felhasznalo) { $this->admin_felhasznalo = $admin_felhasznalo; } }
C
UTF-8
500
2.609375
3
[]
no_license
#pragma once #include <stdio.h> #include <uthash.h> /* Removes every element from the hashtable and calls free(3) on it * ty: Element type of the table * hashtable: The table */ #define CLEAR_AND_DELETE(ty, hashtable)\ do {\ ty *cur, *tmp;\ HASH_ITER(hh, hashtable, cur, tmp) { \ HASH_DEL(hashtable, cur);\ free(cur);\ }\ } while (0); FILE *ensure_open(const char *path, const char *mode); typedef struct hashable_int { int value; UT_hash_handle hh; } hashable_int;
Python
UTF-8
407
4.71875
5
[]
no_license
#An example of using a for loops students = ["Alice", "Dan", "Suzie"] for student in students: print(student)#prints out each student is the list x = "Hello" for char in x:#prints out every char in what is stored in x print(char) y = list(range(1,11)) print(y) for i in y:#prints out 1-10 print(i) for i in range(1,10):#range(min, max+1) print(i)#using the range function, prints out 1-9
JavaScript
UTF-8
1,305
2.671875
3
[]
no_license
import React, { Component } from 'react'; class ToyForm extends Component { state = { name: "", image: "" } handleChange = (e) => { let t = e.target this.setState({ [t.name]: t.value }) } handleSubmit = (e) => { const { appSubmitHandler } = this.props e.preventDefault() appSubmitHandler(this.state) this.setState({ name: "", image: "" }) } render() { const { name, image } = this.state return ( <div className="container"> <form className="add-toy-form" onSubmit={this.handleSubmit}> <h3>Create a toy!</h3> <input type="text" name="name" placeholder="Enter a toy's name..." className="input-text" value={name} onChange={this.handleChange} /> <br/> <input type="text" name="image" placeholder="Enter a toy's image URL..." className="input-text" value={image} onChange={this.handleChange} /> <br/> <input type="submit" name="submit" value="Create New Toy" className="submit"/> </form> </div> ); } } export default ToyForm;
PHP
UTF-8
5,171
2.609375
3
[]
no_license
<?php /** * Fichier source de la classe CohortepdfsShell. * * PHP 5.3 * * @package app.Console.Command * @license CeCiLL V2 (http://www.cecill.info/licences/Licence_CeCILL_V2-fr.html) */ App::uses( 'XShell', 'Console/Command' ); App::uses( 'Component', 'Controller' ); App::uses( 'GedoooComponent', 'Gedooo.Controller/Component' ); /** * La classe CohortepdfsShell ... * * @package app.Console.Command */ class CohortepdfsShell extends XShell { /** * * @var type */ public $uses = array( 'Pdf', 'Orientstruct', 'User' ); /** * * @var type */ public $Gedooo; /** * * @var type */ public $user_id = null; /** * * @return type */ public function getOptionParser() { $parser = parent::getOptionParser(); $parser->description( array( 'Ce script se charge de créer une impression d\'orientation en .pdf en base de données pour toutes les personnes ayant été orientées avant la version 2.0rc2.', 'Ces fichiers doivent être enregistrés en base pour voir les personnes orientées depuis le menu «  Cohorte -> Orientation -> Demandes orientées  " ou le menu «  Recherches -> Par Orientation  ".', 'Ce script n\'est à exécuter qu\'une seule fois.' ) ); $options = array( 'username' => array( 'short' => 'u', 'help' => 'L\'identifiant de l\'utilisateur qui sera utilisé pour la récupération d\'informations lors de l\'impression.', 'default' => '' ), 'limit' => array( 'short' => 'L', 'help' => 'Nombre d\'enregistrements à traiter. Doit être un nombre entier positif. Par défaut: 10. Utiliser 0 ou null pour ne pas avoir de limite et traiter tous les enregistrements.', 'default' => 10 ), 'order' => array( 'short' => 'o', 'help' => 'Permet de trier les enregistrements à traiter par date de validation de l\'orentation (date_valid) en ordre ascendant ou descendant.', 'default' => 'asc', 'choices' => array( 'asc', 'desc' ) ) ); $parser->addOptions( $options ); return $parser; } /** * */ protected function _showParams() { parent::_showParams(); $this->out( '<info>Identifiant de l\'utilisateur</info> : <important>'.$this->params['username'].' </important>' ); $this->out( '<info>Nombre d\'enregistrements à traiter</info> : <important>'.$this->params['limit'].'</important>' ); $this->out( '<info>Ordre de tri</info> : <important>'.$this->params['order'].'</important>' ); } /** * * */ public function startup() { // Username $user_id = $this->User->field( 'id', array( 'username' => $this->params['username'] ) ); if( isset( $this->params['username'] ) && is_string( $this->params['username'] ) && !empty( $user_id ) ) { $this->user_id = $user_id; } else { $this->out(); $this->err( sprintf( "Veuillez entrer un identifiant valide", $this->params['username'] ) ); $this->out(); $this->out( $this->OptionParser->help() ); $this->_stop( 1 ); } parent::startup(); } /** * */ public function main() { $success = true; $nSuccess = 0; $nErrors = 0; $this->Gedooo = new GedoooComponent( new ComponentCollection() ); $orientsstructsQuerydatas = array( 'conditions' => array( 'Orientstruct.statut_orient' => 'Orienté', 'Orientstruct.id NOT IN ( SELECT pdfs.fk_value FROM pdfs WHERE pdfs.modele = \'Orientstruct\' )' ), 'order' => array( 'Orientstruct.date_valid '.$this->params['order'] ) ); if( !empty( $this->params['limit'] ) ) { $orientsstructsQuerydatas['limit'] = $this->params['limit']; } $orientsstructs_ids = $this->Orientstruct->find( 'list', $orientsstructsQuerydatas ); $this->_wait( sprintf( "%d enregistrements à traiter.", count( $orientsstructs_ids ) ) ); $this->XProgressBar->start( count( $orientsstructs_ids ) ); $cpt = 0; foreach( $orientsstructs_ids as $orientstruct_id ) { $this->Orientstruct->begin(); $orientstruct = $this->Orientstruct->find( 'first', array( 'conditions' => array( 'Orientstruct.id' => $orientstruct_id ), 'recursive' => -1, 'contain' => false ) ); $orientstruct['Orientstruct']['user_id'] = $this->user_id; $this->Orientstruct->create( $orientstruct ); $tmpSuccess = $this->Orientstruct->save(); if( empty($tmpSuccess) ) { $nErrors++; } if( !empty($tmpSuccess) ) { $this->Orientstruct->commit(); } else { $this->Orientstruct->rollback(); $success = false; } $this->XProgressBar->next( 1, "<info>Génération PDFs (Orientstruct.id=".$orientstruct_id.")</info>" ); $cpt++; } /// Fin de la transaction $this->out(); $this->out(); $message = "%s (<important>{$cpt}</important> pdfs d'orientation à générer, <important>{$nSuccess}</important> succès, <important>{$nErrors}</important> erreurs)"; if( $success ) { $this->out( sprintf( $message, "<success>Script terminé avec succès</success>" ) ); } else { $this->out( sprintf( $message, "<error>Script terminé avec erreurs</error>" ) ); } } } ?>
C++
UTF-8
4,703
2.5625
3
[ "MIT" ]
permissive
#pragma once #include "PCH.h" namespace SlimShader { enum class OperandType { /// <summary> /// Temporary Register File /// </summary> Temp = 0, /// <summary> /// General Input Register File /// </summary> Input = 1, /// <summary> /// General Output Register File /// </summary> Output = 2, /// <summary> /// Temporary Register File (indexable) /// </summary> IndexableTemp = 3, /// <summary> /// 32bit/component immediate value(s) /// // If for example, operand token bits /// [01:00]==OPERAND_4_COMPONENT, /// this means that the operand type: /// OPERAND_TYPE_IMMEDIATE32 /// results in 4 additional 32bit /// DWORDS present for the operand. /// </summary> Immediate32 = 4, /// <summary> /// // 64bit/comp.imm.val(s)HI:LO /// </summary> Immediate64 = 5, /// <summary> /// Reference to sampler state /// </summary> Sampler = 6, /// <summary> /// Reference to memory resource (e.g. texture) /// </summary> Resource = 7, /// <summary> /// Reference to constant buffer /// </summary> ConstantBuffer = 8, /// <summary> /// Reference to immediate constant buffer /// </summary> ImmediateConstantBuffer = 9, /// <summary> /// Label /// </summary> Label = 10, /// <summary> /// Input primitive ID /// </summary> InputPrimitiveID = 11, /// <summary> /// Output Depth /// </summary> OutputDepth = 12, /// <summary> /// Null register, used to discard results of operations /// </summary> Null = 13, // Below are operands new in DX 10.1 /// <summary> /// DX10.1 Rasterizer register, used to denote the depth/stencil and render target resources /// </summary> Rasterizer = 14, /// <summary> /// DX10.1 PS output MSAA coverage mask (scalar) /// </summary> OutputCoverageMask = 15, // Below Are operands new in DX 11 /// <summary> /// Reference to GS stream output resource /// </summary> Stream = 16, /// <summary> /// Reference to a function definition /// </summary> FunctionBody = 17, /// <summary> /// Reference to a set of functions used by a class /// </summary> FunctionTable = 18, /// <summary> /// Reference to an interface /// </summary> Interface = 19, /// <summary> /// Reference to an input parameter to a function /// </summary> FunctionInput = 20, /// <summary> /// Reference to an output parameter to a function /// </summary> FunctionOutput = 21, /// <summary> /// HS Control Point phase input saying which output control point ID this is /// </summary> OutputControlPointID = 22, /// <summary> /// HS Fork Phase input instance ID /// </summary> InputForkInstanceID = 23, /// <summary> /// HS Join Phase input instance ID /// </summary> InputJoinInstanceID = 24, /// <summary> /// HS Fork+Join, DS phase input control points (array of them) /// </summary> InputControlPoint = 25, /// <summary> /// HS Fork+Join phase output control points (array of them) /// </summary> OutputControlPoint = 26, /// <summary> /// DS+HSJoin Input Patch Constants (array of them) /// </summary> InputPatchConstant = 27, /// <summary> /// DS Input Domain point /// </summary> InputDomainPoint = 28, /// <summary> /// Reference to an interface this pointer /// </summary> ThisPointer = 29, /// <summary> /// Reference to UAV u# /// </summary> UnorderedAccessView = 30, /// <summary> /// Reference to Thread Group Shared Memory g# /// </summary> ThreadGroupSharedMemory = 31, /// <summary> /// Compute Shader Thread ID /// </summary> InputThreadID = 32, /// <summary> /// Compute Shader Thread Group ID /// </summary> InputThreadGroupID = 33, /// <summary> /// Compute Shader Thread ID In Thread Group /// </summary> InputThreadIDInGroup = 34, /// <summary> /// Pixel shader coverage mask input /// </summary> InputCoverageMask = 35, /// <summary> /// Compute Shader Thread ID In Group Flattened to a 1D value. /// </summary> InputThreadIDInGroupFlattened = 36, /// <summary> /// Input GS instance ID /// </summary> InputGSInstanceID = 37, /// <summary> /// Output Depth, forced to be greater than or equal than current depth /// </summary> OutputDepthGreaterEqual = 38, /// <summary> /// Output Depth, forced to be less than or equal to current depth /// </summary> OutputDepthLessEqual = 39, /// <summary> /// Cycle counter /// </summary> CycleCounter = 40 }; std::string ToString(OperandType value); bool RequiresRegisterNumberFor1DIndex(OperandType type); bool RequiresRegisterNumberFor2DIndex(OperandType type); };
Java
UTF-8
1,993
3.5625
4
[]
no_license
package sample; import java.util.ArrayList; public class Snake { ArrayList<tetrominoes> cordinates = new ArrayList<>(); public Snake(){ cordinates.add(new tetrominoes(0,1)); cordinates.add(new tetrominoes(0,2)); cordinates.add(new tetrominoes(0,3)); cordinates.add(new tetrominoes(0,4)); } public void moveSnake(){ for(int i = 0; i < cordinates.size() - 1 ; i++){ cordinates.get(i).x = cordinates.get(i+1).x; cordinates.get(i).y = cordinates.get(i+1).y; } cordinates.get(cordinates.size()-1).addCordinate(); } public void changeDirection(String direction){ if(direction == "left"){ cordinates.get(cordinates.size()-1).setSpeedX(-1); cordinates.get(cordinates.size()-1).setSpeedY(0); } if(direction == "right"){ cordinates.get(cordinates.size()-1).setSpeedX(1); cordinates.get(cordinates.size()-1).setSpeedY(0); } if(direction == "up"){ cordinates.get(cordinates.size()-1).setSpeedX(0); cordinates.get(cordinates.size()-1).setSpeedY(-1); } if(direction == "down"){ cordinates.get(cordinates.size()-1).setSpeedX(0); cordinates.get(cordinates.size()-1).setSpeedY(1); } } public void add(){ cordinates.add(0,new tetrominoes(cordinates.get(0).getX(),cordinates.get(0).getY())); } public boolean check() { int x = cordinates.get(cordinates.size()-1).getX(); int y = cordinates.get(cordinates.size()-1).getY(); for(int i = 0 ;i<cordinates.size()-1; i++){ if ((cordinates.get(i).getX() == x)&&(cordinates.get(i).getY() == y)){ Menu menu = new Menu(); System.out.println("Your score " + menu.score); return true; } } return false; } }
Java
UTF-8
442
2.9375
3
[]
no_license
package predconssupp; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; public class ConsumerDemo { public static void main(String[] args) { // Consumer<Integer> con =(integer) -> System.out.println("Printing:"+ integer); // con.accept(10); List<Integer> list = Arrays.asList(1,2,3,4); list.stream().forEach(integer -> System.out.println("Printing:"+ integer)); } }
Ruby
UTF-8
2,345
2.53125
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'json' require 'open-uri' require 'faker' require 'cloudinary' puts "Let's seed!" puts 'cleaning the DB' Ingredient.destroy_all Cocktail.destroy_all puts 'DB cleaned' puts "Seeding the DB" url = "https://www.thecocktaildb.com/api/json/v1/1/random.php" 10.times do data = JSON.parse(open(url).read) cocktail_data = data["drinks"].first break if Cocktail.find_by_name(cocktail_data["strDrink"]) cocktail = Cocktail.new cocktail.name = cocktail_data["strDrink"] cocktail.remote_photo_url = cocktail_data["strDrinkThumb"] if cocktail_data["strDrinkThumb"].present? cocktail.save! 15.times do |i| ingredient_data_name = cocktail_data["strIngredient#{i+1}"] break if ingredient_data_name.empty? ingredient = Ingredient.find_or_create_by!(name: ingredient_data_name) description = cocktail_data["strMeasure#{i+1}"].present? ? cocktail_data["strMeasure#{i+1}"] : 'some' Dose.create!( cocktail: cocktail, ingredient: ingredient, description: description ) end end # ingredients["drinks"].each do |b| # ingredient = Ingredient.new(name: b["strIngredient1"]) # ingredient.save! # end # url= https://www.thecocktaildb.com/images/ingredients/ice.png # images = ["http://res.cloudinary.com/doyl8dhkb/image/upload/v1511609816/lnuzy1rwse9r5thrc3st.jpg", "http://res.cloudinary.com/doyl8dhkb/image/upload/v1511609817/trbukchn4li4g5g6ibay.jpg", "http://res.cloudinary.com/doyl8dhkb/image/upload/v1511609818/rahtw0ahy5zrbyv9krk8.jpg", "http://res.cloudinary.com/doyl8dhkb/image/upload/v1511609819/h721tvfska6obubiunns.jpg"] # desc = ["1cl", "1.5cl", "2cl", "2.5cl", "3cl", "3.5cl", "4cl", "4.5cl", "5cl", "5.5cl", "6cl", "1 drop", "2 drops"] # 10.times do # cocktail = Cocktail.new(name: Faker::Hipster.words(2).join(" ").capitalize) # cocktail.remote_photo_url = images.sample # cocktail.save! # Dose.create!(description: desc.sample, ingredient: Ingredient.all.sample, cocktail: cocktail) # end
Rust
UTF-8
315
3
3
[]
no_license
pub mod camera; /// The current game state that the player is experiencing. #[derive(Copy, Clone)] pub enum ViewState { Spatial, System, } impl Default for ViewState { fn default() -> Self { ViewState::Spatial } } #[derive(Default)] pub struct GameState { pub view_state: ViewState, }
C#
UTF-8
1,257
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Clinic { public partial class AppointmentsPanel : UserControl, IAppointmentsPanelView { #region Properties public List<string> Content { set { if (listBox1.Items.Count != 0) listBox1.Items.Clear(); foreach (var d in value) { listBox1.Items.Add(d); } } } public int ChosenAppointment { get { return listBox1.SelectedIndex; } } #endregion #region Events public event Action ChosenAppointmentClick; #endregion public AppointmentsPanel() { InitializeComponent(); } #region Methods private void listBox1_SelectedIndexChanged(object sender, EventArgs e) { if (ChosenAppointmentClick != null) ChosenAppointmentClick(); } #endregion } }
Python
UTF-8
2,209
3.46875
3
[]
no_license
__author__ = 'zl' from functools import reduce import math """ python 高阶函数 Higher-order function """ def f_map1(): """ map() 函数 每一项单独取出来处理作用在函数上 :return: """ # 将一个list 每项 x2 ls = [2, 4, 5, 1, 8] def x2(i): return i*2 # r = map(x2, ls) r = map(lambda x:x*2, ls) print(list(r)) def f_reduce1(): """ map() 函数,把结果和下一项作用在函数上 :return: """ ls = [2, 4, 5, 1, 8] # 求这个list之和 def c(x,n): return x+n r = reduce(c,ls) r = reduce(lambda x,n:x+n, ls) print(r) def f_sorted1(): """ sorted() 函数,排序 :return: """ ls = [2, 4, -5, 1, 8] r = sorted(ls, key=abs) # 根据绝对值排序 print(r) ls = ['az', 'Vg', '6d', 'ZR'] r = sorted(ls, key=lambda x: str.lower(x)) # 忽略大小写排序 print(r) data = [('ab', 34), ('Vg', 57), ('ZR', 76), ('az', 33)] r = sorted(data, key=lambda x: str.lower(x[0])) # 根据第0项排序 print(r) def f_filter1(): """ filter() 函数,过滤 :return: """ # 回数 两边读都是一样的 ls = filter(is_palindrome, range(1, 1000)) print(list(ls)) pass def is_palindrome(num): s = int(math.log10(num)+1) # 数字长度 if s == 1: return False # 取数字的某一位,从右开始 def get_v(i): return int((num % (10 ** i)) / 10 ** (i-1)) x, y = s, 1 while True: if get_v(x) == get_v(y): x -= 1 y += 1 else: return False if x <= y: return True def is_palindrome2(num): return num == int(str(num)[::-1]) # 反转数字,效率比较高 def read_pwd(): def sp_data(line): name, pwd, id, reset = line.split(':', 3) return {'name': name, 'id': id} with open('/etc/passwd') as f: ls = [sp_data(line) for line in f if not line.startswith('#')] print(id(ls)) print(ls) pass def main(): f_map1() f_reduce1() f_sorted1() f_filter1() read_pwd() if __name__ == '__main__': main()
C++
UTF-8
3,971
3.21875
3
[ "MIT" ]
permissive
//////////////////////////////////////////////////////////////////////////////// // // Udacity self-driving car course : unscented Kalman filter project. // // Author : Charlie Wartnaby, Applus IDIADA // Email : charlie.wartnaby@idiada.com // //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include "tools.h" using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { // Calculate the root mean square error over the set of estimated // and ground truth points provided. // Taken from previous (extended Kalman filter) project. // Note: following project template here, but not efficient because we // are recomputing RMSE over the entire dataset each time we get a new // measurement point; would be better to maintain the sums and just // divide by the new number of points at each timestep, or even use // a moving average over the last 'n' points, but OK for this project. int num_est_points = estimations.size(); int num_truth_points = ground_truth.size(); if (num_est_points <= 0 || num_truth_points <= 0 || num_est_points != num_truth_points) { cerr << "Error in CalculateRMSE(): supplied vectors must have non-zero and equal size" << endl; } int num_est_elements = estimations[0].size(); int ground_t_elements = ground_truth[0].size(); // Initialise return vector to a copy of a dynamically-created // vector of required size retVector_ = VectorXd::Zero(num_est_elements); if (num_est_elements <= 0) { cerr << "Error in CalculateRMSE(): supplied vectors must have non-zero size" << endl; } else if (num_est_elements != ground_t_elements) { cerr << "Error in CalculateRMSE(): supplied vectors must have equal size" << endl; } else { // Sizes valid so compute mean squared errors // Firstly sum of square residuals for (int i = 0; i < num_est_points; i++) { VectorXd residuals = estimations[i] - ground_truth[i]; // element-wise subtraction VectorXd resids_sqd = residuals.array() * residuals.array(); // achieves dot product retVector_ += resids_sqd; // element-wise addition } // Form mean by dividing by number of samples retVector_ /= num_est_points; // element-wise division // Finally, square root of that mean sum retVector_ = retVector_.array().sqrt(); } return retVector_; // Should be copied by caller so we can reuse } double Tools::NormaliseAnglePlusMinusPi(double angle) { // Normalises the angle provided to be in the interval [-pi, pi] // Not done by reference as we want to use it in at least one place // on a matrix element which we can't pass directly as a reference if ((angle > 20.0 * M_PI) || (angle < -20.0 * M_PI) || isnan(angle) ) { // Angle looks implausible. To avoid locking up with very lengthy // or even infinite* loop, force it to zero (with a warning). // (Shouldn't happen unless we get wildly wrong data, e.g. restarting // simulator at completely different point.) // *Can get infinite loop if number is so large that subtracting 2.pi // leaves same number behind, in double representation. cerr << "WARNING: angle=" << angle << " replaced with zero" << endl; angle = 0.0; } else { while (angle < -M_PI) { angle += 2 * M_PI; } while (angle > M_PI) { angle -= 2 * M_PI; } } return angle; }
PHP
UTF-8
8,875
3.421875
3
[]
no_license
<?php namespace Common\Tool; /** * Simple FTP client class. * * Contains methods to: * - create connection (ftp, ssl-ftp) * - close connection * - get connection * - login * - upload file from string * - upload file from path * - get the current directory name * - change to the parent directory * - change the current directory * - remove a directory * - create a directory * - __call method to forward to native FTP functions. * Example: "$ftpSimpleClient->delete($filePath)" will execute "ftp_delete($this->conn, $filePath)" function * * Usage example: * $ftp = new \Common\Tool\FtpSimpleClient(); * $ftp->createConnection($host, $ssl, $port)->login($user, $pass)->chdir($directory); * $ftp->putFromPath($filePath); * $ftp->delete(basename($filePath)); * $ftp->closeConnection(); */ class FtpSimpleClient { /** * @var string $error Default exception error message mask */ protected $error = 'FTP Error: %s!'; /** * @var resource $conn Connection with the server */ protected $conn; /** * Class constructor. * * @access public * @param boolean $ignore_user_abort Ignore user abort, true by default * @throws \Exception If ftp extension is not loaded. */ public function __construct($ignore_user_abort = true) { if (!extension_loaded('ftp')) { throw new \Exception(sprintf($this->error, 'FTP extension is not loaded')); } ignore_user_abort($ignore_user_abort); } /** * Class destructor. * * @access public * @return void */ public function __destruct() { $this->closeConnection(); } /** * Overwrite maximum execution time limit. * * @access public * @param mixed $time Max execution time, unlimited by default * @return \Common\Tool\FtpSimpleClient */ public function setMaxExecutionTimeLimit($time = 0) { if (null !== $time) { set_time_limit($time); } return $this; } /** * Opens a FTP or SSL-FTP connection. * Sets up stream resource on success or FALSE on error. * * @access public * @param string $host * @param boolean $ssl * @param int $port * @param int $timeout * @return \Common\Tool\FtpSimpleClient * @throws \Exception on failure */ public function createConnection($host, $ssl = false, $port = 21, $timeout = 90) { if ($ssl === true) { $this->conn = ftp_ssl_connect($host, $port, $timeout); } else { $this->conn = ftp_connect($host, $port, $timeout); } if (!$this->conn) { throw new \Exception(sprintf($this->error, 'Can not connect')); } return $this; } /** * Close the active FTP or SSL-FTP connection. * * @access public */ public function closeConnection() { if ($this->conn) { ftp_close($this->conn); } } /** * Get current active FTP or SSL-FTP connection. * * @access public * @return $conn resource */ public function getConnection() { return $this->conn; } /** * Log in to an FTP connection * * @access public * @param string $username * @param string $password * @return \Common\Tool\FtpSimpleClient * @throws \Exception on failure */ public function login($username = 'anonymous', $password = '') { $result = ftp_login($this->conn, $username, $password); if ($result === false) { throw new \Exception(sprintf($this->error, 'Login incorrect')); } return $this; } /** * Uploads a file to the server from a string * * @access public * @param string $remote_file * @param string $content * @return \Common\Tool\FtpSimpleClient * @throws \Exception on failure */ public function putFromString($remote_file, $content) { $handle = fopen('php://temp', 'w'); fwrite($handle, $content); rewind($handle); if (ftp_fput($this->conn, $remote_file, $handle, FTP_BINARY)) { return $this; } throw new \Exception(sprintf($this->error, 'Unable to put the file "' . $remote_file . '"' )); } /** * Uploads a file to the server * * @access public * @param string $local_file * @return \Common\Tool\FtpSimpleClient * @throws \Exception on failure */ public function putFromPath($local_file) { $remote_file = basename($local_file); $handle = fopen($local_file, 'r'); if (ftp_fput($this->conn, $remote_file, $handle, FTP_BINARY)) { rewind($handle); return $this; } throw new \Exception(sprintf($this->error, 'Unable to put the remote file from the local file "' . $local_file . '"' )); } /** * Get the current directory name * * @access public * @return string $result Current directory name * @throws \Exception on failure */ public function pwd() { $result = ftp_pwd($this->conn); if ($result === false) { throw new \Exception(sprintf($this->error, 'Unable to resolve the current directory' )); } return $result; } /** * Changes to the parent directory * * @access public * @return \Common\Tool\FtpSimpleClient * @throws \Exception on failure */ public function cdup() { $result = ftp_cdup($this->conn); if ($result === false) { throw new \Exception(sprintf($this->error, 'Unable to get parent folder' )); } return $this; } /** * Changes the current directory * * @access public * @param string $directory * @return \Common\Tool\FtpSimpleClient * @throws \Exception on failure */ public function chdir(string $directory): self { $result = ftp_chdir($this->conn, $directory); if ($result === false) { throw new \Exception(sprintf($this->error, 'Unable to change the current directory' )); } return $this; } /** * Removes a directory * * @access public * @param string $directory Directory * @return \Common\Tool\FtpSimpleClient * @throws \Exception on failure */ public function rmdir($directory) { $result = ftp_rmdir($this->conn, $directory); if ($result === false) { throw new \Exception(sprintf($this->error, 'Unable to remove directory' )); } return $this; } /** * Creates a directory * * @access public * @param string $directory Directory * @return string Newly created directory name * @throws \Exception on failure */ public function mkdir($directory) { $result = ftp_mkdir($this->conn, $directory); if ($result === false) { throw new \Exception(sprintf($this->error, 'Unable to create directory' )); } return $result; } /** * Check if a directory exist. * * @access public * @param string $directory * @return boolean * @throws \Exception on failure */ public function isDir($directory) { $result = false; // Get current dir $pwd = ftp_pwd($this->conn); if ($pwd === false) { throw new \Exception(sprintf($this->error, 'Unable to resolve the current directory' )); } // Check if needed directory exists if (ftp_chdir($this->conn, $directory)) { $result = true; } // Set up back currnet directory ftp_chdir($this->conn, $pwd); return $result; } /** * Forward the method call to FTP functions. * Note: set up function name without native "ftp_" prefix * * @access public * @param string $function Function name * @param array $arguments * @return mixed Return value of the callback * @throws \Exception When the function is not valid */ public function __call($function, array $arguments) { $function = 'ftp_' . $function; if (function_exists($function)) { array_unshift($arguments, $this->conn); return call_user_func_array($function, $arguments); } throw new \Exception(sprintf($this->error, "{$function} is not a valid FTP function" )); } }
Python
UTF-8
82,908
2.5625
3
[ "MIT" ]
permissive
''' Extensions to Matplotlib, including 3D plotting and plot customization. Highlights: - :func:`sc.plot3d() <plot3d>`: easy way to render 3D plots - :func:`sc.boxoff() <boxoff>`: turn off top and right parts of the axes box - :func:`sc.commaticks() <commaticks>`: convert labels from "10000" and "1e6" to "10,000" and "1,000,0000" - :func:`sc.SIticks() <SIticks>`: convert labels from "10000" and "1e6" to "10k" and "1m" - :func:`sc.maximize() <maximize>`: make the figure fill the whole screen - :func:`sc.savemovie() <savemovie>`: save a sequence of figures as an MP4 or other movie - :func:`sc.fonts() <fonts>`: list available fonts or add new ones ''' ############################################################################## #%% Imports ############################################################################## import os import tempfile import datetime as dt import pylab as pl import numpy as np import matplotlib as mpl from . import sc_settings as scs from . import sc_odict as sco from . import sc_utils as scu from . import sc_fileio as scf from . import sc_printing as scp from . import sc_datetime as scd from . import sc_versioning as scv ############################################################################## #%% 3D plotting functions ############################################################################## __all__ = ['fig3d', 'ax3d', 'plot3d', 'scatter3d', 'surf3d', 'bar3d'] def fig3d(num=None, nrows=1, ncols=1, index=1, returnax=False, figkwargs=None, axkwargs=None, **kwargs): ''' Shortcut for creating a figure with 3D axes. Usually not invoked directly; kwargs are passed to :func:`pl.figure() <matplotlib.pyplot.figure>` ''' figkwargs = scu.mergedicts(figkwargs, kwargs, num=num) axkwargs = scu.mergedicts(axkwargs) fig = pl.figure(**figkwargs) ax = ax3d(nrows=nrows, ncols=ncols, index=index, returnfig=False, figkwargs=figkwargs, **axkwargs) if returnax: # pragma: no cover return fig,ax else: return fig def ax3d(nrows=None, ncols=None, index=None, fig=None, ax=None, returnfig=False, elev=None, azim=None, figkwargs=None, **kwargs): ''' Create a 3D axis to plot in. Usually not invoked directly; kwargs are passed to ``fig.add_subplot()`` Args: nrows (int): number of rows of axes in plot ncols (int): number of columns of axes in plot index (int): index of current plot fig (Figure): if provided, use existing figure ax (Axes): if provided, validate and use these axes returnfig (bool): whether to return the figure (else just the axes) elev (float): the elevation of the 3D viewpoint azim (float): the azimuth of the 3D viewpoint figkwargs (dict): passed to :func:`pl.figure() <matplotlib.pyplot.figure>` kwargs (dict): passed to :func:`pl.axes() <matplotlib.pyplot.axes>` | *New in version 3.0.0:* nrows, ncols, and index arguments first | *New in version 3.1.0:* improved validation; 'silent' and 'axkwargs' argument removed ''' from mpl_toolkits.mplot3d import Axes3D figkwargs = scu.mergedicts(figkwargs) axkwargs = scu.mergedicts(dict(nrows=nrows, ncols=ncols, index=index), kwargs) nrows = axkwargs.pop('nrows', nrows) # Since fig.add_subplot() can't handle kwargs... ncols = axkwargs.pop('ncols', ncols) index = axkwargs.pop('index', index) # Handle the "111" format of subplots try: if ncols is None and index is None: nrows, ncols, index = map(int, str(nrows)) except: pass # This is fine, just a different format # Handle the figure if fig in [True, False] or (fig is None and figkwargs): # Confusingly, any of these things indicate that we want a new figure fig = pl.figure(**figkwargs) elif fig is None: # pragma: no cover if ax is None: if not pl.get_fignums(): fig = pl.figure(**figkwargs) else: fig = pl.gcf() else: fig = ax.figure # Create and initialize the axis if ax is None: if fig.axes and index is None: ax = pl.gca() else: if nrows is None: nrows = 1 if ncols is None: ncols = 1 if index is None: index = 1 ax = fig.add_subplot(nrows, ncols, index, projection='3d', **axkwargs) # Validate the axes if not isinstance(ax, Axes3D): # pragma: no cover errormsg = f'''Cannot create 3D plot into axes {ax}: ensure "projection='3d'" was used when making it''' raise ValueError(errormsg) # Change the view if requested if elev is not None or azim is not None: # pragma: no cover ax.view_init(elev=elev, azim=azim) # Tidy up if returnfig: return fig,ax else: # pragma: no cover return ax def _process_2d_data(x, y, z, c, flatten=False): ''' Helper function to handle data transformations -- not for the user ''' # Swap variables so z always exists if z is None and x is not None: z,x = x,z z = np.array(z) if z.ndim == 2: ny,nx = z.shape x = np.arange(nx) if x is None else np.array(x) y = np.arange(ny) if y is None else np.array(y) assert x.ndim == y.ndim, 'Cannot handle x and y axes with different array shapes' if x.ndim == 1 or y.ndim == 1: x,y = np.meshgrid(x, y) if flatten: x,y,z = x.flatten(), y.flatten(), z.flatten() # Flatten everything to 1D if scu.isarray(c) and c.shape == (ny,nx): # Flatten colors, too, if 2D and the same size as Z c = c.flatten() elif flatten == False: # pragma: no cover raise ValueError('Must provide z values as a 2D array') if x is None or y is None: # pragma: no cover raise ValueError('Must provide x and y values if z is 1D') # Handle automatic color scaling if isinstance(c, str): if c == 'z': c = z elif c == 'index': c = np.arange(len(z)) return x, y, z, c def _process_colors(c, z, cmap=None, to2d=False): ''' Helper function to get color data in the right format -- not for the user ''' from . import sc_colors as scc # To avoid circular import # Handle colors if c.ndim == 1: # Used by scatter3d and bar3d assert len(c) == len(z), 'Number of colors does not match length of data' c = scc.vectocolor(c, cmap=cmap) elif c.ndim == 2: # Used by surf3d assert c.shape == z.shape, 'Shape of colors does not match shape of data' c = scc.arraycolors(c, cmap=cmap) # Used by bar3d -- flatten from 3D to 2D if to2d and c.ndim == 3: c = c.reshape((-1, c.shape[2])) return c def plot3d(x, y, z, c='index', fig=True, ax=None, returnfig=False, figkwargs=None, axkwargs=None, **kwargs): ''' Plot 3D data as a line Args: x (arr): x coordinate data y (arr): y coordinate data z (arr): z coordinate data c (str/tuple): color, can be an array or any of the types accepted by :func:`pl.plot() <matplotlib.pyplot.plot>`; if 'index' (default), color by index fig (fig): an existing figure to draw the plot in (or set to True to create a new figure) ax (axes): an existing axes to draw the plot in returnfig (bool): whether to return the figure, or just the axes figkwargs (dict): :func:`pl.figure() <matplotlib.pyplot.figure>` axkwargs (dict): :func:`pl.axes() <matplotlib.pyplot.axes>` kwargs (dict): passed to :func:`pl.plot() <matplotlib.pyplot.plot>` **Examples**:: x,y,z = pl.rand(3,10) sc.plot3d(x, y, z) fig = pl.figure() n = 100 x = np.array(sorted(pl.rand(n))) y = x + pl.randn(n) z = pl.randn(n) c = np.arange(n) sc.plot3d(x, y, z, c=c, fig=fig) *New in version 3.1.0:* Allow multi-colored line; removed "plotkwargs" argument; "fig" defaults to True ''' # Set default arguments plotkwargs = scu.mergedicts({'lw':2}, kwargs) axkwargs = scu.mergedicts(axkwargs) # Do input checking assert len(x) == len(y) == len(z), 'All inputs must have the same length' n = len(z) # Create axis fig,ax = ax3d(returnfig=True, fig=fig, ax=ax, figkwargs=figkwargs, **axkwargs) # Handle different-colored line segments if c == 'index': c = np.arange(n) # Assign automatically based on index if scu.isarray(c) and len(c) in [n, n-1]: # Technically don't use the last color if the color has the same length as the data # pragma: no cover if c.ndim == 1: c = _process_colors(c, z=z) for i in range(n-1): ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], c=c[i], **plotkwargs) # Standard case: single color else: ax.plot(x, y, z, c=c, **plotkwargs) if returnfig: # pragma: no cover return fig,ax else: return ax def scatter3d(x=None, y=None, z=None, c='z', fig=True, ax=None, returnfig=False, figkwargs=None, axkwargs=None, **kwargs): ''' Plot 3D data as a scatter Typically, ``x``, ``y``, and ``z``, are all vectors. However, if a single 2D array is provided, then this will be treated as ``z`` values and ``x`` and ``y`` will be inferred on a grid (or they can be provided explicitly). Args: x (arr): 1D or 2D x coordinate data (or z-coordinate data if 2D and ``z`` is ``None``) y (arr): 1D or 2D y coordinate data z (arr): 1D or 2D z coordinate data c (arr): color data; defaults to match z; to use default colors, explicitly pass ``c=None``; to use index, use c='index' fig (fig): an existing figure to draw the plot in (or set to True to create a new figure) ax (axes): an existing axes to draw the plot in returnfig (bool): whether to return the figure, or just the axes figkwargs (dict): passed to :func:`pl.figure() <matplotlib.pyplot.figure>` axkwargs (dict): passed to :func:`pl.axes() <matplotlib.pyplot.axes>` kwargs (dict): passed to :func:`pl.scatter() <matplotlib.pyplot.scatter>` **Examples**:: # Implicit coordinates, color by height (z-value) data = pl.randn(10, 10) sc.scatter3d(data) # Explicit coordinates, color by index (i.e. ordering) x,y,z = pl.rand(3,50) sc.scatter3d(x, y, z, c='index') | *New in version 3.0.0:* Allow 2D input | *New in version 3.1.0:* Allow "index" color argument; removed "plotkwargs" argument; "fig" defaults to True ''' # Set default arguments plotkwargs = scu.mergedicts({'s':200, 'depthshade':False, 'linewidth':0}, kwargs) axkwargs = scu.mergedicts(axkwargs) # Create figure fig,ax = ax3d(returnfig=True, fig=fig, ax=ax, figkwargs=figkwargs, **axkwargs) # Process data x, y, z, c = _process_2d_data(x, y, z, c, flatten=True) # Actually plot ax.scatter(x, y, z, c=c, **plotkwargs) if returnfig: # pragma: no cover return fig,ax else: return ax def surf3d(x=None, y=None, z=None, c='z', fig=True, ax=None, returnfig=False, colorbar=None, figkwargs=None, axkwargs=None, **kwargs): ''' Plot 2D or 3D data as a 3D surface Typically, ``x``, ``y``, and ``z``, are all 2D arrays of the same size. However, if a single 2D array is provided, then this will be treated as ``z`` values and ``x`` and ``y`` will be inferred on a grid (or they can be provided explicitly, either as vectors or 2D arrays). Args: x (arr): 1D or 2D array of x coordinates (or z-coordinate data if 2D and ``z`` is ``None``) y (arr): 1D or 2D array of y coordinates (optional) z (arr): 2D array of z coordinates c (arr): color data; defaults to match z fig (fig): an existing figure to draw the plot in (or set to True to create a new figure) ax (axes): an existing axes to draw the plot in returnfig (bool): whether to return the figure, or just the axes colorbar (bool): whether to plot a colorbar (true by default unless color data is provided) figkwargs (dict): passed to :func:`pl.figure() <matplotlib.pyplot.figure>` axkwargs (dict): passed to :func:`pl.axes() <matplotlib.pyplot.axes>` kwargs (dict): passed to :func:`ax.plot_surface() <mpl_toolkits.mplot3d.axes3d.Axes3D.plot_surface>` **Examples**:: # Simple example data = sc.smooth(pl.rand(30,50)) sc.surf3d(data) # Use non-default axes and colors nx = 20 ny = 50 x = 10*np.arange(nx) y = np.arange(ny) + 100 z = sc.smooth(pl.randn(ny,nx)) c = z**2 sc.surf3d(x=x, y=y, z=z, c=c, cmap='orangeblue') *New in 3.1.0:* updated arguments from "data" to x, y, z, c; removed "plotkwargs" argument; "fig" defaults to True ''' # Set default arguments plotkwargs = scu.mergedicts({'cmap':pl.get_cmap()}, kwargs) axkwargs = scu.mergedicts(axkwargs) if colorbar is None: colorbar = False if scu.isarray(c) else True # Use a colorbar unless colors provided # Create figure fig,ax = ax3d(returnfig=True, fig=fig, ax=ax, figkwargs=figkwargs, **axkwargs) # Process data x, y, z, c = _process_2d_data(x, y, z, c, flatten=False) # Handle colors if scu.isarray(c): c = _process_colors(c, z=z, cmap=plotkwargs.get('cmap')) plotkwargs['facecolors'] = c # Actually plot surf = ax.plot_surface(x, y, z, **plotkwargs) if colorbar: fig.colorbar(surf) if returnfig: # pragma: no cover return fig,ax else: return ax def bar3d(x=None, y=None, z=None, c='z', dx=0.8, dy=0.8, dz=None, fig=True, ax=None, returnfig=False, figkwargs=None, axkwargs=None, **kwargs): ''' Plot 2D data as 3D bars Args: x (arr): 1D or 2D array of x coordinates (or z-coordinate data if 2D and ``z`` is ``None``) y (arr): 1D or 2D array of y coordinates (optional) z (arr): 2D array of z coordinates; interpreted as the heights of the bars unless ``dz`` is also provided c (arr): color data; defaults to match z dx (float/arr): width of the bars dy (float/arr): depth of the bars dz (float/arr): height of the bars, in which case ``z`` is interpreted as the base of the bars fig (fig): an existing figure to draw the plot in (or set to True to create a new figure) ax (axes): an existing axes to draw the plot in returnfig (bool): whether to return the figure, or just the axes colorbar (bool): whether to plot a colorbar (true by default unless color data is provided) figkwargs (dict): passed to :func:`pl.figure() <matplotlib.pyplot.figure>` axkwargs (dict): passed to :func:`pl.axes() <matplotlib.pyplot.axes>` kwargs (dict): passed to :func:`ax.bar3d() <mpl_toolkits.mplot3d.axes3d.Axes3D.bar3d>` **Examples**:: # Simple example data = pl.rand(5,4) sc.bar3d(data) # Use non-default axes and colors (note: this one is pretty!) nx = 5 ny = 6 x = 10*np.arange(nx) y = np.arange(ny) + 10 z = -pl.rand(ny,nx) dz = -2*z c = z**2 sc.bar3d(x=x, y=y, z=z, dx=0.5, dy=0.5, dz=dz, c=c, cmap='orangeblue') *New in 3.1.0:* updated arguments from "data" to x, y, z, c; removed "plotkwargs" argument; "fig" defaults to True ''' # Set default arguments plotkwargs = scu.mergedicts(dict(shade=True), kwargs) axkwargs = scu.mergedicts(axkwargs) # Create figure fig,ax = ax3d(returnfig=True, fig=fig, ax=ax, figkwargs=figkwargs, **axkwargs) # Process data z_base = None # Assume no base is provided, and ... z_height = z # ... height was provided if z is not None and dz is not None: # Handle dz and z separately if both provided z_base = z.flatten() # In case z is provided as 2D z_height = dz elif z is None and dz is not None: # Swap order if dz is provided instead of z z_height = dz x, y, z_height, c = _process_2d_data(x=x, y=y, z=z_height, c=c, flatten=True) # Ensure the bottom of the bars is provided if z_base is None: z_base = np.zeros_like(z) # Process colors c = _process_colors(c, z_height, cmap=kwargs.get('cmap'), to2d=True) # Plot ax.bar3d(x=x, y=y, z=z_base, dx=dx, dy=dy, dz=z_height, color=c, **plotkwargs) if returnfig: # pragma: no cover return fig,ax else: return ax ############################################################################## #%% Other plotting functions ############################################################################## __all__ += ['stackedbar', 'boxoff', 'setaxislim', 'setxlim', 'setylim', 'commaticks', 'SIticks', 'getrowscols', 'get_rows_cols', 'figlayout', 'maximize', 'fonts'] def stackedbar(x=None, values=None, colors=None, labels=None, transpose=False, flipud=False, cum=False, barh=False, **kwargs): ''' Create a stacked bar chart. Args: x (array) : the x coordinates of the values values (array) : the 2D array of values to plot as stacked bars colors (list/arr) : the color of each set of bars labels (list) : the label for each set of bars transpose (bool) : whether to transpose the array prior to plotting flipud (bool) : whether to flip the array upside down prior to plotting cum (bool) : whether the array is already a cumulative sum barh (bool) : whether to plot as a horizontal instead of vertical bar kwargs (dict) : passed to :func:`pl.bar() <matplotlib.pyplot.bar>` **Example**:: values = pl.rand(3,5) sc.stackedbar(values, labels=['bottom','middle','top']) pl.legend() *New in version 2.0.4.* ''' from . import sc_colors as scc # To avoid circular import # Handle inputs if x is not None and values is None: values = x x = None if values is None: # pragma: no cover errormsg = 'Must supply values to plot, typically as a 2D array' raise ValueError(errormsg) values = scu.toarray(values) if values.ndim == 1: # pragma: no cover values = values[None,:] # Convert to a 2D array if transpose: # pragma: no cover values = values.T if flipud: # pragma: no cover values = values[::-1,:] nstack = values.shape[0] npts = values.shape[1] if x is None: x = np.arange(npts) if not cum: # pragma: no cover values = values.cumsum(axis=0) values = np.concatenate([np.zeros((1,npts)), values]) # Handle labels and colors if labels is not None: # pragma: no cover nlabels = len(labels) if nlabels != nstack: errormsg = f'Expected {nstack} labels, got {nlabels}' raise ValueError(errormsg) if colors is not None: # pragma: no cover ncolors = len(colors) if ncolors != nstack: errormsg = f'Expected {nstack} colors, got {ncolors}' raise ValueError(errormsg) else: colors = scc.gridcolors(nstack) # Actually plot artists = [] for i in range(nstack): if labels is not None: label = labels[i] else: # pragma: no cover label = None h = values[i+1,:] b = values[i,:] kw = dict(facecolor=colors[i], label=label, **kwargs) if not barh: artist = pl.bar(x=x, height=h, bottom=b, **kw) else: # pragma: no cover artist = pl.barh(y=x, width=h, left=b, **kw) artists.append(artist) return artists def boxoff(ax=None, which=None, removeticks=True): ''' Removes the top and right borders ("spines") of a plot. Also optionally removes the tick marks, and flips the remaining ones outside. Can be used as an alias to ``pl.axis('off')`` if ``which='all'``. Args: ax (Axes): the axes to remove the spines from (if None, use current) which (str/list): a list or comma-separated string of spines: 'top', 'bottom', 'left', 'right', or 'all' (default top & right) removeticks (bool): whether to also remove the ticks from these spines flipticks (bool): whether to flip remaining ticks out **Examples**:: pl.figure() pl.plot([2,5,3]) sc.boxoff() fig, ax = pl.subplots() pl.plot([1,4,1,4]) sc.boxoff(ax=ax, which='all') fig = pl.figure() pl.scatter(np.arange(100), pl.rand(100)) sc.boxoff('top, bottom') *New in version 1.3.3:* ability to turn off multiple spines; removed "flipticks" arguments ''' # Handle axes if isinstance(ax, (str, list)): # Swap input arguments # pragma: no cover ax,which = which,ax if ax is None: ax = pl.gca() # Handle which if not isinstance(which, list): if which is None: which = 'top, right' if which == 'all': # pragma: no cover which = 'top, bottom, right, left' if isinstance(which, str): which = which.split(',') which = [w.rstrip().lstrip() for w in which] for spine in which: # E.g. ['top', 'right'] ax.spines[spine].set_visible(False) if removeticks: ax.tick_params(**{spine:False, f'label{spine}':False}) return ax def setaxislim(which=None, ax=None, data=None): ''' A small script to determine how the y limits should be set. Looks at all data (a list of arrays) and computes the lower limit to use, e.g.:: sc.setaxislim([np.array([-3,4]), np.array([6,4,6])], ax) will keep Matplotlib's lower limit, since at least one data value is below 0. Note, if you just want to set the lower limit, you can do that with this function via:: sc.setaxislim() ''' # Handle which axis if which is None: # pragma: no cover which = 'both' if which not in ['x','y','both']: # pragma: no cover errormsg = f'Setting axis limit for axis {which} is not supported' raise ValueError(errormsg) if which == 'both': # pragma: no cover setaxislim(which='x', ax=ax, data=data) setaxislim(which='y', ax=ax, data=data) return # Ensure axis exists if ax is None: ax = pl.gca() # Get current limits if which == 'x': currlower, currupper = ax.get_xlim() elif which == 'y': currlower, currupper = ax.get_ylim() # Calculate the lower limit based on all the data lowerlim = 0 upperlim = 0 if scu.checktype(data, 'arraylike'): # Ensure it's numeric data (probably just None) # pragma: no cover flatdata = scu.toarray(data).flatten() # Make sure it's iterable lowerlim = min(lowerlim, flatdata.min()) upperlim = max(upperlim, flatdata.max()) # Set the new y limits if lowerlim<0: lowerlim = currlower # If and only if the data lower limit is negative, use the plotting lower limit upperlim = max(upperlim, currupper) # Shouldn't be an issue, but just in case... # Specify the new limits and return if which == 'x': ax.set_xlim((lowerlim, upperlim)) elif which == 'y': ax.set_ylim((lowerlim, upperlim)) return lowerlim,upperlim def setxlim(data=None, ax=None): ''' Alias for :func:`sc.setaxislim(which='x') <setaxislim>` ''' return setaxislim(data=data, ax=ax, which='x') def setylim(data=None, ax=None): ''' Alias for :func:`sc.setaxislim(which='y') <setaxislim>`. **Example**:: pl.plot([124,146,127]) sc.setylim() # Equivalent to pl.ylim(bottom=0) ''' return setaxislim(data=data, ax=ax, which='y') def _get_axlist(ax): # pragma: no cover ''' Helper function to turn either a figure, an axes, or a list of axes into a list of axes ''' if ax is None: # If not supplied, get current axes axlist = [pl.gca()] elif isinstance(ax, pl.Axes): # If it's an axes, turn to a list axlist = [ax] elif isinstance(ax, pl.Figure): # If it's a figure, pull all axes axlist = ax.axes elif isinstance(ax, list): # If it's a list, use directly axlist = ax else: errormsg = f'Could not recognize object {type(ax)}: must be None, Axes, Figure, or list of axes' raise ValueError(errormsg) return axlist def commaticks(ax=None, axis='y', precision=2, cursor_precision=0): ''' Use commas in formatting the y axis of a figure (e.g., 34,000 instead of 34000). To use something other than a comma, set the default separator via e.g. :class:`sc.options(sep='.') <sciris.sc_settings.ScirisOptions>`. Args: ax (any): axes to modify; if None, use current; else can be a single axes object, a figure, or a list of axes axis (str/list): which axis to change (default 'y'; can accept a list) precision (int): shift how many decimal places to show for small numbers (+ve = more, -ve = fewer) cursor_precision (int): ditto, for cursor **Example**:: data = pl.rand(10)*1e4 pl.plot(data) sc.commaticks() See http://stackoverflow.com/questions/25973581/how-to-format-axis-number-format-to-thousands-with-a-comma-in-matplotlib | *New in version 1.3.0:* ability to use non-comma thousands separator | *New in version 1.3.1:* added "precision" argument | *New in version 2.0.0:* ability to set x and y axes simultaneously ''' def commaformatter(x, pos=None): # pragma: no cover interval = thisaxis.get_view_interval() prec = precision + cursor_precision if pos is None else precision # Use higher precision for cursor decimals = int(max(0, prec-np.floor(np.log10(np.ptp(interval))))) string = f'{x:0,.{decimals}f}' # Do the formatting if pos is not None and '.' in string: # Remove trailing decimal zeros from axis labels string = string.rstrip('0') if string[-1] == '.': # If we trimmed 0.0 to 0., trim the remaining period string = string[:-1] if sep != ',': # Use custom separator if desired string = string.replace(',', sep) return string sep = scs.options.sep axlist = _get_axlist(ax) axislist = scu.tolist(axis) for ax in axlist: for axis in axislist: if axis=='x': thisaxis = ax.xaxis elif axis=='y': thisaxis = ax.yaxis elif axis=='z': thisaxis = ax.zaxis # pragma: no cover else: raise ValueError('Axis must be x, y, or z') # pragma: no cover thisaxis.set_major_formatter(mpl.ticker.FuncFormatter(commaformatter)) return def SIticks(ax=None, axis='y', fixed=False): ''' Apply SI tick formatting to one axis of a figure (e.g., 34k instead of 34000) Args: ax (any): axes to modify; if None, use current; else can be a single axes object, a figure, or a list of axes axis (str): which axes to change (default 'y') fixed (bool): use fixed-location tick labels (by default, update them dynamically) **Example**:: data = pl.rand(10)*1e4 pl.plot(data) sc.SIticks() ''' def SItickformatter(x, pos=None, sigfigs=2, SI=True, *args, **kwargs): # formatter function takes tick label and tick position # pragma: no cover ''' Formats axis ticks so that e.g. 34000 becomes 34k -- usually not invoked directly ''' output = scp.sigfig(x, sigfigs=sigfigs, SI=SI) # Pretty simple since scp.sigfig() does all the work return output axlist = _get_axlist(ax) for ax in axlist: if axis=='x': thisaxis = ax.xaxis elif axis=='y': thisaxis = ax.yaxis elif axis=='z': thisaxis = ax.zaxis # pragma: no cover else: raise ValueError('Axis must be x, y, or z') # pragma: no cover if fixed: # pragma: no cover ticklocs = thisaxis.get_ticklocs() ticklabels = [] for tickloc in ticklocs: ticklabels.append(SItickformatter(tickloc)) thisaxis.set_major_formatter(mpl.ticker.FixedFormatter(ticklabels)) else: thisaxis.set_major_formatter(mpl.ticker.FuncFormatter(SItickformatter)) return def getrowscols(n, nrows=None, ncols=None, ratio=1, make=False, tight=True, remove_extra=True, **kwargs): ''' Get the number of rows and columns needed to plot N figures. If you have 37 plots, then how many rows and columns of axes do you know? This function convert a number (i.e. of plots) to a number of required rows and columns. If nrows or ncols is provided, the other will be calculated. Ties are broken in favor of more rows (i.e. 7x6 is preferred to 6x7). It can also generate the plots, if ``make=True``. Note: :func:`sc.getrowscols() <getrowscols>` and :func:`sc.get_rows_cols() <get_rows_cols>` are aliases. Args: n (int): the number (of plots) to accommodate nrows (int): if supplied, keep this fixed and calculate the columns ncols (int): if supplied, keep this fixed and calculate the rows ratio (float): sets the number of rows relative to the number of columns (i.e. for 100 plots, 1 will give 10x10, 4 will give 20x5, etc.). make (bool): if True, generate subplots tight (bool): if True and make is True, then apply tight layout remove_extra (bool): if True and make is True, then remove extra subplots kwargs (dict): passed to pl.subplots() Returns: A tuple of ints for the number of rows and the number of columns (which, of course, you can reverse) **Examples**:: nrows,ncols = sc.get_rows_cols(36) # Returns 6,6 nrows,ncols = sc.get_rows_cols(37) # Returns 7,6 nrows,ncols = sc.get_rows_cols(100, ratio=2) # Returns 15,7 nrows,ncols = sc.get_rows_cols(100, ratio=0.5) # Returns 8,13 since rows are prioritized fig,axs = sc.getrowscols(37, make=True) # Create 7x6 subplots, using the alias | *New in version 1.0.0.* | *New in version 1.2.0:* "make", "tight", and "remove_extra" arguments | *New in version 1.3.0:* alias without underscores ''' # Simple cases -- calculate the one missing if nrows is not None: # pragma: no cover ncols = int(np.ceil(n/nrows)) elif ncols is not None: # pragma: no cover nrows = int(np.ceil(n/ncols)) # Standard case -- calculate both else: guess = np.sqrt(n) nrows = int(np.ceil(guess*np.sqrt(ratio))) ncols = int(np.ceil(n/nrows)) # Could also call recursively! # If asked, make subplots if make: # pragma: no cover fig, axs = pl.subplots(nrows=nrows, ncols=ncols, **kwargs) if remove_extra: for ax in axs.flat[n:]: ax.set_visible(False) # to remove last plot if tight: figlayout(fig, tight=True) return fig,axs else: # Otherwise, just return rows and columns return nrows,ncols get_rows_cols = getrowscols # Alias def figlayout(fig=None, tight=True, keep=False, **kwargs): ''' Alias to both fig.set_tight_layout() and fig.subplots_adjust(). Args: fig (Figure): the figure (by default, use current) tight (bool, or dict): passed to fig.set_tight_layout(); default True keep (bool): if True, then leave tight layout on; else, turn it back off kwargs (dict): passed to fig.subplots_adjust() **Example**:: fig,axs = sc.get_rows_cols(37, make=True, tight=False) # Create 7x6 subplots, squished together sc.figlayout(bottom=0.3) *New in version 1.2.0.* ''' if isinstance(fig, bool): # pragma: no cover fig = None tight = fig # To allow e.g. sc.figlayout(False) if fig is None: fig = pl.gcf() layout = ['none', 'tight'][tight] try: # Matplotlib >=3.6 fig.set_layout_engine(layout) except: # Earlier versions # pragma: no cover fig.set_tight_layout(tight) if (not keep) and (not pl.get_backend() == 'agg'): # pragma: no cover pl.pause(0.01) # Force refresh if using an interactive backend try: fig.set_layout_engine('none') except: # pragma: no cover fig.set_tight_layout(False) if len(kwargs): # pragma: no cover fig.subplots_adjust(**kwargs) return def maximize(fig=None, die=False): # pragma: no cover ''' Maximize the current (or supplied) figure. Note: not guaranteed to work for all Matplotlib backends (e.g., agg). Args: fig (Figure): the figure object; if not supplied, use the current active figure die (bool): whether to propagate an exception if encountered (default no) **Example**:: pl.plot([2,3,5]) sc.maximize() *New in version 1.0.0.* ''' backend = pl.get_backend().lower() if fig is not None: pl.figure(fig.number) # Set the current figure try: mgr = pl.get_current_fig_manager() if 'qt' in backend: mgr.window.showMaximized() elif 'gtk' in backend: mgr.window.maximize() elif 'wx' in backend: mgr.frame.Maximize(True) elif 'tk' in backend: mgr.resize(*mgr.window.maxsize()) else: errormsg = f'The maximize() function is not supported for the backend "{backend}"; use Qt5Agg if possible' raise NotImplementedError(errormsg) except Exception as E: errormsg = f'Warning: maximizing the figure failed because: "{str(E)}"' if die: raise RuntimeError(errormsg) from E else: print(errormsg) return def fonts(add=None, use=False, output='name', dryrun=False, rebuild=False, verbose=False, die=False, **kwargs): ''' List available fonts, or add new ones. Alias to Matplotlib's font manager. Note: if the font is not available after adding it, set rebuild=True. However, note that this can be very slow. Args: add (str/list): path of the fonts or folders to add; if none, list available fonts use (bool): set the last-added font as the default font output (str): what to display the listed fonts as: options are 'name' (list of names, default), 'path' (dict of name:path), or 'font' (dict of name:font object) dryrun (bool): list fonts to be added rather than adding them rebuild (bool): whether to rebuild Matplotlib's font cache (slow) verbose (bool): print out information on errors die (bool): whether to raise an exception if fonts can't be added kwargs (dict): passed to matplotlib.font_manager.findSystemFonts() **Examples**:: sc.fonts() # List available font names sc.fonts(fullfont=True) # List available font objects sc.fonts('myfont.ttf', use=True) # Add this font and immediately set to default sc.fonts(['/folder1', '/folder2']) # Add all fonts in both folders sc.fonts(rebuild=True) # Run this if added fonts aren't appearing ''' fm = mpl.font_manager # Shorten # List available fonts if add is None and not rebuild: # Find fonts f = sco.objdict() # Create a dictionary for holding the results keys = ['names', 'paths', 'objs'] for key in keys: f[key] = scu.autolist() for fontpath in fm.findSystemFonts(**kwargs): try: fontobj = fm.get_font(fontpath) fontname = fontobj.family_name if fontname not in f.names: # Don't allow duplicates f.names += fontname f.paths += fontpath f.objs += fontobj except Exception as E: if verbose: # pragma: no cover print(f'Could not load {fontpath}: {str(E)}') # Handle output order = np.argsort(f.names) # Order by name for key in keys: f[key] = [f[key][o] for o in order] if 'name' in output: out = f.names elif 'path' in output: # pragma: no cover out = dict(zip(f.names, f.paths)) elif 'font' in output: # pragma: no cover out = dict(zip(f.names, f.objs)) else: # pragma: no cover errormsg = f'Output type not recognized: must be "name", "path", or "font", not "{output}"' raise ValueError(errormsg) return out # Or, add new fonts else: # Try, but by default don't crash if they can't be added try: fontname = None fontpaths = [] paths = scu.tolist(add) for path in paths: path = str(path) if os.path.isdir(path): # pragma: no cover fps = fm.findSystemFonts(path, **kwargs) fontpaths.extend(fps) else: fontpaths.append(scf.makefilepath(path)) if dryrun: # pragma: no cover print(fontpaths) else: for path in fontpaths: fm.fontManager.addfont(path) fontname = fm.get_font(path).family_name if verbose: print(f'Added "{fontname}"') if verbose and fontname is None: # pragma: no cover print('Warning: no fonts were added') if use and fontname: # Set as default font pl.rc('font', family=fontname) if rebuild: # pragma: no cover print('Rebuilding font cache, please be patient...') try: fm._load_fontmanager(try_read_cache=False) # This used to be fm._rebuild(), but this was removed; this works as of Matplotlib 3.4.3 print(f'Font cache rebuilt in folder: {mpl.get_cachedir()}') except Exception as E: exc = type(E) errormsg = f'Rebuilding font cache failed:\n{str(E)}' raise exc(errormsg) from E if verbose: print(f'Done: added {len(fontpaths)} fonts.') # Exception was encountered, quietly print except Exception as E: # pragma: no cover exc = type(E) errormsg = f'Warning, could not install some fonts:\n{str(E)}' if die: raise exc(errormsg) from E else: print(errormsg) return ############################################################################## #%% Date plotting ############################################################################## __all__ += ['ScirisDateFormatter', 'dateformatter', 'datenumformatter'] class ScirisDateFormatter(mpl.dates.ConciseDateFormatter): ''' An adaptation of Matplotlib's ConciseDateFormatter with a slightly different approach to formatting dates. Specifically: - Years are shown below dates, rather than on the RHS - The day and month are always shown. - The cursor shows only the date, not the time This formatter is not intended to be called directly -- use :func:`sc.dateformatter() <dateformatter>` instead. It is also optimized for plotting dates, rather than times -- for those, ConciseDateFormatter is better. See :func:`sc.dateformatter() <dateformatter>` for explanation of arguments. *New in version 1.3.0.* ''' def __init__(self, locator, formats=None, zero_formats=None, show_offset=False, show_year=True, **kwargs): # Handle inputs self.show_year = show_year if formats is None: formats = [ '%Y', # ticks are mostly years '%b', # ticks are mostly months '%b-%d', # ticks are mostly days '%H:%M', # hrs '%H:%M', # min '%S.%f', # secs ] if zero_formats is None: zero_formats = [ '%Y', # ticks are mostly years -- no zeros '%b', # ticks are mostly months '%b-%d', # ticks are mostly days '%b-%d', # hrs '%H:%M', # min '%H:%M', # secs ] # Initialize the ConciseDateFormatter with the corrected input super().__init__(locator, formats=formats, zero_formats=zero_formats, show_offset=show_offset, **kwargs) return def format_data_short(self, value): # pragma: no cover ''' Show year-month-day, not with hours and seconds ''' return pl.num2date(value, tz=self._tz).strftime('%Y-%b-%d') def format_ticks(self, values): # pragma: no cover ''' Append the year to the tick label for the first label, or if the year changes. This avoids the need to use offset_text, which is difficult to control. ''' def addyear(label, year): ''' Add the year to the label if it's not already present ''' yearstr = str(year) if yearstr not in label: # Be agnostic about where in the label the year string might be present label += f'\n{yearstr}' return label # Get the default labels and years labels = super().format_ticks(values) years = [pl.num2date(v).year for v in values] # Add year information to any labels that require it if self.show_year: for i,label in enumerate(labels): year = years[i] if i == 0 or (year != years[i-1]): labels[i] = addyear(label, year) return labels def dateformatter(ax=None, style='sciris', dateformat=None, start=None, end=None, rotation=None, locator=None, axis='x', **kwargs): ''' Format the x-axis to use a given date formatter. By default, this will apply the Sciris date formatter to the current x-axis. This formatter is a combination of Matplotlib's Concise date formatter, and Plotly's date formatter. See also :func:`sc.datenumformatter() <datenumformatter>` to convert a numeric axis to date labels. Args: ax (axes) : if supplied, use these axes instead of the current one style (str) : the style to use if the axis already uses dates; options are "sciris", "auto", "concise", or a Formatter object dateformat (str) : the date format (default ``'%Y-%b-%d'``; not needed if x-axis already uses dates) start (str/int) : if supplied, the lower limit of the axis end (str/int) : if supplied, the upper limit of the axis rotation (float) : rotation of the labels, in degrees locator (Locator) : if supplied, use this instead of the default ``AutoDateLocator`` locator axis (str) : which axis to apply to the formatter to (default 'x') kwargs (dict) : passed to the date formatter (e.g., :class:`ScirisDateFormatter`) **Examples**:: # Reformat date data pl.figure() x = sc.daterange('2021-04-04', '2022-05-05', asdate=True) y = sc.smooth(pl.rand(len(x))) pl.plot(x, y) sc.dateformatter() # Configure with Matplotlib's Concise formatter fig,ax = pl.subplots() pl.plot(sc.date(np.arange(365), start_date='2022-01-01'), pl.randn(365)) sc.dateformatter(ax=ax, style='concise') | *New in version 1.2.0.* | *New in version 1.2.2:* "rotation" argument; renamed "start_day" to "start_date" | *New in version 1.3.0:* refactored to use built-in Matplotlib date formatting | *New in version 1.3.2:* "axis" argument | *New in version 1.3.3:* split ``sc.dateformatter()`` from ``sc.datenumformatter()`` ''' # Handle deprecation style = kwargs.pop('dateformatter', style) # Allow this as an alias # Handle axis if isinstance(ax, str): # Swap style and axes -- allows sc.dateformatter(ax) or sc.dateformatter('auto') # pragma: no cover style = ax ax = None if ax is None: ax = pl.gca() # Handle dateformat, if provided if dateformat is not None: # pragma: no cover if isinstance(dateformat, str): kwargs['formats'] = [dateformat]*6 elif isinstance(dateformat, list): kwargs['formats'] = dateformat else: errormsg = f'Could not recognize date format {type(dateformat)}: expecting string or list' raise ValueError(errormsg) kwargs['zero_formats'] = kwargs['formats'] # Handle locator and styles if locator is None: locator = mpl.dates.AutoDateLocator(minticks=3) style = str(style).lower() if style in ['none', 'sciris', 'house', 'default']: formatter = ScirisDateFormatter(locator, **kwargs) elif style in ['auto', 'matplotlib']: formatter = mpl.dates.AutoDateFormatter(locator, **kwargs) elif style in ['concise', 'brief']: formatter = mpl.dates.ConciseDateFormatter(locator, **kwargs) elif isinstance(style, mpl.ticker.Formatter): # If a formatter is provided, use directly # pragma: no cover formatter = style else: # pragma: no cover errormsg = f'Style "{style}" not recognized; must be one of "sciris", "auto", or "concise"' raise ValueError(errormsg) # Handle axis and set the locator and formatter if axis == 'x': axis = ax.xaxis elif axis == 'y': # If it's not x or y (!), assume it's an axis object # pragma: no cover axis = ax.yaxis axis.set_major_locator(locator) axis.set_major_formatter(formatter) # Handle limits xmin, xmax = ax.get_xlim() if start: xmin = scd.date(start) if end: xmax = scd.date(end) ax.set_xlim((xmin, xmax)) # Set the rotation if rotation: ax.tick_params(axis='x', labelrotation=rotation) # Set the formatter ax.xaxis.set_major_formatter(formatter) return formatter def datenumformatter(ax=None, start_date=None, dateformat=None, interval=None, start=None, end=None, rotation=None): ''' Format a numeric x-axis to use dates. See also :func:`sc.dateformatter() <dateformatter>`, which is intended for use when the axis already has date data. Args: ax (axes) : if supplied, use these axes instead of the current one start_date (str/date) : the start day, either as a string or date object (not needed if x-axis already uses dates) dateformat (str) : the date format (default ``'%Y-%b-%d'``; not needed if x-axis already uses dates) interval (int) : if supplied, the interval between ticks (not needed if x-axis already uses dates) start (str/int) : if supplied, the lower limit of the axis end (str/int) : if supplied, the upper limit of the axis rotation (float) : rotation of the labels, in degrees **Examples**:: # Automatically configure a non-date axis with default options pl.plot(np.arange(365), pl.rand(365)) sc.datenumformatter(start_date='2021-01-01') # Manually configure fig,ax = pl.subplots() ax.plot(np.arange(60), np.random.random(60)) formatter = sc.datenumformatter(start_date='2020-04-04', interval=7, start='2020-05-01', end=50, dateformat='%m-%d', ax=ax) | *New in version 1.2.0.* | *New in version 1.2.2:* "rotation" argument; renamed "start_day" to "start_date" | *New in version 1.3.3:* renamed from ``sc.dateformatter()`` to ``sc.datenumformatter()`` ''' # Handle axis if isinstance(ax, str): # Swap inputs # pragma: no cover ax, start_date = start_date, ax if ax is None: ax = pl.gca() # Set the default format -- "2021-01-01" if dateformat is None: dateformat = '%Y-%b-%d' # Convert to a date object if start_date is None: # pragma: no cover start_date = pl.num2date(ax.dataLim.x0) start_date = scd.date(start_date) @mpl.ticker.FuncFormatter def formatter(x, pos): # pragma: no cover return (start_date + dt.timedelta(days=int(x))).strftime(dateformat) # Handle limits xmin, xmax = ax.get_xlim() if start: xmin = scd.day(start, start_date=start_date) if end: xmax = scd.day(end, start_date=start_date) ax.set_xlim((xmin, xmax)) # Set the x-axis intervals if interval: # pragma: no cover ax.set_xticks(np.arange(xmin, xmax+1, interval)) # Set the rotation if rotation: # pragma: no cover ax.tick_params(axis='x', labelrotation=rotation) # Set the formatter ax.xaxis.set_major_formatter(formatter) return formatter ############################################################################## #%% Figure saving ############################################################################## __all__ += ['savefig', 'savefigs', 'loadfig', 'emptyfig', 'separatelegend', 'orderlegend'] def _get_dpi(dpi=None, min_dpi=200): ''' Helper function to choose DPI for saving figures ''' if dpi is None: mpl_dpi = pl.rcParams['savefig.dpi'] if mpl_dpi == 'figure': mpl_dpi = pl.rcParams['figure.dpi'] dpi = max(mpl_dpi, min_dpi) # Don't downgrade DPI return dpi def savefig(filename, fig=None, dpi=None, comments=None, pipfreeze=False, relframe=0, folder=None, makedirs=True, die=True, verbose=True, **kwargs): ''' Save a figure, including metadata Wrapper for Matplotlib's :func:`pl.savefig() <matplotlib.pyplot.savefig>` function which automatically stores metadata in the figure. By default, it saves (git) information from the calling function. Additional comments can be added to the saved file as well. These can be retrieved via :func:`sc.loadmetadata() <sciris.sc_versioning.loadmetadata>`. Metadata can be stored and retrieved for PNG or SVG. Metadata can be stored for PDF, but cannot be automatically retrieved. Args: filename (str/Path) : name of the file to save to fig (Figure) : the figure to save (if None, use current) dpi (int) : resolution of the figure to save (default 200 or current default, whichever is higher) comments (str) : additional metadata to save to the figure pipfreeze (bool) : whether to store the contents of ``pip freeze`` in the metadata relframe (int) : which calling file to try to store information from (default 0, the file calling :func:`sc.savefig() <savefig>`) folder (str/Path) : optional folder to save to (can also be provided as part of the filename) makedirs (bool) : whether to create folders if they don't already exist die (bool) : whether to raise an exception if metadata can't be saved verbose (bool) : if die is False, print a warning if metadata can't be saved kwargs (dict) : passed to ``fig.save()`` **Examples**:: pl.plot([1,3,7]) sc.savefig('example1.png') print(sc.loadmetadata('example1.png')) sc.savefig('example2.png', comments='My figure', freeze=True) sc.pp(sc.loadmetadata('example2.png')) | *New in version 1.3.3.* | *New in version 3.0.0:* "freeze" renamed "pipfreeze"; "frame" replaced with "relframe"; replaced metadata with ``sc.metadata()`` ''' # Handle deprecation orig_metadata = kwargs.pop('metadata', {}) # In case metadata is supplied, as it can be for fig.save() pipfreeze = kwargs.pop('freeze', pipfreeze) frame = kwargs.pop('frame', None) if frame is not None: # pragma: no cover relframe = frame - 2 # Handle figure if fig is None: fig = pl.gcf() # Handle DPI dpi = _get_dpi(dpi) # Get caller and git info jsonstr = scv.metadata(relframe=relframe+1, pipfreeze=pipfreeze, comments=comments, tostring=True, **orig_metadata) # Handle different formats filename = str(filename) lcfn = filename.lower() # Lowercase filename if lcfn.endswith('png'): metadata = {scv._metadataflag:jsonstr} elif lcfn.endswith('svg') or lcfn.endswith('pdf'): # pragma: no cover metadata = dict(Keywords=f'{scv._metadataflag}={jsonstr}') else: errormsg = f'Warning: filename "{filename}" has unsupported type for metadata: must be PNG, SVG, or PDF. For JPG, use the separate exif library. To silence this message, set die=False and verbose=False.' if die: raise ValueError(errormsg) else: metadata = None if verbose: print(errormsg) # Save the figure if metadata is not None: kwargs['metadata'] = metadata # To avoid warnings for unsupported filenames # Allow savefig to make directories filepath = scf.makefilepath(filename=filename, folder=folder, makedirs=makedirs) fig.savefig(filepath, dpi=dpi, **kwargs) return filename def savefigs(figs=None, filetype=None, filename=None, folder=None, savefigargs=None, aslist=False, verbose=False, **kwargs): ''' Save the requested plots to disk. Args: figs (list) : the figure objects to save filetype (str) : the file type; can be 'fig', 'singlepdf' (default), or anything supported by savefig() filename (str) : the file to save to (only uses path if multiple files) folder (str) : the folder to save the file(s) in savefigargs (dict) : arguments passed to savefig() aslist (bool) : whether or not return a list even for a single file varbose (bool) : whether to print progress **Examples**:: import pylab as pl import sciris as sc fig1 = pl.figure(); pl.plot(pl.rand(10)) fig2 = pl.figure(); pl.plot(pl.rand(10)) sc.savefigs([fig1, fig2]) # Save everything to one PDF file sc.savefigs(fig2, 'png', filename='myfig.png', savefigargs={'dpi':200}) sc.savefigs([fig1, fig2], filepath='/home/me', filetype='svg') sc.savefigs(fig1, position=[0.3,0.3,0.5,0.5]) If saved as 'fig', then can load and display the plot using sc.loadfig(). Version: 2018aug26 ''' # Preliminaries wasinteractive = pl.isinteractive() # You might think you can get rid of this...you can't! if wasinteractive: pl.ioff() if filetype is None: filetype = 'singlepdf' # This ensures that only one file is created # Either take supplied plots, or generate them figs = sco.odict.promote(figs) nfigs = len(figs) # Handle file types filenames = [] if filetype=='singlepdf': # See http://matplotlib.org/examples/pylab_examples/multipage_pdf.html # pragma: no cover from matplotlib.backends.backend_pdf import PdfPages defaultname = 'figures.pdf' fullpath = scf.makefilepath(filename=filename, folder=folder, default=defaultname, ext='pdf', makedirs=True) pdf = PdfPages(fullpath) filenames.append(fullpath) if verbose: print(f'PDF saved to {fullpath}') for p,item in enumerate(figs.items()): key,plt = item # Handle filename if filename and nfigs==1: # Single plot, filename supplied -- use it fullpath = scf.makefilepath(filename=filename, folder=folder, default='Figure', ext=filetype, makedirs=True) # NB, this filename not used for singlepdf filetype, so it's OK else: # Any other case, generate a filename # pragma: no cover keyforfilename = filter(str.isalnum, str(key)) # Strip out non-alphanumeric stuff for key defaultname = keyforfilename fullpath = scf.makefilepath(filename=filename, folder=folder, default=defaultname, ext=filetype, makedirs=True) # Do the saving if savefigargs is None: savefigargs = {} defaultsavefigargs = {'dpi':200, 'bbox_inches':'tight'} # Specify a higher default DPI and save the figure tightly defaultsavefigargs.update(savefigargs) # Update the default arguments with the user-supplied arguments if filetype == 'fig': scf.save(fullpath, plt) filenames.append(fullpath) if verbose: print(f'Figure object saved to {fullpath}') else: # pragma: no cover reanimateplots(plt) if filetype=='singlepdf': pdf.savefig(figure=plt, **defaultsavefigargs) # It's confusing, but defaultsavefigargs is correct, since we updated it from the user version else: plt.savefig(fullpath, **defaultsavefigargs) filenames.append(fullpath) if verbose: print(f'{filetype.upper()} plot saved to {fullpath}') pl.close(plt) # Do final tidying if filetype=='singlepdf': pdf.close() if wasinteractive: pl.ion() if aslist or len(filenames)>1: # pragma: no cover return filenames else: return filenames[0] def loadfig(filename=None): ''' Load a plot from a file and reanimate it. **Example usage**:: import pylab as pl import sciris as sc fig = pl.figure(); pl.plot(pl.rand(10)) sc.savefigs(fig, filetype='fig', filename='example.fig') **Later**:: example = sc.loadfig('example.fig') ''' pl.ion() # Without this, it doesn't show up try: fig = scf.loadobj(filename) except Exception as E: # pragma: no cover errormsg = f'Unable to open file "{filename}": are you sure it was saved as a .fig file (not an image)?' raise type(E)(errormsg) from E reanimateplots(fig) return fig def reanimateplots(plots=None): ''' Reconnect plots (actually figures) to the Matplotlib backend. Plots must be an odict of figure objects. ''' try: from matplotlib.backends.backend_agg import new_figure_manager_given_figure as nfmgf # Warning -- assumes user has agg on their system, but should be ok. Use agg since doesn't require an X server except Exception as E: # pragma: no cover errormsg = f'To reanimate plots requires the "agg" backend, which could not be imported: {repr(E)}' raise ImportError(errormsg) from E if len(pl.get_fignums()): fignum = pl.gcf().number # This is the number of the current active figure, if it exists else: # pragma: no cover fignum = 1 plots = scu.mergelists(plots) # Convert to an odict for plot in plots: nfmgf(fignum, plot) # Make sure each figure object is associated with the figure manager -- WARNING, is it correct to associate the plot with an existing figure? return def emptyfig(*args, **kwargs): ''' The emptiest figure possible ''' fig = pl.Figure(facecolor='None', *args, **kwargs) return fig def _get_legend_handles(ax, handles, labels): ''' Construct handle and label list, from one of: - A list of handles and a list of labels - A list of handles, where each handle contains the label - An axis object, containing the objects that should appear in the legend - A figure object, from which the first axis will be used ''' if handles is None: if ax is None: ax = pl.gca() elif isinstance(ax, pl.Figure): # Allows an argument of a figure instead of an axes # pragma: no cover ax = ax.axes[-1] handles, labels = ax.get_legend_handles_labels() else: # pragma: no cover if labels is None: labels = [h.get_label() for h in handles] else: assert len(handles) == len(labels), f"Number of handles ({len(handles)}) and labels ({len(labels)}) must match" return ax, handles, labels def separatelegend(ax=None, handles=None, labels=None, reverse=False, figsettings=None, legendsettings=None): ''' Allows the legend of a figure to be rendered in a separate window instead ''' # Handle settings f_settings = scu.mergedicts({'figsize':(4.0,4.8)}, figsettings) # (6.4,4.8) is the default, so make it a bit narrower l_settings = scu.mergedicts({'loc': 'center', 'bbox_to_anchor': None, 'frameon': False}, legendsettings) # Get handles and labels _, handles, labels = _get_legend_handles(ax, handles, labels) # Set up new plot fig = pl.figure(**f_settings) ax = fig.add_subplot(111) ax.set_position([-0.05,-0.05,1.1,1.1]) # This cuts off the axis labels, ha-ha ax.set_axis_off() # Hide axis lines # A legend renders the line/patch based on the object handle. However, an object # can only appear in one figure. Thus, if the legend is in a different figure, the # object cannot be shown in both the original figure and in the legend. Thus we need # to copy the handles, and use the copies to render the legend handles2 = [] for h in handles: h2 = scu.cp(h) h2.axes = None h2.figure = None handles2.append(h2) # Reverse order, e.g. for stacked plots if reverse: # pragma: no cover handles2 = handles2[::-1] labels = labels[::-1] # Plot the new legend ax.legend(handles=handles2, labels=labels, **l_settings) return fig def orderlegend(order=None, ax=None, handles=None, labels=None, reverse=None, **kwargs): ''' Create a legend with a specified order, or change the order of an existing legend. Can either specify an order, or use the reverse argument to simply reverse the order. Note: you do not need to create the legend before calling this function; if you do, you will need to pass any additional keyword arguments to this function since it will override existing settings. Args: order (list or array): the new order of the legend, as from e.g. np.argsort() ax (axes): the axes object; if omitted, defaults to current axes handles (list): the legend handles; can be used instead of ax labels (list): the legend labels; can be used instead of ax reverse (bool): if supplied, simply reverse the legend order kwargs (dict): passed to ax.legend() **Examples**:: pl.plot([1,4,3], label='A') pl.plot([5,7,8], label='B') pl.plot([2,5,2], label='C') sc.orderlegend(reverse=True) # Legend order C, B, A sc.orderlegend([1,0,2], frameon=False) # Legend order B, A, C with no frame pl.legend() # Restore original legend order A, B, C ''' # Get handles and labels ax, handles, labels = _get_legend_handles(ax, handles, labels) if order: handles = [handles[o] for o in order] labels = [labels[o] for o in order] if reverse: handles = handles[::-1] labels = labels[::-1] ax.legend(handles, labels, **kwargs) return #%% Animation __all__ += ['animation', 'savemovie'] class animation(scu.prettyobj): ''' A class for storing and saving a Matplotlib animation. See also :func:`sc.savemovie() <savemovie>`, which works directly with Matplotlib artists rather than an entire figure. Depending on your use case, one is likely easier to use than the other. Use :func:`sc.animation() <animation>` if you want to animate a complex figure including non-artist objects (e.g., titles and legends); use :func:`sc.savemovie() <savemovie>` if you just want to animate a set of artists (e.g., lines). This class works by saving snapshots of the figure to disk as image files, then reloading them either via ``ffmpeg`` or as a Matplotlib animation. While (slightly) slower than working with artists directly, it means that anything that can be rendered to a figure can be animated. Note: the terms "animation" and "movie" are used interchangeably here. Args: fig (fig): the Matplotlib figure to animate (if none, use current) filename (str): the name of the output animation (default: animation.mp4) dpi (int): the resolution to save the animation at fps (int): frames per second for the animation imageformat (str): file type for temporary image files, e.g. 'jpg' basename (str): name for temporary image files, e.g. 'myanimation' nametemplate (str): as an alternative to imageformat and basename, specify the full name template, e.g. 'myanimation%004d.jpg' imagefolder (str): location to store temporary image files; default current folder, or use 'tempfile' to create a temporary folder anim_args (dict): passed to :obj:`matplotlib.animation.ArtistAnimation` or ``ffmpeg.input()`` save_args (dict): passed to :meth:`animation.save() <matplotlib.animation.Animation.save>` or ``ffmpeg.run()`` tidy (bool): whether to delete temporary files verbose (bool): whether to print progress kwargs (dict): also passed to :meth:`animation.save() <matplotlib.animation.Animation.save>` **Example**:: anim = sc.animation() pl.figure() repeats = 21 colors = sc.vectocolor(repeats, cmap='turbo') for i in range(repeats): scale = 1/np.sqrt(i+1) x = scale*pl.randn(10) y = scale*pl.randn(10) label = str(i) if not(i%5) else None pl.scatter(x, y, c=[colors[i]], label=label) pl.title(f'Scale = 1/√{i}') pl.legend() sc.boxoff('all') anim.addframe() anim.save('dots.mp4') | *New in version 1.3.3.* | *New in version 2.0.0:* ``ffmpeg`` option. ''' def __init__(self, fig=None, filename=None, dpi=200, fps=10, imageformat='png', basename='animation', nametemplate=None, imagefolder=None, anim_args=None, save_args=None, frames=None, tidy=True, verbose=True, **kwargs): self.fig = fig self.filename = filename self.dpi = dpi self.fps = fps self.imageformat = imageformat self.basename = basename self.nametemplate = nametemplate self.imagefolder = imagefolder self.anim_args = anim_args self.save_args = scu.mergedicts(save_args, kwargs) self.tidy = tidy self.verbose = verbose self.filenames = scu.autolist() self.frames = frames if frames else [] self.fig_size = None self.fig_dpi = None self.anim = None self.initialize() return def initialize(self): ''' Handle additional initialization of variables ''' # Handle folder if self.imagefolder == 'tempfile': # pragma: no cover self.imagefolder = tempfile.gettempdir() if self.imagefolder is None: self.imagefolder = os.getcwd() self.imagefolder = scf.path(self.imagefolder) # Handle name template if self.nametemplate is None: self.nametemplate = f'{self.basename}_%04d.{self.imageformat}' # ADD name template # Handle dpi self.dpi = _get_dpi(self.dpi) return def _getfig(self, fig=None): ''' Get the Matplotlib figure to save the animation from ''' if fig is None: if self.fig is not None: fig = self.fig else: try: fig = self.frames[0][0].get_figure() except: fig = pl.gcf() return fig def _getfilename(self, path=True): ''' Generate a filename for the next image file to save ''' try: name = self.nametemplate % self.n_files except TypeError as E: # pragma: no cover errormsg = f'Name template "{self.nametemplate}" does not seem valid for inserting current file number {self.n_files} into: should contain the string "%04d" or similar' raise TypeError(errormsg) from E if path: name = self.imagefolder / name return name def __add__(self, *args, **kwargs): # pragma: no cover ''' Allow anim += fig ''' self.addframe(*args, **kwargs) return self def __radd__(self, *args, **kwargs): # pragma: no cover ''' Allow anim += fig ''' self.addframe(self, *args, **kwargs) return self @property def n_files(self): return len(self.filenames) @property def n_frames(self): return len(self.frames) def __len__(self): # pragma: no cover ''' Since we can have either files or frames, need to check both ''' return max(self.n_files, self.n_frames) def addframe(self, fig=None, *args, **kwargs): ''' Add a frame to the animation -- typically a figure object, but can also be an artist or list of artists ''' # If a figure is supplied but it's not a figure, add it to the frames directly if fig is not None and isinstance(fig, (list, mpl.artist.Artist)): # pragma: no cover self.frames.append(fig) # Typical case: add a figure else: if self.verbose and self.n_files == 0: # First frame print('Adding frames...') # Get the figure, name, and save fig = self._getfig(fig) filename = self._getfilename() fig.savefig(filename, dpi=self.dpi) self.filenames += filename # Check figure properties fig_size = fig.get_size_inches() fig_dpi = fig.get_dpi() if self.fig_size is None: self.fig_size = fig_size else: if not np.allclose(self.fig_size, fig_size): # pragma: no cover warnmsg = f'Note: current figure size {fig_size} does not match saved {self.fig_size}, unexpected results may occur!' print(warnmsg) if self.fig_dpi is None: self.fig_dpi = fig_dpi else: if self.fig_dpi != fig_dpi: # pragma: no cover warnmsg = f'Note: current figure DPI {fig_dpi} does not match saved {self.fig_dpi}, unexpected results may occur!' print(warnmsg) if self.verbose: print(f' Added frame {self.n_files}: {self._getfilename(path=False)}') return def loadframes(self): # pragma: no cover ''' Load saved images as artists ''' animfig = pl.figure(figsize=self.fig_size, dpi=self.dpi) ax = animfig.add_axes([0,0,1,1]) if self.verbose: print('Preprocessing frames...') for f,filename in enumerate(self.filenames): if self.verbose: scp.progressbar(f+1, self.filenames) im = pl.imread(filename) self.frames.append(ax.imshow(im)) pl.close(animfig) return def __enter__(self, *args, **kwargs): # pragma: no cover ''' To allow with...as ''' return self def __exit__(self, *args, **kwargs): # pragma: no cover ''' Save on exist from a with...as block ''' return self.save() def rmfiles(self): ''' Remove temporary image files ''' succeeded = 0 failed = scu.autolist() for filename in self.filenames: if os.path.exists(filename): try: os.remove(filename) succeeded += 1 except Exception as E: # pragma: no cover failed += f'{filename} ({E})' if self.verbose: if succeeded: print(f'Removed {succeeded} temporary files') if failed: # pragma: no cover print(f'Failed to remove the following temporary files:\n{scu.newlinejoin(failed)}') def save(self, filename=None, fps=None, dpi=None, engine='ffmpeg', anim_args=None, save_args=None, frames=None, tidy=None, verbose=True, **kwargs): ''' Save the animation -- arguments the same as :func:`sc.animation() <animation>` and :func:`sc.savemovie() <savemovie>`, and are described there ''' # Handle engine if engine == 'ffmpeg': try: import ffmpeg except: print('Warning: engine ffmpeg not available; falling back to Matplotlib. Run "pip install ffmpeg-python" to use in future.') engine = 'matplotlib' engines = ['ffmpeg', 'matplotlib'] if engine not in engines: # pragma: no cover errormsg = f'Could not understand engine "{engine}": must be one of {scu.strjoin(engines)}' raise ValueError(errormsg) # Handle dictionary args anim_args = scu.mergedicts(self.anim_args, anim_args) save_args = scu.mergedicts(self.save_args, save_args) # Handle filename if filename is None: if self.filename is None: # pragma: no cover self.filename = f'{self.basename}.mp4' filename = self.filename # Set parameters if fps is None: fps = save_args.pop('fps', self.fps) if dpi is None: dpi = save_args.pop('dpi', self.dpi) if tidy is None: tidy = self.tidy # Start timing T = scd.timer() if engine == 'ffmpeg': # pragma: no cover save_args = scu.mergedicts(dict(overwrite_output=True, quiet=True), save_args) stream = ffmpeg.input(self.nametemplate, framerate=fps, **anim_args) stream = stream.output(filename) stream.run(**save_args, **kwargs) elif engine == 'matplotlib': # pragma: no cover import matplotlib.animation as mpl_anim # Load and sanitize frames if frames is None: if not self.n_frames: self.loadframes() if self.n_files and (self.n_frames != self.n_files): errormsg = f'Number of files ({self.n_files}) does not match number of frames ({self.n_frames}): please do not mix and match adding figures and adding artists as frames!' raise RuntimeError(errormsg) frames = self.frames for f in range(len(frames)): if not scu.isiterable(frames[f]): frames[f] = (frames[f],) # This must be either a tuple or a list to work with ArtistAnimation # Try to get the figure from the frames, else use the current one fig = self._getfig() # Optionally print progress if verbose: print(f'Saving {len(frames)} frames at {fps} fps and {dpi} dpi to "{filename}"...') callback = lambda i,n: scp.progressbar(i+1, len(frames)) # Default callback callback = save_args.pop('progress_callback', callback) # if provided as an argument else: callback = None # Actually create the animation -- warning, no way to not actually have it render! anim = mpl_anim.ArtistAnimation(fig, frames, **anim_args) anim.save(filename, fps=fps, dpi=dpi, progress_callback=callback, **save_args, **kwargs) if tidy: self.rmfiles() if verbose: print(f'Done; movie saved to "{filename}"') try: # Not essential, so don't try too hard if this doesn't work filesize = os.path.getsize(filename) if filesize<1e6: print(f'File size: {filesize/1e3:0.0f} KB') else: print(f'File size: {filesize/1e6:0.1f} MB') # pragma: no cover except: # pragma: no cover pass T.toc(label='Time saving movie') return def savemovie(frames, filename=None, fps=None, quality=None, dpi=None, writer=None, bitrate=None, interval=None, repeat=False, repeat_delay=None, blit=False, verbose=True, **kwargs): ''' Save a set of Matplotlib artists as a movie. Note: in most cases, it is preferable to use :func:`sc.animation() <animation>`. Args: frames (list): The list of frames to animate filename (str): The name (or full path) of the file; expected to end with mp4 or gif (default movie.mp4) fps (int): The number of frames per second (default 10) quality (string): The quality of the movie, in terms of dpi (default "high" = 300 dpi) dpi (int): Instead of using quality, set an exact dpi writer (str or object): Specify the writer to be passed to :meth:`animation.save() <matplotlib.animation.Animation.save>` (default "ffmpeg") bitrate (int): The bitrate. Note, may be ignored; best to specify in a writer and to pass in the writer as an argument interval (int): The interval between frames; alternative to using fps repeat (bool): Whether or not to loop the animation (default False) repeat_delay (bool): Delay between repeats, if repeat=True (default None) blit (bool): Whether or not to "blit" the frames (default False, since otherwise does not detect changes ) verbose (bool): Whether to print statistics on finishing. kwargs (dict): Passed to :meth:`animation.save() <matplotlib.animation.Animation.save>` Returns: A Matplotlib animation object **Examples**:: import pylab as pl import sciris as sc # Simple example (takes ~5 s) pl.figure() frames = [pl.plot(pl.cumsum(pl.randn(100))) for i in range(20)] # Create frames sc.savemovie(frames, 'dancing_lines.gif') # Save movie as medium-quality gif # Complicated example (takes ~15 s) pl.figure() nframes = 100 # Set the number of frames ndots = 100 # Set the number of dots axislim = 5*pl.sqrt(nframes) # Pick axis limits dots = pl.zeros((ndots, 2)) # Initialize the dots frames = [] # Initialize the frames old_dots = sc.dcp(dots) # Copy the dots we just made fig = pl.figure(figsize=(10,8)) # Create a new figure for i in range(nframes): # Loop over the frames dots += pl.randn(ndots, 2) # Move the dots randomly color = pl.norm(dots, axis=1) # Set the dot color old = pl.array(old_dots) # Turn into an array plot1 = pl.scatter(old[:,0], old[:,1], c='k') # Plot old dots in black plot2 = pl.scatter(dots[:,0], dots[:,1], c=color) # Note: Frames will be separate in the animation pl.xlim((-axislim, axislim)) # Set x-axis limits pl.ylim((-axislim, axislim)) # Set y-axis limits kwargs = {'transform':pl.gca().transAxes, 'horizontalalignment':'center'} # Set the "title" properties title = pl.text(0.5, 1.05, f'Iteration {i+1}/{nframes}', **kwargs) # Unfortunately pl.title() can't be dynamically updated pl.xlabel('Latitude') # But static labels are fine pl.ylabel('Longitude') # Ditto frames.append((plot1, plot2, title)) # Store updated artists old_dots = pl.vstack([old_dots, dots]) # Store the new dots as old dots sc.savemovie(frames, 'fleeing_dots.mp4', fps=20, quality='high') # Save movie as a high-quality mp4 Version: 2019aug21 ''' from matplotlib import animation as mpl_anim # Place here since specific only to this function if not isinstance(frames, list): # pragma: no cover errormsg = f'sc.savemovie(): argument "frames" must be a list, not "{type(frames)}"' raise TypeError(errormsg) for f in range(len(frames)): if not scu.isiterable(frames[f]): # pragma: no cover frames[f] = (frames[f],) # This must be either a tuple or a list to work with ArtistAnimation # Try to get the figure from the frames, else use the current one try: fig = frames[0][0].get_figure() except: fig = pl.gcf() # pragma: no cover # Set parameters if filename is None: # pragma: no cover filename = 'movie.mp4' if writer is None: if filename.endswith('mp4'): writer = 'ffmpeg' elif filename.endswith('gif'): writer = 'imagemagick' else: # pragma: no cover errormsg = f'sc.savemovie(): unknown movie extension for file {filename}' raise ValueError(errormsg) if fps is None: fps = 10 if interval is None: interval = 1000./fps fps = 1000./interval # To ensure it's correct # Handle dpi/quality if dpi is None and quality is None: quality = 'medium' # Make it medium quailty by default if isinstance(dpi, str): # pragma: no cover quality = dpi # Interpret dpi arg as a quality command dpi = None if dpi is not None and quality is not None: # pragma: no cover print(f'sc.savemovie() warning: quality is simply a shortcut for dpi; please specify one or the other, not both (dpi={dpi}, quality={quality})') if quality is not None: if quality == 'low': dpi = 50 elif quality == 'medium': dpi = 150 elif quality == 'high': dpi = 300 # pragma: no cover else: # pragma: no cover errormsg = f'Quality must be high, medium, or low, not "{quality}"' raise ValueError(errormsg) # Optionally print progress if verbose: start = scd.tic() print(f'Saving {len(frames)} frames at {fps} fps and {dpi} dpi to "{filename}" using {writer}...') # Actually create the animation -- warning, no way to not actually have it render! anim = mpl_anim.ArtistAnimation(fig, frames, interval=interval, repeat_delay=repeat_delay, repeat=repeat, blit=blit) anim.save(filename, writer=writer, fps=fps, dpi=dpi, bitrate=bitrate, **kwargs) if verbose: print(f'Done; movie saved to "{filename}"') try: # Not essential, so don't try too hard if this doesn't work filesize = os.path.getsize(filename) if filesize<1e6: print(f'File size: {filesize/1e3:0.0f} KB') else: print(f'File size: {filesize/1e6:0.2f} MB') # pragma: no cover except: # pragma: no cover pass scd.toc(start) return anim
C#
UTF-8
2,056
3.125
3
[]
no_license
using System; using System.Collections.Generic; namespace GildedRose.Inventory.Items.Abstract { public class Item : IEquatable<Item> { public string Name { get; set; } public int SellIn { get; set; } public int Quality { get; set; } protected int _qualityDegradeRate; protected static int _incrementFactor = -1; protected static int _maxQuality = 50; protected static int _minQuality = 0; public Item() { } public Item(Item i) { Name = i.Name; Quality = i.Quality; SellIn = i.SellIn; } public Item(string name, int sellIn, int quality) { CheckParameters(quality); Name = name; SellIn = sellIn; Quality = quality; _qualityDegradeRate = 1; } public virtual void CheckParameters(int quality) { if (quality > _maxQuality || quality < _minQuality) throw new Exception("Quality must be in the range [0, 50]"); } public void Update() { UpdateSellIn(); UpdateQuality(); } public virtual void UpdateSellIn() { if (IsDatePassed()) _qualityDegradeRate = 2; SellIn--; } public virtual void UpdateQuality() { Quality = Quality - (Quality - _qualityDegradeRate >= 0 ? _qualityDegradeRate : Quality); } protected bool IsDatePassed() { return SellIn <= 0; } public override string ToString() { return Name + ", S:" + SellIn + ", Q:" + Quality; } public bool Equals(Item other) { if (other == null) return false; if (Name.Equals(other.Name) && Quality.Equals(other.Quality) && SellIn.Equals(other.SellIn)) return true; else return false; } } }
Python
UTF-8
7,481
2.71875
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import division from pylab import * import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap import matplotlib as mpl import scipy.linalg as LA from matplotlib.animation import FuncAnimation import csv import propagation #zmienne globalne: results= [] rownum =0 atmFactors=[] wind=[] fig=plt.figure(num='Simulation') img = plt.imread('../images/krk_color_scaled.png') #algorytm SimpleKriging #zrodlo: https://sourceforge.net/p/geoms2/wiki/Kriging/ def SimpleKriging(x,y,v,variogram,grid): cov_angles = np.zeros((x.shape[0],x.shape[0])) cov_distances = np.zeros((x.shape[0],x.shape[0])) K = np.zeros((x.shape[0],x.shape[0])) for i in range(x.shape[0]-1): cov_angles[i,i:]=np.arctan2((y[i:]-y[i]),(x[i:]-x[i])) cov_distances[i,i:]=np.sqrt((x[i:]-x[i])**2+(y[i:]-y[i])**2) for i in range(x.shape[0]): for j in range(x.shape[0]): if cov_distances[i,j]!=0: amp=np.sqrt((variogram[1]*np.cos(cov_angles[i,j]))**2+(variogram[0]*np.sin(cov_angles[i,j]))**2) K[i,j]=v[:].var()*(1-np.e**(-3*cov_distances[i,j]/amp)) K = K + K.T for i in range(grid.shape[0]): for j in range(grid.shape[1]): distances = np.sqrt((i-x[:])**2+(j-y[:])**2) angles = np.arctan2(i-y[:],j-x[:]) amplitudes = np.sqrt((variogram[1]*np.cos(angles[:]))**2+(variogram[0]*np.sin(angles[:]))**2) M = v[:].var()*(1-np.e**(-3*distances[:]/amplitudes[:])) W = LA.solve(K,M) grid[i,j] = np.sum(W*(v[:]-v[:].mean()))+v[:].mean() return grid def retX(): #Zwraca punkty pomiarowe na osi x (przyblizone wartosci) x = array([58, 58, 57, 47, 50, 40, 43, 34, 20, 24, 17]) return x def retY(): #Zwraca punkty pomiarowe a osi y y = array([50, 42, 25, 24, 20, 21, 17, 33, 34, 38, 25]) return y def updateV(): #aktualizuje nowe wartosci smogu #v = np.random.randint(0,100,11) #dla losowych global results global rownum v = results[rownum] rownum +=1 return array(v) def update(i): #Pobiera nowa wartosc smogu, ponownie stosuje algorytm Kriging i rysuje nowy wykres (dla danych rzeczywistych) global img, fig, atmFactors x=retX() y=retY() v = updateV() smogColorMap = newColorMap() fig.clf() plt.imshow(img, extent=[0, 75, 0, 60]) grid = np.zeros((75,60),dtype='float32') grid = SimpleKriging(x,y,v,(50,30),grid) plt.imshow(grid.T,origin='lower', interpolation='gaussian',cmap=smogColorMap, alpha=0.5, vmin=0, vmax=300) scatter = plt.scatter(x,y,c=v,cmap=smogColorMap, vmin=0, vmax=300) cb = plt.colorbar(scatter, fraction=0.035, pad=0.04) cb.set_label('SMOG scale') plt.xlim(0,grid.shape[0]) plt.ylim(0,grid.shape[1]) #wypisanie czynnikow atmosferycznych plt.gcf().text(0.02, 0.95, "Temperature: "\ +atmFactors[i+1][0]+"\N{DEGREE SIGN}C", fontsize=14) plt.gcf().text(0.40, 0.95, "Wind: "+atmFactors[i+1][1]\ +"kt "+atmFactors[i+1][2], fontsize=14) plt.gcf().text(0.65, 0.95, "Precipitation: "+atmFactors[i+1][3]\ +"mm", fontsize=14) plt.gcf().text(0.20, 0.9, "Air humidity: "+atmFactors[i+1][4]\ +"%", fontsize=14) plt.gcf().text(0.58, 0.9, "Air pressure: "\ +atmFactors[i+1][5]+"hPa", fontsize=14) def updateSim(i): #Pobiera nowa wartosc smogu, ponownie stosuje algorytm Kriging i rysuje nowy wykres (dla danych predykcyjnych) global img, fig, atmFactors x=retX() y=retY() v = updateV() smogColorMap = newColorMap() fig.clf() plt.imshow(img, extent=[0, 75, 0, 60]) grid = np.zeros((75,60),dtype='float32') grid = SimpleKriging(x,y,v,(50,30),grid) plt.imshow(grid.T,origin='lower', interpolation='gaussian',cmap=smogColorMap, alpha=0.5, vmin=0, vmax=300) scatter = plt.scatter(x,y,c=v,cmap=smogColorMap, vmin=0, vmax=300) cb = plt.colorbar(scatter, fraction=0.035, pad=0.04) cb.set_label('SMOG scale') plt.xlim(0,grid.shape[0]) plt.ylim(0,grid.shape[1]) def newColorMap(): #zwraca nowa skale kolorow dla danych wartosci smogu cdict = {'red': ((0.0, 0.0, 0.0), (0.167, 1.0, 1.0), (0.5, 1.0, 1.0), (0.67, 1.0, 1.0), (1.0, 0.5, 0.5)), 'green': ((0.0, 1.0, 1.0), (0.167, 1.0, 1.0), (0.5, 0.5, 0.5), (0.67, 0.0, 0.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (0.167, 0.0, 0.0), (0.5, 0.0, 0.0), (0.67, 0.0, 0.0), (1.0, 0.7, 0.7)) } smogColorMap = LinearSegmentedColormap('SmogColorMap', cdict) return smogColorMap def readcsv(filename): #odczytanie pliku.csv results = [] with open(filename) as csvfile: reader = csv.reader(csvfile, delimiter = ";") for row in reader: print(row) results.append(row) return results; def matrixToInt(matrix): #zamiana macierzy z wartosciami String na macierz z wartosciami Int newMatrix=[[0]*len(matrix[0]) for i in range(len(matrix))] for i in range(0, len(matrix)): for j in range (0, len(matrix[0])): newMatrix[i][j]=int(matrix[i][j]) return newMatrix def propagationSim(wind, temp, precip, smog): #symulacja propagacji wartosci smogu global results, atmFactors, fig results.append([smog*1.5,smog*1.3,smog*1.1,smog,smog*0.99,smog*1.5,smog*1.3,smog*1.05,smog,smog,smog*1.6]) for i in range(1,6): results.append([0,0,0,0,0,0,0,0,0,0,0]) print("propagation = 5h, pm=10") results = matrixToInt(results); #Podzielenie wiatru na predkosc i kierunek windSp,windDir = wind[:2], wind[2:] for i in range (0,5): atmFactors.append([temp,int(windSp),windDir,precip,90,1000]) i = i+1 frames = 5 #uruchomienie 'propagation': funkcja generuje na podstawie podanych wartosci #smogu oraz czynnikow atmosferycznych kolejne wartosci z nastepnych godzinach results = propagation.propagation(atmFactors, results) print(results) plt.grid() ani = FuncAnimation(fig, updateSim, frames = frames, interval=300, repeat = False) plt.show() plt.close(fig) def mainSim(pm,period): #symulacja rzeczywistych wartosci smogu global results, atmFactors, fig if period==7 and pm==10: results = readcsv('../data_csv/pm10_week.csv') #zmiana pliku z danymi pomiarowymi print("period = 7 tydzien, pm = 10") elif period==7 and pm==25: results = readcsv('../data_csv/pm25_week.csv') print("period = 7 tydzien, pm = 2.5") elif period==24 and pm==10: results = readcsv('../data_csv/pm10_day.csv') print("period = 24 dzien, pm = 10") elif period==24 and pm==25: results = readcsv('../data_csv/pm25_day.csv') print("period = 24 dzien, pm = 2.5") results = matrixToInt(results); if period == 7: atmFactors = readcsv('../data_csv/factors_week.csv') frames=12 else: atmFactors = readcsv('../data_csv/factors_day.csv') frames=24 plt.grid() ani = FuncAnimation(fig, update, frames = frames, interval=300, repeat = False) #uruchomienie animacji plt.show() plt.close(fig)
TypeScript
UTF-8
277
2.5625
3
[]
no_license
import bcrypt from "bcrypt" export class UserUtils{ static async hashPassword(password:string){ return await bcrypt.hash(password, 10); } static async isPasswordMatch(password:string, hash:string){ return bcrypt.compare(password, hash); } }
C#
UTF-8
3,561
3.375
3
[ "Apache-2.0" ]
permissive
using System; namespace DataFilters.Grammar.Syntax { /// <summary> /// A <see cref="FilterExpression"/> implementation that can holds a datetime value /// </summary> public sealed class DateTimeExpression : FilterExpression, IEquatable<DateTimeExpression>, IBoundaryExpression { /// <summary> /// Date part of the expression /// </summary> public DateExpression Date { get; } /// <summary> /// Time part of the expression /// </summary> public TimeExpression Time { get; } /// <summary> /// Definies the kind of the current <see cref="DateTimeExpression"/> instance. /// </summary> public DateTimeExpressionKind Kind { get; } /// <summary> /// Builds a new <see cref="DateTimeExpression"/> instance where only <see cref="Date"/> part is set /// </summary> /// <param name="date"></param> /// <exception cref="ArgumentNullException">if <paramref name="date"/> is <c>null</c>.</exception> public DateTimeExpression(DateExpression date) : this(date, null) { } /// <summary> /// Builds a new <see cref="DateTimeExpression"/> where only the <see cref="Time"/> part is specified /// </summary> /// <param name="time"></param> /// <exception cref="ArgumentNullException">if <paramref name="time"/> is <c>null</c>.</exception> public DateTimeExpression(TimeExpression time) : this(null, time) { } /// <summary> /// Builds a new <see cref="DateTimeExpression"/> with both <paramref name="date"/> and <paramref name="time"/> /// specified. /// </summary> /// <param name="date">date part of the expression</param> /// <param name="time">time part of the expression</param> /// <exception cref="ArgumentException">if both <paramref name="date"/> and <paramref name="time"/> are <c>null</c>.</exception> public DateTimeExpression(DateExpression date, TimeExpression time) { if (date is null && time is null) { throw new ArgumentException($"Both {nameof(date)} and {nameof(time)} cannot be null"); } Date = date; Time = time; Kind = time?.Offset is not null ? DateTimeExpressionKind.Utc : DateTimeExpressionKind.Unspecified; } /// <summary> /// Builds a new <see cref="DateTimeExpression"/> with both <see cref="Date"/> and <see cref="Time"/> values /// extracted from . /// </summary> /// <param name="utc"><see cref="DateTime"/> value to use as source of the current instance</param> public DateTimeExpression(DateTime utc) : this(new DateExpression(utc.Year, utc.Month, utc.Day), new TimeExpression(utc.Hour, utc.Minute, utc.Second)) { } /// <inheritdoc/> public bool Equals(DateTimeExpression other) => (Date, Time).Equals((other?.Date, other?.Time)); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as DateTimeExpression); /// <inheritdoc/> public override int GetHashCode() => (Date, Time).GetHashCode(); /// <inheritdoc/> public void Deconstruct(out DateExpression date, out TimeExpression time) { date = Date; time = Time; } ///<inheritdoc/> public override string ToString() => this.Jsonify(); } }
Java
UTF-8
981
2.390625
2
[ "BSD-3-Clause" ]
permissive
// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. package org.cef.callback; import java.util.Vector; /** * Callback interface for asynchronous continuation of file dialog requests. */ public interface CefFileDialogCallback { /** * Continue the file selection with the specified file_paths. This may be * a single value or a list of values depending on the dialog mode. An empty * value is treated the same as calling Cancel(). * * @param selectedAcceptFilter 0-based index of the value selected from the * accept filters array passed to CefDialogHandler::OnFileDialog. * @param filePaths list of selected file paths or an empty list. */ public void Continue(int selectedAcceptFilter, Vector<String> filePaths); /** * Cancel the file selection. */ public void Cancel(); }
Java
UTF-8
286
2.203125
2
[]
no_license
package br.com.sistemaescolar.observer; import br.com.sistemaescolar.model.Disciplina; public interface SubjectDisciplina { public void addObserver(ObserverDisciplina o); public void removeObserver(ObserverDisciplina o); public void notifyObservers(Disciplina disciplina); }
Java
UTF-8
262
1.664063
2
[]
no_license
package com.toutiao.proxyserver.d; public interface a { void a(String str, String str2, String str3); void b(String str, String str2, String str3); void c(String str, String str2, String str3); void d(String str, String str2, String str3); }
Java
ISO-8859-1
793
3.8125
4
[]
no_license
package org.formation.fonctionnelle; import java.util.Scanner; public class GuessNumber { public static void main(String[] args) { System.out.println("Le but du jeu est de trouver un nombre entre 0 et 1000"); int nbMystre = (int) (Math.random() * 1001); // System.out.println("nbMystre : " + nbMystre); Scanner sc = new Scanner(System.in); int nbSaisie; int nbTentative = 0; do { System.out.print("Saisir un nombre : "); nbSaisie = sc.nextInt(); nbTentative++; if (nbSaisie > nbMystre) { System.out.println("C'est moins"); } else if (nbSaisie < nbMystre) { System.out.println("C'est plus"); } } while (nbSaisie != nbMystre); System.out.println(nbTentative + " tentative ncessaire"); sc.close(); } }
C++
UTF-8
847
2.984375
3
[]
no_license
class Solution { unordered_set<string> memo; int ans; int size; public: int maxUniqueSplit(string s) { size=s.size(); ans=0; memo.clear(); dfs(s,0); return ans; } void dfs(string &s,int start) { //剪枝:假设后面最优情况,每个字母都可以唯一拆分,还是没ans大,也就没必要回溯了 if ((int)memo.size()+(size-start)<=ans) return; if (start==size) { ans=max(ans,(int)memo.size()); return; } string t; for (int j=start;j<size;++j) { t+=s.at(j); if (memo.find(t)==memo.end()) { memo.insert(t); dfs(s,j+1); memo.erase(t); } } return; } };
C
UTF-8
14,207
2.71875
3
[]
no_license
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include <netdb.h> #include <errno.h> #include <unistd.h> #include <time.h> typedef unsigned int dns_rr_ttl; typedef unsigned short dns_rr_type; typedef unsigned short dns_rr_class; typedef unsigned short dns_rdata_len; typedef unsigned short dns_rr_count; typedef unsigned short dns_query_id; typedef unsigned short dns_flags; //All sizes in bytes const int ID_SIZE = 2; const int HDR_SIZE = 12; const int MAX_WIRE_SIZE = 1024; char *PORT = "53"; //getaddrinfo needs port to be a char* //typedef struct { // char *name; // dns_rr_type type; // dns_rr_class class; // dns_rr_ttl ttl; // dns_rdata_len rdata_len; // unsigned char *rdata; //} dns_rr; /* * myopen_clientfd - Open connection with socket type <socktype> to server at <hostname, port> and * return a socket descriptor ready for reading and writing. This * function is reentrant and protocol-independent. use SOCK_DRAM as <socktype> for UDP connections * * On error, returns: * -2 for getaddrinfo error * -1 with errno set for other errors. */ int myopen_clientfd(char *hostname, char *port, int socktype) { int clientfd, rc; struct addrinfo hints, *listp, *p; /* Get a list of potential server addresses */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_socktype = socktype; /* Open a connection */ hints.ai_flags = AI_NUMERICSERV; /* ... using a numeric port arg. */ hints.ai_flags |= AI_ADDRCONFIG; /* Recommended for connections */ if ((rc = getaddrinfo(hostname, port, &hints, &listp)) != 0) { fprintf(stderr, "getaddrinfo failed (%s:%s): %s\n", hostname, port, gai_strerror(rc)); return -2; } /* Walk the list for one that we can successfully connect to */ for (p = listp; p; p = p->ai_next) { /* Create a socket descriptor */ if ((clientfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) < 0) continue; /* Socket failed, try the next */ /* Connect to the server */ if (connect(clientfd, p->ai_addr, p->ai_addrlen) != -1) break; /* Success */ if (close(clientfd) < 0) { /* Connect failed, try another */ //line:netp:openclientfd:closefd fprintf(stderr, "open_clientfd: close failed: %s\n", strerror(errno)); return -1; } } /* Clean up */ freeaddrinfo(listp); if (!p) /* All connects failed */ return -1; else /* The last connect succeeded */ return clientfd; } void print_bytes(unsigned char *bytes, int byteslen) { int i, j, byteslen_adjusted; unsigned char c; if (byteslen % 8) { byteslen_adjusted = ((byteslen / 8) + 1) * 8; } else { byteslen_adjusted = byteslen; } for (i = 0; i < byteslen_adjusted + 1; i++) { if (!(i % 8)) { if (i > 0) { for (j = i - 8; j < i; j++) { if (j >= byteslen_adjusted) { printf(" "); } else if (j >= byteslen) { printf(" "); } else if (bytes[j] >= '!' && bytes[j] <= '~') { printf(" %c", bytes[j]); } else { printf(" ."); } } } if (i < byteslen_adjusted) { printf("\n%02X: ", i); } } else if (!(i % 4)) { printf(" "); } if (i >= byteslen_adjusted) { continue; } else if (i >= byteslen) { printf(" "); } else { printf("%02X ", bytes[i]); } } printf("\n"); } void canonicalize_name(char *name) { /* * Canonicalize name in place. Change all upper-case characters to * lower case and remove the trailing dot if there is any. If the name * passed is a single dot, "." (representing the root zone), then it * should stay the same. * * INPUT: name: the domain name that should be canonicalized in place */ int namelen, i; // leave the root zone alone if (strcmp(name, ".") == 0) { return; } namelen = strlen(name); // remove the trailing dot, if any if (name[namelen - 1] == '.') { name[namelen - 1] = '\0'; } // make all upper-case letters lower case for (i = 0; i < namelen; i++) { if (name[i] >= 'A' && name[i] <= 'Z') { name[i] += 32; } } } //dns_rr rr_from_wire(unsigned char *wire, int *indexp, int query_only) { // /* // * Extract the wire-formatted resource record at the offset specified by // * *indexp in the array of bytes provided (wire) and return a // * dns_rr (struct) populated with its contents. Update the value // * pointed to by indexp to the next value beyond the resource record. // * // * INPUT: wire: a pointer to an array of bytes // * INPUT: indexp: a pointer to the index in the wire where the // * wire-formatted resource record begins // * INPUT: query_only: a boolean value (1 or 0) which indicates whether // * we are extracting a full resource record or only a // * query (i.e., in the question section of the DNS // * message). In the case of the latter, the ttl, // * rdata_len, and rdata are skipped. // * OUTPUT: the resource record (struct) // */ //} //int rr_to_wire(dns_rr rr, unsigned char *wire, int query_only) { // /* // * Convert a DNS resource record struct to DNS wire format, using the // * provided byte array (wire). Return the number of bytes used by the // * name in wire format. // * // * INPUT: rr: the dns_rr struct containing the rr record // * INPUT: wire: a pointer to the array of bytes where the // * wire-formatted resource record should be constructed // * INPUT: query_only: a boolean value (1 or 0) which indicates whether // * we are constructing a full resource record or only a // * query (i.e., in the question section of the DNS // * message). In the case of the latter, the ttl, // * rdata_len, and rdata are skipped. // * OUTPUT: the length of the wire-formatted resource record. // * // */ //} /* * Generates random id and puts it into beginning of wire * Returns the size of the id, which will be the index into wire after the id. * This size (I think) is going to be 4. But maybe not if we need the 0x before everything. */ int generate_random_id(unsigned char *wire) { int i; for (i = 0; i < ID_SIZE; ++i) { wire[i] = rand() % 256; } return i; } /* * Generates header for dns query. For this lab, every header is same except for the id, which is random. * Header looks like: * xx xx 01 00 --> x's are for id. 01 for RD bit. * 00 01 00 00 --> 01 for total questions * 00 00 00 00 * New size of wire is the global constant HDR_SIZE = 12 */ void create_header(unsigned char *wire) { int i = generate_random_id(wire); memset(&wire[i], 0, HDR_SIZE - i); //set all of header besides id to 0 const int rd_index = 2; const int tot_q_index = 5; wire[rd_index] = 1; wire[tot_q_index] = 1; } /* * Convert a DNS name from string representation (dot-separated labels) * to DNS wire format, and put it on the wire starting at position HDR_SIZE. Return * the new wire length. */ int encode_name_to_wire(char *qname, unsigned char *wire) { strcpy(&wire[HDR_SIZE+1], qname); //automatically encodes qname as its byte values. //Now need to insert size encodings at beginning (wire[HDR_SIZE]) and at every '.' that was in qname int qname_i = 0; int end_qname = 0; //0 = false while(!end_qname) { int insertion_i = HDR_SIZE + qname_i; int cnt = 0; //reset the counter for(; qname[qname_i] != '.'; qname_i++) { if(qname[qname_i] == '\0') { end_qname = 1; //1 = true break; } cnt++; //count the number of characters before the next period } wire[insertion_i] = cnt; //insert the count at the appropriate place qname_i++; //go to next char after the current period } return HDR_SIZE + qname_i + 1; //+1 b/c HDR_SIZE + qname_i points at the \0 in the wire, we want to point one past that } /* * Extract the wire-formatted DNS name at the offset specified by * *indexp in the array of bytes provided (wire) and return its string * representation (dot-separated labels) in a char array allocated for * that purpose. Update the value pointed to by indexp to the next * value beyond the name. * * INPUT: wire: a pointer to an array of bytes * INPUT: indexp, the index in the wire where the wire-formatted name begins * OUTPUT: a string containing the string representation of the name, * allocated on the heap. */ /* * Gets the IP from the wire and decodes it into its string representation (decimal dot notation) * For now, assumes that the last 4 bytes of the wire contain the IP address * INPUT: wire: pointer to the array of bytes that have the response from DNS server * INPUT: i: index into the wire where the IP address begins * INPUT: length: length of the wire * OUTPUT: the IP address in human readable form (Ex: 192.168.34.27) */ char *decode_ip_from_wire(unsigned char *wire, int i, int length) { int ipNums[4]; //cout << mem[0] << " | dec: " << (int)(unsigned char)mem[0] << endl; int offset = i; while(i != length) { ipNums[i-offset] = (int)wire[i]; //printf("ipNums[%d]: %d\n", i-offset, ipNums[i-offset]); i++; } char ip[16]; snprintf(ip, sizeof ip, "%d.%d.%d.%d", ipNums[0], ipNums[1], ipNums[2], ipNums[3]); return ip; } /* * Creates question section of dns query * Starts at position HDR_SIZE on the wire. Puts encoding of qname on wire, followed by type and class fields * This should follow the encoding of qname: * 00 01 00 01 --> 1st 00 01 sets type to 1 (A) and 2nd 00 01 sets class to 1 (IN) */ int create_question(char *qname, unsigned char *wire) { int i = encode_name_to_wire(qname, wire); //add type and class to wire: wire[i] = 0; i++; wire[i] = 1; i++; wire[i] = 0; i++; wire[i] = 1; i++; return i; } /* * Create a wire-formatted DNS (query) message using the provided byte * array (wire). Create the header and question sections, including * the qname and qtype. * * INPUT: qname: the string containing the name to be queried * INPUT: wire: the pointer to the array of bytes where the DNS wire * message should be constructed * OUTPUT: the length of the DNS wire message */ unsigned short create_dns_query(char *qname, unsigned char *wire) { create_header(wire); return create_question(qname, wire); } /* * Extract the IPv4 address from the answer section, following any * aliases that might be found, and return the string representation of * the IP address. If no address is found, then return NULL. * * INPUT: qname: the string containing the name that was queried * INPUT: wire: the pointer to the array of bytes representing the DNS wire message * INPUT: length: the length of the wire. * OUTPUT: a string representing the IP address in the answer; or NULL if none is found */ char *get_answer_address(char *qname, unsigned char *wire, int length) { //-------------------------------------------------------------- YOU ARE HERE -------------------------------------------------------------- //Gameplan: First just try and decode example.com's IP address. There are no aliases and no extra IPs, so this will be a simple case // Once this is working, find out about what people are talking about for multiple IP's and aliases (CNAMEs), and implement that. //------------------------------------------------------------------------------------------------------------------------------------------ //Note - Only works if exactly one IP address found. //Doesn't work if no address found or for things like www.intel.com //Also, for multiple IP's found, it returns the wrong one (supposed to return first, but this returns last int i = length - 4; //if an IP address exists, this will not point to the first part of it return decode_ip_from_wire(wire, i, length); } /* * Send a message (request) over UDP to a server (server) and port * (port) and wait for a response, which is placed in another byte * array (response). Create a socket, "connect()" it to the * appropriate destination, and then use send() and recv(); * * INPUT: request: a pointer to an array of bytes that should be sent * INPUT: requestlen: the length of request, in bytes. * INPUT: response: a pointer to an array of bytes in which the * response should be received * OUTPUT: the size (bytes) of the response received */ int send_recv_message(unsigned char *request, int requestlen, unsigned char *response, char *server, char *port) { int clientfd = myopen_clientfd(server, port, SOCK_DGRAM); //connect to dns server on port 53. SOCK_DGRAM means UDP connection if(send(clientfd, request, requestlen, 0) < 0) //0 param just does no flags. this is equivalent to book's rio_writen call. printf("Send failed\n"); return recv(clientfd, response, MAX_WIRE_SIZE, 0); } char *resolve(char *qname, char *server) { //build DNS query message unsigned char msg[MAX_WIRE_SIZE]; int msg_length = create_dns_query(qname, msg); //send message and receive response unsigned char response[MAX_WIRE_SIZE]; int lengthResp = send_recv_message(msg, msg_length, response, server, PORT); // printf("Size of response: %d\n",lengthResp); // print_bytes(response, lengthResp); //extract IP address from response return get_answer_address(qname, response, lengthResp); } //make an open_myclientfd that adds an int type. then set ai_socktype in open_clientfd to SOCK_DGRAM int main(int argc, char *argv[]) { srand(time(NULL)); //for generating random id char *ip; if (argc < 3) { fprintf(stderr, "Usage: %s <domain name> <server>\n", argv[0]); exit(1); } ip = resolve(argv[1], argv[2]); printf("%s => %s\n", argv[1], ip == NULL ? "NONE" : ip); }
C++
UTF-8
3,378
2.734375
3
[]
no_license
#include "lissajous.h" #include "ui_lissajous.h" #include <math.h> Lissajous::Lissajous(QWidget *parent) : QMainWindow(parent), ui(new Ui::Lissajous), chart(), axisX(), axisY(), splineSeries(), scatterSeries(), points(), timer(this), amplitudeA(1), frequencyA(1), phaseA(0), amplitudeB(1), frequencyB(1), phaseB(45), noPoints(500), noDynamicPoints(60), currentPoint(0), dynamicDraw(false) { ui->setupUi(this); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); sizePolicy.setHeightForWidth(true); ui->chartView->setSizePolicy(sizePolicy); setupChart(); connect(this, &Lissajous::dynamicDrawChanged, this, &Lissajous::onDynamicDrawChanged); } Lissajous::~Lissajous() { delete ui; } void Lissajous::setupChart() { chart.legend()->hide(); ui->chartView->setChart(&chart); chart.removeAllSeries(); generatePoints(); chart.addSeries(&splineSeries); chart.addSeries(&scatterSeries); scatterSeries.setColor(splineSeries.color()); scatterSeries.setBorderColor(scatterSeries.color()); scatterSeries.setMarkerSize(1); chart.addAxis(&axisX, Qt::AlignBottom); splineSeries.attachAxis(&axisX); scatterSeries.attachAxis(&axisX); axisX.applyNiceNumbers(); chart.addAxis(&axisY, Qt::AlignLeft); splineSeries.attachAxis(&axisY); scatterSeries.attachAxis(&axisY); axisY.applyNiceNumbers(); updateChartType(); connect(&timer, SIGNAL(timeout()), this, SLOT(updatePoints())); timer.start(1); } void Lissajous::generatePoints() { points.clear(); points.reserve(noPoints); for(int i = 0; i < noPoints; i++) { double t = static_cast<double>(i) / noPoints * 2 * M_PI; QPointF point(getX(t), getY(t)); points.push_back(point); } splineSeries.replace(points); } void Lissajous::selectPoints(int startPos, int endPos) { int length = endPos - startPos; QVector<QPointF> currentPoints = points.mid(startPos, length); int noMissingPoints = endPos - points.size(); if(noMissingPoints > 0) { currentPoints.append(points.mid(0, noMissingPoints)); } scatterSeries.replace(currentPoints); } inline double Lissajous::getX(double t) { return amplitudeA * sin(frequencyA * (t + phaseA)); } inline double Lissajous::getY(double t) { return amplitudeB * sin(frequencyB * (t + phaseB)); } void Lissajous::updateChartType() { scatterSeries.setVisible(dynamicDraw); splineSeries.setVisible(!dynamicDraw); } bool Lissajous::isDynamicDraw() { return dynamicDraw; } void Lissajous::setDynamicDraw(bool value) { dynamicDraw = value; if(ui->actionDynamic_View->isChecked() != value) { ui->actionDynamic_View->toggle(); } emit dynamicDrawChanged(); } void Lissajous::updatePoints() { currentPoint = (currentPoint + 1) % points.size(); selectPoints(currentPoint, currentPoint + noDynamicPoints); } void Lissajous::on_actionExit_triggered() { QCoreApplication::quit(); } void Lissajous::on_actionAbout_Creator_triggered() { QMessageBox msgBox; msgBox.setText("This program was created by Patryk Chodorowski"); msgBox.exec(); } void Lissajous::on_actionDynamic_View_triggered(bool checked) { setDynamicDraw(checked); } void Lissajous::onDynamicDrawChanged() { updateChartType(); }
Python
UTF-8
920
2.53125
3
[]
no_license
from html.entities import codepoint2name from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup hackathonLinks = [line.strip() + '/submissions?page=' for line in open('hackathons.txt', 'r')] print(hackathonLinks) submissionLinks = set() for link in hackathonLinks: pageNum = 1 while True: print("-----------------PAGE", pageNum) try: uClient = uReq(link + str(pageNum)) page_html = uClient.read() uClient.close() except: print("ERROR") break # continue page = soup(page_html, "html.parser") submissions = page.findAll("div", {"class":"gallery-item"}) if submissions == []: # past final page break for submission in submissions: submissionLink = submission.a['href'] print(submissionLink) submissionLinks.add(submissionLink) pageNum += 1 with open('projects.txt', 'a') as file: for link in submissionLinks: file.write(link + '\n')
Java
UTF-8
4,070
2.453125
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. */ import java.io.IOException; import java.io.Serializable; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; /** * * @author rama */ @ManagedBean @SessionScoped public class Login implements Serializable { /** * Creates a new instance of Login */ private String id; private String password; private String msg; private FriendBookAccount theLoginAccount; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public FriendBookAccount getTheLoginAccount() { return theLoginAccount; } public void setTheLoginAccount(FriendBookAccount theLoginAccount) { this.theLoginAccount = theLoginAccount; } public Login() { //at the biginning, there is no login account theLoginAccount = null; } public String login() throws IOException { try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { return ("Internal Error! Please try again later.123"); } final String DATABASE_URL = "jdbc:mysql://mis-sql.uhcl.edu/saripellaa6306"; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { //connect to the databse connection = DriverManager.getConnection(DATABASE_URL, "saripellaa6306", "1517381"); //create statement statement = connection.createStatement(); //search the accountID in the onlineAccount table resultSet = statement.executeQuery("Select * from friendbookaccount " + "where userID = '" + id + "'"); if(resultSet.next()) { //the id is found, check the password if(password.equals(resultSet.getString(4))) { //password is good theLoginAccount = new FriendBookAccount(resultSet.getString(1), resultSet.getString(2),resultSet.getString(3), resultSet.getString(4),resultSet.getString(5), resultSet.getString(6)); return "home"; } else { //password is not correct id=""; password=""; return "loginNotOk"; } } else { id=""; password=""; return "loginNotOk"; } } catch (SQLException e) { e.printStackTrace(); return ("internalError"); } finally { try { statement.close(); connection.close(); resultSet.close(); } catch(Exception e) { e.printStackTrace(); } } } }
C#
UTF-8
1,542
2.75
3
[ "MIT" ]
permissive
using System; using Xamarin.Forms; namespace XamKit { public class TouchEffect : RoutingEffect { public event TouchActionEventHandler TouchAction; public TouchEffect() : base("XamKit.TouchEffect") { } public void OnTouchAction(Element element, TouchActionEventArgs args) { TouchAction?.Invoke(element, args); } } public class TouchActionEventArgs : EventArgs { /// <summary> /// Point relative to element /// </summary> public Point Point { get; private set; } /// <summary> /// Point relative to application window /// </summary> public Point ApplicationPoint { get; private set; } /// <summary> /// Touch action type /// </summary> public TouchActionType Type { get; private set; } /// <summary> /// Is touch pressed to any place on the app /// </summary> public bool IsPressed { get; private set; } public TouchActionEventArgs(TouchActionType type, Point point, Point applicationPoint, bool isPressed) { Point = point; Type = type; ApplicationPoint = applicationPoint; IsPressed = isPressed; } } public delegate void TouchActionEventHandler(object sender, TouchActionEventArgs args); public enum TouchActionType { Entered, Pressed, Move, Released, Exited, Cancelled } }
Java
UTF-8
2,127
2.515625
3
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.runtime.js.threading; import im.actor.runtime.actors.ActorTime; import im.actor.runtime.actors.dispatch.AbstractDispatchQueue; import im.actor.runtime.actors.dispatch.AbstractDispatcher; import im.actor.runtime.actors.dispatch.Dispatch; import im.actor.runtime.actors.dispatch.DispatchResult; public class JsThreads<T, Q extends AbstractDispatchQueue<T>> extends AbstractDispatcher<T, Q> { private static final int ITERATION_COUNT_MAX = 10; private JsSecureInterval secureInterval; private boolean isDoingIteration = false; protected JsThreads(Q queue, Dispatch<T> dispatch) { super(queue, dispatch); secureInterval = JsSecureInterval.create(new Runnable() { @Override public void run() { isDoingIteration = true; long delay = -1; int iteration = 0; while (delay < 0 && iteration < ITERATION_COUNT_MAX) { delay = doIteration(); iteration++; } isDoingIteration = false; if (delay < 0) { secureInterval.scheduleNow(); } else { if (delay > 15000) { delay = 15000; } if (delay < 1) { delay = 1; } secureInterval.schedule((int) delay); } } }); } @Override protected void notifyDispatcher() { if (!isDoingIteration) { secureInterval.scheduleNow(); } } protected long doIteration() { long time = ActorTime.currentTime(); DispatchResult action = getQueue().dispatch(time); if (action.isResult()) { dispatchMessage((T) action.getRes()); return -1; } else { if (action.getDelay() < 1) { return 1; } else { return action.getDelay(); } } } }
PHP
UTF-8
2,324
2.53125
3
[ "MIT" ]
permissive
<?php namespace AppBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Class Score * @ORM\Entity(repositoryClass="AppBundle\Repository\ScoreRepository") * @ORM\Table(name="score") */ class Score { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer", name="id") */ private $id; /** * @var Exam * * @ORM\ManyToOne(targetEntity="Exam") * @ORM\JoinColumn(name="exam_id", referencedColumnName="id") */ private $exam; /** * @var Question * @ORM\ManyToOne(targetEntity="Question") * @ORM\JoinColumn(name="question_id", referencedColumnName="id") */ private $question; /** * @var User * * @ORM\ManyToOne(targetEntity="User") * @ORM\JoinColumn(name="student_id", referencedColumnName="id") */ private $student; /** * @var boolean * @ORM\Column(type="boolean", name="is_good_ans", nullable=false) */ private $good; /** * @return bool */ public function isGood(): bool { return $this->good; } /** * @param bool $good * * @return Score */ public function setGood(bool $good): Score { $this->good = $good; return $this; } /** * @return mixed */ public function getId() { return $this->id; } /** * @return Exam */ public function getExam(): Exam { return $this->exam; } /** * @param Exam $exam * * @return Score */ public function setExam(Exam $exam): Score { $this->exam = $exam; return $this; } /** * @return Question */ public function getQuestion(): Question { return $this->question; } /** * @param Question $question * * @return Score */ public function setQuestion(Question $question): Score { $this->question = $question; return $this; } /** * @return User */ public function getStudent(): User { return $this->student; } /** * @param User $student * * @return Score */ public function setStudent(User $student): Score { $this->student = $student; return $this; } }
C
UTF-8
3,113
3.765625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> typedef struct _dllNode { int key; struct _dllNode* left; struct _dllNode* right; } DLLNode; typedef DLLNode* DoublyLinkedList; DoublyLinkedList addFront(DoublyLinkedList dll, int key) { if(dll == NULL) { dll = malloc(sizeof(DLLNode)); dll->key = key; dll->left = dll->right = NULL; return dll; } DoublyLinkedList temp = malloc(sizeof(DLLNode)); temp->key = key; temp->right = dll; temp->left = NULL; dll->left = temp; dll = temp; return dll; } void printList(DoublyLinkedList dll) { if(dll == NULL) { printf("The list is empty\n"); } else { printf("The Doubly linked list is: \n"); while(dll != NULL) { printf("%i ", dll->key); dll = dll->right; } } printf("\n"); } void findNode(DoublyLinkedList dll, int value) { int* arr = (int*) malloc(sizeof(int)); int len = 1, actLen = 0; if(dll == NULL) { printf("List is empty hence not found\n"); } else { int i=0; for(DoublyLinkedList temp = dll; temp != NULL; temp = temp->right, i++) { if(temp->key == value) { arr[actLen++] = i; if(actLen == len) { arr = (int*) realloc(arr, len * 2); len *= 2; } } } if(actLen == 0) { printf("No occurraces found\n"); return; } printf("The indices of all occurraces of %i are: \n", value); for(int i=0; i<actLen; i++) { printf("%i ", arr[i]); } printf("\n"); } } DoublyLinkedList deleteAllOccurrances(DoublyLinkedList dll, int value) { int* arr = (int*) malloc(sizeof(int)); int len = 1, actLen = 0; if(dll == NULL) { printf("List is empty hence not found\n"); } else { int i=0; for(DoublyLinkedList temp = dll; temp != NULL; temp = temp->right, i++) { // printf("i = %i\n", i); if(i == 0 && temp->key == value) { temp = temp->right; temp->left = NULL; dll = temp; } else if(temp->right == NULL && temp->key == value) { temp = temp->left; temp->right = NULL; } else if(temp->key == value) { //deletion code temp->right->left = temp->left; temp->left->right = temp->right; temp = temp->left; } else { continue; } arr[actLen++] = i; if(actLen == len) { arr = (int*) realloc(arr, len * 2); len *= 2; } // printList(dll); } if(actLen == 0) { printf("No deletions\n"); return dll; } printf("The deletions are done at the indices:\n"); for(int i=0; i<actLen; i++) { printf("%i ", arr[i]); } printf("\n"); } return dll; } DoublyLinkedList insertBefore(DoublyLinkedList dll, int value, int check) { if(dll == NULL) { printf("List is empty hence not added\n"); return dll; } for(DoublyLinkedList temp = dll; temp != NULL; temp = temp->right) { if(temp->key == check) { DoublyLinkedList temp2 = malloc(sizeof(DLLNode)); temp2->key = value; temp->left->right = temp2; temp2->left = temp->left; temp->left = temp2; temp2->right = temp; // printf("Insertion done\n"); return dll; } } printf("%i was not found hence %i is not being added\n", check, value); return dll; }
Java
UTF-8
826
2.203125
2
[]
no_license
package com.platacad.business; import java.util.List; import javax.annotation.Resource; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.stereotype.Controller; import com.platacad.model.entities.TrabajoEncargado; import com.platacad.model.enums.EstadoEntidad; import com.platacad.repositories.TrabajoRepository; @Controller public class TrabajoBusiness { @Resource TrabajoRepository trabajoRepository; public TrabajoEncargado registrarTrabajo(TrabajoEncargado trabajoEncargado) { trabajoEncargado.setEstado(EstadoEntidad.ACTIVO.getCodigo()); return trabajoRepository.save(trabajoEncargado); } public List<TrabajoEncargado> obtenerTrabajos(){ return trabajoRepository.findAll(new Sort(Direction.ASC,"fechaPresentacion")); } }
Markdown
UTF-8
1,704
3.015625
3
[]
no_license
# planning-poker Planning poker web app. ## Features - multiple, independent rooms can vote in parallel - real-time voting (via SSE -- no websockets required) - basic interface with no clutter or cruft - automatic room teardown when no users present ## Screenshots ![room list](/images/room-list.png) ![room view](/images/room.png) ![score](/images/score.png) ## Usage You can create a new room from the room list view. Alternatively, just visit any room name directly in the URL (ie, if you want to make a room named `Red`, just goto `poker-app.url/Red`). This allows you to bookmark common rooms even if it's not currently active (and thus not listed on in the room list). The top right text in the room view will let you know how many other people are there with you. To add a task to vote on, click the blockquote near the top of the page to enable edit mode. Once you are done, click Save to present the task to everyone in the room. Anyone in the room can edit the current task by clicking on the blockquote. While editing the task, you may cancel by pressing ESC or save by pressing Ctrl + Enter. a name must be present to vote. The name you typed in is saved to `localStorage`, so your browser will remember your name the next time you use the poker app. To vote, select one of the fibonacci numbers and click Submit. To reset all votes, edit the current task and click Save. All task edits, even if the task content doesn't actually change, will reset all votes. The app will automatically remove the room from the list once everyone has abandoned it. ## Tech - Node server - Express API - sse-node real-time connections/messaging - Intercooler client-side interactions with API
Java
UTF-8
3,344
2.953125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sserver; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; /** *name is mistaken--sserver but actually this is client side * @author igloo */ public class Sserver implements Runnable,ActionListener{ private JFrame jfm; // private ServerSocket serverSocket; private Socket socket; private ObjectInputStream ois; private ObjectOutputStream oos; private JTextArea jta; private JScrollPane jscrlp; private JTextField jtfInput; private JButton jbtnSend; public Sserver(){ jfm=new JFrame("Chat client"); jfm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jfm.setLayout(new FlowLayout()); jfm.setSize(300, 320); Thread myThread=new Thread(this); myThread.start(); jta=new JTextArea(15, 15); jta.setEditable(false); jta.setLineWrap(true); jscrlp=new JScrollPane(jta); jtfInput=new JTextField(15); jtfInput.addActionListener(this); jbtnSend=new JButton("Send"); jbtnSend.addActionListener(this); jfm.getContentPane().add(jscrlp); jfm.getContentPane().add(jtfInput); jfm.getContentPane().add(jbtnSend); jfm.setVisible(true); } @Override public void run(){ try{ socket=new Socket("localhost", 4444); //socket=serverSocket.accept(); oos=new ObjectOutputStream(socket.getOutputStream()); ois=new ObjectInputStream(socket.getInputStream()); while(true){ //client receive message from this Object input=ois.readObject(); jta.setText(jta.getText()+"Server says:"+(String)input+"\n"); } } catch(IOException e){ e.printStackTrace(); } catch(ClassNotFoundException e){ e.printStackTrace(); } } public void actionPerformed(ActionEvent ae){ if(ae.getActionCommand().equals("Send") || ae.getSource() instanceof JTextField){ try{ oos.writeObject(jtfInput.getText()); jta.setText(jta.getText()+"You say:"+jtfInput.getText()+"\n"); } catch(IOException e){ e.printStackTrace(); } } } /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here SwingUtilities.invokeLater(new Runnable(){ @Override public void run(){ new Sserver(); // System.out.println("hi"); } }); } }
Go
UTF-8
4,631
2.96875
3
[ "Apache-2.0" ]
permissive
/************************************************************************************ **Author:  Axe Tang; Email: axetang@163.com **Package: net **Element: net.Resolver **Type: struct ------------------------------------------------------------------------------------ **Definition: type Resolver struct { // PreferGo controls whether Go's built-in DNS resolver is preferred // on platforms where it's available. It is equivalent to setting // GODEBUG=netdns=go, but scoped to just this resolver. PreferGo bool // StrictErrors controls the behavior of temporary errors // (including timeout, socket errors, and SERVFAIL) when using // Go's built-in resolver. For a query composed of multiple // sub-queries (such as an A+AAAA address lookup, or walking the // DNS search list), this option causes such errors to abort the // whole query instead of returning a partial result. This is // not enabled by default because it may affect compatibility // with resolvers that process AAAA queries incorrectly. StrictErrors bool // Dial optionally specifies an alternate dialer for use by // Go's built-in DNS resolver to make TCP and UDP connections // to DNS services. The host in the address parameter will // always be a literal IP address and not a host name, and the // port in the address parameter will be a literal port number // and not a service name. // If the Conn returned is also a PacketConn, sent and received DNS // messages must adhere to RFC 1035 section 4.2.1, "UDP usage". // Otherwise, DNS messages transmitted over Conn must adhere // to RFC 7766 section 5, "Transport Protocol Selection". // If nil, the default dialer is used. Dial func(ctx context.Context, network, address string) (Conn, error) // contains filtered or unexported fields } func (r *Resolver) LookupAddr(ctx context.Context, addr string) (names []string, err error) func (r *Resolver) LookupCNAME(ctx context.Context, host string) (cname string, err error) func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error) func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error) func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error) func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error) func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error) func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (cname string, addrs []*SRV, err error) func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error) ------------------------------------------------------------------------------------ **Description: A Resolver looks up names and numbers. A nil *Resolver is equivalent to a zero Resolver. LookupAddr performs a reverse lookup for the given address, returning a list of names mapping to that address. LookupCNAME returns the canonical name for the given host. Callers that do not care about the canonical name can call LookupHost or LookupIP directly; both take care of resolving the canonical name as part of the lookup. A canonical name is the final name after following zero or more CNAME records. LookupCNAME does not return an error if host does not contain DNS "CNAME" records, as long as host resolves to address records. LookupHost looks up the given host using the local resolver. It returns a slice of that host's addresses. LookupIPAddr looks up host using the local resolver. It returns a slice of that host's IPv4 and IPv6 addresses. LookupMX returns the DNS MX records for the given domain name sorted by preference. LookupNS returns the DNS NS records for the given domain name. LookupPort looks up the port for the given network and service. LookupSRV tries to resolve an SRV query of the given service, protocol, and domain name. The proto is "tcp" or "udp". The returned records are sorted by priority and randomized by weight within a priority. LookupSRV constructs the DNS name to look up following RFC 2782. That is, it looks up _service._proto.name. To accommodate services publishing SRV records under non-standard names, if both service and proto are empty strings, LookupSRV looks up name directly. LookupTXT returns the DNS TXT records for the given domain name. ------------------------------------------------------------------------------------ **要点总结: *************************************************************************************/ package main func main() { }
C#
UTF-8
3,179
2.734375
3
[ "MIT" ]
permissive
using System; using System.IO; namespace ParallelStacks.Runtime { public static class ConsoleApp { public static void Run(string name, string version, string[] args) { if (args.Length == 0) { ShowHelp(name, version, "Missing dump file path or process ID..."); return; } string dacFilePath = (args.Length >= 2) ? args[1] : null; if (dacFilePath != null) { if (!File.Exists(dacFilePath)) { Console.WriteLine($"{dacFilePath} file does not exist..."); return; } } ParallelStack ps; var input = args[0]; // attach to live process if (int.TryParse(input, out var pid)) { try { ps = ParallelStack.Build(pid, dacFilePath); } catch (InvalidOperationException x) { Console.WriteLine($"Impossible to build call stacks: {x.Message}"); return; } } // open memory dump else { if (!File.Exists(input)) { Console.WriteLine($"'{input}' does not exist..."); return; } try { ps = ParallelStack.Build(input, dacFilePath); } catch (InvalidOperationException x) { Console.WriteLine($"Impossible to build call stacks: {x.Message}"); return; } } int threadIDsCountlimit = 4; var visitor = new ConsoleRenderer(useDml: false, limit: threadIDsCountlimit); Console.WriteLine(); foreach (var stack in ps.Stacks) { Console.Write("________________________________________________"); stack.Render(visitor); Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); } Console.WriteLine($"==> {ps.ThreadIds.Count} threads with {ps.Stacks.Count} roots{Environment.NewLine}"); } static void ShowHelp(string name, string version, string message) { Console.WriteLine(string.Format(Header, name, version)); if (!string.IsNullOrEmpty(message)) { Console.WriteLine(); Console.WriteLine(message); } Console.WriteLine(); Console.WriteLine(Help, name); } private static string Header = "{0} v{1} - Parallel Stacks" + Environment.NewLine + "by Christophe Nasarre" + Environment.NewLine + "Aggregate the threads callstacks a la Visual Studio 'Parallel Stacks'"; private static string Help = "Usage: {0} <dump file path or process ID> [dac file path if any]" + Environment.NewLine + ""; } }
Java
UTF-8
1,313
2.53125
3
[]
no_license
package net.highwayfrogs.editor.file.map.entity.data.retro; import lombok.Getter; import lombok.Setter; import net.highwayfrogs.editor.file.map.entity.data.MatrixData; import net.highwayfrogs.editor.file.reader.DataReader; import net.highwayfrogs.editor.file.writer.DataWriter; import net.highwayfrogs.editor.gui.GUIEditorGrid; /** * Represents "ORG_BABY_FROG_DATA", which is the data for the pink frog you can pickup on the retro logs. * Created by Kneesnap on 11/27/2018. */ @Getter @Setter public class EntityBabyFrog extends MatrixData { private short logId; // The id of the log this frog will stand on. private short awardedPoints; // The points awarded when collected. @Override public void load(DataReader reader) { super.load(reader); this.logId = reader.readShort(); this.awardedPoints = reader.readShort(); } @Override public void save(DataWriter writer) { super.save(writer); writer.writeShort(this.logId); writer.writeShort(this.awardedPoints); } @Override public void addData(GUIEditorGrid editor) { super.addData(editor); editor.addShortField("Log ID", getLogId(), this::setLogId, null); editor.addShortField("Points", getAwardedPoints(), this::setAwardedPoints, null); } }
PHP
UTF-8
1,024
3.890625
4
[]
no_license
<?php class Movie { private $name = null; private $description = "une description"; private $duration = 120; public function __construct($name = "", $description= "", $duration = "") { $this->name = $name; $this->description = $description; $this->duration = $duration; } public function getName() { return $this->name; } public function setName($name = "") { $this->name = $name; } public function getDescription() { return $this->description; } public function setDescription($description = "") { $this->description = $description; } public function getDuration() { return $this->duration; } public function setDuration($duration = "") { $this->duration = $duration; } } $movie = new Movie("Mon film","C'est bien",123); echo $movie->getName().'<br>'.$movie->getDescription().'<br>'.$movie->getDuration();//ez
JavaScript
UTF-8
418
3.921875
4
[]
no_license
//Given 2 arrays and an index //Copy each element of 1st array into 2nd array in order //Begin inserting at index n of 2nd array // The input arrays should remain unchanged function frankenSplice(arr1, arr2, n) { var arr3 = arr2.slice(); //copy original arr2 so don't change it arr3.splice(n,0,...arr1); //spread to do whole arr1 without loop return arr3; } frankenSplice([1, 2, 3], [4, 5, 6], 1);
Java
UTF-8
8,280
1.796875
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 Phil Shadlyn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.physphil.android.unitconverterultimate.settings; import android.content.ActivityNotFoundException; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceFragment; import android.widget.Toast; import com.physphil.android.unitconverterultimate.AcknowledgementsActivity; import com.physphil.android.unitconverterultimate.BuildConfig; import com.physphil.android.unitconverterultimate.R; import com.physphil.android.unitconverterultimate.UnitConverterApplication; import com.physphil.android.unitconverterultimate.models.Language; import com.physphil.android.unitconverterultimate.util.IntentFactory; import java.util.Arrays; import java.util.Comparator; /** * Fragment to display preferences screen * Created by Phizz on 15-08-02. */ public class PreferencesFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { private static final String GITHUB_ISSUE = "https://github.com/physphil/UnitConverterUltimate/issues"; private static final String PRIVACY_POLICY = "https://privacypolicies.com/privacy/view/f7a41d67f1b0081f249c2ff0a3123136"; public static PreferencesFragment newInstance() { return new PreferencesFragment(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Add listeners to preferences Preference rateApp = findPreference("rate_app"); rateApp.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { rateApp(); return true; } }); Preference openIssue = findPreference("open_issue"); openIssue.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openIssue(); return true; } }); Preference viewSource = findPreference("view_source"); viewSource.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { viewSource(); return true; } }); Preference privacy = findPreference("privacy_policy"); privacy.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openPrivacyPolicy(); return true; } }); Preference donate = findPreference("donate"); if (BuildConfig.FLAVOR.equals(UnitConverterApplication.BUILD_FLAVOUR_GOOGLE)) { donate.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { startActivity(IntentFactory.getDonateIntent(getActivity())); return true; } }); } else { ((PreferenceCategory) findPreference("other")).removePreference(donate); } Preference acknowledgements = findPreference("acknowledgements"); acknowledgements.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { AcknowledgementsActivity.start(getActivity()); return true; } }); final ListPreference language = (ListPreference) findPreference("language"); sortLanguageOptions(language); } @Override public void onResume() { super.onResume(); Preferences.getInstance(getActivity()).getPreferences().registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { super.onPause(); Preferences.getInstance(getActivity()).getPreferences().unregisterOnSharedPreferenceChangeListener(this); } private void requestUnit() { try { startActivity(IntentFactory.getRequestUnitIntent(getString(R.string.request_unit))); } catch (ActivityNotFoundException ex) { Toast.makeText(getActivity(), R.string.toast_error_no_email_app, Toast.LENGTH_SHORT).show(); } } private void rateApp() { try { startActivity(IntentFactory.getOpenPlayStoreIntent(getActivity().getPackageName())); } catch (ActivityNotFoundException ex) { Toast.makeText(getActivity(), R.string.toast_error_google_play, Toast.LENGTH_SHORT).show(); } } private void viewSource() { try { startActivity(IntentFactory.getOpenUrlIntent(IntentFactory.GITHUB_REPO)); } catch (ActivityNotFoundException ex) { Toast.makeText(getActivity(), R.string.toast_error_no_browser, Toast.LENGTH_SHORT).show(); } } private void openIssue() { try { startActivity(IntentFactory.getOpenUrlIntent(GITHUB_ISSUE)); } catch (ActivityNotFoundException ex) { Toast.makeText(getActivity(), R.string.toast_error_no_browser, Toast.LENGTH_SHORT).show(); } } private void openPrivacyPolicy() { try { startActivity(IntentFactory.getOpenUrlIntent(PRIVACY_POLICY)); } catch (ActivityNotFoundException ex) { Toast.makeText(getActivity(), R.string.toast_error_no_browser, Toast.LENGTH_SHORT).show(); } } private void sortLanguageOptions(final ListPreference preference) { // Sort language options so they're always alphabetical, no matter what language the user has chosen final Language[] languages = Language.values(); Arrays.sort(languages, new Comparator<Language>() { @Override public int compare(Language lang1, Language lang2) { // Always put DEFAULT at top of list, then sort the rest alphabetically if (lang1 == Language.DEFAULT) { return Integer.MIN_VALUE; } else if (lang2 == Language.DEFAULT) { return Integer.MAX_VALUE; } else { return getString(lang1.getDisplayStringId()).compareTo(getString(lang2.getDisplayStringId())); } } }); // Create CharSequence[] arrays from the sorted list of Languages to supply to ListPreference final int size = languages.length; final CharSequence[] entries = new CharSequence[size]; final CharSequence[] entryValues = new CharSequence[size]; for (int i = 0; i < size; i++) { entries[i] = getString(languages[i].getDisplayStringId()); entryValues[i] = languages[i].getId(); } preference.setEntries(entries); preference.setEntryValues(entryValues); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(Preferences.PREFS_THEME)) { // Theme change, restart all open activities and reload with new theme getActivity().finish(); } } }
PHP
UTF-8
4,457
2.640625
3
[]
no_license
<?php class Widget_Static_Text extends Widget_Tag { public function getCategory() { return 'Static'; } public function getName() { return 'Text'; } public function getContext() { return ''; } /** * * @return array */ public function getTemplates() { $arrTemplates = array(); if ( is_object( App_Application::getInstance()->getConfig()->widgets->contexts ) ) { $lstContexts = App_Application::getInstance()->getConfig()->widgets->contexts; foreach ( $lstContexts as $strNameContext => $strSlugContext ) { if ( $strSlugContext == 'header' || $strSlugContext == 'sidebar-right' || $strSlugContext == 'footer' ) { $arrTemplates[ $strSlugContext ] = $strNameContext; } } } return $arrTemplates; } /** * * @param string $strName * @return string */ public function getTemplateContent( $strName, $bPreview ) { $strContent = ''; $view = new App_View(); $objContext = Widget_Context::Table()->fetchByName( $strName ); if (is_object($objContext) ) { $strContent = $objContext->render( $view, $bPreview ); } return $strContent; } /** * * @return array */ public function getOptions() { $arrData = array( array( 'name' => 'text-align', 'type' => 'dropdown', 'value' => 'center', 'width' => '120px', 'options' => array( 'left' => 'Left', 'center' => 'Center', 'right' => 'Right' ), 'caption' => 'Text Align' ) , array( 'name' => 'font-size', 'type' => 'dropdown', 'value' => '12', 'width' => '80px', 'options' => array( '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', '13' => '13', '14' => '14', '16' => '16', '18' => '18', '20' => '20', '22' => '22', '24' => '24', '26' => '26', '28' => '28', '30' => '30', '32' => '32', '36' => '36', '40' => '40', '48' => '48', '64' => '64', '72' => '72' ), 'caption' => 'Font size' ) , array( 'name' => 'content', 'type' => 'html', 'value' => 'Static Text', 'caption' => 'Content' ) , array( 'name' => 'cssclass', 'type' => 'text', 'value' => '', 'caption' => 'CSS Class' ) , array( 'name' => 'css', 'type' => 'css', 'value' => '', 'caption' => 'Additional CSS' ) ); $arrTemplates = $this->getTemplates(); if ( count( $arrTemplates ) ) { $arrData[] = array( 'name' => 'tpl', 'type' => 'dropdown', 'value' => '', 'options' => array( '' => 'No Template' ) + $arrTemplates, 'caption' => 'Template' ); } return $arrData; } /** * Routine to render a widget * @param App_View $view * @param boolean $bPreview * @return string */ public function render( App_View $view, $bPreview = false ) { // $objForm = $this->getPaymentForm(); // if ( $this->get( 'text-align') ) $this->arrStyles['text-align'] = $this->get( 'text-align', 'center'); if ( $this->get( 'font-size') ) { $this->arrStyles['font-size'] = $this->get( 'font-size').'px'; $this->arrStyles['line-height'] = ($this->get( 'font-size') + 4 ).'px'; } $this->arrClasses[ $this->get( 'cssclass' ) ] = $this->get( 'cssclass' ); $strContent = $this->get( 'content', '' ); if ( $this->get('tpl') != '' ) { $strContent = $this->getTemplateContent( $this->get('tpl'), $bPreview ); } $strOut = $this->getTagHtml( 'div', ' '.$strContent.' ', $this->get('css') ); if ( $bPreview ) { $strOut = $this->getConstructorHtml ( $strOut ); } return $strOut; } }
Swift
UTF-8
888
3.734375
4
[]
no_license
// // PriorityQueue.swift // Otus_algo // // Created by Alexander Kraev on 22.02.2021. // import Foundation protocol PriorityQueueProtocol { associatedtype Item func size() -> Int ///поместить элемент в очередь mutating func enqueue(priority: Int, item: Item) ///выбрать элемент из очереди mutating func dequeue() -> Item? } struct PriorityQueue<Element>: PriorityQueueProtocol { typealias Item = Element var items = [(priority: Int, item: Element)]() func size() -> Int { items.count } mutating func enqueue(priority: Int, item: Element) { items.append((priority, item)) items = items.sorted(by: { $0.priority < $1.priority }) } mutating func dequeue() -> Element? { items.removeLast().item } }
Java
UTF-8
10,491
1.945313
2
[ "Apache-2.0" ]
permissive
package com.anjlab.eclipse.tapestry5.internal.visitors; import org.apache.commons.lang3.StringUtils; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jdt.core.IAnnotation; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.TypeLiteral; import org.eclipse.jdt.core.search.IJavaSearchConstants; import com.anjlab.eclipse.tapestry5.Activator; import com.anjlab.eclipse.tapestry5.DeclarationReference.ASTNodeReference; import com.anjlab.eclipse.tapestry5.EclipseUtils; import com.anjlab.eclipse.tapestry5.ObjectCallback; import com.anjlab.eclipse.tapestry5.TapestryModule; import com.anjlab.eclipse.tapestry5.TapestryService; import com.anjlab.eclipse.tapestry5.TapestryService.ServiceDefinition; import com.anjlab.eclipse.tapestry5.TapestryUtils; public class TapestryServiceCapturingVisitor extends ASTVisitor { private final IProgressMonitor monitor; private final TapestryModule tapestryModule; private final ObjectCallback<TapestryService, RuntimeException> serviceFound; private ServiceDefinition serviceDefinition; public TapestryServiceCapturingVisitor(IProgressMonitor monitor, TapestryModule tapestryModule, ObjectCallback<TapestryService, RuntimeException> serviceFound) { this.monitor = monitor; this.tapestryModule = tapestryModule; this.serviceFound = serviceFound; } private ServiceDefinition serviceDefinition() { if (serviceDefinition == null) { serviceDefinition = new ServiceDefinition(); } return serviceDefinition; } private boolean analyzeInvocationChain(MethodInvocation node) { if (node.getExpression() instanceof MethodInvocation) { visit((MethodInvocation) node.getExpression()); } else { // Unsupported method chain, drop captured service definition serviceDefinition = null; } return false; } @Override public boolean visit(MethodInvocation node) { if (monitor.isCanceled()) { return false; } String identifier = node.getName().getIdentifier(); if ("withMarker".equals(identifier)) { // Copy annotations from module class serviceDefinition().addMarkers(tapestryModule.markers()); for (Object arg : node.arguments()) { if (arg instanceof TypeLiteral) { serviceDefinition().addMarker( EclipseUtils.toClassName(tapestryModule.getEclipseProject(), (TypeLiteral) arg)); } } return analyzeInvocationChain(node); } else if ("preventReloading".equals(identifier)) { serviceDefinition().setPreventReloading(true); return analyzeInvocationChain(node); } else if ("preventDecoration".equals(identifier)) { serviceDefinition().setPreventDecoration(true); return analyzeInvocationChain(node); } else if ("eagerLoad".equals(identifier)) { serviceDefinition().setEagerLoad(true); return analyzeInvocationChain(node); } else if ("scope".equals(identifier)) { if (node.arguments().size() == 1) { serviceDefinition().setScope( EclipseUtils.evalExpression( tapestryModule.getEclipseProject(), node.arguments().get(0))); } return analyzeInvocationChain(node); } else if ("withId".equals(identifier)) { if (node.arguments().size() == 1) { serviceDefinition().setId( EclipseUtils.evalExpression( tapestryModule.getEclipseProject(), node.arguments().get(0))); } return analyzeInvocationChain(node); } else if ("withSimpleId".equals(identifier)) { serviceDefinition().setSimpleId(true); return analyzeInvocationChain(node); } else if ("bind".equals(identifier)) { bind(node); serviceDefinition = null; return false; } return super.visit(node); } private void bind(MethodInvocation node) { String intfClass = null; String implClass = null; switch (node.arguments().size()) { case 2: // Interface, Implementation intfClass = typeLiteralToClassName(node.arguments().get(0)); implClass = typeLiteralToClassName(node.arguments().get(1)); break; case 1: // Check if it's actually an interface, or a non-interface class // It it's an interface, then name of implementation class can be computed String className = typeLiteralToClassName(node.arguments().get(0)); // TODO Implement caching for type lookups IType type = EclipseUtils.findTypeDeclaration( tapestryModule.getEclipseProject(), IJavaSearchConstants.CLASS_AND_INTERFACE, className); if (type == null) { // Something is wrong with this service binding Activator.getDefault().logError("Unable to find java type: " + className); return; } try { if (type.isInterface()) { intfClass = type.getFullyQualifiedName(); implClass = intfClass + "Impl"; } else { implClass = type.getFullyQualifiedName(); } break; } catch (JavaModelException e) { Activator.getDefault().logError("Unable to read java model", e); return; } default: Activator.getDefault().logWarning("Unexpected method signature: " + node); return; } ServiceDefinition definition = serviceDefinition(); definition.setIntfClass(intfClass); definition.setImplClass(implClass); if (definition.isSimpleId()) { if (StringUtils.isNotEmpty(definition.getImplClass())) { definition.setId(TapestryUtils.getSimpleName(definition.getImplClass())); } } else if (StringUtils.isEmpty(definition.getId())) { // Try getting serviceId from @ServiceId & @Named annotations on implementation class // see tapestry's ServiceBinderImpl#bind() for details String serviceId = readServiceIdFromAnnotations(definition.getImplClass()); String classNameForServiceId = StringUtils.defaultIfEmpty( // In tapestry it's not possible to have null interface, // it's plugin's implementation detail -- // should fallback to implClass in this case definition.getIntfClass(), definition.getImplClass()); definition.setId( StringUtils.defaultIfEmpty( serviceId, StringUtils.isNotEmpty(classNameForServiceId) ? TapestryUtils.getSimpleName(classNameForServiceId) : null)); } if (StringUtils.isEmpty(definition.getId())) { // Something is wrong with this service definition // Maybe that was not ServiceBinder#bind(), but some other `bind` method? return; } definition.resolveMarkers(tapestryModule); serviceFound.callback(new TapestryService( tapestryModule, definition, new ASTNodeReference(tapestryModule, tapestryModule.getModuleClass(), node))); } private String readServiceIdFromAnnotations(String implClass) { try { IType implType = EclipseUtils.findTypeDeclaration( tapestryModule.getEclipseProject(), IJavaSearchConstants.CLASS, implClass); if (implType == null) { return null; } IAnnotation serviceIdAnnotation = TapestryUtils.findAnnotation( implType.getAnnotations(), TapestryUtils.ORG_APACHE_TAPESTRY5_IOC_ANNOTATIONS_SERVICE_ID); if (serviceIdAnnotation != null) { return EclipseUtils.readFirstValueFromAnnotation( tapestryModule.getEclipseProject(), serviceIdAnnotation, "value"); } IAnnotation namedAnnotation = TapestryUtils.findAnnotation( implType.getAnnotations(), TapestryUtils.JAVAX_INJECT_NAMED); if (namedAnnotation != null) { return StringUtils.trimToNull( EclipseUtils.readFirstValueFromAnnotation( tapestryModule.getEclipseProject(), namedAnnotation, "value")); } } catch (JavaModelException e) { Activator.getDefault().logError("Error determining ServiceId from implementation class", e); } return null; } private String typeLiteralToClassName(Object node) { if (node instanceof TypeLiteral) { return EclipseUtils.toClassName(tapestryModule.getEclipseProject(), (TypeLiteral) node); } return null; } }
Java
UTF-8
3,732
2.953125
3
[]
no_license
package org.rainbow.service.services; import java.util.List; import org.rainbow.criteria.Predicate; import org.rainbow.criteria.SearchOptions; /** * Interface representing the service layer. It focuses on tasks, such as * coordinating business logic, demarcating transactions, applying security * restrictions, doing validations, and so on. The service layer individually * requests data access operations from the data access layer, or DAO layer for * short; and data access-specific implementation details are completely hidden * behind its interface. Service objects depend on one or several different data * access objects through their interfaces, and they make use of those DAO * objects while executing their business tasks at hand. * * @author Biya-Bi * * @param <TEntity> * the type of the entity serviced by this layer. */ public interface Service<TEntity extends Object> { /** * Create an entity * * @param entity * the entity to be added. * @throws Exception * if an error occurs while creating the entity * */ void create(TEntity entity) throws Exception; /** * Update an entity * * @param entity * the entity to be updated. * @throws Exception * if an error occurs while updating the entity * */ void update(TEntity entity) throws Exception; /** * Delete an entity * * @param entity * the entity to be deleted. * @throws Exception * if an error occurs while deleting the entity * */ void delete(TEntity entity) throws Exception; /** * Get an entity by id * * @param id * the ID of the entity to be searched. * @return a {@code TEntity} whose ID is supplied as argument. * @throws Exception * if an error occurs while searching the entity with the given * ID * */ TEntity findById(Object id) throws Exception; /** * Get all entities * * @throws Exception * if an error occurs while searching all the entities * */ List<TEntity> findAll() throws Exception; /** * Get entities that satisfy the specified {@link SearchOptions}. * * @param options * the search options used to search for the entities * @return the entities that satisfy the specified search options * @throws Exception * if an error occurs while searching the entities */ List<TEntity> find(SearchOptions options) throws Exception; /** * Get count of entities that satisfy the specified {@link Predicate}. * * @param predicate * the predicate used to count the entities * @return the number of entities that satisfy the specified search options * @throws Exception * if an error occurs while counting the entities */ long count(Predicate predicate) throws Exception; /** * Create entities * * @param entities * the entities to be added. * @throws Exception * if an error occurs while creating the entities * */ void create(List<TEntity> entities) throws Exception; /** * Update entities * * @param entities * the entities to be updated. * @throws Exception * if an error occurs while updating the entities * */ void update(List<TEntity> entities) throws Exception; /** * Delete entities * * @param entities * the entities to be deleted. * @throws Exception * if an error occurs while deleting the entities * */ void delete(List<TEntity> entities) throws Exception; }
Java
UTF-8
278
1.921875
2
[]
no_license
package com.le.rpc.enumeration; import lombok.AllArgsConstructor; import lombok.Getter; /** * @Author happy_le * @date 2021/2/20 下午12:00 */ @AllArgsConstructor @Getter public enum PackageType { REQUEST_PACK(0), RESPONSE_PACK(1); private final int code; }
Java
UTF-8
699
1.960938
2
[]
no_license
package ksbysample.webapp.email.test; import org.junit.rules.ExternalResource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; @Component public class MockMvcResource extends ExternalResource { @Autowired private WebApplicationContext context; public MockMvc nonauth; @Override protected void before() throws Throwable { this.nonauth = MockMvcBuilders.webAppContextSetup(this.context) .build(); } }
Python
UTF-8
651
2.859375
3
[]
no_license
''' Created on Mar 19, 2019 @author: Gabriel Torrandella ''' import pytest import xmlschema from xmlschema.etree import ParseError class TestXML(object): def test_Invalid_Schema(self): with pytest.raises(ParseError) as excinfo: xmlschema.XMLSchema("formacion_invalido.xsd") print("ParseError: %s" % excinfo.value) def test_is_Valid_XML(self): XSFormacion = xmlschema.XMLSchema("BancoSchema.xsd") assert XSFormacion.is_valid("Banco.xml") def test_is_Invalid_XML(self): XSFormacion = xmlschema.XMLSchema("BancoSchema.xsd") assert not XSFormacion.is_valid("Banco_Invalido.xml")
Java
UTF-8
864
2.25
2
[]
no_license
package org.darkquest.gs.phandler.ls; import org.darkquest.gs.connection.LSPacket; import org.darkquest.gs.connection.Packet; import org.darkquest.gs.model.Player; import org.darkquest.gs.phandler.PacketHandler; import org.darkquest.gs.util.Logger; import org.darkquest.gs.world.World; import org.jboss.netty.channel.Channel; public class ForceLogout implements PacketHandler { /** * World instance */ public static final World world = World.getWorld(); public void handlePacket(Packet p, Channel session) throws Exception { long uID = ((LSPacket) p).getUID(); Logger.event("LOGIN_SERVER requested player logout (uID: " + uID + ")"); Player player = world.getPlayer(p.readLong()); if (player != null) { player.getActionSender().sendLogout(); player.destroy(true); } } }
PHP
UTF-8
889
2.65625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; use App\Models\Review; use App\Models\Rating; class ReviewSeeder extends Seeder { /** * Run the admin seeder. * * @return void */ public function run() { // Create an instance of Faker $faker = Faker\Factory::create(); for ($i=0;$i<100;$i++){ // Create a review $review = Review::create([ 'title' => $faker->text(80), 'content' => $faker->text(600), 'thing_id' => $faker->numberBetween(1,100), 'user_id' => $faker->numberBetween(1,3) ]); // Then save rating $rating = [ 'rating' => $faker->numberBetween(1,5), 'user_id' => $review->user_id ]; $review->find($review->id)->rating()->save(new Rating($rating)); } } }
PHP
UTF-8
626
2.609375
3
[ "MIT" ]
permissive
<?php namespace Pishran\LaravelPersianString; trait HasPersianString { public static function bootHasPersianString() { $ps = app('PersianString'); static::saving(function ($model) use ($ps) { foreach ($model->getPersianStrings() as $persianString) { if (is_string($model->{$persianString})) { $model->{$persianString} = $ps->convert($model->{$persianString}); } } }); } public function getPersianStrings() { return property_exists($this, 'persianStrings') ? $this->persianStrings : []; } }
Java
UTF-8
904
4.15625
4
[ "Apache-2.0" ]
permissive
package atUniProMaven.array; import java.util.Scanner; /** * 1. Input an integer array and output it to the console */ public class Task1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 1. Input the length of a new array: System.out.print("Input the length of the array: "); int n = scanner.nextInt(); // 2. Create the array with n elements: int myArray[] = new int[n]; // 3. Fill the array with data for (int i = 0; i < myArray.length; i++) { System.out.print("Input " + i + " element: "); myArray[i] = scanner.nextInt(); } // 4. PrintInterface the array to the console: for (int i = 0; i < myArray.length; i++) { System.out.print(myArray[i] + " "); } System.out.println(); scanner.close(); } }
Python
UTF-8
407
2.984375
3
[]
no_license
from model.Neighbourhoods.NeighbourhoodBase import NeighbourhoodBase class HexagonalRight(NeighbourhoodBase): def _set_neighbours(self): self._append_neighbour(-1, 0) self._append_neighbour(-1, 1) self._append_neighbour(0, -1) self._append_neighbour(0, 0) self._append_neighbour(0, 1) self._append_neighbour(1, -1) self._append_neighbour(1, 0)
Markdown
UTF-8
4,113
2.828125
3
[]
no_license
--- title: 使用Nginx进行反向代理用于解决前端跨域问题 date: 2017-09-16 23:24:15 tags: server categories: 服务器 description: 解决跨域问题 --- #使用Nginx进行反向代理用于解决前端跨域问题 最近写完了静态,准备向后端拿API直接拿数据做渲染测试,但是却因为跨域问题,造成了浏览器无法获取后端获取的数据 具体报错如下: XMLHttpRequest cannot load http://www.example.com No 'Access-Control-Allow-Origin' header is present on the requested resource. 这个问题也一直干扰我很久了,也用过诸如JSONP,后端设置CORS等方法。 **这次最开始的想法是:**因为跨域限制仅存在于浏览器,而真正的后端(java)由于安全考虑是不会设置CORS的,那么我就通过一个node中间层去获取java后端的数据,然后在node设置CROS,这样我前端直接请求node的话,是可以拿到数据的。 具体的一次request-response为: ![](https://git.oschina.net/vueman/md_pic/raw/master/technote/node-java.png) 1. **前端请求node** 2. **node接受请求,并向java请求** 3. **java返回给node数据** 4. **node返回给前端** 当时想着正好可以练下Node,就没有考虑其他更好的解决方案,也马上开始用express搭了一个简陋的node,然后跑了一下,数据能拿到。好的,没问题了。 接下来的半天继续根据后台的api写着路由,拿数据没有任何的问题,当涉及到登录保存token的时候,**问题终于出现了:** 当写到登录/注册的时候采用的是**token验证**,后端在`http response body` 里面回传**token**,并且在`response header里设置set-cookie`,我当然想着`node`拿到**token**并且在响应前端请求的时候在`header`里写入`set-cookie`就可以了,**但是,又出现了跨域问题**: **先解释下什么`同域`的要求** 1. 协议相同 2. 域名相同 3. 端口相同 我的node服务在本地的3000端口,前端静态文件服务在1258端口,这就造成了`set-cookie`因跨域问题而造成的set失败,node无法跨域给1258端口set-cookie,从而无法实现`token登录验证` >(虽然可以通过sessionStorage/localStorage的方法间接实现token认证,但是走到这里,基本上算是小题大作了,杀鸡用了宰牛刀) > 没办法只能请教boss了,boss给我介绍了nginx,简直就是跨域问题的大杀器。 **回到正题,nginx是什么** 来自百度百科:`Nginx (engine x) 是一个高性能的HTTP和反向代理服务器。` **先说说什么是正向/反向代理** 1. **正向代理**:代理网络用户去取得网络信息。形象的说:它是网络信息的中转站。 2. **反向代理**:代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器。 >按照我的理解,正向代理就像是你找一跑腿的帮你取快递而不用自己去,反向代理则像是你给10086打电话的时候,10086帮你分配接线员一样的模式。值得注意的是,正向代理的话,服务器无法知道你的真实IP,反向代理的话,用户是无法知道究竟是哪一台服务器在为他服务。 **所以,为什么nginx可以解决跨域问题?** 因为现在我可以这么做: 1. 让前端路由的所有路径都在`~/static/*`下,全部转发至前端静态文件的1258端口 2. 让node的服务放在`~/server/*`下,也可以直接`~/*`,全部转发至3000端口 最后`nginx`做服务器容器(例如监听80端口)开启的服务使得两者被整合到了同域(因为满足同协议,域名,端口) **甚至,直接废掉写的node服务** 1. 前端监听端口不变 2. `/*`直接代理转发至java后台,根本不存在跨域问题 **分析** **配置流程** [网上教程一大堆](http://jingyan.baidu.com/article/fdbd4277d2acfdb89e3f48a3.html) **配置文件解释** ![](https://git.oschina.net/vueman/md_pic/raw/master/technote/nginx1.png) ![](https://git.oschina.net/vueman/md_pic/raw/master/technote/nginx2.png)
Python
UTF-8
416
2.84375
3
[]
no_license
import matplotlib.pyplot as plt import pandas as pd data = pd.read_csv('Scatter_plot.csv') view = data['view_count'] likes = data['likes'] ratio = data['ratio'] plt.style.use("dark_background") plt.scatter(view,likes,edgecolors='black',cmap='winter',c=ratio) plt.xscale('log') plt.yscale("log") plt.title("Youtube Trending Videos") plt.tight_layout() cbar = plt.colorbar() cbar.set_label("Views : Likes") plt.show()
Java
UTF-8
27,685
1.578125
2
[]
no_license
package transporte.controller.gestion; import java.io.Serializable; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.model.SelectItem; import javax.inject.Inject; import org.primefaces.context.RequestContext; import tranporte.controller.access.SesionBean; import transporte.model.dao.entities.Persona; import transporte.model.dao.entities.TransSolicitud; import transporte.model.dao.entities.TransConductore; import transporte.model.dao.entities.TransFuncionarioConductor; import transporte.model.dao.entities.TransLugare; import transporte.model.dao.entities.TransVehiculo; import transporte.model.generic.Funciones; import transporte.model.generic.Mensaje; import transporte.model.manager.ManagerBuscar; import transporte.model.manager.ManagerCarga; import transporte.model.manager.ManagerGestion; import transporte.model.manager.ManagerSolicitud; @SessionScoped @ManagedBean public class solicituduBean implements Serializable { private static final long serialVersionUID = 1L; @EJB private ManagerGestion managergest; @EJB private ManagerSolicitud managersol; // private ManagerCarga mc; @EJB private ManagerBuscar mb; // SOLICITUD private Integer sol_id; private Timestamp sol_fecha; private Timestamp sol_fecha_aprobacion; private String sol_pasajeros; private String sol_motivo; private String sol_tipovehiculo; private String sol_hora_inicio; private String sol_hora_fin; private boolean sol_flexibilidad; private String sol_observacion; private String sol_estado; private String sol_estadonombre; private Integer sol_id_origen; private Integer sol_id_destino; private String sol_fcoid; private String sol_conductornombrefuncionario; private String sol_vehi; private String sol_conductor; private String sol_conductornombre; private String sol_usuario_cedula; private String sol_usuario_nombre; private String sol_correo; private boolean sol_regresorigen; private String cedula; // private transolicitante solicitante; private TransLugare lugorigen; private TransLugare lugdestino; private TransFuncionarioConductor fco_id; private TransVehiculo vehi_idplaca; private TransConductore cond_cedula; private TransSolicitud soli; // mmostrar private boolean edicion; private boolean ediciontipo; private boolean guardaredicion; private boolean verregresorigen; private List<TransSolicitud> listaSolicitudes; // fechas private Date date; private Date fecha; private Time horainiciotiemp; private Time horafintiemp; @Inject SesionBean ms; private String usuario; private Persona per; public solicituduBean() { } @PostConstruct public void ini() { usuario = ms.validarSesion("trans_solicitudesu.xhtml"); // mc = new ManagerCarga(); BuscarPersona(); sol_hora_inicio = null; sol_hora_fin = null; sol_id = null; sol_estado = "P"; sol_estadonombre = ""; sol_conductor = "Ninguno"; sol_correo = ""; sol_vehi = "Ninguno"; sol_tipovehiculo = ""; sol_fcoid = "Ninguno"; sol_flexibilidad = true; sol_pasajeros = null; edicion = false; ediciontipo = false; guardaredicion = true; sol_regresorigen = false; verregresorigen = true; sol_conductornombre = ""; sol_conductornombrefuncionario = ""; } public String getCedula() { return cedula; } public void setCedula(String cedula) { this.cedula = cedula; } public boolean isVerregresorigen() { return verregresorigen; } public void setVerregresorigen(boolean verregresorigen) { this.verregresorigen = verregresorigen; } public String getUsuario() { return usuario; } public String getSol_estadonombre() { return sol_estadonombre; } public void setSol_estadonombre(String sol_estadonombre) { this.sol_estadonombre = sol_estadonombre; } public String getSol_conductornombrefuncionario() { return sol_conductornombrefuncionario; } public void setSol_conductornombrefuncionario( String sol_conductornombrefuncionario) { this.sol_conductornombrefuncionario = sol_conductornombrefuncionario; } public String getSol_conductornombre() { return sol_conductornombre; } public void setSol_conductornombre(String sol_conductornombre) { this.sol_conductornombre = sol_conductornombre; } public Time getHorainiciotiemp() { return horainiciotiemp; } public boolean isGuardaredicion() { return guardaredicion; } public void setGuardaredicion(boolean guardaredicion) { this.guardaredicion = guardaredicion; } public void setHorainiciotiemp(Time horainiciotiemp) { this.horainiciotiemp = horainiciotiemp; } public Time getHorafintiemp() { return horafintiemp; } public void setHorafintiemp(Time horafintiemp) { this.horafintiemp = horafintiemp; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public Date getDate() { date = new Date(); return date; } public TransSolicitud getSoli() { return soli; } public void setSoli(TransSolicitud soli) { this.soli = soli; } public String getSol_conductor() { return sol_conductor; } public void setSol_conductor(String sol_conductor) { this.sol_conductor = sol_conductor; } public Integer getSol_id_origen() { return sol_id_origen; } public void setSol_id_origen(Integer sol_id_origen) { this.sol_id_origen = sol_id_origen; } public Integer getSol_id_destino() { return sol_id_destino; } public void setSol_id_destino(Integer sol_id_destino) { this.sol_id_destino = sol_id_destino; } public String getSol_fcoid() { return sol_fcoid; } public void setSol_fcoid(String sol_fcoid) { this.sol_fcoid = sol_fcoid; } public String getSol_vehi() { return sol_vehi; } public void setSol_vehi(String sol_vehi) { this.sol_vehi = sol_vehi; } public String getSol_usuario_cedula() { return sol_usuario_cedula; } public void setSol_usuario_cedula(String sol_usuario_cedula) { this.sol_usuario_cedula = sol_usuario_cedula; } public String getSol_usuario_nombre() { return sol_usuario_nombre; } public void setSol_usuario_nombre(String sol_usuario_nombre) { this.sol_usuario_nombre = sol_usuario_nombre; } public Integer getSol_id() { return sol_id; } public void setSol_id(Integer sol_id) { this.sol_id = sol_id; } public Timestamp getSol_fecha() { return sol_fecha; } public void setSol_fecha(Timestamp sol_fecha) { this.sol_fecha = sol_fecha; } public Timestamp getSol_fecha_aprobacion() { return sol_fecha_aprobacion; } public void setSol_fecha_aprobacion(Timestamp sol_fecha_aprobacion) { this.sol_fecha_aprobacion = sol_fecha_aprobacion; } public String getSol_pasajeros() { return sol_pasajeros; } public void setSol_pasajeros(String sol_pasajeros) { this.sol_pasajeros = sol_pasajeros; } public String getSol_motivo() { return sol_motivo; } public void setSol_motivo(String sol_motivo) { this.sol_motivo = sol_motivo; } public String getSol_tipovehiculo() { return sol_tipovehiculo; } public void setSol_tipovehiculo(String sol_tipovehiculo) { this.sol_tipovehiculo = sol_tipovehiculo; } public String getSol_hora_inicio() { return sol_hora_inicio; } public void setSol_hora_inicio(String sol_hora_inicio) { this.sol_hora_inicio = sol_hora_inicio; } public String getSol_hora_fin() { return sol_hora_fin; } public void setSol_hora_fin(String sol_hora_fin) { this.sol_hora_fin = sol_hora_fin; } public boolean isSol_flexibilidad() { return sol_flexibilidad; } public void setSol_flexibilidad(boolean sol_flexibilidad) { this.sol_flexibilidad = sol_flexibilidad; } public String getSol_observacion() { return sol_observacion; } public void setSol_observacion(String sol_observacion) { this.sol_observacion = sol_observacion; } public String getSol_estado() { return sol_estado; } public void setSol_estado(String sol_estado) { this.sol_estado = sol_estado; } public TransLugare getLugorigen() { return lugorigen; } public void setLugorigen(TransLugare lugorigen) { this.lugorigen = lugorigen; } public TransLugare getLugdestino() { return lugdestino; } public void setLugdestino(TransLugare lugdestino) { this.lugdestino = lugdestino; } public TransFuncionarioConductor getFco_id() { return fco_id; } public void setFco_id(TransFuncionarioConductor fco_id) { this.fco_id = fco_id; } public TransVehiculo getVehi_idplaca() { return vehi_idplaca; } public void setVehi_idplaca(TransVehiculo vehi_idplaca) { this.vehi_idplaca = vehi_idplaca; } public TransConductore getCond_cedula() { return cond_cedula; } public void setCond_cedula(TransConductore cond_cedula) { this.cond_cedula = cond_cedula; } public List<TransSolicitud> getListaSolicitudes() { return listaSolicitudes; } public void setListaSolicitudes(List<TransSolicitud> listaSolicitudes) { this.listaSolicitudes = listaSolicitudes; } public boolean isEdicion() { return edicion; } public void setEdicion(boolean edicion) { this.edicion = edicion; } public boolean isEdiciontipo() { return ediciontipo; } public void setEdiciontipo(boolean ediciontipo) { this.ediciontipo = ediciontipo; } public boolean isSol_regresorigen() { return sol_regresorigen; } public void setSol_regresorigen(boolean sol_regresorigen) { this.sol_regresorigen = sol_regresorigen; } // SOLICITUDES /** * accion para invocar el manager y crear solicitud o editar el solicitud * * @param pro_id * @param prodfoto_id * @param pro_nombre * @param pro_descripcion * @param pro_costo * @param pro_precio * @param pro_stock * @param pro_estado * @param pro_estado_fun * @throws Exception */ public String crearSolicitud() { try { sol_fecha = new Timestamp(fecha.getTime()); Integer pasajeros; pasajeros = Integer.parseInt(sol_pasajeros); DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); horainiciotiemp = new java.sql.Time(formatter .parse(sol_hora_inicio).getTime()); horafintiemp = new java.sql.Time(formatter.parse(sol_hora_fin) .getTime()); if (edicion) { // managersol.editarSolicitud(sol_id, sol_fecha, pasajeros, // sol_motivo.trim(), horainiciotiemp, horafintiemp, // sol_flexibilidad, sol_observacion.trim(), // sol_estado,sol_fcoid,sol_conductor,sol_correo, // sol_regresorigen); Mensaje.crearMensajeINFO("Actualizado - Modificado"); limpiarCampos(); getListaSolicitudDesc().clear(); getListaSolicitudDesc() .addAll(managersol .findAllSolicitudesOrdenados(sol_usuario_cedula)); } else { managersol.insertarSolicitud(sol_fecha, sol_usuario_cedula, sol_usuario_nombre, pasajeros, sol_motivo.trim(), horainiciotiemp, horafintiemp, sol_flexibilidad, sol_fcoid, sol_regresorigen, sol_tipovehiculo); Mensaje.crearMensajeINFO("Registrado - Creado"); String mensaje = "<!DOCTYPE html><html lang='es'><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' />" + "<meta name='viewport' content='width=device-width'></head><body>" + "Estimado(a) Administrador. <br/>" + "Le notificamos que posee una solicitud de Transporte Pendiente.<br/><br/>" // +"N�mero de Solicitud: "+query.consultaSQL("SELECT max(sol_id) FROM trans_solicitud;")+"<br/>" + "Nombre del Solicitante: " + Funciones.utf8Sting(sol_usuario_nombre) + "<br/>" + "Por el Motivo: " + Funciones.utf8Sting(sol_motivo) + "<br/>" + "Tipo de Automóvil: " + Funciones.utf8Sting(sol_tipovehiculo) + "<br/>" + "Correo del Solicitante: " + Funciones.utf8Sting(sol_correo) + "<br/>" + "Fecha de Petición: " + Funciones.dateToString(sol_fecha) + "<br/>" + "Lugar Origen y Destino: " + managergest.LugarByID(sol_id_origen).getLugNombre() + " - " + managergest.LugarByID(sol_id_destino).getLugNombre() + "<br/>" + "Hora Origen y Destino: " + horainiciotiemp.toString() + " - " + horafintiemp.toString() + "<br/>" + "Número de Pasajeros: " + sol_pasajeros.toString() + "<br/><br/>" + "<br/>Atentamente,<br/>Sistema de gestión de Transportes Yachay." + "<br/><em><strong>NOTA:</strong> Este correo es generado automáticamente por el sistema favor no responder al mismo.</em></body></html>"; ; // Mail.generateAndSendEmail("lcorrea@yachay.gob.ec", // "Petici�n de Veh�culo", mensaje); // mb.envioMailAdminWS("Petición de Vehículo", mensaje); mensaje = null; limpiarCampos(); getListaSolicitudDesc().clear(); getListaSolicitudDesc() .addAll(managersol .findAllSolicitudesOrdenados(sol_usuario_cedula)); } return "trans_solicitudesu?faces-redirect=true"; } catch (Exception e) { e.printStackTrace(); Mensaje.crearMensajeWARN("Error al crear solicitud"); return ""; } } public void limpiarCampos(){ sol_id = null; date = new Date(); sol_id_origen = null; sol_id_destino = null; sol_fcoid = ""; sol_vehi = ""; sol_tipovehiculo = null; sol_conductor = ""; sol_regresorigen = false; sol_fecha = null; sol_fecha_aprobacion = null; sol_pasajeros = null; sol_motivo = null; sol_hora_inicio = null; sol_hora_fin = null; sol_flexibilidad = true; sol_observacion = null; sol_estado = "P"; sol_estadonombre = ""; edicion = true; ediciontipo = false; sol_hora_inicio = null; sol_hora_fin = null; horainiciotiemp = null; horafintiemp = null; sol_correo = ""; guardaredicion = false; } public void abrirDialog() { DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); try { horainiciotiemp = new java.sql.Time(formatter .parse(sol_hora_inicio).getTime()); horafintiemp = new java.sql.Time(formatter.parse(sol_hora_fin) .getTime()); if (horafintiemp.getTime() < horainiciotiemp.getTime()) { Mensaje.crearMensajeWARN("Verifique su horario"); } else RequestContext.getCurrentInstance().execute("PF('gu').show();"); } catch (ParseException e) { e.printStackTrace(); } } /** * JAVA.DATE TO SQL.TIME * * @throws Exception */ @SuppressWarnings("deprecation") public Time fechaAtiempo(Date fecha) { DateFormat dateFormatH = new SimpleDateFormat("HH:mm"); String hora = dateFormatH.format(fecha).toString(); String[] array = hora.split(":"); Time resp = new Time(Integer.parseInt(array[0]), Integer.parseInt(array[1]), 00); return resp; } /** * accion para cargar los datos en el formulario * * @param pro_id * @param prodfoto_id * @param pro_nombre * @param pro_descripcion * @param pro_costo * @param pro_precio * @param pro_stock * @param pro_estado * @param pro_estado_fun * @throws Exception */ public String cargarSolicitud(TransSolicitud sol) { String r = ""; try { sol_id = sol.getSolId(); // sol_idsolicitante = sol.getSolicitante(); sol_usuario_cedula = sol.getSolIdSolicitante(); sol_usuario_nombre = sol.getSolNomSolicitante(); sol_id_origen = sol.getTransLugare2().getLugId(); sol_id_destino = sol.getTransLugare1().getLugId(); if (sol.getTransVehiculo() == null) sol_vehi = ""; else sol_vehi = sol.getTransVehiculo().getVehiIdplaca(); if (sol.getTransConductore() == null) { sol_conductor = ""; sol_conductornombre = ""; } else { sol_conductor = sol.getTransConductore().getCondCedula(); sol_conductornombre = sol.getTransConductore().getCondNombre() + " " + sol.getTransConductore().getCondApellido(); } if (sol.getTransFuncionarioConductor() == null) { sol_fcoid = ""; sol_conductornombrefuncionario = ""; } else { sol_fcoid = sol.getTransFuncionarioConductor().getFcoId(); sol_conductornombrefuncionario = sol .getTransFuncionarioConductor().getFcoNombres(); } fecha = sol.getSolFecha(); sol_fecha_aprobacion = sol.getSolFechaAprobacion(); sol_pasajeros = sol.getSolPasajeros().toString(); sol_motivo = sol.getSolMotivo(); sol_tipovehiculo = sol.getSolTipovehiculo(); sol_hora_inicio = sol.getSolHoraInicio().toString(); sol_hora_fin = sol.getSolHoraFin().toString(); sol_flexibilidad = sol.getSolFlexibilidad(); sol_observacion = sol.getSolObservacion(); sol_estado = sol.getSolEstado(); sol_regresorigen = sol.getSolRegresorigen(); edicion = true; ediciontipo = false; guardaredicion = false; if (sol.getSolEstado().equals("P")) sol_estadonombre = "Pendiente"; else if (sol.getSolEstado().equals("N")) sol_estadonombre = "Anulado"; else if (sol.getSolEstado().equals("A")) sol_estadonombre = "Aprobado"; else if (sol.getSolEstado().equals("R")) sol_estadonombre = "Rechazado"; r = "trans_nsolicitudu?faces-redirect=true"; } catch (Exception e) { e.printStackTrace(); } return r; } /** * activar y desactivar estado Solicitud * * @param vehi_id * @throws Exception */ public String cambiarEstadoSoli() { try { Mensaje.crearMensajeINFO(managersol.cambioEstadoSolicitud(getSoli() .getSolId())); getListaSolicitudDesc().clear(); getListaSolicitudDesc().addAll( managersol.findAllSolicitudesOrdenados(sol_usuario_cedula)); } catch (Exception e) { e.printStackTrace(); } return ""; } /** * Metodo para cambiar el estado de la solicitud * * @param soli */ public void cambiarEstadoSoli(TransSolicitud soli) { setSoli(soli); RequestContext.getCurrentInstance().execute("PF('ce').show();"); } /** * metodo para conocer el prodid si esta usado * */ public boolean averiguarSoliid(Integer soli_id) { Integer t = 0; boolean r = false; List<TransSolicitud> soli = managersol .findAllSolicitudesOrdenados(sol_usuario_cedula); for (TransSolicitud y : soli) { if (y.getSolId().equals(soli_id)) { t = 1; r = true; Mensaje.crearMensajeWARN("El código del producto existe"); } } if (t == 0) { r = false; } return r; } /** * Lista de estados * * @return lista de items de estados */ public List<SelectItem> getlistEstados() { List<SelectItem> lista = new ArrayList<SelectItem>(); lista.add(new SelectItem(Funciones.estadoAprobado, Funciones.estadoAprobado + " : " + Funciones.valorEstadoAprobado)); lista.add(new SelectItem(Funciones.estadoRechazado, Funciones.estadoRechazado + " : " + Funciones.valorEstadoRechazado)); return lista; } /** * Lista de horas * * @return lista de items de horas */ public List<SelectItem> getlistHoras() { List<SelectItem> lista = new ArrayList<SelectItem>(); lista.add(new SelectItem(Funciones.hora_8, Funciones.hora_8)); lista.add(new SelectItem(Funciones.hora_9, Funciones.hora_9)); lista.add(new SelectItem(Funciones.hora_10, Funciones.hora_10)); lista.add(new SelectItem(Funciones.hora_11, Funciones.hora_11)); lista.add(new SelectItem(Funciones.hora_12, Funciones.hora_12)); lista.add(new SelectItem(Funciones.hora_13, Funciones.hora_13)); lista.add(new SelectItem(Funciones.hora_14, Funciones.hora_14)); lista.add(new SelectItem(Funciones.hora_15, Funciones.hora_15)); lista.add(new SelectItem(Funciones.hora_16, Funciones.hora_16)); lista.add(new SelectItem(Funciones.hora_17, Funciones.hora_17)); return lista; } /** * Lista de vehiculos * * @return lista de items de vehiculos */ public List<SelectItem> getlistVehiculo() { List<SelectItem> lista = new ArrayList<SelectItem>(); lista.add(new SelectItem(Funciones.automovil, Funciones.automovil)); lista.add(new SelectItem(Funciones.camioneta, Funciones.camioneta)); return lista; } /** * metodo para mostrar los lugaresorigen en solicitud * */ public List<SelectItem> getListaOrigen() { List<SelectItem> listadoSI = new ArrayList<SelectItem>(); for (TransLugare t : managergest.findAllLugares()) { if (!t.getLugEstado().equals("I")) { listadoSI.add(new SelectItem(t.getLugId(), t.getLugNombre() + " - " + t.getLugCiudad())); } } return listadoSI; } /** * metodo para mostrar los lugaresdestino en solicitud * */ public List<SelectItem> getListaDestino() { List<SelectItem> listadoSI = new ArrayList<SelectItem>(); for (TransLugare t : managergest.findAllLugares()) { if (!t.getLugEstado().equals("I")) { listadoSI.add(new SelectItem(t.getLugId(), t.getLugNombre() + " - " + t.getLugCiudad())); } } return listadoSI; } /** * metodo para mostrar los conductores en solicitud * */ public List<SelectItem> getListaConductor() { List<SelectItem> listadoSI = new ArrayList<SelectItem>(); for (TransConductore t : managergest.findAllConductores()) { if (!t.getCondEstado().equals("I")) { listadoSI.add(new SelectItem(t.getCondCedula(), t .getCondNombre() + " " + t.getCondApellido())); } } return listadoSI; } /** * metodo para mostrar los conductorefunacionario en solicitud * */ public List<SelectItem> getListaConductorfuncionario() { List<SelectItem> listadoSI = new ArrayList<SelectItem>(); listadoSI.add(new SelectItem("Ninguno", "Ninguno")); for (TransFuncionarioConductor t : managersol .findAllConductFuncionarios()) { if (!t.getFcoEstado().equals("I")) { if (per.getPerGerencia().equals(t.getFcoGerencia())) listadoSI.add(new SelectItem(t.getFcoId(), t .getFcoNombres())); } } return listadoSI; } /** * metodo para mostrar los vehiculos en solicitud * * @return listaveh�culo * */ public List<SelectItem> getListaVehiculo() { List<SelectItem> listadoSI = new ArrayList<SelectItem>(); for (TransVehiculo t : managergest.findAllVehiculos()) { if (!t.getVehiEstado().equals("I")) { listadoSI.add(new SelectItem(t.getVehiIdplaca(), t .getVehiIdplaca() + " " + t.getVehiNombre())); } } return listadoSI; } /** * metodo para asignar el condutor a solicitud * */ public void asignarConductor() { managersol.asignarConductor(sol_conductor); } // /** // * metodo para asignar el condutorfuncionario a solicitud // * // */ // public void asignarConductorFuncionario() { // managersol.asignarConductorfuncionario(sol_fcoid); // } /** * metodo para asignar el lugarorigen a solicitud * */ public String asignarLugarOrigen() { managersol.asignarlugarini(sol_id_origen); return ""; } /** * metodo para asignar el lugarorigen a solicitud * */ public String asignarLugarDestino() { managersol.asignarlugarfin(sol_id_destino); return ""; } /** * metodo para asignar el vehiculo a solicitud * */ public String asignarVehiculo() { managersol.asignarvehiculo(sol_vehi); return ""; } /** * metodo para asignar el lugarorigen a solicitud * */ public String asignarHoraFin() { sol_hora_fin = sol_hora_inicio; return ""; } /** * limpia la informacion de horario * * @throws Exception */ public String volverSolicitud() throws Exception { // limpiar datos sol_id = null; date = new Date(); // sol_idsolicitante = sol.getSolicitante(); sol_id_origen = null; sol_id_destino = null; sol_fcoid = null; sol_vehi = null; sol_conductor = null; sol_conductornombre = null; sol_conductornombrefuncionario = ""; sol_fecha = null; sol_fecha_aprobacion = null; sol_tipovehiculo = null; sol_regresorigen = false; sol_pasajeros = null; sol_motivo = null; sol_hora_inicio = null; sol_hora_fin = null; sol_flexibilidad = true; sol_correo = ""; sol_observacion = null; sol_estado = "P"; sol_estadonombre = ""; edicion = true; ediciontipo = false; sol_hora_inicio = null; sol_hora_fin = null; horainiciotiemp = null; horafintiemp = null; getListaSolicitudDesc().clear(); getListaSolicitudDesc().addAll( managersol.findAllSolicitudesOrdenados(sol_usuario_cedula)); return "trans_solicitudesu?faces-redirect=true"; } /** * Redirecciona a la pagina de creacion de vehiculos * */ public String nuevoSolicitud() { String r = ""; if (usuario.equals(null)) { sol_id = null; date = new Date(); fecha = addDays(date, 1); // sol_idsolicitante = sol.getSolicitante(); sol_id_origen = null; sol_id_destino = null; sol_fcoid = ""; sol_vehi = ""; sol_conductor = ""; sol_fecha = null; sol_fecha_aprobacion = null; sol_pasajeros = null; sol_motivo = null; sol_regresorigen = false; verregresorigen = true; sol_hora_inicio = null; sol_tipovehiculo = null; sol_hora_fin = null; sol_flexibilidad = true; sol_observacion = null; sol_estado = "P"; sol_estadonombre = ""; ediciontipo = false; sol_hora_inicio = null; sol_hora_fin = null; horainiciotiemp = null; horafintiemp = null; edicion = false; r = ""; } else { BuscarPersona(); sol_id = null; date = new Date(); fecha = addDays(date, 1); // sol_idsolicitante = sol.getSolicitante(); sol_id_origen = null; sol_id_destino = null; sol_fcoid = ""; sol_vehi = ""; sol_conductor = ""; sol_fecha = null; sol_fecha_aprobacion = null; sol_pasajeros = null; sol_tipovehiculo = null; sol_motivo = null; sol_regresorigen = false; verregresorigen = true; sol_hora_inicio = null; sol_hora_fin = null; sol_flexibilidad = true; sol_observacion = null; sol_estado = "P"; sol_estadonombre = ""; ediciontipo = false; sol_hora_inicio = null; sol_hora_fin = null; horainiciotiemp = null; horafintiemp = null; edicion = false; asignarVehiculo(); asignarConductor(); // asignarConductorFuncionario(); r = "trans_nsolicitudu?faces-redirect=true"; } return r; } /** * metodo para listar los registros * */ public List<TransSolicitud> getListaSolicitudDesc() { BuscarPersona(); List<TransSolicitud> a = managersol .findAllSolicitudesOrdenados(sol_usuario_cedula); List<TransSolicitud> l1 = new ArrayList<TransSolicitud>(); for (TransSolicitud t : a) { l1.add(t); } return l1; } /** * Metodo para buscar persona logeada * * @throws Exception */ public void BuscarPersona() { try { cedula = ManagerCarga.consultaSQL(usuario); // per = mc.personasolicitudByDNI(cedula); per = mb.buscarPersonaWSReg(cedula); if (per != null) { sol_usuario_nombre = per.getPerNombres() + " " + per.getPerApellidos(); sol_usuario_cedula = per.getPerDNI(); sol_correo = per.getPerCorreo(); } else { throw new Exception("PERSONA NULA"); } } catch (Exception e) { e.printStackTrace(); } } /** * Metodo para obtener la fecha de tipo Date * * @param date * @param days * @return Date */ public static Date addDays(Date date, int days) { days = 1; Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); // minus number would decrement the days return cal.getTime(); } /** * Metodo para saber si va a regresar el veh�culo al lugar de donde partio * * @throws Exception */ public void regresoOrigen() { try { if (sol_regresorigen == true) { verregresorigen = false; } else { verregresorigen = true; } } catch (Exception e) { e.printStackTrace(); } } /** * Validar sesi�n y permiso */ public void vSesionPermiso() { ms.validarSesion("trans_solicitudesu.xhtml"); } }
SQL
UTF-8
164
2.5625
3
[ "CC0-1.0" ]
permissive
-- !Ups create table tasks ( id serial not null, name varchar(100) not null, description varchar(100), PRIMARY KEY (id) ); -- !Downs DROP TABLE IF EXISTS tasks
Python
UTF-8
638
3.078125
3
[]
no_license
''' Created on Apr 14, 2012 @author: namnx ''' import sys def solve(line): vals = line.split() n = int(vals[0]) s = int(vals[1]) p = int(vals[2]) re = 0 for val in vals[3:]: val = int(val) if p==1: if val>=1: re += 1 elif val >= 3*p-2: re += 1 elif val >= 3*p-4 and s > 0: re += 1 s -= 1 return re if __name__ == '__main__': f = open(sys.argv[1]) t = int(f.readline().strip()) for i in xrange(t): line = f.readline().strip() re = solve(line) print 'Case #' + str(i+1) + ': ' + str(re) f.close()
C#
UTF-8
2,778
2.671875
3
[ "MIT" ]
permissive
using System; using System.Linq; using Manatee.Json.Parsing; using Manatee.Json.Path.ArrayParameters; using Manatee.Json.Path.Operators; using Manatee.Json.Path.Parsing; namespace Manatee.Json.Path.Expressions.Parsing { internal class PathExpressionParser : IJsonPathExpressionParser { public bool Handles(string input, int index) { return input[index] == '@' || input[index] == '$'; } public string TryParse<T>(string source, ref int index, out JsonPathExpression expression) { expression = null; PathExpression<T> node; var isLocal = source[index] == '@'; var error = JsonPathParser.Parse(source, ref index, out JsonPath path); // Swallow this error from the path parser and assume the path just ended. // If it's really a syntax error, the expression parser should catch it. if (error != null && error != "Unrecognized JSON Path element.") return error; var lastOp = path.Operators.Last(); if (lastOp is NameOperator name) { path.Operators.Remove(name); if (name.Name == "indexOf") { if (source[index] != '(') return "Expected '('. 'indexOf' operator requires a parameter."; index++; error = JsonParser.Parse(source, ref index, out JsonValue parameter, true); // Swallow this error from the JSON parser and assume the value just ended. // If it's really a syntax error, the expression parser should catch it. if (error != null && error != "Expected \',\', \']\', or \'}\'.") return $"Error parsing parameter for 'indexOf' expression: {error}."; if (source[index] != ')') return "Expected ')'."; index++; node = new IndexOfExpression<T> { Path = path, IsLocal = isLocal, Parameter = parameter }; } else node = new NameExpression<T> { Path = path, IsLocal = isLocal, Name = name.Name }; } else if (lastOp is LengthOperator length) { path.Operators.Remove(length); node = new LengthExpression<T> { Path = path, IsLocal = isLocal }; } else if (lastOp is ArrayOperator array) { path.Operators.Remove(array); var query = array.Query as SliceQuery; var constant = query?.Slices.FirstOrDefault()?.Index; if (query == null || query.Slices.Count() != 1 || !constant.HasValue) return "JSON Path expression indexers only support single constant values."; node = new ArrayIndexExpression<T> { Path = path, IsLocal = isLocal, Index = constant.Value }; } else throw new NotImplementedException(); expression = new PathValueExpression<T> {Path = node}; return null; } } }
SQL
UTF-8
921
3.921875
4
[]
no_license
DROP TABLE IF EXISTS handle CASCADE; CREATE TABLE IF NOT EXISTS handle ( handle_id integer PRIMARY KEY, handle_name varchar ); DROP TABLE IF EXISTS tweet CASCADE; CREATE TABLE IF NOT EXISTS tweet ( handle_id integer references handle(handle_id), timeTweeted timestamp NOT NULL, PRIMARY KEY(timeTweeted, handle_id), favouriteCount integer CONSTRAINT positive_favcount CHECK (favouriteCount >= 0), retweetCount integer CONSTRAINT positive_retweetcount CHECK (retweetCount >= 0), text varchar NOT NULL, originalAuthor varchar ); DROP TABLE IF EXISTS hashtag CASCADE; CREATE TABLE IF NOT EXISTS hashtag ( tag_id integer PRIMARY KEY, tag varchar ); DROP TABLE IF EXISTS has CASCADE; CREATE TABLE IF NOT EXISTS has ( timeTweeted timestamp NOT NULL, handle_id integer NOT NULL, FOREIGN KEY (timeTweeted, handle_id) references tweet(timeTweeted, handle_id), tag_id integer references hashtag(tag_id) );
Python
UTF-8
12,580
3.453125
3
[]
no_license
import numpy as np NULL = 0 class bsearch(object): ''' simple binary search tree, with public functions of search, insert and traversal ''' def __init__ (self, value) : self.value = value self.left = self.right = NULL def search(self, value) : if self.value==value : return True elif self.value>value : if self.left==NULL : return False else: return self.left.search(value) else : if self.right==NULL : return False else : return self.right.search(value) def insert(self, value) : if self.value==value : return False elif self.value>value : if self.left==NULL : self.left = bsearch(value) return True else : return self.left.insert(value) else : if self.right==NULL : self.right = bsearch(value) return True else : return self.right.insert(value) def inorder(self) : if self.left !=NULL : self.left.inorder() if self != NULL : print (self.value, " ", end="") if self.right != NULL : self.right.inorder() class TreeNode(object): ''' A class for storing necessary information at each tree node. Nodes should be initialized as objects of this class. ''' def __init__(self, d=None, threshold=None, l_node=None, r_node=None, label=None, is_leaf=False, gini=None, n_samples=None): ''' Input: d: index (zero-based) of the attribute/feature selected for splitting use. int threshold: the threshold for attribute d. If the attribute d of a sample is <= threshold, the sample goes to left branch; o/w right branch. float l_node: left children node/branch of current node. TreeNode r_node: right children node/branch of current node. TreeNode label: the most common label at current node. int/float is_leaf: True if this node is a leaf node; o/w False. bool gini: stores gini impurity at current node. float n_samples: number of training samples at current node. int ''' self.d = d self.threshold = threshold self.l_node = l_node self.r_node = r_node self.label = label self.is_leaf = is_leaf self.gini = gini self.n_samples = n_samples def load_data(fdir): ''' Load attribute values and labels from a npy file. Data is assumed to be stored of shape (N, D) where the first D-1 cols are attributes and the last col stores the labels. Input: fdir: file directory. str Output: data_x: feature vector. np ndarray data_y: label vector. np ndarray ''' data = np.load(fdir) data_x = data[:, :-1] data_y = data[:, -1].astype(int) print(f"x: {data_x.shape}, y:{data_y.shape}") return data_x, data_y class CART(object): ''' Classification and Regression Tree (CART). ''' def __init__(self, max_depth=None): ''' Input: max_depth: maximum depth allowed for the tree. int/None. Instance Variables: self.max_depth: stores the input max_depth. int/inf self.tree: stores the root of the tree. TreeNode object ''' self.max_depth = float('inf') if max_depth is None else max_depth self.tree = None #root node def gini_Impure(self, X, y): uni_arr, counts = np.unique(y, return_counts=True) freq = counts / np.sum(counts) gini_I = 1 - np.sum(np.square(freq)) return gini_I def Thresh_split(self, X, y, threshold, feature): X_left = X[X[:, feature] <= threshold] y_left = y[X[:, feature] <= threshold] X_right = X[X[:, feature] > threshold] y_right = y[X[:, feature] > threshold] l_gini = self.gini_Impure(X_left, y_left) r_gini = self.gini_Impure(X_right, y_right) return X_left, y_left, X_right, y_right, l_gini, r_gini def best_split(self, parent, train_X, train_y, depth_remain): l_node = None r_node = None best_gini_split = None best_l_split_X = None best_l_split_y = None best_r_split_X = None best_r_split_y = None parent.n_samples = train_X.shape[0] uni_arr, counts = np.unique(train_y, return_counts=True) parent.label = uni_arr[np.argmax(counts)].astype(int) if (depth_remain is 0) or (parent.gini is 0): parent.is_leaf = True return parent for feature_i, features in enumerate(train_X.T): uni_arr, counts = np.unique(features, return_counts=True) if (len(uni_arr) <= 1): continue for index in range(len(uni_arr)-1): threshold = (uni_arr[index] + uni_arr[index + 1]) / 2 l_train_X, l_train_y, r_train_X, r_train_y, l_gini, r_gini = self.Thresh_split(train_X, train_y, threshold, feature_i) split_gini = l_gini * (l_train_X.shape[0] / parent.n_samples) + r_gini * (r_train_X.shape[0] / parent.n_samples) if (split_gini < parent.gini): if (best_gini_split is None) or (split_gini < best_gini_split): best_gini_split = split_gini parent.d = feature_i parent.threshold = threshold best_l_split_X = l_train_X best_l_split_y = l_train_y best_r_split_X = r_train_X best_r_split_y = r_train_y l_node = TreeNode(gini=l_gini) r_node = TreeNode(gini=r_gini) if (best_gini_split is None): parent.is_leaf = True return parent parent.l_node = self.best_split(l_node, best_l_split_X, best_l_split_y, (depth_remain - 1)) parent.r_node = self.best_split(r_node, best_r_split_X, best_r_split_y, (depth_remain - 1)) return parent def train(self, X, y): ''' Build the tree from root to all leaves. The implementation follows the pseudocode of CART algorithm. Input: X: Feature vector of shape (N, D). N - number of training samples; D - number of features. np ndarray y: label vector of shape (N,). np ndarray ''' gini = self.gini_Impure(X, y) root = TreeNode() root.gini = gini self.tree = self.best_split(root, X, y, self.max_depth) def accuracy(self, X_val, y_val): accuracy = np.mean(self.test(X_val) == y_val) return accuracy def traverse(self, node, feature): if (node.is_leaf): return node.label else: if (feature[node.d] <= node.threshold): return self.traverse(node.l_node, feature) else: return self.traverse(node.r_node, feature) def test(self, X_test): ''' Predict labels of a batch of testing samples. Input: X_test: testing feature vectors of shape (N, D). np array Output: prediction: label vector of shape (N,). np array, dtype=int ''' pred = [] for feature in X_test: pred.append(self.traverse(self.tree, feature)) pred = np.array(pred) return pred def visualize_tree(self): ''' A simple function for tree visualization. ''' print('ROOT: ') def print_tree(tree, indent='\t|', dict_tree={}, direct='L'): if tree.is_leaf == True: dict_tree = {direct: str(tree.label)} else: print(indent + 'attribute: %d/threshold: %.5f' % (tree.d, tree.threshold)) if tree.l_node.is_leaf == True: print(indent + 'L -> label: %d' % tree.l_node.label) else: print(indent + "L -> ",) a = print_tree(tree.l_node, indent=indent + "\t|", direct='L') aa = a.copy() if tree.r_node.is_leaf == True: print(indent + 'R -> label: %d' % tree.r_node.label) else: print(indent + "R -> ",) b = print_tree(tree.r_node, indent=indent + "\t|", direct='R') bb = b.copy() aa.update(bb) stri = indent + 'attribute: %d/threshold: %.5f' % (tree.d, tree.threshold) if indent != '\t|': dict_tree = {direct: {stri: aa}} else: dict_tree = {stri: aa} return dict_tree try: if self.tree is None: raise RuntimeError('No tree has been trained!') except: raise RuntimeError('No self.tree variable!') _ = print_tree(self.tree) def GridSearchCV(X, y, depth=[1, 40]): ''' Grid search and cross validation. Input: X: full training dataset. Not split yet. np ndarray y: full training labels. Not split yet. np ndarray depth: [minimum depth to consider, maximum depth to consider]. list of integers Output: best_depth: the best max_depth value from grid search results. int best_acc: the validation accuracy corresponding to the best_depth. float best_tree: a decision tree object that is trained with full training dataset and best max_depth from grid search. instance ''' depths = np.linspace(depth[0], depth[1], num=10, dtype=int) best_depth = None best_acc = 0.0 best_tree = None y = np.array([y]).T data = np.append(X, y, 1) np.random.shuffle(data) split1, split2, split3, split4, split5 = np.array_split(data, 5) for max_depth in depths: #5-fold cross validation for cv in range(5): if cv is 0: validation = split1 training = np.append(split2, split3, 0) training = np.append(training, split4, 0) training = np.append(training, split5, 0) elif cv is 1: validation = split2 training = np.append(split1, split3, 0) training = np.append(training, split4, 0) training = np.append(training, split5, 0) elif cv is 2: validation = split3 training = np.append(split1, split2, 0) training = np.append(training, split4, 0) training = np.append(training, split5, 0) elif cv is 3: validation = split4 training = np.append(split1, split2, 0) training = np.append(training, split3, 0) training = np.append(training, split5, 0) elif cv is 4: validation = split5 training = np.append(split1, split2, 0) training = np.append(training, split3, 0) training = np.append(training, split5, 0) X_train = training[:,:-1] y_train = np.array([training[:,-1]]).T X_val = validation[:,:-1] y_val = np.array([validation[:,-1]]).T tree = CART() tree.train(X_train, y_train) accuracy = tree.accuracy(X_val, y_val) if best_acc < accuracy: best_acc = accuracy best_depth = max_depth cart = CART(best_depth) cart.train(X,y) best_tree = cart return best_depth, best_acc, best_tree # main X_train, y_train = load_data('winequality-red-train.npy') best_depth, best_acc, best_tree = GridSearchCV(X_train, y_train, [1, 40]) print('Best depth from 5-fold cross validation: %d' % best_depth) print('Best validation accuracy: %.5f' % (best_acc))
C
UTF-8
597
3.921875
4
[]
no_license
#include <stdlib.h> #include "lists.h" /** * delete_nodeint_at_index - delete node at index * @head: head node * @index: where to delete * Return: 1 (succes) -1 (fail) */ int delete_nodeint_at_index(listint_t **head, unsigned int index) { listint_t *current, *previous; if (head == NULL) return (-1); for (current = *head; current != NULL && index > 0; index--) { previous = current; current = current->next; } if (current == NULL) return (-1); if (current == *head) { *head = current->next; } else { previous->next = current->next; } free(current); return (1); }
Python
UTF-8
644
4.125
4
[]
no_license
#!/usr/bin/env python # encoding: utf-8 #简单选择排序的第i趟是从数组中选择第i小的元素,并将元素放在第i位上 def select_sort(data_array,n) : for i in range(n-1) : low_index = i #记录data_array[i...n-1]中最小元素的下标 for j in range(i+1,n) : if data_array[j] <data_array[low_index] : low_index = j swap(data_array,i,low_index) def swap(data_array, low, high) : temp = data_array[low] data_array[low] = data_array[high] data_array[high] = temp data=[10,9,8,7,6,5,4,3,2,1] select_sort(data,10) for i in range(10) : print data[i],
Java
UTF-8
406
2.8125
3
[]
no_license
package maratonajava.abstrato; public class Manager extends Employe{ public Manager() { } public Manager(String name, String clt, double salary) { super(name, clt, salary); } @Override public double calculateSalary() { this.setSalary(this.getSalary() + (this.getSalary() * 0.1)); return this.getSalary(); } }
PHP
UTF-8
1,178
2.609375
3
[]
no_license
<!-- classe responsavel por conectar com o bando de dados e gravar erros em arquivo txt --> <?php class DB{ private static $conn; static function getConn(){ if(is_null(self::$conn)){ self::$conn = new PDO('mysql:host=localhost;dbname=afaid','root',''); self::$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); } return self::$conn; } } function logErros($errno){ if(error_reporting()==0) return; $exec = func_get_arg(0); $errno = $exec->getCode(); $errstr = $exec->getMessage(); $errfile = $exec->getFile(); $errline = $exec->getLine(); $err = 'CAUGHT EXCEPTION'; if(ini_get('log_errrors')) error_log(sprintf("PHP %s: %s in %s on line %d",$err,$errstr,$errfile,$errline)); $strErro = 'erro: '.$err.' no arquivo: '.$errfile.' ( linha '.$errline.' ) :: IP('.$_SERVER['REMOTE_ADDR'].') data:'.date('d/m/y H:i:s')."\n"; $arquivo = fopen('logerro.txt','a'); fwrite($arquivo,$strErro); fclose($arquivo); set_error_handler('logErros'); } session_start(); require_once'facebook/autoload.php'; $fb = new Facebook\Facebook([ 'app_id' => '959243830854531', 'app_secret' => 'b54e9d951a35463cf545425bddcd0139', 'default_graph_version' => 'v2.9', ]);
C++
UTF-8
4,986
3.0625
3
[ "MIT" ]
permissive
#ifndef SYSMODULE_HPP #define SYSMODULE_HPP #include <atomic> #include <chrono> #include <functional> #include <mutex> #include <queue> #include "Types.hpp" #include <vector> // The sysmodule class communicates with the sysmodule via IPC calls. // All values are cached, allowing for fast access and no race conditions! class Sysmodule { public: // Reasons for loss of communication enum class Error { None, // No error DifferentVersion, // App and sysmodule versions don't match NotConnected, // Couldn't establish a connection Unknown // Unknown error }; private: std::atomic<bool> connected_; std::atomic<Error> error_; std::atomic<bool> exit_; std::atomic<int> limit_; std::chrono::steady_clock::time_point lastUpdateTime; // === Status vars === std::atomic<SongID> currentSong_; std::atomic<bool> keepPosition; std::atomic<bool> keepVolume; std::mutex playingFromMutex; std::string playingFrom_; std::atomic<double> position_; std::atomic<bool> queueChanged_; // Set true when the whole queue has been updated (not just a single song) std::vector<SongID> queue_; std::mutex queueMutex; std::atomic<size_t> queueSize_; std::atomic<RepeatMode> repeatMode_; std::atomic<ShuffleMode> shuffleMode_; std::atomic<bool> subQueueChanged_; // Set true when the whole queue has been updated (not just a single song) std::vector<SongID> subQueue_; std::mutex subQueueMutex; std::atomic<size_t> subQueueSize_; std::atomic<size_t> songIdx_; std::atomic<PlaybackStatus> status_; std::atomic<double> volume_; // ====== // Queue of IPC commands std::queue< std::function<bool()> > ipcQueue; std::mutex ipcMutex; // Returns if the message was added to the queue bool addToIpcQueue(std::function<bool()>); public: // Constructor creates a socket and attempts connection to sysmodule Sysmodule(); // Returns type of error occurred Error error(); // Uses syscalls to try to launch the sysmodule bool launch(); // Drops current connection if there is one and attempts to reconnect void reconnect(); // Uses syscalls to try and terminate the sysmodule bool terminate(); // Set a limit on the number of songs to queue (negative indicates no limit) void setQueueLimit(int); // Main function which updates state when replies received void process(); // === Returns private (state) variables === SongID currentSong(); std::string playingFrom(); double position(); bool queueChanged(); std::vector<SongID> queue(); size_t queueSize(); RepeatMode repeatMode(); ShuffleMode shuffleMode(); size_t songIdx(); bool subQueueChanged(); std::vector<SongID> subQueue(); size_t subQueueSize(); PlaybackStatus status(); double volume(); // The following commands block the calling thread until a response is received bool waitRequestDBLock(); bool waitReset(); size_t waitSongIdx(); // === Send command to sysmodule === // Updates relevant variable when reply received or sets error() true // See Common/Protocol.hpp for explanation of functions // Playback commands void sendResume(); void sendPause(); void sendPrevious(); void sendNext(); void sendGetVolume(); void sendSetVolume(const double); void sendMute(); void sendUnmute(); // Manipulate queue void sendGetSubQueue(); void sendGetSubQueueSize(); void sendAddToSubQueue(const SongID); void sendRemoveFromSubQueue(const size_t); void sendSkipSubQueueSongs(const size_t); void sendGetQueue(); void sendGetQueueSize(); void sendSetQueue(const std::vector<SongID> &); void sendGetSongIdx(); void sendSetSongIdx(const size_t); void sendRemoveFromQueue(const size_t); // Shuffle/repeat void sendGetRepeat(); void sendSetRepeat(const RepeatMode); void sendGetShuffle(); void sendSetShuffle(const ShuffleMode); // Status void sendGetSong(); void sendGetStatus(); void sendGetPosition(); void sendSetPosition(double); void sendGetPlayingFrom(); void sendSetPlayingFrom(const std::string &); void sendReleaseDBLock(); void sendReloadConfig(); // Call to 'join' thread (stops main loop) void exit(); // Destructor closes socket ~Sysmodule(); }; #endif
C++
GB18030
7,967
2.890625
3
[]
no_license
#include "fight.h" FIGHT::FIGHT() { } FIGHT::FIGHT(POKEMON *F1, POKEMON *F2) { realA = F1; realB = F2; A = *realA; B = *realB; } FIGHT::FIGHT(const FIGHT & theFight) { realA = theFight.realA; realB = theFight.realB; A = theFight.A; B = theFight.B; } void FIGHT::A_VS_B() { //srand((unsigned)time(NULL)); //int Attacker;//0ʾA1ʾB POKEMON *Attacker = NULL; POKEMON *Defender = NULL; int currentTime = 0; int Aorder = 0; int Border = 0; int SleepTime = 0; if (A.Get_AtkI() <= B.Get_AtkI()) { Attacker = &A; currentTime += A.Get_AtkI(); Defender = &B; } else { Attacker = &B; currentTime += B.Get_AtkI(); Defender = &A; } //ս˫ǰֵ string defenderName = Defender->Get_Name(); string attackName = Attacker->Get_Name(); cout << "սʼ" << endl; cout << attackName << ": " << "HP=" << Attacker->Get_Hp() << ", Atk=" << Attacker->Get_Atk() << ", Def=" << Attacker->Get_Def() << ", Accuracy=" << Attacker->Get_Accuracy() << ", Evasiveness=" << Attacker->Get_Evasiveness() << endl; cout << defenderName << ": " << "HP=" << Defender->Get_Hp() << ", Atk=" << Defender->Get_Atk() << ", Def=" << Defender->Get_Def() << ", Accuracy=" << Defender->Get_Accuracy() << ", Evasiveness=" << Defender->Get_Evasiveness() << endl; while (A.Get_Hp() > 0 && B.Get_Hp() > 0) { defenderName = Defender->Get_Name(); attackName = Attacker->Get_Name(); //Ҫıһatkiעٶ෴ĸ if (Attacker == &A)//A { ++Aorder; } else //B { ++Border; } //ȷʽ int theSkill = rand() % (Attacker->Get_GotSkillCnt());//ѡȡһʽ߼һأûѡʽ SKILL* theSkillPtr = Attacker->Access_GotSkill(theSkill); cout << endl; cout << "ʽ" << Aorder + Border << ":" << endl; cout << attackName << "" << theSkillPtr->SkillName << endl; // double theHitNum = (theSkillPtr->SkillHit)*(Attacker->Get_Accuracy())*(1 - (Defender->Get_Evasiveness())) * 100; int isHit = rand() % 100 + 1; double addition = 1;//ӳɣ switch (theSkillPtr->SkillKind) { case ATTACK: //ʺ˺ //double addition = 1;//ӳɣ if (Defender->Get_Type() - Attacker->Get_Type() == 1 || Defender->Get_Type() - Attacker->Get_Type() == 4) addition = 1.2; else if (Attacker->Get_Type() - Defender->Get_Type() == 1 || Attacker->Get_Type() - Defender->Get_Type() == 4) addition = 0.8; if (isHit <= theHitNum)// { //˺ ///////////////////////////////////// //cout <<"-----add="<<addition<< "------atk=" << Attacker->Get_Atk() << "------def=" << Defender->Get_Def() << "-------skillpower=" << theSkillPtr->SkillPower << endl; double hurt = ((double)(Attacker->Get_Atk()) /(double) (Defender->Get_Def()))*(double)(theSkillPtr->SkillPower)*(addition); double theHp = Defender->Get_Hp(); if (theHp > hurt) { theHp = theHp - hurt; cout << "У" << defenderName << "ܵ" << hurt << "˺" << endl; } else { theHp = 0; cout << "һ" << defenderName << "ܵ" << hurt << "㱩" << endl; } Defender->Input_Hp(theHp); } else { cout << "δУ" << defenderName << "ɵض˹" << endl; } break; case REHP: if (isHit <= theHitNum)//ɹʹʽѪ { double theHp = Attacker->Get_Hp(); theHp = theHp + theSkillPtr->SkillPower; Attacker->Input_Hp(theHp); cout << "ɹѪ" << attackName << "ֵ" << theSkillPtr->SkillPower << "" << endl; } else { cout << "Ѫʧܣ" << endl; } break; case SELFDEFFENCE: if (isHit <= theHitNum)//ɹʹʽ { int theDef = Attacker->Get_Def(); theDef = theDef + theSkillPtr->SkillPower; Attacker->Input_Def(theDef); cout << "ɹУ" << attackName << "" << theSkillPtr->SkillPower << "" << endl; } else { cout << "ʧܣ" << endl; } break; case OPPDEFEENCE: if (isHit <= theHitNum)//ɹʹʽͶԷ { int theDef = Attacker->Get_Def(); if (theDef - theSkillPtr->SkillPower > 10)//Ϊ10 { theDef = theDef - theSkillPtr->SkillPower; cout << "ɹУ" << defenderName << "" << theSkillPtr->SkillPower << "" << endl; } else { cout << "ɹУ" << defenderName << "͵ޣ10㣩" << endl; theDef = 10; } Attacker->Input_Def(theDef); } else { cout << "δܶԵзʵв" << endl; } break; case SELFATTACK: if (isHit <= theHitNum)//ɹʹʽ { int theAtk = Attacker->Get_Atk(); theAtk = theAtk + theSkillPtr->SkillPower; Attacker->Input_Atk(theAtk); cout << "ɹУ" << attackName << "" << theSkillPtr->SkillPower << "" << endl; } else { cout << "ʧܣ" << endl; } break; default: break; } //ս˫ǰֵ cout << attackName << ": " << "HP=" << Attacker->Get_Hp() << ", Atk=" << Attacker->Get_Atk() << ", Def=" << Attacker->Get_Def() //<< ", Accuracy=" << Attacker->Get_Accuracy() << ", Evasiveness=" //<< Attacker->Get_Evasiveness() << endl; << endl; cout << defenderName << ": " << "HP=" << Defender->Get_Hp() << ", Atk=" << Defender->Get_Atk() << ", Def=" << Defender->Get_Def() //<< ", Accuracy=" << Defender->Get_Accuracy() << ", Evasiveness=" //<< Defender->Get_Evasiveness() << endl << endl; << endl; //üʽ;ʺ //һеľ if (((Aorder + 1)*A.Get_AtkI()) < ((Border + 1)*B.Get_AtkI())) { Attacker = &A; Defender = &B; SleepTime = ((Aorder + 1)*A.Get_AtkI()) - currentTime; } else { Attacker = &B; Defender = &A; SleepTime = ((Aorder + 1)*B.Get_AtkI()) - currentTime; } //Sleep(SleepTime);/////////////////////////////////////////////// } //սӳСľ cout << endl; if (A.Get_Hp() > 0)//AӮ { int nowExp = A.Get_Exp(); nowExp = nowExp + winExp; A.Input_Exp(nowExp); nowExp = B.Get_Exp(); nowExp = nowExp + loseExp; B.Input_Exp(nowExp); cout << A.Get_Name() << "WIN!" << "EXP+" << winExp << endl; cout << B.Get_Name() << "LOSE!" << "EXP+" << loseExp << endl; } else if (B.Get_Hp() > 0)//BӮ { int nowExp = B.Get_Exp(); nowExp = nowExp + winExp; B.Input_Exp(nowExp); nowExp = A.Get_Exp(); nowExp = nowExp + loseExp; A.Input_Exp(nowExp); cout << B.Get_Name() << "WIN!" << "EXP+" << winExp << endl; cout << A.Get_Name() << "LOSE!" << "EXP+" << loseExp << endl; } else//ABƽ֣ʵʲ֣ { int nowExp = A.Get_Exp(); nowExp = nowExp + tieExp; A.Input_Exp(nowExp); nowExp = B.Get_Exp(); nowExp = nowExp + tieExp; B.Input_Exp(nowExp); cout << B.Get_Name() << "TIE!" << "EXP+" << tieExp << endl; cout << A.Get_Name() << "TIE!" << "EXP+" << tieExp << endl; } //³ȼϢ A.RefershRank(); B.RefershRank(); //Ƿ if (A.Get_Rank() > realA->Get_Rank())// { //ٰµĵȼ;鷵ظ realA->Input_Exp(A.Get_Exp()); realA->Input_Rank(A.Get_Rank()); realA->Upgrade();// } else { realA->Input_Exp(A.Get_Exp()); realA->Input_Rank(A.Get_Rank()); } if (B.Get_Rank() > realB->Get_Rank()) { realB->Input_Exp(B.Get_Exp()); realB->Input_Rank(B.Get_Rank()); realB->Upgrade(); } else { realB->Input_Exp(B.Get_Exp()); realB->Input_Rank(B.Get_Rank()); } }
PHP
UTF-8
2,177
2.71875
3
[]
no_license
<?php namespace customer\frontend\models; use Yii; use customer\models\sms\MobileCode; use customer\models\sms\EmailCode; /** * 验证码登录方式 * * @author zhangyang <zhangyang@cadoyi.com> */ class CaptchaLoginForm extends CaptchaForm { /** * @var int 发送的验证码 */ public $code; /** * @inheritDoc */ public function rules() { return [ ['username', 'required', 'message' => '请填写手机号或者邮箱'], ['code', 'required', 'message' => '请输入验证码'], ['code', 'validateCode'], ]; } /** * 验证验证码 * * @return void */ public function validateCode() { $data = $this->getSavedCode(); if(!$data || !isset($data['code'])) { return $this->addError('code', '验证码不正确'); } if($data['username'] != $this->username) { return $this->addError('code', '验证码不正确'); } if(time() > $data['expire']) { return $this->addError('code', '验证码已过期'); } } /** * @inheritDoc */ public function clearCode() { $data = $this->getSavedCode(); if($this->isMobile()) { $log = MobileCode::find() ->andWhere(['mobile' => $this->username]) ->andWhere(['code' => $data['code']]) ->orderBy(['id' => SORT_DESC]) ->limit(1) ->one(); } else { $log = EmailCode::find() ->andWhere(['email' => $this->username]) ->andWhere(['code' => $data['code']]) ->orderBy(['id' => SORT_DESC]) ->limit(1) ->one(); } $log->verified = 1; $log->save(); } /** * 开始登陆 * * @return void */ public function login() { if(!$this->validate()) { return false; } $this->clearCode(); $user = $this->getUser(); $customer = $user->customer; return Yii::$app->user->login($customer); } }
C++
UTF-8
13,031
2.625
3
[ "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-other-permissive", "BSL-1.0", "LicenseRef-scancode-mit-old-style" ]
permissive
// Copyright (c) Microsoft Corporation. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // test <atomic> C++11 header with multiple threads #define TEST_NAME "<atomic>, part 1" #undef NDEBUG #include "tdefs.h" #include <assert.h> #include <atomic> #include <limits> #include <memory> #include <thread> // These tests look for synchronization failures on an atomic type. They // test only the unsigned arithmetic types, assuming that the signed types // rely on the same underlying code; they also take advantage of the // standard wraparound behavior of unsigned types. // The tests exercise the following functions: // load() // store() // exchange() // compare_exchange_weak() // compare_exchange_strong() // fetch_add() // fetch_sub() // fetch_xor() // fetch_and and fetch_or are omitted -- it's hard to come up with a useful // invariant that remains true over multiple asynchronous applications of these // operations. These functions will, in general, rely on the same // synchronization mechanism as fetch_xor. If there is an error // in the implementation it should show up in the semantic tests. // All of the tests use the assert() macro for internal checks. They can't // use the CHECK_XXX macros because the CHECK_XXX macros // aren't synchronized, and adding synchronization to the macros would // introduce external synchronization into these tests, defeating their // purpose. // SUPPORT AND CONFIGURATION // adjust to get reasonable testing times for the platform: #if ATOMIC_LLONG_LOCK_FREE static const unsigned long iterations = 1000000; #else // ATOMIC_LLONG_LOCK_FREE static const unsigned long iterations = 100000; #endif // ATOMIC_LLONG_LOCK_FREE inline unsigned long select(unsigned long first, unsigned long second) { // silence warnings return first < second ? first + 1 : second; } template <class Ty> static unsigned long test_iterations() { // limit test iterations to // numeric_limits<Ty>::max() + 1 for small types return select((unsigned long) STD numeric_limits<Ty>::max(), iterations); } // CLASS test_runner class test_runner { // class to run multiple threads and wait for them all to finish public: template <class Fn0> void run_threads(Fn0 fn0) { // run 1 thread thread_count = 1; STD thread thr0(fn0); threads[0].swap(thr0); wait(); } template <class Fn0, class Fn1> void run_threads(Fn0 fn0, Fn1 fn1) { // run 2 threads thread_count = 2; STD thread thr0(fn0); threads[0].swap(thr0); STD thread thr1(fn1); threads[1].swap(thr1); wait(); } template <class Fn0, class Fn1, class Fn2> void run_threads(Fn0 fn0, Fn1 fn1, Fn2 fn2) { // run 3 threads thread_count = 3; STD thread thr0(fn0); threads[0].swap(thr0); STD thread thr1(fn1); threads[1].swap(thr1); STD thread thr2(fn2); threads[2].swap(thr2); wait(); } template <class Fn0, class Fn1, class Fn2, class Fn3> void run_threads(Fn0 fn0, Fn1 fn1, Fn2 fn2, Fn3 fn3) { // run 4 threads thread_count = 4; STD thread thr0(fn0); threads[0].swap(thr0); STD thread thr1(fn1); threads[1].swap(thr1); STD thread thr2(fn2); threads[2].swap(thr2); STD thread thr3(fn3); threads[3].swap(thr3); wait(); } private: void wait() { // wait for all threads to finish for (int i = 0; i < thread_count; ++i) threads[i].join(); } int thread_count; STD thread threads[4]; }; // TESTERS struct flag_tester { // class for testing atomic_flag public: static void run() { // run 4 threads competing for flag test_runner runner; runner.run_threads(&flag_tester::do_it, &flag_tester::do_it, &flag_tester::do_it, &flag_tester::do_it); CHECK_INT(val0, 0); } private: static void do_it() { // use flag as lock surrounding non-optimizable // manipulations of shared variable for (unsigned long i = 0; i < iterations; ++i) { // lock, manipulate, unlock while (flag.test_and_set(STD memory_order_acquire)) { // wait for lock } ++val0; assert(val0 == 1); val0 += 3; val0 /= 2; val0 *= 3; val0 -= 5; assert(val0 == 1); --val0; flag.clear(STD memory_order_release); STD this_thread::yield(); } } static STD atomic_flag flag; static unsigned long val0; }; STD atomic_flag flag_tester::flag; unsigned long flag_tester::val0; // CLASS TEMPLATE read_write_tester template <class Ty> struct read_write_tester { // class for testing acquire/release semantics for load/store ops public: static void run() { // run 2 threads, one writing and one reading test_runner runner; runner.run_threads(&read_write_tester::write, &read_write_tester::read); CHECK_INT(val0 == test_iterations<Ty>() - 1, true); CHECK_INT(val1 == test_iterations<Ty>() - 1, true); } private: static void write() { // do atomic writes with relaxed/release memory order unsigned long limit = test_iterations<Ty>() - 1; for (unsigned long i = 0; i < limit; ++i) { // do atomic stores Ty my_val = val0.load(STD memory_order_relaxed); val0.store(my_val + 1, STD memory_order_relaxed); val1.store(my_val + 1, STD memory_order_release); } } static void read() { // do atomic reads with relaxed/acquire memory order unsigned long limit = test_iterations<Ty>() - 1; for (unsigned long i = 0; i < limit; ++i) { // read values and check for proper update visibility Ty my_val1a = val1.load(STD memory_order_acquire); Ty my_val0a = val0.load(STD memory_order_relaxed); Ty my_val1b = STD atomic_load_explicit(&val1, STD memory_order_relaxed); Ty my_val0b = STD atomic_load_explicit(&val0, STD memory_order_relaxed); assert(my_val1a <= my_val0a); assert(my_val1b <= my_val0b); } } static STD atomic<Ty> val0; static STD atomic<Ty> val1; }; template <class Ty> STD atomic<Ty> read_write_tester<Ty>::val0; template <class Ty> STD atomic<Ty> read_write_tester<Ty>::val1; // CLASS TEMPLATE exchange_tester template <class Ty> struct exchange_tester { // class for testing atomicity of exchange operations public: static void run() { // run 4 threads, all exchanging shared value test_runner runner; runner.run_threads( &exchange_tester::do_it, &exchange_tester::do_it, &exchange_tester::do_it, &exchange_tester::do_it); CHECK_INT(val0 == (iterations & STD numeric_limits<Ty>::max()), true); } private: static void do_it() { // repeatedly exchange values for (unsigned long i = 0; i < iterations; ++i) val0.exchange((Ty)(i + 1)); } static STD atomic<Ty> val0; }; template <class Ty> STD atomic<Ty> exchange_tester<Ty>::val0; template <class Ty> struct cas_weak_tester { // class for testing atomicity of // compare-and-exchange-weak operations public: static void run() { // run 4 threads, all comparing and exchanging shared value test_runner runner; runner.run_threads( &cas_weak_tester::do_it, &cas_weak_tester::do_it, &cas_weak_tester::do_it, &cas_weak_tester::do_it); CHECK_INT(val0 == (Ty) test_iterations<Ty>(), true); } private: static void do_it() { // repeatedly compare-and-exchange values Ty my_val = 0; Ty my_old_val = my_val; unsigned long limit = test_iterations<Ty>() / 4; for (unsigned long i = 0; i < limit; ++i) { // compare-and-exchange incremented value while (!val0.compare_exchange_weak(my_val, my_val + 1)) assert(my_old_val < my_val); my_old_val = my_val; STD this_thread::yield(); } } static STD atomic<Ty> val0; }; template <class Ty> STD atomic<Ty> cas_weak_tester<Ty>::val0; template <class Ty> struct cas_strong_tester { // class for testing atomicity of // compare-and-exchange-strong operations public: static void run() { // run 4 threads, all comparing and exchanging shared value test_runner runner; runner.run_threads( &cas_strong_tester::do_it, &cas_strong_tester::do_it, &cas_strong_tester::do_it, &cas_strong_tester::do_it); CHECK_INT(val0 == (Ty) test_iterations<Ty>(), true); } private: static void do_it() { // repeatedly compare-and-exchange values Ty my_val = 0; Ty my_old_val = my_val; unsigned long limit = test_iterations<Ty>() / 4; for (unsigned long i = 0; i < limit; ++i) { // compare-and-exchange incremented value while (!val0.compare_exchange_strong(my_val, my_val + 1)) assert(my_old_val < my_val); my_old_val = my_val; STD this_thread::yield(); } } static STD atomic<Ty> val0; }; template <class Ty> STD atomic<Ty> cas_strong_tester<Ty>::val0; template <class Ty> struct arithmetic_tester { // class for testing atomicity of arithmetic operations public: static void run() { // run 4 threads, all updating shared value test_runner runner; runner.run_threads(&arithmetic_tester::do_it0, &arithmetic_tester::do_it1, &arithmetic_tester::do_it2, &arithmetic_tester::do_it3); CHECK_INT(val0 == 0, true); } private: static void do_it0() { // increment/decrement by 2 inc_dec(2); } static void do_it1() { // increment/decrement by 3 inc_dec(3); } static void do_it2() { // increment/decrement by max() - 5 inc_dec(STD numeric_limits<Ty>::max() - 5); } static void do_it3() { // increment/decrement by max() - 7 inc_dec(STD numeric_limits<Ty>::max() - 7); } static void inc_dec(Ty value) { // increment/decrement by value unsigned long limit = iterations; for (unsigned long i = 0; i < limit; ++i) val0.fetch_add(value, STD memory_order_acq_rel); for (unsigned long i = 0; i < limit; ++i) val0.fetch_sub(value, STD memory_order_acq_rel); } static STD atomic<Ty> val0; }; template <class Ty> STD atomic<Ty> arithmetic_tester<Ty>::val0; template <class Ty> struct xor_tester { // class for testing atomicity of xor operations public: static void run() { // run 4 threads, all updating shared value test_runner runner; runner.run_threads(&xor_tester::do_it0, &xor_tester::do_it1, &xor_tester::do_it2, &xor_tester::do_it3); CHECK_INT(val0 == 0, true); } private: static void do_it0() { // xor with 0011... xor_it(0x3333333333333333ULL & STD numeric_limits<Ty>::max()); } static void do_it1() { // xor with 0101... xor_it(0x5555555555555555ULL & STD numeric_limits<Ty>::max()); } static void do_it2() { // xor with 1010... xor_it(0xAAAAAAAAAAAAAAAAULL & STD numeric_limits<Ty>::max()); } static void do_it3() { // xor with 1100... xor_it(0xCCCCCCCCCCCCCCCCULL & STD numeric_limits<Ty>::max()); } static void xor_it(Ty value) { // xor with value for (unsigned long i = 0; i < iterations; ++i) val0.fetch_xor(value, STD memory_order_acq_rel); } static STD atomic<Ty> val0; }; template <class Ty> STD atomic<Ty> xor_tester<Ty>::val0; // RUN TESTS template <class Ty> void test_for_type() { // run tests for type Ty read_write_tester<Ty>::run(); exchange_tester<Ty>::run(); cas_weak_tester<Ty>::run(); cas_strong_tester<Ty>::run(); arithmetic_tester<Ty>::run(); xor_tester<Ty>::run(); } void display(const char* mesg) { // optionally display progress message if (!terse) printf("%s", mesg); } void test_main() { // test header <atomic> display("testing atomic_flag:\n"); flag_tester::run(); display("testing type unsigned char:\n"); test_for_type<unsigned char>(); display("testing type unsigned short:\n"); test_for_type<unsigned short>(); display("testing type unsigned int:\n"); test_for_type<unsigned int>(); display("testing type unsigned long:\n"); test_for_type<unsigned long>(); display("testing type unsigned long long:\n"); test_for_type<unsigned long long>(); }
Markdown
UTF-8
1,609
2.59375
3
[]
no_license
--- title: tailwindをAnagularにインストールして使う description: null tags: tailwind updatedAt: 2021-09-21 published: true --- いつもどおり Angular のプロジェクトを作る ```shell > npx -p @angular/cli ng new handson-angular-tailwind 21:01 ? Would you like to add Angular routing? No ? Which stylesheet format would you like to use? SCSS [ https://sass-lang.com/documentation/syntax#scss ``` ```shell npm i -D tailwindcss ``` configファイルを作る ```shell npx tailwindcss init Created Tailwind CSS config file: tailwind.config.js ``` Tailwind のスタイルを参照する ```scss // src/styles.scss @import 'tailwindcss/base'; @import 'tailwindcss/components'; @import 'tailwindcss/utilities'; ``` Tailwind のスタイルは膨大な数があり `@import` で全て参照した状態でビルドすると `.css` ファイルが 4MB近くに膨れ上がってしまう。未使用のスタイルをビルドファイルに含めないようにするには **パージ(purge)** というオプションを使う。 ```js // package.json "scripts": { "build": "NODE_ENV=production ng build", ``` ```js // tailwind.config.js module.exports = { purge: { enabled: process.env.NODE_ENV === 'production', content: ['./src/**/*.{html,ts}'], }, ``` これで `npm run build` した時に CSS が 4KB と小さくなる。`npm start` した時はパージされないため、ブラウザ上でスタイル変更が試せる。
Python
UTF-8
862
4.0625
4
[]
no_license
##Lab 4 ##Nathan Wisla ##1375068 ##AUCSC111 ##October 13, 2016 ##Lab 5: screwing around with a .txt file ##Given a text file, perform operations on the file. ##3. Find the number of occurrences of a number in the entire file 'howMany(inF, num)' ##inF is the open input file def howMany(inF,num): '''Finds the number of times num appears in the file''' ultimateList = [] for line in inF: listOfTheLine = line.split() for element in listOfTheLine: #append each element of the file into the ultimate list ultimateList.append(int(element)) if num in ultimateList: print(ultimateList.count(num)) #count the number you want to count in the ultimate list else: print('Can\'t find it, sorry.') myFile = open('data.txt','r') howMany(myFile, 23) myFile.close()
Java
UTF-8
371
1.804688
2
[]
no_license
package com.chinags.auth.dao; import com.chinags.auth.entity.Article; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; public interface ArticleDao extends JpaRepository<Article, String>, JpaSpecificationExecutor<Article> { Article getArticleByArticleCode(String articleCode); }
Java
UTF-8
2,873
2.640625
3
[]
no_license
package pers.tuershen.nbtedit.compoundlibrary.nms.io; import pers.tuershen.nbtedit.compoundlibrary.nms.code.Base64; import pers.tuershen.nbtedit.compoundlibrary.nms.minecraft.nbt.TagBase; import java.io.*; public class SerializableStream { private static final Base64.Encoder encoder = Base64.getEncoder(); private static final Base64.Decoder decoder = Base64.getDecoder(); private static ByteArrayOutputStream byteArrayOutputStream; protected static String encode(byte[] bytes) { return encoder.encodeToString(bytes); } protected static byte[] decode(String encodedText) { return decoder.decode(encodedText); } /** * 序列化 * @param serializableFormat * @return */ public static String getByteStream(SerializableFormat serializableFormat) { try { byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objStream = new ObjectOutputStream(byteArrayOutputStream); objStream.writeObject(serializableFormat); byte[] data = byteArrayOutputStream.toByteArray(); return encode(data); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 反序列化 * @param data * @return */ public static SerializableFormat deserializeObj(String data) { ByteArrayInputStream byteStream = decodeByteInputStream(data); ObjectInputStream ois = null; try { ois = new ObjectInputStream(byteStream); SerializableFormat obj = (SerializableFormat)ois.readObject(); return obj; } catch (IOException|ClassNotFoundException e) { e.printStackTrace(); } return null; } public static <T extends TagBase> String getTagBaseByteStream(T t){ try { byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objStream = new ObjectOutputStream(byteArrayOutputStream); objStream.writeObject(t); byte[] data = byteArrayOutputStream.toByteArray(); return encode(data); } catch (IOException e) { e.printStackTrace(); } return null; } public static <T extends TagBase> T deserializeTagBase(String data){ ByteArrayInputStream byteStream = decodeByteInputStream(data); ObjectInputStream ois = null; try { ois = new ObjectInputStream(byteStream); T obj = (T)ois.readObject(); return obj; } catch (IOException|ClassNotFoundException e) { e.printStackTrace(); } return null; } public static ByteArrayInputStream decodeByteInputStream(String data){ return new ByteArrayInputStream(decode(data)); } }
Java
UTF-8
2,448
2.53125
3
[]
no_license
package com.isa.restaurant.domain.DTO; import com.isa.restaurant.domain.*; import com.isa.restaurant.ulitity.Utilities; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; /** * Created by Q on 13-May-17. */ @Getter @Setter @AllArgsConstructor(suppressConstructorProperties = true) public class ReservationDTO { private Long id; private RestaurantDTO restaurant; private String startDate; private String startTime; private Long duration; private GuestDTO reserver; private Set<RestaurantTableDTO> tables; private Set<GuestDTO> invites; private Set<DrinkOrderDTO> drinkOrders; private Set<DishOrderDTO> dishOrders; public ReservationDTO() { this.tables = new HashSet<>(); this.invites = new HashSet<>(); this.drinkOrders = new HashSet<>(); this.dishOrders = new HashSet<>(); } public ReservationDTO(Reservation reservation) { this(); DateFormat dfDate = new SimpleDateFormat("dd/MM/yyyy"); DateFormat dfTime = new SimpleDateFormat("HH:mm"); this.id = reservation.getId(); this.restaurant = new RestaurantDTO(reservation.getRestaurant()); this.startDate = dfDate.format(reservation.getDateTimeStart()); this.startTime = dfTime.format(reservation.getDateTimeStart()); this.duration = Utilities.diffDatesToMinutes(reservation.getDateTimeStart(), reservation.getDateTimeEnd()); this.reserver = new GuestDTO(reservation.getReserver()); for (RestaurantTable rt : reservation.getTables()) this.tables.add(new RestaurantTableDTO(rt, false)); for (Invitation invitation : reservation.getInvitations()) this.invites.add(new GuestDTO(invitation.getInvited())); for (Order o : reservation.getOrders()) { for (OrderItem oi : o.getOrderItems()) { if (oi.getIsDish()) this.dishOrders.add(new DishOrderDTO(oi.getDish(), oi.getNumber())); else this.drinkOrders.add(new DrinkOrderDTO(oi.getDrink(), oi.getNumber())); } } // for (Guest g : reservation.getInvites()) // this.invites.add(new GuestDTO(g)); } }
Python
UTF-8
1,978
2.578125
3
[ "BSD-3-Clause" ]
permissive
# -*- coding: utf-8 -*- __docformat__='restructuredtext' """The application's Globals object""" from pylons import config import glob, os from os.path import dirname, exists, join, abspath class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ self._initBundles() self._getRevision() def _getRevision(self): """ Intenta recuperar la revision de 'popserver' a partir de un archivo 'REVISION' en el app root """ rev_file = join(dirname(abspath(__file__)), '..', '..', 'REVISION') self.revision = open(rev_file).read().strip() if exists(rev_file) else None def _initBundles(self): self.stylesheet_bundle_path = None self.javascript_bundle_path = None root = dirname(dirname(abspath(__file__))) mtime_cmp = lambda fname1, fname2: cmp(os.path.getmtime(fname1), os.path.getmtime(fname2)) if config.get('popego.serve_bundled_stylesheets', False): bundles = glob.glob(os.path.join(root, 'public/css', 'popego_style_[0-9]*.css')) # si llegara a haber más de un 'bundle', traer el más nuevo (ie, mayor modification time) self.stylesheet_bundle_path = '/css/%s' % os.path.basename(sorted(bundles, mtime_cmp)[-1]) if len(bundles) > 0 else None # if config.get('popego.serve_bundled_javascripts', False): # bundles = glob.glob(os.path.join(root, 'public/javascripts', 'popego_scripts_[0-9]*.css')) # # si llegara a haber más de un 'bundle', traer el más nuevo (ie, mayor modification time) # self.javascript_bundle_path = '/javascripts/%s' % os.path.basename(sorted(bundles, mtime_cmp)[-1]) if len(bundles) > 0 else None
Markdown
UTF-8
1,308
2.8125
3
[]
no_license
#### Dockerizing Magento 2 with Docker-Compose In this project, we are using: > Web Server: Apache2 > Database Server: Mysql-server-5.7 > PHP version: PHP-7.1 > Magento version: Magento-CE-2.3.4 To begin with, please install docker and docker-compose. Then follow the following steps: 1). Download Magento-CE-2.3.4 and unzip the files and diretories to magento2 folder 2). Set mysql root credentials and name of the database to be created . Go to ~/docker-compose.yml and change mysql root password in database_server in: > MYSQL_DATABASE: magento2 > MYSQL_USER: dbuser > MYSQL_USER: dbpass 3). Set up custom port to set up up magento localhost url, Currently 8005 is used so the local site is accesed as http://127.0.0.1:8005/ > - "8005:80" 4). Build the docker image. > docker-compose build 5). Check the built image as: > docker images 6). Run the containers from built image as: > docker-compose up -d 7). Check the running docker containers by command: > docker ps 8). You can check the server requirement are ok for magento installation in this url : http://127.0.0.1:8005/reqCheck.php 9). Set up Magento by using http://127.0.0.1:8005/, provide the same DB details added in docker-compose.yml 10). Complete the setup and site is visible in http://127.0.0.1:8005/ url.
Markdown
UTF-8
2,250
2.8125
3
[ "MIT" ]
permissive
--- layout: post title: "Seattle Chocolates Espresso Truffles" excerpt: "If its hot and humid enough, even the staunchest coffee drinker will look for alternative ways to enjoy coffee. This weekend some friends provided such an outlet for my coffee cravings - Espresso Truffles." modified: categories: reviews tags: [Review] image: feature: review-default.jpg credit: WeGraphics creditlink: http://wegraphics.net/downloads/free-ultimate-blurred-background-pack/ comments: true share: true author: --- ![Seattle Chocolates](/images/seattle_choc.jpg){: .pull-right}If its hot and humid enough, even the staunchest coffee drinker will look for alternative ways to enjoy coffee. This weekend some friends provided such an outlet for my coffee cravings - Espresso Truffles. This being my first experience with the Seattle Chocolates Company, I was not sure what to expect. If the presentation was any indication of the chocolate inside (the ribbon is nice touch), I was in for a treat. Opening the box revealed individually wrapped candy, I quickly opened one of the truffles and found something I love — Dark Chocolate. Things were starting to look promising! Now there are two types of candy eaters in my opinion, those who take several bites to extend the enjoyment time of the candy, and those who take more of a neanderthalian approach and pop the entire treat into their mouth. Since it was an espresso truffle I threw decorum out the window and popped the entire piece in my mouth. As my teeth breached the dark chocolate exterior I quickly discovered the espresso infused milk chocolate interior. Unlike lesser creations that simple add coffee flavouring to their chocolate, these truffles contain actual espresso coffee. The espresso flavour is clearly evident along with hints of vanilla and coconut. I could eat an entire box of these truffles they are that good. I thought I quite possibly had found the perfect melding of chocolate and coffee until to my horror I read on the ingredient list… >Decaffeinated Espresso Coffee Who am I kidding, its hard to split hairs about something like this when you are talking about fine chocolate. I will be buying these for my coffee loving friends soon.
Java
UTF-8
739
2.046875
2
[]
no_license
package struts; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.ServletContext; import org.apache.struts.action.*; public final class CalcurationAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res ){ HttpSession session = req.getSession(); ActionMessages errors = new ActionMessages(); CalcurationForm calcuForm = ( CalcurationForm )form; int num1 = calcuForm.getNum1(); int num2 = calcuForm.getNum2(); session.setAttribute( "result", num1 + num2 ); return ( mapping.findForward( "success" )); } }
PHP
UTF-8
2,474
2.640625
3
[]
no_license
<?php namespace frontend\models; use Yii; /** * This is the model class for table "conferences". * * @property int $conf_id * @property string $conf_name * @property string $conf_year * @property string $conf_venue * @property string $conf_domain * @property string $conf_scope * @property string $conf_start_date * @property string $conf_end_date * @property string $conf_abstract_DL * @property string $conf_poster_DL * @property string $conf_fullpaper_DL * @property string $created_at * @property string $updated_at * @property int $created_by * @property int $updated_by * * @property Submissions[] $submissions */ class Conferences extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'conferences'; } /** * {@inheritdoc} */ public function rules() { return [ [['conf_name', 'conf_year', 'conf_venue', 'conf_start_date', 'conf_end_date', 'conf_abstract_DL', 'conf_poster_DL', 'conf_fullpaper_DL'], 'required'], [['conf_year', 'conf_start_date', 'conf_end_date', 'conf_abstract_DL', 'conf_poster_DL', 'conf_fullpaper_DL', 'created_at', 'updated_at', 'conf_domain', 'conf_scope', 'created_by', 'updated_by'], 'safe'], [['created_by', 'updated_by'], 'integer'], [['conf_name'], 'string', 'max' => 512], [['conf_venue'], 'string', 'max' => 100], [['conf_domain', 'conf_scope'], 'string', 'max' => 255], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'conf_id' => 'Conf ID', 'conf_name' => 'Conf Name', 'conf_year' => 'Year', 'conf_venue' => 'Venue', 'conf_domain' => 'Domain', 'conf_scope' => 'Scope', 'conf_start_date' => 'Start Date', 'conf_end_date' => 'End Date', 'conf_abstract_DL' => 'Abstract Deadline', 'conf_poster_DL' => 'Poster Deadline', 'conf_fullpaper_DL' => 'Fullpaper Deadline', 'created_at' => 'Created At', 'updated_at' => 'Updated At', 'created_by' => 'Created By', 'updated_by' => 'Updated By', ]; } /** * @return \yii\db\ActiveQuery */ public function getSubmissions() { return $this->hasMany(Submissions::className(), ['conf_id' => 'conf_id']); } }
Python
UTF-8
2,144
2.71875
3
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
""" How to use: Step 1 - Edit this file variables accordingly: host = 'HOSTNAME_OR_IP' user = 'SSH_USER_NAME' password = 'SSH_USER_PASSWORD' Step 2 - Go to another terminal and execute the test (for ANY code modification, please restart this step) docker exec -it netapi_app python ./manage.py shell execfile('networkapi/plugins/Juniper/JUNOS/samples/sample_networkapi_junos_plugin.py') Step 3 [optional] - Check more logs in networkapi: docker exec -it netapi_app tail -f /tmp/networkapi.log Step 4 - Check result in equipment, exp.: ssh SSH_USER@HOSTNAME_OR_IP cli show interfaces gr-0/0/0 """ import logging from networkapi.plugins.Juniper.JUNOS.plugin import JUNOS # Temporary Equipment class class EquipamentoAcesso: def __init__(self, fqdn, user, password): self.fqdn = fqdn self.user = user self.password = password # Config log messages log = logging.getLogger(__name__) log_test_prefix = '[Junos Plugin]' log.debug('%s Start sample' % log_test_prefix) # Requirements (args, equipment and plugin) host = 'HOSTNAME_OR_IP' user = 'SSH_USER_NAME' password = 'SSH_USER_PASSWORD' # Temporary equipment access object (defined above as EquipamentoAcesso) equipment_access = EquipamentoAcesso(host, user, password) # NetworkAPI junos plugin object equip_plugin = JUNOS(equipment_access=equipment_access) """ OPEN CONNECTION """ print("Open connection {}...".format(host)) print("Connection result: {}".format(equip_plugin.connect())) """ CHECK PRIVILEGES """ print("Check privilege {}...".format(host)) print("Privilege result: {}".format(equip_plugin.ensure_privilege_level())) """ EXECUTE CONFIGURATION """ print("Execute configuration file {}...".format(host)) # equip_plugin.exec_command(command='set interfaces gr-0/0/0 description "Some description teste3 for gr-0/0/0 at "') print("Execute configuration result: {}".format(equip_plugin.copyScriptFileToConfig(filename="networkapi/plugins/Juniper/JUNOS/samples/sample_command.txt"))) """ CLOSE CONNECTION """ print("Close connection {}...".format(host)) print("Close connection result: {}".format(equip_plugin.close()))
Java
UTF-8
1,669
2.34375
2
[]
no_license
package top.flobby.boot.quickstart.controller.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @author :Flobby * @version :1.0 * @date :2021/3/4 * @description :统一结果封装 */ @Data @AllArgsConstructor @NoArgsConstructor @Builder @ApiModel("统一响应结果") public class AjaxResponse { @ApiModelProperty("请求响应状态码") private Integer code; @ApiModelProperty("请求结果描述信息") private String message; @ApiModelProperty("请求返回数据") private Object data; public static AjaxResponse success() { AjaxResponse ajaxResponse = new AjaxResponse(); ajaxResponse.setCode(200); ajaxResponse.setMessage("请求成功"); return ajaxResponse; } public static AjaxResponse success(Object obj) { AjaxResponse ajaxResponse = new AjaxResponse(); ajaxResponse.setCode(200); ajaxResponse.setMessage("请求成功"); ajaxResponse.setData(obj); return ajaxResponse; } public static AjaxResponse success(Object obj, String message) { AjaxResponse ajaxResponse = new AjaxResponse(); ajaxResponse.setCode(200); ajaxResponse.setMessage(message); ajaxResponse.setData(obj); return ajaxResponse; } public static AjaxResponse failure(String message) { AjaxResponse ajaxResponse = new AjaxResponse(); ajaxResponse.setCode(5001); ajaxResponse.setMessage(message); return ajaxResponse; } }
Java
UTF-8
4,145
2.375
2
[ "Apache-2.0" ]
permissive
package org.ubg.org.ubg.graph; import com.arangodb.ArangoCursor; import com.arangodb.ArangoDBException; import com.arangodb.ArangoGraph; import com.arangodb.entity.EdgeEntity; import com.arangodb.entity.VertexEntity; import com.arangodb.velocypack.exception.VPackParserException; import org.ubg.builder.connection.ConnectionBuilder; import org.ubg.builder.connection.exception.UException; import org.ubg.graph.elements.CategoryEdge; import org.ubg.graph.elements.CategoryVertex; import org.ubg.org.ubg.math.FTrending; import org.ubg.org.ubg.utils.Constants; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; /** * Created by dincaus on 2/16/17. */ public class GraphManager { private ConnectionBuilder arangoInstance; public GraphManager() throws IOException, UException { this.arangoInstance = new ConnectionBuilder.Builder().build(); } public GraphManager(String host) throws IOException, UException { this.arangoInstance = new ConnectionBuilder.Builder().host(host).build(); } public GraphManager(String host, String username, String password, Boolean useSsl) throws IOException, UException { if(useSsl != null && useSsl != true) this.arangoInstance = new ConnectionBuilder.Builder().host(host).username(username).password(password).build(); else this.arangoInstance = new ConnectionBuilder.Builder().host(host).useSSL(true).username(username).password(password).build(); } public VertexEntity addNode(ArangoGraph ag, String userId, CategoryVertex cv) throws UException { if(ag == null) throw new UException("The graph isn't provided."); return ag.vertexCollection(Constants.getVertexCollectionName(userId)).insertVertex(cv); } public void processCategory(String userId, String category) throws UException { ArangoGraph ag = this.arangoInstance.createGraph(Constants.GRAPH_DB_NAME, userId); String nodes[] = category.split("/"); Collection<VertexEntity> vNodes = new ArrayList<>(); Collection<EdgeEntity> vEdges = new ArrayList<>(); for(String n: nodes) { try { VertexEntity ve = ag.vertexCollection(Constants.getVertexCollectionName(userId)).getVertex(n, VertexEntity.class); vNodes.add(ve); } catch (ArangoDBException adbe) { vNodes.add(addNode(ag, userId, new CategoryVertex(n))); } catch (Exception ex) { throw new UException(ex); } } FTrending fTrening = (step, param) -> (float)(Math.exp(-param*step) + 0.005*step); int index = 0; while(index++ < vNodes.size()-1) { VertexEntity lNode = (VertexEntity)((ArrayList)vNodes).get(index-1); VertexEntity fNode = (VertexEntity)((ArrayList)vNodes).get(index); if(lNode == null || fNode == null) continue; try { String edgeKey = lNode.getKey() + "_" + fNode.getKey(); CategoryEdge ee = ag.edgeCollection(Constants.getEdgeCollectionName(userId)).getEdge(edgeKey, CategoryEdge.class); ee.incCount(1L); ee.incWeight(fTrening.calculate(ee.getCount(), 2L)); ag.edgeCollection(Constants.getEdgeCollectionName(userId)).updateEdge(edgeKey, ee); } catch (ArangoDBException adbe) { if(adbe.getCause() != null && adbe.getCause().getClass().getName().compareTo(VPackParserException.class.getName()) == 0) throw new UException(adbe); vEdges.add(ag.edgeCollection(Constants.getEdgeCollectionName(userId)).insertEdge(new CategoryEdge(lNode, fNode))); } catch (Exception ex) { throw new UException(ex); } } } public void processCategory(String userId, Collection<String> categories) { categories.forEach(category -> { try { this.processCategory(userId, category); } catch (UException ue) { } }); } }
Python
UTF-8
5,816
2.84375
3
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2021/8/1 17:54 # @Author : Tty # @Email : 1843222968@qq.com # @File : hand_pysheds.py import warnings import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from calculate_acc_thresh import get_threshold_automatically from array_to_raster import array2Raster def fill_nan(array: np.ndarray) -> np.ndarray: """Replace NaNs with values interpolated from their neighbors Replace NaNs with values interpolated from their neighbors using a 2D Gaussian kernel, see: https://docs.astropy.org/en/stable/convolution/#using-astropy-s-convolution-to-replace-bad-data """ try: import astropy.convolution except ImportError: raise ImportError('fill_nan calculation requires astropy to be installed') kernel = astropy.convolution.Gaussian2DKernel(x_stddev=3) # kernel x_size=8*stddev with warnings.catch_warnings(): warnings.simplefilter("ignore") array = astropy.convolution.interpolate_replace_nans( array, kernel, convolve=astropy.convolution.convolve ) return array # N NE E SE S SW W NW ArcGIS = (64, 128, 1, 2, 4, 8, 16, 32) def calculate_hand(dem_file, msn=None, acc_thresh=None, dirmap=ArcGIS): """ Calculate Height Above Nearest Drainage 参考: https://github.com/mdbartos/pysheds/blob/master/examples/hand.ipynb https://github.com/ASFHyP3/asf-tools/blob/9f83b9f6cdbe20f5785b0130b051d3c01c2661aa/asf_tools/hand/calculate.py#L77 :param dem_file:dem文件路径 :param msn:map stream network,精确的河道数据 :param acc_thresh:界定河道的阈值 :param dirmap:流向图的流向表示,默认为ArcGIS流向图的表示方法 :return: """ try: from pysheds.grid import Grid except ImportError: raise ImportError('HAND calculation requires Pysheds to be installed') # 读取DEM grid = Grid.from_raster(dem_file, data_name='dem') dem_plot(grid.dem, grid.extent) # fill填洼 print('filling depressions') grid.fill_depressions('dem', out_name='filled_dem') if np.isnan(grid.filled_dem).any(): print('NaNs encountered in filled DEM; filling.') grid.filled_dem = fill_nan(grid.filled_dem) # Resolving flats print('Resolving flats') grid.resolve_flats('filled_dem', out_name='inflated_dem') if np.isnan(grid.inflated_dem).any(): print('NaNs encountered in inflated DEM; replacing NaNs with original DEM values') grid.inflated_dem[np.isnan(grid.inflated_dem)] = grid.dem[np.isnan(grid.inflated_dem)] array2Raster(grid.inflated_dem, 'ps_corrected_dem.tif', refImg=dem_file) # 计算流向图 # D8 flow directions print('Obtaining flow direction') grid.flowdir(data='inflated_dem', out_name='dir', dirmap=dirmap) if np.isnan(grid.dir).any(): print('NaNs encountered in flow direction; filling.') grid.dir = fill_nan(grid.dir) dir_plot(grid.dir, grid.extent, dirmap) array2Raster(grid.dir, 'dir.tif', refImg=dem_file) # 计算流量图 print('Calculating flow accumulation') grid.accumulation(data='dir', out_name='acc') if np.isnan(grid.acc).any(): print('NaNs encountered in accumulation; filling.') grid.acc = fill_nan(grid.acc) acc_plot(grid.acc, grid.extent) array2Raster(grid.acc, 'acc.tif', refImg=dem_file) # 若未设置界定河道的阈值,则依据MSN自动计算阈值 if acc_thresh is None: acc_thresh = get_threshold_automatically(msn, 'acc.tif') print(f'Calculating HAND using accumulation threshold of {acc_thresh}') hand = grid.compute_hand('dir', 'inflated_dem', grid.acc > acc_thresh, inplace=False) if np.isnan(hand).any(): print('NaNs encountered in HAND; filling.') hand = fill_nan(hand) hand_plot(hand, extent=grid.extent) array2Raster(hand, 'hand_' + str(acc_thresh) + '.tif', refImg=dem_file) def dem_plot(dem, extent): fig, ax = plt.subplots(figsize=(8, 6)) fig.patch.set_alpha(0) plt.imshow(dem, extent=extent, cmap='terrain', zorder=1) plt.colorbar(label='Elevation (m)') plt.grid(zorder=0) plt.title('Digital elevation map') plt.xlabel('Longitude') plt.ylabel('Latitude') plt.tight_layout() plt.show() def dir_plot(dir, extent, dirmap): fig = plt.figure(figsize=(8, 6)) fig.patch.set_alpha(0) plt.imshow(dir, extent=extent, cmap='viridis', zorder=2) boundaries = ([0] + sorted(list(dirmap))) plt.colorbar(boundaries=boundaries, values=sorted(dirmap)) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.title('Flow direction grid') plt.grid(zorder=-1) plt.tight_layout() plt.show() def acc_plot(acc, extent): fig, ax = plt.subplots(figsize=(8, 6)) fig.patch.set_alpha(0) plt.grid('on', zorder=0) im = ax.imshow(acc, extent=extent, zorder=2, cmap='cubehelix', norm=colors.LogNorm(1, acc.max())) plt.colorbar(im, ax=ax, label='Upstream Cells') plt.title('Flow Accumulation') plt.xlabel('Longitude') plt.ylabel('Latitude') plt.show() def hand_plot(hand, extent): plt.subplots(figsize=(8, 6)) # minvalue must be positive plt.imshow(hand + 1, zorder=1, cmap='terrain', interpolation='bilinear', extent=extent, norm=colors.LogNorm(vmin=1, vmax=np.nanmax(hand))) plt.colorbar(label='Height above nearest drainage (m)') plt.title('Height above nearest drainage', size=14) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.tight_layout() plt.show() if __name__ == '__main__': import os os.chdir('../data') hand = calculate_hand('zhengzhou_dem.tif', msn='zhengzhou_river.shp')
Swift
UTF-8
2,035
2.75
3
[]
no_license
// // CommitStatus.swift // OctoKit // // Created by Matthew on 01/02/2017. // Copyright © 2017 Matthew. All rights reserved. // import Foundation import ObjectMapper /// A status belonging to a commit. public class CommitStatus: Object { // MARK: - Instance Properties /// The date at which the status was originally created. public internal(set) dynamic var creationDate: Date? /// The date the status was last updated. This will be equal to /// creationDate if the status has not been updated. public internal(set) dynamic var updatedDate: Date? /// The state of this status. public internal(set) dynamic var state: String? /// The URL where more information can be found about this status. Typically this /// URL will display the build output for the commit this status belongs to. public internal(set) dynamic var targetURLString: String? /// A description for this status. Typically this will be a high-level summary of /// the build output for the commit this status belongs to. public internal(set) dynamic var statusDescription: String? /// A context indicating which service (or kind of service) provided the status. public internal(set) dynamic var context: String? /// The user whom created this status. public internal(set) dynamic var creator: User? // MARK: - Lifecycle public required convenience init?(map: Map) { self.init() } // MARK: - Mapping public override func mapping(map: Map) { super.mapping(map: map) let dateTransform = ISO8601DateTransform() creationDate <- (map["created_at"], dateTransform) updatedDate <- (map["updated_at"], dateTransform) state <- map["state"] targetURLString <- map["target_url"] statusDescription <- map["description"] context <- map["context"] creator <- map["creator"] } }
JavaScript
UTF-8
2,784
2.515625
3
[]
no_license
define(['$','util','../base'],function(require) { var $=require('$'); var util=require('util'); var sl=require('../base'); var slice=Array.prototype.slice; var Tip=function(text) { this._tip=$('<div class="tip" style="display:none">'+(text||'')+'</div>').appendTo(document.body); }; Tip.prototype={ _hideTimer: null, _clearHideTimer: function() { var me=this; if(me._hideTimer) { clearTimeout(me._hideTimer); me._hideTimer=null; } }, _visible: false, show: function(msec) { var me=this, tip=me._tip; me._clearHideTimer(); if(msec) me._hideTimer=setTimeout(function() { me._hideTimer=null; me.hide(); },msec); if(me._visible) { return; } me._visible=true; tip.css({ '-webkit-transform': 'scale(0.2,0.2)', display: 'block', visibility: 'visible', opacity: 0 }).animate({ scale: "1,1", opacity: 0.9 },200,'ease-out'); return me; }, hide: function() { var me=this, tip=me._tip; if(!me._visible) { return; } me._visible=false; tip.animate({ scale: ".2,.2", opacity: 0 },200,'ease-in',function() { tip.hide().css({ '-webkit-transform': 'scale(1,1)' }) }); me._clearHideTimer(); return me; }, msg: function(msg) { var me=this, tip=me._tip; tip.html(msg).css({ '-webkit-transform': 'scale(1,1)', '-webkit-transition': '' }); if(tip.css('display')=='none') { tip.css({ visibility: 'hidden', display: 'block', marginLeft: -1000 }); } tip.css({ marginTop: -1*tip.height()/2, marginLeft: -1*tip.width()/2 }); return me; } }; var t=new Tip(); var tip=function(msg) { if(msg==='this') return t; else if($.inArray(['msg','show','hide'],msg)>=0) { var args=slice.apply(arguments); t[args.shift()].apply(t,args); } else t.msg(msg).show(2000); } sl.Tip=Tip; sl.tip=tip; return tip; });
C++
UTF-8
624
2.90625
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; bool is_prime(long long p) { if (p < 2) return false; if (p == 2) return true; if (p % 2 == 0) return false; for (long long d = 3; d * d <= p; d += 2) { if (p % d == 0) return false; } return true; } int main() { long long n; cin >> n; for (int q = 2; q < 64; q++) { long long p = round(exp(log(n) / q)); long long nn = 1; for (int i=0; i < q; i++) nn *= p; if (nn == n && is_prime(p)) { cout << p << ' ' << q; return 0; } } cout << 0; return 0; }
Java
UTF-8
2,125
2.328125
2
[]
no_license
package com.metropia.requests; import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.json.JSONException; import android.content.Context; import com.metropia.models.User; import com.metropia.utils.HTTP.Method; import com.metropia.utils.datetime.RecurringTime; public class TripUpdateRequest extends UpdateRequest { /** * Trip ID */ private int tid; private User user; /** * Trip name */ private String name; /** * Origin address ID */ private int oid; /** * Destination address ID */ private int did; private RecurringTime recurringTime; private String link; public TripUpdateRequest(String link, int tid, User user, String name, int oid, int did, RecurringTime recurringTime) { this.tid = tid; this.user = user; this.name = name; this.oid = oid; this.did = did; this.recurringTime = recurringTime; this.link = link; } public void execute(Context ctx) throws IOException, JSONException, InterruptedException { if(NEW_API){ this.username = user.getUsername(); this.password = user.getPassword(); url = link.replaceAll("\\{id\\}", String.valueOf(tid)); Map<String, String> params = new HashMap<String, String>(); params.put("user_id", String.valueOf(user.getId())); params.put("name", name); params.put("origin_id", String.valueOf(oid)); params.put("destination_id", String.valueOf(did)); params.put("arrival_time", String.format("%02d:%2d:00", recurringTime.getHour() % 24, recurringTime.getMinute())); params.put("datetype", String.format("%d", recurringTime.getWeekdays())); executeHttpRequest(Method.PUT, url, params, ctx); }else{ String url = String.format("%s/favroutes-update/?rid=%d&uid=%d&name=%s&oid=%d&did=%d&arrivaltime=%d:%d:00&datetype=%d", HOST, tid, user.getId(), URLEncoder.encode(name), oid, did, recurringTime.getHour(), recurringTime.getMinute(), recurringTime.getWeekdays()); executeUpdateRequest(url, ctx); } } }
Python
UTF-8
3,175
3.09375
3
[]
no_license
import sys, os sys.path.append(os.path.relpath('../../')) from src.datasets import * from pathIO import * import timeit, time from functools import partial class BenchmarkMethodInterface: """An interface for benchmarking and testing of various searching methods Set whatever you want in __init__, but leave any real data manipulation to initialize(). Set self.result to a DataPath in run() for validation. Assert initialization in run """ def __init__(self): self.result = None self.result_is_valid = None self.result_is_best_known = None def initialize(self, data_path): """ Load data """ raise NotImplementedError( "Should have implemented this" ) def run(self): """ Run your method and save reslut to self.result as a DataPath """ raise NotImplementedError( "Should have implemented this" ) def validate(self, known_paths_file=None): """ Validates the self.result for consistency with rules. Optionaly compares to provided results file """ assert self.result, "initialize, run and then validate" known_paths = parse_paths_file(known_paths_file) if known_paths is not None: best_known_path = get_best_path(known_paths) self.result_is_valid = self.result in known_paths self.result_is_best_known = self.result == best_known_path else: known_paths = [] best_known_path = None #what if we found a path that we didn't put in? if not self.result_is_valid and self.result.is_valid(): self.result_is_valid = True if best_known_path and self.result.price <= best_known_path.price: print( "New best path discovered!" ) self.result_is_best_known = True known_paths.append(self.result) save_paths_file(known_paths, known_paths_file) return self.result_is_valid def benchmark(self, input_file, valid_results_file=None, reps=10, timeout=10): """ Check the average time of execution on given file. """ t_init = timeit.timeit(partial(self.initialize, input_file), number=reps)/reps t_run = timeit.timeit(self.run, number=reps)/reps print( "input: {}, {} reps".format(input_file, reps) ) print( "average time: {:.6f} ({:.6f} + {:.6f})".format(t_init + t_run, t_init, t_run)) if self.result : if len( self.result.flights ) > 10: print( "->path: {} ... {} \n->price: {}".format(self.result.flights[:3], self.result.flights[-3:], self.result.price) ) else: print( "->path: {}\n ->price: {}".format(self.result.flights, self.result.price) ) self.validate(valid_results_file) print ( "Result valid?: {}".format(self.result_is_valid) ) print ( "Result best known?: {}".format(self.result_is_best_known) ) else: print ( "Failed to find path" )
JavaScript
UTF-8
1,376
2.90625
3
[ "MIT" ]
permissive
/* jshint latedef:false */ var win = window; var doc = document; var domNs = 'get-image-url'; var dom = { body : doc.getElementsByTagName('body')[0], head : doc.getElementsByTagName('head')[0], style: doc.querySelector('.' + domNs + '-style') }; function cleanup () { dom.head.removeChild(dom.style); dom.body.removeEventListener('click', getImageUrl, false); } function resolveUrl ( url ) { if ( !(/^https?\:\/\/|^\/\//.test(url)) ) { url = win.location.protocol + '//' + win.location.host + (/^\//.test(url) ? '' : '/') + url; } return url; } function getImageUrl ( e ) { var target = e.target; e.preventDefault(); if ( target.nodeName === 'IMG' ) { cleanup(); win.prompt('Image URL', resolveUrl(target.getAttribute('src'))); } } // Check for existence of stylesheet // If it doesn’t exist, create one if ( dom.style === null ) { dom.style = doc.createElement('style'); dom.style.appendChild(doc.createTextNode('')); dom.style.classList.add('get-image-url-style'); dom.head.appendChild(dom.style); // Add stylesheet rules dom.style.sheet.insertRule('body:after { content:""; position:fixed; z-index:9998; top:0; right:0; bottom:0; left:0; background:rgba(0,0,0,0.8); }', 0); dom.style.sheet.insertRule('img { position:relative; z-index:9999; outline:4px solid hotpink; }', 0); dom.body.addEventListener('click', getImageUrl, false); }
PHP
UTF-8
4,012
2.734375
3
[]
no_license
<?php /** * This file is part of the DpnXmlSitemapBundle package. * * (c) Björn Fromme <mail@bjo3rn.com> * * For the full copyright and license information, please view the Resources/meta/LICENSE * file that was distributed with this source code. */ namespace Dpn\XmlSitemapBundle\Sitemap; use Symfony\Component\Templating\EngineInterface; /** * Sitemap manager class * * @author Björn Fromme <mail@bjo3rn.com> * @author Kevin Bond <kevinbond@gmail.com> */ class SitemapManager { /** * @var array */ protected $defaults; /** * @var int */ protected $maxPerSitemap; /** * @var \Dpn\XmlSitemapBundle\Sitemap\Entry[]|null */ protected $entries; /** * @var GeneratorInterface[] */ protected $generators = array(); /** * @var EngineInterface */ protected $templating; /** * @param array $defaults * @param int $maxPerSitemap * @param EngineInterface $templating */ public function __construct(array $defaults, $maxPerSitemap, EngineInterface $templating) { $this->defaults = array_merge( array( 'priority' => null, 'changefreq' => null, ), $defaults ); $this->maxPerSitemap = intval($maxPerSitemap); $this->templating = $templating; } /** * @param GeneratorInterface $generator */ public function addGenerator(GeneratorInterface $generator) { $this->generators[] = $generator; } /** * @return \Dpn\XmlSitemapBundle\Sitemap\Entry[] */ public function getSitemapEntries() { if (null !== $this->entries) { return $this->entries; } $entries = array(); foreach ($this->generators as $generator) { $entries = array_merge($entries, $generator->generate()); } $this->entries = $entries; return $this->entries; } /** * @return int */ public function countSitemapEntries() { return count($this->getSitemapEntries()); } /** * @return int */ public function getNumberOfSitemaps() { $total = $this->countSitemapEntries(); if ($total <= $this->maxPerSitemap) { return 1; } return intval(ceil($total / $this->maxPerSitemap)); } /** * @param int $number * * @return \Dpn\XmlSitemapBundle\Sitemap\Entry[] * * @throws \InvalidArgumentException */ public function getEntriesForSitemap($number) { $numberOfSitemaps = $this->getNumberOfSitemaps(); if ($number > $numberOfSitemaps) { throw new \InvalidArgumentException('Number exceeds total sitemap count.'); } if (1 === $numberOfSitemaps) { return $this->getSitemapEntries(); } $sitemaps = array_chunk($this->getSitemapEntries(), $this->maxPerSitemap); return $sitemaps[$number - 1]; } /** * @param int|null $number * * @return string */ public function renderSitemap($number = null) { $entries = null === $number ? $this->getSitemapEntries() : $this->getEntriesForSitemap($number); return $this->templating->render( 'DpnXmlSitemapBundle::sitemap.xml.twig', array( 'entries' => $entries, 'default_priority' => Entry::normalizePriority($this->defaults['priority']), 'default_changefreq' => Entry::normalizeChangeFreq($this->defaults['changefreq']), ) ); } /** * @param string $host * * @return string */ public function renderSitemapIndex($host) { return $this->templating->render( 'DpnXmlSitemapBundle::sitemap_index.xml.twig', array( 'num_sitemaps' => $this->getNumberOfSitemaps(), 'host' => $host, ) ); } }
Java
UTF-8
868
3.390625
3
[ "MIT" ]
permissive
package prob046.permutations; import java.util.*; /** * Created by yanya04 on 7/23/2017. * Modified by yanya04 on 5/2/2018. * Modified by yanya04 on 5/14/2018. */ public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if(nums == null || nums.length == 0) return res; backtrack(res, new LinkedHashSet<Integer>(), nums); return res; } private void backtrack(List<List<Integer>> res, Set<Integer> set, int[] nums){ if(set.size() == nums.length){ res.add(new ArrayList<>(set)); return; } for(int i = 0; i < nums.length; i ++){ if(set.contains(nums[i])) continue; set.add(nums[i]); backtrack(res, set, nums); set.remove(nums[i]); } } }
Markdown
UTF-8
4,392
2.578125
3
[]
no_license
<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* - [Base release off latest release tag](#base-release-off-latest-release-tag) - [Base release off latest commit (for "unstable packages")](#base-release-off-latest-commit-for-unstable-packages) - [Arch Linux VCS guidelines](#arch-linux-vcs-guidelines) - [Debian](#debian) - [My personal preference](#my-personal-preference) <!-- END doctoc generated TOC please keep comment here to allow auto update --> #Pkg versioning [Snapshot packages](https://fedoraproject.org/wiki/Packaging:NamingGuidelines#Snapshot_packages) contain data about where the snapshot came from as well as ordering information for rpm. The information about the snapshot will be called %{checkout} in this section. %{checkout} consists of the date that the snapshot is made in YYYYMMDD format, a short (2-5 characters) string identifying the type of revision control system or that this is a snapshot, and optionally, up to 13 characters (ASCII) alphanumeric characters that could be useful in finding the revision in the revision control system. For instance, if you create a snapshot from a git repository on January 2, 2011 with git hash 9e88d7e9efb1bcd5b41a408037bb7cfd47220a64, %{checkout} string could be any of the following: ``` 20110102snap 20110102git 20110102git9e88d7e ``` If the snapshot package is considered a "pre-release package", follow the guidelines listed in Pre-Release Packages for snapshot packages, using the %{checkout} that you decide on above. (For instance, in kismet-0-0.3.20040204svn, 20040204svn is the %{checkout}) If the snapshot is a "post-release package", follow the guidelines in the Post-Release Packages section. Where the %{posttag} in that section is the %{checkout} string you decided on above. Example (post-release cvs): ``` kismet-1.0-1%{?dist} (this is the formal release of kismet 1.0) kismet-1.0-2%{?dist} (this is a bugfix build to the 1.0 release) kismet-1.0-3.20050515cvs%{?dist} (move to a post-release cvs checkout) kismet-1.0-4.20050515cvs%{?dist} (bugfix to the post-release cvs checkout) kismet-1.0-5.20050517cvs%{?dist} (new cvs checkout, note the increment of %{X}) ``` *** ## Base release off latest release tag ``` # clone and checkout desired commit git clone -b "$branch" "$git_url" "${git_dir}" cd "${git_dir}" # get latest base release # This is used because upstream does tends to use release tags release_tag=$(git describe --abbrev=0 --tags) git checkout $release_tag 1> /dev/null # cleanup for pkg version naming pkgver=$(sed "s|[-|a-z]||g" <<<"$release_tag") # Alter pkg suffix based on commit pkgsuffix="git+bsos${pkgrev}" ``` ## Base release off latest commit (for "unstable packages") ``` # clone and checkout desired commit git clone -b "$branch "$git_url" "${git_dir}" cd "${git_dir}" latest_commit=$(git log -n 1 --pretty=format:"%h") git checkout $latest_commit 1> /dev/null # get latest base release for changelog # This is used because upstream does tend to use release tags pkgver_orig=$(git tag | tail -n 1) pkgver=$(sed "s|[-|a-z]||g" <<<"$pkgver_orig") # Alter pkg suffix based on commit pkgsuffix="${latest_commit}git+bsos${pkgrev}" ``` # Arch Linux VCS guidelines I actually prefer to use the guidelines Arch Linux sets forth, unless otherwise already set. See: https://wiki.archlinux.org/index.php/VCS_package_guidelines # Debian Debian tends to use this format (as seen with [llvm-snapshot](http://debian.cc.lehigh.edu/debian/pool/main/l/llvm-toolchain-snapshot/)): ``` package_4.0~svn279916-1_all.deb ``` Which us essentially the the packge version + revision count. # My personal preference I prefer to version packages like this: **Tagged:** ``` # ${PKG_VER}+${OS_TAG}-${PKG_REV} package_0.1+bsos-1 ``` **Snapshot:** ``` # ${PKG_VER}+r${REV}.${COMMIT}+${OS_TAG}-${PKG_REV} package_0.1+r000.0000000a+bsos-1 ``` **Alternatively::** ``` package_0.1+git20161114.0000000a+bsos-1 ``` **Code:** ``` DATE_SHORT=$(date +%Y%m%d) LATEST_COMMIT=$(git log -n 1 --pretty=format:"%h") REVISION_COMMIT=$(printf "r%s.%s" "$(git rev-list --count HEAD)" "$(git rev-parse --short HEAD)") ``` If There is no package version to go of off, use something like `0.0` or `0.0.0`.
JavaScript
UTF-8
4,347
2.515625
3
[]
no_license
import React from 'react'; import {observable, action} from "mobx"; import QueueApi from "../api/QueueApi"; class QueueStore { @observable queues = []; @observable isLoading = false; @observable queue = {}; @observable messages = {}; @observable currentPage = 1; @observable lastPage = 1; @action getAllQueues = async (page = 1) => { this.isLoading = true; try { const res = await QueueApi.getAllQueues(page); this.queues = res.data.data; this.currentPage = res.data.meta.current_page; this.lastPage = res.data.meta.last_page; } catch (e) { } finally { this.isLoading = false; } }; @action unregisterQueue = async (queueId) => { try { this.queues = this.queues.map(q => { if (q.id === queueId) return { ...q, isLoading: true }; return q; }); const res = await QueueApi.unregisterQueue(queueId); this.queues = this.queues.map(q => { if (q.id === queueId) return { ...q, number_waiting_people: q.number_waiting_people - 1, status: res.data.status }; return q; }); } catch (e) { } finally { this.queues = this.queues.map(q => { return { ...q, isLoading: false }; }) } }; @action registerQueue = async (queueId) => { try { this.queues = this.queues.map(q => { if (q.id === queueId) return { ...q, isLoading: true }; return q; }); const res = await QueueApi.registerQueue(queueId); this.queues = this.queues.map(q => { if (q.id === queueId) return { ...q, number_waiting_people: q.number_waiting_people + 1, status: res.data.status }; return q; }); } catch (e) { } finally { this.queues = this.queues.map(q => { return { ...q, isLoading: false }; }) } }; @action getQueues = async (userId, page = 1) => { this.isLoading = true; try { const res = await QueueApi.getQueues(userId, page); this.queues = res.data.data; this.currentPage = res.data.meta.current_page; this.lastPage = res.data.meta.last_page; } catch (e) { } finally { this.isLoading = false; } }; @action updateForm = (field, value) => { this.queue[field] = value; }; @action saveQueue = async () => { try { this.isLoading = true; await QueueApi.saveQueue(this.queue); return true; } catch (e) { this.messages = e.response.data.messages; return false; } finally { this.isLoading = false; } }; @action resetForm = () => { this.queue = {}; this.messages = {} }; @action loadQueue = async (id) => { this.isLoading = true; try { const res = await QueueApi.getQueue(id); this.queue = res.data.queue; } catch (e) { } finally { this.isLoading = false; } } @action updateQueue = async () => { this.isLoading = true; try { await QueueApi.updateQueue(this.queue); return true; } catch (e) { this.messages = e.response.data.message; return false; } finally { } }; @action deleteQueue = (id) => { QueueApi.deleteQueue(id); this.queues = this.queues.filter(queue => queue.id !== id); } } export default new QueueStore();
Python
UTF-8
4,263
2.671875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.10.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + default_dir = './' import random import json from matplotlib import pyplot as plt import matplotlib.font_manager as fm import datetime import tweepy import os def output_char_list(question_json, cell_min=10, cell_max=20): with open(question_json, 'r') as f_in: question_list = json.load(f_in) char_list = question_list[random.choice(list(question_list))] vertical = random.randint(cell_min, cell_max) horizontal = random.randint(cell_min, cell_max) num_char = vertical*horizontal diff_char_no = random.randint(1, num_char) output_list = [] for num in range(1, num_char+1): if num == diff_char_no: output_list.append(char_list[1]) else: output_list.append(char_list[0]) return vertical, horizontal, diff_char_no, output_list, char_list def font_pick(fonts_json, default_dir): with open(fonts_json, 'r') as f_in: fonts_list = json.load(f_in) font_name = random.choice(list(fonts_list)) font_path = os.path.join(default_dir, fonts_list[font_name]) return font_name, font_path def question_fig(font_path, vertical, horizontal, output_list, fig_dir, timenow): fp = fm.FontProperties(fname=font_path) fig = plt.figure(figsize=(horizontal, vertical)) plt.clf() i = 0 for x in range(1, horizontal+1): for y in range(1, vertical+1): plt.text((x-1)/horizontal, (y-1)/vertical, output_list[i], fontsize=55, fontproperties=fp) i = i + 1 plt.gca().spines['right'].set_visible(False) plt.gca().spines['top'].set_visible(False) plt.gca().spines['bottom'].set_visible(False) plt.gca().spines['left'].set_visible(False) plt.tick_params(labelbottom=False, labelleft=False, labelright=False, labeltop=False, bottom=False, left=False, right=False, top=False) plt.xlabel('3PySci https://3pysci.com', fontsize=30, fontproperties=fp) plt.savefig(f'{fig_dir}/{timenow}.png', facecolor="white", bbox_inches='tight', pad_inches = 0.1) def log_write(question_log, timenow, vertical, horizontal, diff_char_num, char_list, font_name): with open(question_log, 'a') as f_in: row = f'{timenow},{vertical},{horizontal},{diff_char_num},{char_list},{font_name}\n' f_in.write(row) def applytotwitter(settings_json, fig_dir): png_files = [] for file in os.listdir(fig_dir): if file[-4:] == '.png': png_files.append(file) upload_png = sorted(png_files)[-1] with open(settings_json, 'r') as f_in: settings = json.load(f_in) auth = tweepy.OAuthHandler(settings['consumer_key'], settings['consumer_secret']) auth.set_access_token(settings['access_token'], settings['access_token_secret']) api = tweepy.API(auth, wait_on_rate_limit = True) text = 'この中に一つだけ違う文字があります😁\n#見つけたらRT\n\n#間違い探し\n#まちがいさがし\n#脳トレ\n#アハ体験\n#クイズ\n#Python\n#プログラミング\n\nhttps://github.com/Nori-3PySci/find_the_difference' api.update_with_media(status = text, filename = f'{fig_dir}/{upload_png}') # - def main(): question_json = os.path.join(default_dir, 'question.json') fonts_json = os.path.join(default_dir, 'fonts.json') settings_json = os.path.join(default_dir, 'settings.json') question_log = os.path.join(default_dir, 'question_log.txt') timenow = datetime.datetime.now().strftime("%Y%m%d%H%M%S") fig_dir = os.path.join(default_dir, 'fig') vertical, horizontal, diff_char_num, output_list, char_list = output_char_list(question_json) font_name, font_path = font_pick(fonts_json, default_dir) question_fig(font_path, vertical, horizontal, output_list, fig_dir, timenow) log_write(question_log, timenow, vertical, horizontal, diff_char_num, char_list, font_name) applytotwitter(settings_json, fig_dir) if __name__ == '__main__': main()
C++
UTF-8
1,246
2.859375
3
[ "Apache-2.0" ]
permissive
// // Created by Lai on 2020/12/1. // #ifndef OPENGLDEMO_IMAGEINFO_H #define OPENGLDEMO_IMAGEINFO_H #include <cstdlib> class ImageInfo { public: int width, height; unsigned char *pixels; //std::string brushId; ImageInfo() : width(0), height(0), pixels(nullptr)/*,brushId(nullptr)*/ { } ImageInfo(int width, int height, unsigned char *pixels) : width(width), height(height), pixels(pixels)/*,brushId(brushId) */{} ~ImageInfo() { if (pixels != nullptr) { free(pixels); pixels = nullptr; //LOGE("11111", "free(pixels)") } }; }; class BrushInfo { public: typedef enum { DRAW = 0, ERASER = 1 } OutType; BrushInfo() : brushSize(15.0f), outType(DRAW), imageInfo(nullptr), R(0.0f), G(0.0f), B(0.0f), A(1.0f), isTextureRotate(true) {} ~BrushInfo() { if (imageInfo != nullptr) { delete imageInfo; imageInfo = nullptr; } } float brushSize; OutType outType; ImageInfo *imageInfo; float R; float G; float B; float A; bool isTextureRotate; }; #endif //OPENGLDEMO_IMAGEINFO_H