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
Markdown
UTF-8
1,859
2.78125
3
[ "Apache-2.0" ]
permissive
# ml optic This is a Jupyter Magic to run Optic statements against a MarkLogic endpoint. ### Installation 1. Download the code and run pip -install . from the directory 2. Start Jupyter and create a notebook. 3. Run %load_ext ml_optic. The notebook should reply: marklogic optic magic loaded. 4. You can use %%ml_optic? to get the docs 5. Open tests.ipynb for the test notebook ### Usage The magic needs a connection string to a working MarkLogic endpoint along with user credentials. Internally, we use /v1/eval and /v1/rows so you need the following Privileges for the connecting user: - http://marklogic.com/xdmp/privileges/xdmp-eval - http://marklogic.com/xdmp/privileges/xdmp-eval-in - http://marklogic.com/xdmp/privileges/xdbc-eval - http://marklogic.com/xdmp/privileges/xdbc-eval-in - http://marklogic.com/xdmp/privileges/rest-reader In a cell as the first line put the magic, for example: %%ml_optic op://admin:admin@localhost:8000 The rest of the cell contains the Optic query, exactly as it would look in Query Console. Note it must finish with op:result() #### Connections and Output Once a connection is made it's persisted, so subsequent cells only need to have %%ml_optic in them. Output is to a named variable or ml_optic if not set. Results are returned as a Pandas DataFrame by default. #### Substitution Python variables can be substituted into the Optic query in the usual way {VAR}, i.e if there is a python var ROWS=10 then => op:limit({ROWS}) will be substituted before evaluation. In the case of XQuery and Javascript, the optic library import will get inserted automatically into the first line of the cell.. #### Example List all TDEs using the standard port using xquery as parser and default var. ``` %%ml_optic op://admin:admin@localhost:8000 -p xquery op:from-view("sys", "sys_tables",'') => op:result() ```
PHP
UTF-8
3,196
2.75
3
[]
no_license
<?php require_once("php_include/basic_includes.php"); require_once("php_include/db_user.php"); echo "<title>Login</title>"; if (isset($_GET["source"]) && $_GET["source"] == "cart") { echo "Bitte loggen Sie sich ein um den Warenkorb zu nutzen!<br>"; } if (isset($_GET["newuser"])) { echo "Vielen Dank für die Registrierung! Loggen Sie sich bitte ein!"; } if (isset($_SESSION["temp_cart"])) $ifcart = "&source=cart"; else { $idcart = ""; } if (isset($_POST["email"]) && isset($_POST["password"]) && isset($_POST["firstname"]) && isset($_POST["lastname"]) && isset($_POST["street"]) && isset($_POST["zip"]) && isset($_POST["city"]) && isset($_POST["phone"])) { if (!db_check_if_user($_POST["email"])) { db_create_user($_POST["email"], $_POST["password"], $_POST["firstname"], $_POST["lastname"], $_POST["street"], $_POST["zip"], $_POST["city"], $_POST["country"], $_POST["phone"]); header("Location: /login.php?newuser=true$ifcart"); } else { echo "Es besteht bereits ein Konto mit dieser Email-Adresse!"; } } else if (isset($_POST["email"])) { if (db_check_login($_POST["email"], $_POST["password"])) { session_create(db_get_user($_POST["email"])); header("Location: /"); } else { echo "Anmeldedaten fehlerhaft!"; } } ?> <html> <body> <div> <div class="login"> <h5>Mit bestehendem Konto anmelden:</h5> <form method="POST"> <input type="email" name="email" placeholder="email" requiered> <input type="password" name="password" placeholder="password" required> <input type="submit" value="Login"> </form><br> </div> <div class="register"> <h5>Neues Konto eröffnen:</h5> <form method="POST"> <label for="email"><b>Email</b></label> <input type="email" name="email" required><br> <label for="password"><b>Passwort</b></label> <input type="password" name="password" required><br> <label for="firstname"><b>Vorname</b></label> <input type="text" name="firstname" required><br> <label for="lastname"><b>Nachname</b></label> <input type="text" name="lastname" required><br> <label for="street"><b>Straße</b></label> <input type="text" name="street" required><br> <label for="zip"><b>PLZ</b></label> <input type="text" name="zip" required><br> <label for="city"><b>Stadt</b></label> <input type="text" name="city" required><br> <label for="country"><b>Land</b></label> <input type="text" name="country" required><br> <label for="phone"><b>Telefon</b></label> <input type="text" name="phone" required> <input type="submit" value="Registrieren"> </form> </div> </div> <form action="/login.php"> </form>
Markdown
UTF-8
1,963
3.5
4
[ "MIT" ]
permissive
# Computing-Eigenvalues-and-Eigenvectors-using-Normalized-Power-Iteration-together-with-Deflation In this project, I implemented the normalized power iteration algorithm together with deflation to find two eigenvalues and corresponding eigenvector for the dominant eigenvalue of a given matrix A, where A is a square matrix. Implementation of the normalized power iteration algorithm together with deflation to find two eigenvalues and corresponding eigenvector for the dominant eigenvalue of a given matrix A on C++ ---------------------- Command Line Arguments ---------------------- The program has three command line arguments for the parameters. The first argument is the name of the file you read the matrix from, the second argument is the tolerance, which will be used in the normalized power iteration algorithm, and the third argument is the name of your output file. ------------------------- How to Run "source.cpp" ------------------------- “source.cpp” is written in C++. You can use any compiler as you wish. Dev-C++, with TDM-GCC 4.9.2 compiler is tested and recommended. ------------------ Design Decisions ------------------ This program computes Eigenvalues and Eigenvectors using Normalized Power Iteration together with Deflation. This program contains many matrix operations thus I decided to create a matrix class and implement all the operations. The calc_eigenThings() method computes the eigen things of the corresponding matrix. Since I was going to use the algorithm I mentioned above I decided this function to be a recursive function, i.e call itself until the conditions are met, to find the eigenthings of the given matrix. After finding, I decided to remove the eigenthings and create a new matrix B from A. Then call the same function calc_eigenThings() for matrix B. This operation yields the second eigenthings for the matrix A. Same prodecure can be followed to obtain further eigenthings of the matrix A.
PHP
UTF-8
2,437
2.765625
3
[]
no_license
<?php namespace App\Library; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use Illuminate\Support\Facades\Log; /** * Class GuzzleLibrary * @package App\Library * * @author joven <joven@cafe24corp.com>, * @version 1.0 * @date 12/3/2020 4:24 PM */ class GuzzleLibrary { /** * [URL] End point to use for * API requests * @var string $sEndpoint */ private $sEndpoint; /** * Return value of guzzle * @var array|string $mGuzzleResponse */ private $mGuzzleResponse; /** * Generate a Guzzle/HTTP request. * @param $sUri * @param $aRequest * @param $sRequestType * @return array|string */ static function requestGuzzle($sRequestType, $sUri, $aRequest) { try { $oClient = new Client(['verify' => false]); $oResponse = $oClient->request($sRequestType, $sUri, $aRequest); $mResponse = $oResponse->getBody()->getContents(); } catch (GuzzleException $e) { return self::requestGuzzle($sRequestType, $sUri, $aRequest); } return $mResponse; } /** * Set API endpoint * @param string $sEndpoint * @return $this */ public function setEndpoint($sEndpoint) { $this->sEndpoint = $sEndpoint; return $this; } /** * @param array $aRequest * @param array $aHeaders * @param $sRequestBodyType * @return $this */ private function setLogs(array $aRequest, array $aHeaders, $sRequestBodyType) { Log::info($this->mGuzzleResponse); Log::info([ 'request' => $aRequest, 'headers' => $aHeaders, 'body_type' => $sRequestBodyType ]); return $this; } /** * Send Request to API * * @param array $aParams * @param string $sMethod * @return mixed */ public function guzzleApi($aParams = [], $sMethod = 'GET') { $sUri = env('API_URL') . $this->sEndpoint; $aParams = [ 'json' => $aParams ]; $this->mGuzzleResponse = GuzzleLibrary::requestGuzzle($sMethod, $sUri, $aParams); $this->setLogs($aParams, $aHeaders = [], $sRequestBodyType = ''); if (is_array($this->mGuzzleResponse) === true) { return $this->mGuzzleResponse; } return json_decode($this->mGuzzleResponse, true); } }
C++
UTF-8
529
2.671875
3
[]
no_license
#include <stdio.h> #include <iostream> #include <uuid/uuid.h> int main() { uuid_t uu; int i; uuid_generate(uu); for(i=0; i<16; i++) { printf("%02X-",uu[i]); } printf("\n"); char buf[33]; uuid_generate(uu); snprintf(buf,33,"%02X",uu[0]); snprintf(buf,33, "%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", uu[0],uu[1],uu[2], uu[3], uu[4], uu[5], uu[6], uu[7], uu[8],uu[9],uu[10],uu[11],uu[12],uu[13],uu[14],uu[15]); std::cout << buf << std::endl; return 0; }
Markdown
UTF-8
4,761
3.1875
3
[ "MIT" ]
permissive
# Paso 6: Crear la primer componente de React [Volver al paso 5](/es/step5_add_django_webpack_loader) ## Conceptos de React que vamos a usar en este paso Si nunca has visto estos conceptos, puedes tomarse tu tiempo y leer sobre ellos accediendo a los enlaces. Usaremos: - Componentes de presentación y contenedores: [presentational vs container components](https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0) - Composición: [composition vs inheritance](https://reactjs.org/docs/composition-vs-inheritance.html) - Jsx: [introducing jsx](https://reactjs.org/docs/introducing-jsx.html) and [jsx in depth](https://reactjs.org/docs/jsx-in-depth.html) - Children prop: [this.props.children](https://learn.co/lessons/react-this-props-children) ## Crear una vista Primero, creamos una vista en la carpeta `src/views` (en `workshop/front/src/views`) y agregamos el archivo `App.jsx` adentro. Este va a ser uno de nuestros puntos de entrada para **webpack**. **webpack** buscará ese archivo, luego seguirá todas sus importaciones y las agregará al paquete, para que al final tengamos un gran archivo `App.jsx` que pueda ser utilizado por el navegador. ```javascript import React from "react" import { render } from "react-dom" import App from '../containers/App' render(<App/>, document.getElementById('app')) ``` ## Crear un contenedor Después, creamos una carpeta `src/containers` (en `workshop/front/src/containers`) y agreguamos el archivo `App.jsx` adentro. Este es el primer componente de React, en su interior tendrá una función de renderizado con el componente de presentación **App**. ```javascript import React from "react" import AppComponent from "../components/App" export default class App extends React.Component { render() { return ( <AppComponent /> ) } } ``` ## Crear una componente Como podes ver, **App** intenta importar otra componente llamada `AppComponent`. Ahora vamos a crear el archivo que intenta importar, `workshop/front/src/components/App/index.jsx`: ```javascript import React from "react" import Headline from "../Headline" export default class App extends React.Component { render() { return ( <div className="container"> <div className="row"> <div className="col-sm-12"> <Headline>Sample App!</Headline> </div> </div> </div> ) } } ``` ## Agregar sub-componente Y otra vez, esa componente importa otra componente llamada `Headline`. Vamos a crearla en `workshop/front/src/components/Headline/index.jsx`: ```javascript import React from "react" export default class Headline extends React.Component { render() { return ( <h1>{ this.props.children }</h1> ) } } ``` ## Agregar la vista App a las entidades de webpack En `workshop/front/webpack.base.config.js`: ```diff entry: { // Add as many entry points as you have container-react-components here + App: ['./src/views/App'], vendors: ['react', 'babel-polyfill'], }, ``` En `workshop/front/webpack.local.config.js`: ```diff // Use webpack dev server config.entry = { + App: ['./src/views/App'], vendors: ['react', 'babel-polyfill'], } ``` ## Actualizar gitignore Y finalmente debemos actualizar el archivo `.gitignore` y agregarle el archivo `workshop/front/workshop/static/`. ## Resultado Puede que te preguntes por qué estoy usando la componente `App` (container) y otra `AppComponent`. Esto tendrá más sentido en posteriores pasos. Usaremos `Redux` para administrar el estado de nuestra aplicación y veremos que Redux requiere varias configuraciones para envolver su aplicación y manejar sus estados. Para mantener mis archivos más limpios, me gusta tener un archivo contenedor, que luego importa el componente real de ReactJS que quiero construir. También notarás que separé mis componentes en una carpeta `containers` y en una carpeta `components`. Puedes pensar en esto un poco como las vistas de Django. La template principal es tu contenedor. Contiene la estructura general y dependencias para tu página. En la carpeta `componentes` tendremos mucho componentes más pequeñas que hacen una unica cosa. Estos componentes serán reutilizados y orquestados por `containers`, por ende las componentes serían las equivalentes a las templates parciales más pequeñas que usted importa en Django usando el etiqueta `{% import %}`. En este punto puedes ejecutar el build: ```bash # con docker docker exec -it workshopjs ./node_modules/.bin/webpack --config webpack.local.config.js # sin docker cd front/src ./node_modules/.bin/webpack --config webpack.local.config.js ``` Y esto debe generar algunos archivos en `workshop/front/workshop/static/bundles/`. [Paso 7: Usar el paquete](/es/step7_use_the_bundle)
JavaScript
UTF-8
1,054
2.84375
3
[]
no_license
angular.module('WebMIDI').service('Command', function () { const minNote = 0; const maxNote = 127; var baseNotes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']; var notes = {}; // 60 = middle C (C3) this.getNote = getNote; this.getNumber = getNumber; function init() { initNotes(); console.debug(notes); } function initNotes() { for (var startNote = minNote; startNote <= maxNote; startNote++) { notes[startNote] = getBaseNote(startNote) + getOctave(startNote); } } function getOctave(startNote) { var num = Math.floor((startNote - minNote) / 12); return num === 0 ? '' : num; } function getBaseNote(startNote) { var mod = startNote % 12; return baseNotes[mod]; } function getNote(number) { return notes[number]; } function getNumber(note) { return Object.keys(notes).find(function (key) { return notes[key] === note; }); } init(); });
Python
UTF-8
91
2.8125
3
[]
no_license
def print_sorry(): for i in range(1,101): print("I am sorry! \n") print_sorry()
Java
UTF-8
709
2.609375
3
[]
no_license
/* * Classname: FileSystemUtils.java * Author: Héctor Hernández Chávez * Date: 12-ago-2019 */ package javaee.examples.cdi.events.reactive; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; /** * @author Héctor Hernández Chávez */ public class FileSystemUtils { public static String save(File file, String path, String fileName) throws IOException { File fileToSave = new File(System.getProperty("java.io.tmpdir") + "/" + path + "/" + fileName); try (InputStream input = new FileInputStream(file)) { Files.copy(input, fileToSave.toPath()); } return fileToSave.getAbsolutePath(); } }
Python
UTF-8
3,284
2.90625
3
[]
no_license
def segment(data: str, slice_size: int): encoded = data.encode() packet_list = [] slices = [encoded[i * slice_size:i * slice_size + slice_size] for i in range(len(encoded) // slice_size + 1)] i = 0 for slice in slices: syn = 0 fin = 0 if i == 0: syn = 1 if i == len(slices): fin = 1 packet_list.append(Datagram(SYN=syn, FIN=fin, SEQ=i, PAYLOAD=slice)) i = i + 1 return packet_list class Datagram(object): def __init__(self, SYN=0, FIN=0, ACK=0, TYPE=0, SEQ=0, SEQACK=0, MAX_LENGTH=1024, PAYLOAD=b''): self.SYN = SYN self.FIN = FIN self.ACK = ACK self.TYPE = TYPE # Type is add to present whether the packet is a syn or fin packet self.SEQ = SEQ self.SEQACK = SEQACK self.LEN = len(PAYLOAD) self.MAX_LENGTH = MAX_LENGTH self.PAYLOAD = PAYLOAD self.packet = b'' self.CHECKSUM = self.checksum() self.pack() def set_ack(self, ACK): self.ACK = ACK self.packet[0:1] = int.to_bytes(self.TYPE * 8 + self.SYN * 4 + self.FIN * 2 + self.ACK * 1, byteorder='big', length=1) def set_type(self, TYPE): self.TYPE = TYPE self.packet[0:1] = int.to_bytes(self.TYPE * 8 + self.SYN * 4 + self.FIN * 2 + self.ACK * 1, byteorder='big', length=1) def set_seqack(self, SEQACK): self.SEQACK = SEQACK self.packet[5:9] = int.to_bytes(SEQACK, length=4, byteorder='big') def checksum(self): # Input: data # Output: checksum checksum = 0 for byte in self.PAYLOAD: checksum += byte checksum %= 65536 return ~checksum & 0xffff def pack(self): # Input: a str with LEN length # Output: the package with header and data send_data = int.to_bytes(self.TYPE * 8 + self.ACK * 4 + self.FIN * 2 + self.SYN * 1, byteorder='big', length=1) send_data = send_data + self.SEQ.to_bytes(4, "big") send_data = send_data + self.SEQACK.to_bytes(4, "big") send_data = send_data + self.LEN.to_bytes(4, "big") send_data = send_data + self.CHECKSUM.to_bytes(2, "big") send_data = send_data + self.PAYLOAD self.packet = send_data def depack(self, data: bytes): # Input: data # Output: If the data satisfy the checksum, # The inf and header # header_list = [] pre = int.from_bytes(data[0:1], "big") self.SEQ = int.from_bytes(data[1:5], "big") self.SEQACK = int.from_bytes(data[5:9], "big") self.LEN = int.from_bytes(data[9:13], "big") self.CHECKSUM = int.from_bytes(data[13:15], "big") self.PAYLOAD = data[15:] if __name__ == "__main__": a = "1234512345123451234512" b = 'iagsdgajsgadsda' dg = Datagram(PAYLOAD=a.encode()) print(dg.packet) a2 = segment(a, 8) for item in a2: print(item.packet) dg.depack(item.packet) print(dg.SEQ) print(dg.PAYLOAD.decode()) print(dg.LEN)
C++
UTF-8
7,780
2.59375
3
[]
no_license
#include <assign2.h> void error(const char *msg) { perror(msg); exit(1); } string get_time(){ time_t t = time(0); // get time now tm* now = localtime(&t); string ts = to_string(now->tm_mday) + "-" + to_string((now->tm_mon + 1))+ "-" + to_string((now->tm_year + 1900)) + " " + to_string(now->tm_hour) + ":" + to_string(now->tm_min) + ":" + to_string(now->tm_sec) + " "; return ts; } string get_time_compact(){ time_t t = time(0); // get time now tm* now = localtime(&t); string ts = to_string((now->tm_mon + 1))+ "-" + to_string(now->tm_mday) + "-" + to_string((now->tm_year + 1900)) + "-" + to_string(now->tm_hour) + "-" + to_string(now->tm_min); return ts; } string get_base_name(string file_path){ string base_filename = file_path.substr(file_path.find_last_of("/") + 1); return base_filename; } string strip_extn(string basename){ string file_name_wo_extn = basename.substr(0,basename.find_last_of(".")); return file_name_wo_extn; } int* open_log_file(int port){ struct stat st = {0}; if (stat("logs", &st) == -1) { mkdir("logs", 0777); } string log_file_path="logs/peer-"+to_string(port)+"_"+get_time_compact()+".log"; int *logfd = (int *) malloc(sizeof(int)); *logfd = open(log_file_path.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644); return logfd; } int* open_file(string dir_path, string file_name){ struct stat st = {0}; if (stat(dir_path.c_str(), &st) == -1) { mkdir(dir_path.c_str(), 0777); } string file_path=dir_path+"/"+file_name; int *fd = (int *) malloc(sizeof(int)); //*fd = open(file_path.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644); *fd = open(file_path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); return fd; } void write_to_file(string dir_path, string file_name, string content){ struct stat st = {0}; if (stat(dir_path.c_str(), &st) == -1) { mkdir(dir_path.c_str(), 0777); } string file_path=dir_path+"/"+file_name; ofstream outfile; outfile.open(file_path.c_str(), ios::out | ios::trunc); outfile << content << endl; outfile.close(); } char* read_from_file(string dir_path, string file_name){ //cout << "reading from file: " << file_name<< endl; struct stat st = {0}; if (stat(dir_path.c_str(), &st) == -1) { mkdir(dir_path.c_str(), 0777); } string file_path=dir_path+"/"+file_name; ifstream f(file_path); stringstream buffer; buffer << f.rdbuf(); const string& tmp = buffer.str(); char* cstr = (char*)tmp.c_str(); return clone(cstr); } pair<int*,char*> read_from_file_ld(string dir_path, string file_name){ //cout << "reading from file: " << file_name<< endl; struct stat st = {0}; if (stat(dir_path.c_str(), &st) == -1) { mkdir(dir_path.c_str(), 0777); } string file_path=dir_path+"/"+file_name; ifstream f(file_path); stringstream buffer; buffer << f.rdbuf(); const string& tmp = buffer.str(); char* cstr = (char*)tmp.c_str(); int *read_size = (int *) malloc(sizeof(int)); //memcpy(read_size, &(buffer.str().size()), sizeof(int)); *read_size = buffer.str().size(); //pair<int,char*> p_r = clone3(tmp); //*read_size = p_r.first; return make_pair(read_size,clone(cstr)); //return make_pair(read_size,p_r.second); } char* read_piece_data_from_file(string file_path, int piece_idx, int piece_size){ ifstream fl(file_path, ios::binary); int seek_pos = piece_idx*CHUNK_SIZE; char* piece_data = new char[piece_size]; fl.seekg(seek_pos,ios::beg); fl.read(piece_data, piece_size); cout << "PIECE IDX " << piece_idx << endl; cout << "PIECE SIZE " << piece_size << endl; cout << "SEEK POS " << seek_pos << endl; cout << "READ SIZE " << fl.gcount() << endl; fl.close(); return piece_data; } void write_piece_data_to_file(string file_path, int piece_idx, int piece_size, char* piece_data){ ofstream fl; //fl.open(file_path, ios::out|ios::binary); fl.open(file_path, ios::binary); int seek_pos = piece_idx*CHUNK_SIZE; fl.seekp(seek_pos,ios::beg); cout << "----------------------------------------" << endl; cout << "idx :" << piece_idx << ", seek_pos: " << seek_pos << endl; /*char* mybuff = (char *)malloc(piece_size); bzero(mybuff,piece_size); memcpy(mybuff,piece_data, piece_size); cout << mybuff << endl; fl.write(mybuff, piece_size); free(mybuff); */ fl.write(piece_data, piece_size); fl.flush(); cout << "PIECE SIZE: " << piece_size << " Filepath: " << file_path<< endl; cout << "piece_idx*CHUNK_SIZE: " << piece_idx*CHUNK_SIZE << endl; fl.close(); } void write_piece_data_to_file2(string file_path, int piece_idx, int piece_size, char* piece_data){ /*cout << "=====================================" << endl; cout << "SIZE: " << strlen(piece_data) << endl; cout << "IDX: " << piece_idx << endl; cout << "DOWNLOAD 2: " << endl;*/ FILE *file_ptr; file_ptr = fopen(file_path.c_str(), "r+b"); int offset = piece_idx*CHUNK_SIZE; fseek(file_ptr, offset, SEEK_SET); char* mybuff = (char *)malloc(piece_size); bzero(mybuff,piece_size); memcpy(mybuff,piece_data, piece_size); //cout << "PIECE SIZE: " << piece_size << " Filepath: " << file_path<< endl; int written_c = fwrite(mybuff, 1, piece_size, file_ptr);; //int written_c = fwrite(piece_data, 1, piece_size, file_ptr); //cout << "DATA WIRTING" << mybuff << endl; //cout << "WRITTEN SIZE: " << written_c << endl; fflush(file_ptr); fclose(file_ptr); } Value parseJson(char* pieces_info_str){ Value pieces_info_root; Reader reader; bool parsing_status = reader.parse( pieces_info_str, pieces_info_root ); if(!parsing_status) return "issues on parsing pieces info"; return pieces_info_root; } pair<int,char*> get_msg(string s){ char* msg = clone((char*)s.c_str()); return make_pair(s.size(),msg); } int write_msg(int* fd, string msg_str){ pair<int,char*> msg = get_msg(msg_str); int written_size = write (*fd, msg.second, (ssize_t) msg.first); return written_size; } int write_msg_line(int* fd, string msg_str){ msg_str=msg_str+"\n"; return write_msg(fd,msg_str); } unsigned char* get_hash(char* str1){ const unsigned char* str = (const unsigned char*) str1; //unsigned char hash[SHA_DIGEST_LENGTH]; // == 20 unsigned char* hash = (unsigned char *) malloc(SHA_DIGEST_LENGTH); SHA1(str, sizeof(str) - 1, hash); cout << "hash val = "<<hash<<endl; char mdString[SHA_DIGEST_LENGTH*2+1]; for (int i = 0; i < SHA_DIGEST_LENGTH; i++) sprintf(&mdString[i*2], "%02x", (unsigned int)hash[i]); printf("SHA1 digest: %s\n", mdString); return hash; } char* clone2(char* orig, int size){ //make sure size <=BUFFER_SIZE char* cl = (char *) malloc(BUFFER_SIZE*sizeof(char)); for(int g=0; g<size; g++){ cl[g] = orig[g]; g++; } return cl; } pair<int,char*> clone3(string str){ int l = str.size(); char* mybuff = (char *)malloc(l); memset(mybuff, 0, l); strncpy(mybuff, (char*)str.c_str(), l - 1); make_pair(l,mybuff); } char* clone(char* orig){ char* cl = (char *) malloc(BUFFER_SIZE); int g = 0; while(orig[g] != '\0') { cl[g] = orig[g]; g++; } cl[g]='\0'; return cl; } bool does_file_exist(char* full_path){ struct stat st = {0}; if (stat(full_path, &st) == -1) { return false; } return true; }
Python
UTF-8
819
2.75
3
[]
no_license
from santas_little_helpers import day, get_data, timed from knot_hash import arr_size, hex_representation, to_ascii today = day(2017, 10) def hash_data(lengths: [int], repeat: int = 1) -> [int]: l = list(range(arr_size)) idx = 0 skip = 0 for _ in range(repeat): for n in lengths: l = l[idx % arr_size:]+l[:idx % arr_size] l = list(reversed(l[:n]))+l[n:] l = l[(arr_size-idx) % arr_size:]+l[:(arr_size-idx) % arr_size] idx += n+skip skip += 1 return l def main() -> None: data = next(get_data(today)).strip() new_list = hash_data([int(x) for x in data.split(',')]) final_list = hash_data(to_ascii(data), 64) print(f'{today} star 1 = {new_list[0]*new_list[1]}') print(f'{today} star 2 = {hex_representation(final_list)}') if __name__ == '__main__': timed(main)
Python
UTF-8
5,662
3.078125
3
[ "MIT" ]
permissive
import random from games.abstract_ruleset import Ruleset import numpy as np from games.simple_ramsch.state import RamschState from utils import one_hot_to_int from numba import jit dealing_pattern = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 1, 1, 1, 2, 2, 2]) card_values = [0, 0, 0, 10, 2, 3, 4, 11] @jit(nopython=True) def suit(card): if (card % 8) == 4: return 0 # Trumf return 1 + card // 8 # Other suits in order @jit(nopython=True) def card_playabilities(trick): if len(trick) == 0 or len(trick) == 3: return [0] * 32 # Every card can be played initially starting_suit = suit(trick[0]) def priority(card): return 1 if suit(card) == starting_suit else 0 # Follow suit! return [priority(card) for card in range(32)] @jit(nopython=True) def card_priorities(starting_card): assert starting_card is not None starting_suit = suit(starting_card) def priority(card): if suit(card) == 0: return card + 100 # Jacks have highet priority (and are sorted in order) elif suit(card) != starting_suit: # Wrong suits have min priority return -1 else: value = card % 8 if value == 3: # It is a ten value = 6.5 # Put it between king and ace return value return [priority(card) for card in range(32)] class RamschRuleset(Ruleset): @staticmethod def generate_init_state(last_game_final_state): if last_game_final_state is None: dealer = 0 else: dealer = (one_hot_to_int(last_game_final_state.dealer)[0] + 1) % 3 deck = np.array(list(range(32))) random.shuffle(deck) hands = [list(deck[dealing_pattern == 0]), list(deck[dealing_pattern == 1]), list(deck[dealing_pattern == 2]), list(deck[dealing_pattern == 3])] return RamschState.from_initial_hands(hands, dealer) @staticmethod def rotate_init_state(init_state): new_state = RamschState(init_state.full_state.copy()) new_state.dealer = init_state.dealer[np.array([2, 0, 1])] new_state.active_player = (init_state.active_player + 1) % 3 new_state.all_hands = init_state.all_hands[np.array([2, 0, 1, 3])] return new_state @staticmethod def available_actions(state): active_player_hand = one_hot_to_int(state.all_hands[state.active_player]) trick = state.current_trick_as_ints playabilities = card_playabilities(trick) playability_on_hand = [(playabilities[card], card) for card in active_player_hand] max_playability = max(playability_on_hand)[0] equal_to_max = [card for val, card in playability_on_hand if val == max_playability] ans = np.array(equal_to_max) return ans @staticmethod def trick_winner(trick): # returns index of card winning the trick (index 0 is first card played) assert len(trick) == 3 priorities = card_priorities(starting_card=trick[0]) priorities_in_trick = [priorities[card] for card in trick] max_priority = max(priorities_in_trick) equal_to_max = [i for i, prio in enumerate(priorities_in_trick) if prio == max_priority] assert len(equal_to_max) == 1 # Unique trick winner return equal_to_max[0] @staticmethod def do_action(state, action): new_state = RamschState(state.full_state.copy()) trick = new_state.current_trick_as_ints implications = RamschRuleset.action_public_implications(trick, action) new_state.apply_public_implications(*implications) new_state.play_card(action) if new_state.num_played_cards % 3 == 0: # End of trick trick = new_state.current_trick_as_ints winning_card = RamschRuleset.trick_winner(trick) winning_player = (winning_card + new_state.active_player) % 3 current_scores = new_state.current_scores current_scores[winning_player] += sum([card_values[c % 8] for c in trick]) if new_state.num_played_cards == 30: skat_cards = one_hot_to_int(state.skat) current_scores[winning_player] += sum([card_values[c % 8] for c in skat_cards]) else: new_state.active_player = winning_player new_state.current_scores = current_scores return new_state @staticmethod def action_public_implications(trick, action): has_cards = [action] playabilities = card_playabilities(trick) doesnt_have_cards = [card for card in range(32) if playabilities[card] > playabilities[action]] return has_cards, doesnt_have_cards @staticmethod def finalize_scores(state): scores = state.current_scores assert scores.sum() == 120 if 120 in scores: # Durchmarsch final_scores = scores else: coef = 2 if 0 in scores else 1 # Jungfrau final_scores = [-coef * c if c == max(scores) else 0 for c in scores] new_state = RamschState(state.full_state.copy()) new_state.current_scores = final_scores return new_state @staticmethod def is_finished(state): return state.num_played_cards == 30 @staticmethod def final_rewards(state): if RamschRuleset.is_finished(state): return RamschRuleset.finalize_scores(state).current_scores else: return None
Java
UTF-8
2,235
2.3125
2
[]
no_license
package fex.signs.util; import java.sql.Date; import java.util.Calendar; //import java.util.HashSet; //import java.util.Set; import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; public class Util { public static boolean isSign(Material m){ return m.toString().endsWith("_SIGN"); // Set<Material> signTypes = new HashSet<>(); // signTypes.add(Material.ACACIA_SIGN); // signTypes.add(Material.ACACIA_WALL_SIGN); // signTypes.add(Material.SPRUCE_SIGN); // signTypes.add(Material.SPRUCE_WALL_SIGN); // signTypes.add(Material.OAK_SIGN); // signTypes.add(Material.OAK_WALL_SIGN); // signTypes.add(Material.DARK_OAK_SIGN); // signTypes.add(Material.DARK_OAK_WALL_SIGN); // signTypes.add(Material.JUNGLE_SIGN); // signTypes.add(Material.JUNGLE_WALL_SIGN); // signTypes.add(Material.BIRCH_SIGN); // signTypes.add(Material.BIRCH_WALL_SIGN); // return signTypes.contains(m); } public static boolean isStandingSign(Material m){ return (m.toString().endsWith("_SIGN") && !m.toString().contains("WALL")); // Set<Material> signTypes = new HashSet<>(); // signTypes.add(Material.ACACIA_SIGN); // signTypes.add(Material.SPRUCE_SIGN); // signTypes.add(Material.OAK_SIGN); // signTypes.add(Material.DARK_OAK_SIGN); // signTypes.add(Material.JUNGLE_SIGN); // signTypes.add(Material.BIRCH_SIGN); // return signTypes.contains(m); } public static boolean isWallSign(Material m){ return m.toString().endsWith("_WALL_SIGN"); // Set<Material> signTypes = new HashSet<>(); // signTypes.add(Material.ACACIA_WALL_SIGN); // signTypes.add(Material.SPRUCE_WALL_SIGN); // signTypes.add(Material.OAK_WALL_SIGN); // signTypes.add(Material.DARK_OAK_WALL_SIGN); // signTypes.add(Material.JUNGLE_WALL_SIGN); // signTypes.add(Material.BIRCH_WALL_SIGN); // return signTypes.contains(m); } public static boolean isSign(Location e) { return isSign(e.getBlock().getType()); } public static Date now() { Calendar c = Calendar.getInstance(); return new Date(c.getTimeInMillis()); } public static String UUIDtoPlayer(String UUID_) { return Bukkit.getOfflinePlayer(UUID.fromString(UUID_)).getName(); } }
JavaScript
UTF-8
1,854
2.8125
3
[]
no_license
import React from 'react'; import uuid from 'uuid/v4'; import Form from './Form'; import Todo from './Todo'; import '../styles/Todolist.css'; class Todolist extends React.Component { constructor(props) { super(props); this.state = { todos: [] } this.addTodo = this.addTodo.bind(this); this.removeTodo = this.removeTodo.bind(this); this.updateTodo = this.updateTodo.bind(this); this.toggleCompletion = this.toggleCompletion.bind(this); } addTodo(todo) { const newTodo = { text: todo, id: uuid(), completed: false } this.setState({ todos: [...this.state.todos, newTodo] }); } removeTodo(id) { this.setState({ todos: this.state.todos.filter(todo => todo.id !== id) }); } updateTodo(id, updatedTask) { const updatedTodos = this.state.todos.map(todo => { if(todo.id === id) { return {...todo, text: updatedTask} } return todo; }); this.setState({ todos: updatedTodos }); } toggleCompletion(id) { const updatedTodos = this.state.todos.map(todo => { if(todo.id === id) { return {...todo, completed: !todo.completed} } return todo; }); this.setState({ todos: updatedTodos }); } render() { return ( <div className="Todolist"> <h1>Todo List!</h1> <h2>A Simple React Todo List App.</h2> {this.state.todos.map(todo => ( <Todo text={todo.text} completed={todo.completed} id={todo.id} key={todo.id} removeTodo={this.removeTodo} updateTodo={this.updateTodo} toggleCompletion={this.toggleCompletion} /> ))} <Form addTodo={this.addTodo} /> </div> ) } } export default Todolist;
C
UTF-8
190
2.625
3
[]
no_license
Rows and columns{ int i, j, r ,c; printf("enter number of Rows and columsn"); scanf_s("%d%d", &r,&c); for (i=0;i<r;i++) { for (j = 0; j<c; j++) printf("*"); printf("\n"); } }
JavaScript
UTF-8
2,058
2.828125
3
[ "Apache-2.0" ]
permissive
const assert=require('assert'); const fs=require('fs'); const http=require('http'); const concat=require('concat-stream'); const crypto=require('crypto'); const arg1=process.argv[2]; function getData() { const username = 'psf.ginfo'; const password = 'xisto917'; const options = { host: 'wwwapp.sistemafiergs.org.br', port: 7880, path: '/psf/api/senai/programacao-cursos', headers: { 'Authorization': 'Basic ' + new Buffer(username + ':' + password).toString('base64') } }; return new Promise((res,rej)=>{ if(arg1 == 'concat') { console.log('USANDO CONCAT!'); return http.get(options,resp=>{ return resp.pipe(concat(data=>{ return res(data); })); }); } http.get(options,resp=>{ let data=''; resp.on('data',chunk=>{ return data+=chunk; }); resp.on('end',()=>{ return res(data); }); }); }); } // getData function saveFile(data) { const md5Hasher=crypto.createHash('md5'); const md5=md5Hasher.update(data).digest('hex'); const filename=`./files/${md5}-webservice.json`; fs.writeFileSync(filename,data); return filename; } function processTest() { return new Promise((res,rej)=>{ try { return getData() .then(ret=>{ const filename=saveFile(ret); console.log(filename); return res({ok:true,filename}); }).catch(err=>rej(err)); } catch(e) { return rej(e); } }); } const qtd=20; // let array=[]; // for(let i=1; i<=qtd; i++) { // array.push(processTest()); // } // Promise.all(array) // .then(ret=>{ // console.log('RESOLVED!',ret); // }) // .catch(err=>{ // console.log(err); // }); processTest() .then(ret=>{ console.log(ret); }) .catch(err=>{ console.log(err); });
Python
UTF-8
10,102
3.03125
3
[]
no_license
__author__ = 'Roderik' import pygame import colorsys from math import * class LinearLayout: HORIZONTAL = 1 VERTICAL = 2 def __init__(self, layout_type=None, gravity=None, padding=0, padding_left=None, padding_right=None, padding_top=None, padding_bottom=None, width=0, height=0, fill_width=False, fill_height=False, rotation=0, color=None, childs=[], id=None, debug_id=None, intensity=1, predrawer=None, postdrawer=None, visible=True): self.id = id if layout_type == "HORIZONTAL": self.layout_type = LinearLayout.HORIZONTAL elif layout_type == "VERTICAL": self.layout_type = LinearLayout.VERTICAL else: self.layout_type = None self.childs = [] self.offset_x = 0 self.offset_y = 0 self.gravity = gravity self.padding_left = padding self.padding_right = padding self.padding_top = padding self.padding_bottom = padding if padding_left: self.padding_left = padding_left if padding_right: self.padding_right = padding_right if padding_top: self.padding_top = padding_top if padding_bottom: self.padding_bottom = padding_bottom self.debug_id = debug_id self.fill_width = fill_width self.fill_height = fill_height self.width = width self.height = height # dimensions before rotation are needed to create the surface when drawing self.width_before_rotation = 0 self.height_before_rotation = 0 self.rotation = rotation self.predrawer = predrawer self.postdrawer = postdrawer if color: hsv = colorsys.rgb_to_hsv(color[0], color[1], color[2]) self.color = colorsys.hsv_to_rgb(hsv[0], hsv[1], hsv[2]*intensity) else: self.color = None for child in childs: if type(child) is tuple: for i in range(child[1]): self.add_child(child[0].get_instance()) else: self.add_child(child) self.visible = visible # validation if layout_type is None and len(self.childs) > 1: raise ValueError("Layout type cannot be none when there is more than one child!") if self.width > 0: if self.padding_left > 0 or self.padding_right > 0: raise ValueError("Setting both padding and specific width is weird") if self.height > 0: if self.padding_top > 0 or self.padding_bottom > 0: raise ValueError("Setting both padding and specific height is weird") # calculate own width and height def measure(self): if not self.visible: return # this is a hack if not self.width_before_rotation == 0 and not self.height_before_rotation == 0 and not self.rotation == 0: return measured_childs_width = 0 measured_childs_height = 0 for child in self.childs: child.measure() if self.layout_type == LinearLayout.HORIZONTAL: measured_childs_width += child.width if measured_childs_height < child.height: measured_childs_height = child.height elif self.layout_type == LinearLayout.VERTICAL: measured_childs_height += child.height if measured_childs_width < child.width: measured_childs_width = child.width else: # should only be one child measured_childs_width = child.width measured_childs_height = child.height # add padding to childs measured and summed dimensions computed_width = measured_childs_width + self.padding_left + self.padding_right computed_height = measured_childs_height + self.padding_top + self.padding_bottom # finally, set the computed width and height, if provided dimension bigger then computed take those self.width_before_rotation = max(self.width, computed_width) self.height_before_rotation = max(self.height, computed_height) # adjust width/height to rotation topLeft = self.rotatePoint(self.rotation, (0, self.height_before_rotation), (0, 0)) topRight = self.rotatePoint(self.rotation, (self.width_before_rotation, self.height_before_rotation), (0, 0)) bottomLeft = self.rotatePoint(self.rotation, (0, 0), (0, 0)) bottomRight = self.rotatePoint(self.rotation, (self.width_before_rotation, 0), (0, 0)) mostLeft = min(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]) mostRight = max(topLeft[0], topRight[0], bottomLeft[0], bottomRight[0]) mostBottom = min(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]) mostTop = max(topLeft[1], topRight[1], bottomLeft[1], bottomRight[1]) self.width = abs(mostRight - mostLeft) self.height = abs(mostTop - mostBottom) def post_measure(self, available_fill_width, available_fill_height): if not self.visible: return if self.fill_width: self.width = available_fill_width self.width_before_rotation = available_fill_width if self.fill_height: self.height = available_fill_height self.height_before_rotation = available_fill_height width_weight_sum = 0 height_weight_sum = 0 used_width = 0 used_height = 0 if self.layout_type == LinearLayout.HORIZONTAL: for child in self.childs: if child.fill_width: width_weight_sum += 1 else: used_width += child.width width_weight_sum = max(width_weight_sum, 1) for child in self.childs: child.post_measure( float((self.width - (used_width+self.padding_left+self.padding_right)) / float(width_weight_sum)), self.height - (self.padding_top+self.padding_bottom)) elif self.layout_type == LinearLayout.VERTICAL: for child in self.childs: if child.fill_height: height_weight_sum += 1 else: used_height += child.height height_weight_sum = max(height_weight_sum, 1) for child in self.childs: child.post_measure( self.width-(self.padding_left+self.padding_right), float((self.height - (used_height+self.padding_bottom+self.padding_top)) / float(height_weight_sum))) else: # no orientation supplied if len(self.childs) > 1: raise ValueError("Having more than one child does not make sense when not having an orientation!!") for child in self.childs: child.post_measure(self.width-(self.padding_left + self.padding_right), self.height-(self.padding_bottom+self.padding_top)) def apply_gravity(self, offset_x, offset_y, available_width, available_height): if not self.visible: return self.offset_x = offset_x self.offset_y = offset_y if self.gravity == 'top': self.offset_y -= (available_height - self.height) elif self.gravity == 'right': self.offset_x -= (available_width - self.width) elif self.gravity == 'bottom': self.offset_y += (available_height - self.height) elif self.gravity == 'center_horizontal': self.offset_x += ((available_width/2) - (self.width / 2)) elif self.gravity == 'center_vertical': self.offset_y += ((available_height/2) - (self.height/ 2)) elif self.gravity == 'center': self.offset_x += ((available_width/2) - (self.width/ 2)) self.offset_y += ((available_height/2) - (self.height / 2)) draw_x = self.padding_left draw_y = self.padding_top for child in self.childs: child.apply_gravity(draw_x, draw_y, self.width-(self.padding_left+self.padding_right), self.height-(self.padding_top+self.padding_bottom)) if self.layout_type == LinearLayout.HORIZONTAL: draw_x += child.width elif self.layout_type == LinearLayout.VERTICAL: draw_y += child.height def add_child(self, child): self.childs.append(child) def draw(self): # print (self.width_before_rotation, self.height_before_rotation) surface = pygame.Surface((self.width_before_rotation, self.height_before_rotation), pygame.SRCALPHA, 32) if not self.visible: surface if self.color: pygame.draw.rect(surface, self.color, ( 0, 0, self.width, self.height ), 0) if self.predrawer: self.predrawer.draw(surface, self.offset_x, self.offset_y, self.width, self.height) for child in self.childs: childsurface = child.draw() surface.blit(childsurface, (child.offset_x, child.offset_y)) if self.postdrawer: self.postdrawer.draw(surface, self.offset_x, self.offset_y, self.width, self.height) if self.rotation is not 0: surface = pygame.transform.rotate(surface, self.rotation) return surface def rotatePoint(self, angle, point, origin): sinT = sin(radians(angle)) cosT = cos(radians(angle)) return (origin[0] + (cosT * (point[0] - origin[0]) - sinT * (point[1] - origin[1])), origin[1] + (sinT * (point[0] - origin[0]) + cosT * (point[1] - origin[1])))
JavaScript
UTF-8
2,260
2.890625
3
[]
no_license
function consultaUsuario(){ //pegando valor com jquery do form var cpf = $("#cpf").val(); var formData = { 'cpf' : cpf }; $.ajax({ type : 'POST', url : '/CadastroUsuario/ConsultarUsuario', contentType : 'application/json', data : JSON.stringify(formData), dataType : 'json', encode : true, success : function(data) { alertaSuccess("Usuario : "+data.nomeUsuario); }, error: function(result) { alertaErro("Nenhum usuario encontrado"); } }); return false; } function salvaUsuario(){ //pegando valor com jquery do form var nome = $("#nome").val(); var dtNasc = $("#dtNasc").val(); var cpf = $("#cpf").val(); var genero = $("#genero").val(); var endereco = $("#endereco").val(); var numero = $("#numero").val(); var cidade = $("#cidade").val(); var estado = $("#estado").val(); var cep = $("#cep").val(); var bairro = $("#bairro").val(); var telefone = $("#telefone").val(); var formData = { 'nomeUsuario' : nome, 'dataNascimento': dtNasc, 'cpf' : cpf, 'genero' : genero, 'logradouro' : endereco, 'numLogradouro' : numero, 'cidade' : cidade, 'estado' : estado, 'cep' : cep, 'bairro' : bairro, 'telefone' : telefone }; $.ajax({ type : 'POST', url : '/CadastroUsuario/SalvarUsuario', contentType : 'application/json', data : JSON.stringify(formData), dataType : 'json', encode : true, success : function(data) { alertaSuccess("Cadastrado com sucesso"); }, error: function(result) { alertaErro("Ocorreu um erro"); } }); return false; } function alertaErro(mensagem){ $("#alertaErro").html(mensagem); $("#alertaErro").fadeIn() .css({bottom:-100,position:'fixed', display:'flex!important'}) .animate({bottom:30}, 800, function() { $("#alertaErro").fadeOut(3000); }) } function alertaSuccess(mensagem){ console.log("alertaSucess: "+mensagem); $("#alertaSucess").html(mensagem); $("#alertaSucess").fadeIn() .css({bottom:-100,position:'fixed', display:'flex!important'}) .animate({bottom:30}, 800, function() { $("#alertaSucess").fadeOut(3000); }) }
Markdown
UTF-8
508
2.90625
3
[]
no_license
# Project Euler Solutions This is a repo where I store my Python solutions to problems on <https://projecteuler.net>. I recently noticed that the Project Euler website says users are not supposed to share answers on public repos. But since I am using this repo mostly for keeping track of my own progress, I would like to keep it this way. It would be great if you only check out my solutions after you have solved the problem yourself. Do not give up the challenge and more importantly the FUN :P
C#
UTF-8
550
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VisualScript.Commads { public class CaseCommand : Stmt { private Stmt command; private Expr expression; public CaseCommand(Expr expression, Stmt command) { this.command = command; this.expression = expression; } public void execute(IBindingEnvironment environment) { command.execute(environment); } public Stmt Command { get { return this.command; } } public Expr Expression { get { return this.expression; } } } }
Java
UTF-8
1,668
2.625
3
[]
no_license
package edu.nitin.testng.pull459; import org.testng.Assert; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.Arrays; /** * Created on 12/29/15. * * @author <a href="mailto:nitin.matrix@gmail.com">Nitin Verma</a> */ public class VarArgsDataProviderTest { @DataProvider public Object[][] data() { return new Object[][]{ new String[]{"query1", "query1#response0", "query1#response1"}, new String[]{"query2", "query2#response0", "query2#response1"}, }; } public String getResponse(String query, int responseIndex) { final String response = String.format("%s#response%d", query, responseIndex); System.out.println(query + ", " + responseIndex + " = " + response); return response; } @Test(dataProvider = "data") public void testNoVararg(String query, String response0, String response1) { Assert.assertEquals(getResponse(query, 0), response0); Assert.assertEquals(getResponse(query, 1), response1); } @Test(dataProvider = "data") public void testVararg(String... data) { String query = data[0]; String[] expectedResponses = Arrays.copyOfRange(data, 1, data.length); for (int responseIndex = 0; responseIndex < expectedResponses.length; ++responseIndex) { Assert.assertEquals(getResponse(query, responseIndex), expectedResponses[responseIndex]); } } @Test(dataProvider = "data") public void testMixed(String query, String... expectedResponses) { for (int responseIndex = 0; responseIndex < expectedResponses.length; ++responseIndex) { Assert.assertEquals(getResponse(query, responseIndex), expectedResponses[responseIndex]); } } }
Markdown
UTF-8
2,596
3.546875
4
[ "MIT" ]
permissive
select方法是用的最广泛、同时也是最复杂的查询条件 ### 使用方法 在所有sql链式调用方法之后 调用 `.select()` 即为查询 > 所有语法采用链式调用方式 > 默认用 * 查询所有字段,可以使用 .field 方法精确字段查询 > union方法优先级最高,如果查询中有次方法,则其他查询字段无效 > 同时存在 limt 和 page 方法时,page方法将优先于limit方法 > sql的查询方式有很多,尽可能按照正确的sql语句语法查询 > 对所有的方法没有固定的顺序,内部会自动排序 ### 简单用法 ```js sql .table('node_table') .where('id=1') .select() SELECT * FROM node_table WHERE id=1 sql .table('node_table') .field('id,name') .where({id:1}) .select() SELECT id,name FROM node_table WHERE id=1 ``` ### 高级用法 ```js //参数json多字段 sql .table('node_table') .where({id:1,name:'zane'}) .select() SELECT * FROM node_table WHERE id=1 AND name=`zane` //参数数组 let data=[ {id:1,name:'zhangsan',_type:'or'}, {sex:1,number:3} ] sql.table('node_table').where(data).select() SELECT * FROM node_table WHERE (id=1 OR name=`zhangsan` ) AND (sex=1 AND number=3 ) //多字段连接方式 let data=[ {id:1,name:'zhangsan',_type:'or',_nexttype:'or'}, {sex:1,number:3,_type:'and'} ] sql.table('node_table').where(data).select() SELECT * FROM node_table WHERE (id=1 OR name=`zhangsan`) OR (sex=1 AND number=3) //表达式查询 let data={ id:{eq:100,egt:10,_type:'or'}, name:'zhangshan' } sql.table('node_table').where(data).select() SELECT * FROM node_table WHERE ((id=100) OR (id>=10)) AND name=`zhangshan` //混合查询 let data=[{ id:{eq:100,egt:10,_type:'or'}, name:'zhangshan', _nexttype:'or' },{ status:1, name:{like:'%zane%'} }] sql.table('node_table').where(data).select() SELECT * FROM node_table WHERE (((id=100) OR (id>=10)) AND name=`zhangshan`) OR (status=1 AND ((name LIKE `%zane%`))) //UNION , UNION ALL 组合使用 sql .union('SELECT * FROM think_user_1',true) .union('SELECT * FROM think_user_2',true) .union(['SELECT * FROM think_user_3','SELECT name FROM think_user_4']) .union('SELECT * FROM think_user_5',true) .select() 得到 (SELECT * FROM think_user_1) UNION ALL (SELECT * FROM think_user_2) UNION ALL (SELECT * FROM think_user_3) UNION (SELECT name FROM think_user_4) UNION (SELECT * FROM think_user_5) ```
C#
UTF-8
864
3.109375
3
[]
no_license
public class WaitableWorker { private readonly System.Threading.Timer timer; public WaitableWorker(int interval, Action callback, bool blocking = false) { if (blocking) { Thread.Sleep(interval); callback(); } else { timer = new System.Threading.Timer(_ => { timer.Dispose(); callback(); }, null, interval, Timeout.Infinite); } } }
C#
UTF-8
7,743
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Entidades; using System.Data.Entity.Validation; namespace Repositorio { public class CocineroRepositorio { public ComentariosRepositorio comenRepo = new ComentariosRepositorio(); PW3_TP_20161CEntities Contexto; public CocineroRepositorio() { Contexto = new PW3_TP_20161CEntities(); } //////////EVENTOS //creacion de la lista de eventos public static List<Eventos> ListaEventos = new List<Eventos>(); //método para añadir nuevo evento a la lista public void CrearEvento(Eventos nuevoEvento) { nuevoEvento.Estado = 1; // estado 1 = Programado, 2 = en curso, 3 = finalizado, 4 = Cancelado Contexto.Eventos.Add(nuevoEvento); try { Contexto.SaveChanges(); } catch (DbEntityValidationException e) { throw; } } public void EventoReceta(int idEve ) { } //método para obtener un evento por su nombre public IQueryable<Eventos> ObtenerPorNombre(string nombreEvento) { var evento = from c in Contexto.Comentarios join e in Contexto.Eventos on c.IdEvento equals e.IdEvento where e.Nombre == nombreEvento select e; return evento; } public Eventos ObtenerPorId(int id) { var evento = (from e in Contexto.Eventos where e.IdEvento == id select e).FirstOrDefault(); return evento; } public IQueryable<Eventos> ObtenerEventoId(int id) { var evento = from e in Contexto.Eventos where e.IdEvento == id select e; return evento; } //método para cancelar un evento public void cancelarEvento(int id) { Eventos eventoACancelar = new Eventos(); eventoACancelar = ObtenerPorId(id); eventoACancelar.Estado = 4; Contexto.SaveChanges(); } //método para finalizar un evento public void finalizarEvento() { foreach (Eventos ev in Contexto.Eventos) { if (ev.Fecha <= DateTime.Now) ev.Estado = 3 ; } Contexto.SaveChanges(); } //metodo de retorno de eventos por usuario public IQueryable<Eventos> eventoPorUsuario(int autor) { var evento = from e in Contexto.Eventos where e.IdUsuario == autor select e; return evento; } //metodo de retorno de eventos por estado public IQueryable<Eventos> eventoPorEstado(int estado, int autor) { /* List<Eventos> eventoPorStatus = new List<Eventos>(); foreach (Eventos ev in ListaEventos) { if (ev.Estado != estado & ev.IdUsuario == autor) eventoPorStatus.Add(ev); } */ var evento = from e in Contexto.Eventos where e.IdUsuario == autor && e.Estado == 1 select e; return evento; } public int eventoPorEstadoI(int estado, int autor) { int cantidad = 0; foreach (var item in Contexto.Eventos) { var evento = (from e in Contexto.Eventos where e.IdUsuario == autor && e.Estado == 1 || e.Estado == 2 select e).FirstOrDefault(); cantidad = cantidad + 1; } return cantidad; } //Eventos disponibles para reservar public IQueryable<Eventos> eventoDisponibles() { var evento = from e in Contexto.Eventos where e.Estado == 1 select e; return evento; } public Eventos ObtenerRecientes(int id) { var evento = (from e in Contexto.Eventos where e.Fecha < DateTime.Today && e.IdEvento == id // && e.Fecha > DateTime.Today && e.Estado == 3 select e).FirstOrDefault(); return evento; } public decimal ObtenerPuntuacion(int id) { decimal puntuacionEvento = 0; byte i = 0; foreach (var item in Contexto.Comentarios) { byte puntua = (from e in Contexto.Comentarios where e.IdEvento == id select e.Puntuacion).FirstOrDefault(); puntuacionEvento = puntuacionEvento + puntua; i++; } puntuacionEvento = puntuacionEvento / i; return puntuacionEvento; } //////////RECETAS //creacion de la lista de recetas // public static List<Recetas> ListaRecetas = new List<Recetas>(); //método para añadir nueva receta a la lista public void CrearReceta(Recetas nuevaReceta) { Contexto.Recetas.Add(nuevaReceta); Contexto.SaveChanges(); } //metodo de retorno de recetas por usuario public IQueryable<Recetas> recetasPorUsuario(int autor) { var receta = from e in Contexto.Recetas where e.IdUsuario == autor select e; return receta; } public Recetas recetasPorId(int id) { var receta = (from e in Contexto.Recetas where e.IdReceta == id select e).FirstOrDefault(); return receta; } public int cantRecetas(int id) { int cantidad = 0; foreach (var item in Contexto.Recetas) { var receta = (from e in Contexto.Recetas where e.IdReceta == id select e).FirstOrDefault(); cantidad = cantidad + 1; } return cantidad; } public IEnumerable<Recetas> recetasPorEvento(int id) { var receta = from r in Contexto.Recetas /* join e in Contexto.Eventos on r.Eventos equals e.Recetas*/ where !Contexto.Eventos.Select( e => e.IdEvento).Contains(r.IdReceta) select r; return receta; } public List<Recetas> obtenerRecetas() { List<Recetas> nueva = new List<Recetas>(); foreach (Recetas item in Contexto.Recetas) { var receta = (from e in Contexto.Recetas where e.IdReceta == item.IdReceta select e).FirstOrDefault(); nueva.Add(receta); } return nueva; } } }
JavaScript
UTF-8
1,672
2.984375
3
[]
no_license
import Board from "./Board"; import { Pawn, Bishop, Rook, Queen, King, Knight } from "./Piece"; import Square from "./Square"; import Color from "./Color"; export default class Game { constructor() { this.board = new Board(); let pieces = [ new Knight(this.board, new Square(1, 0), Color.white), new Knight(this.board, new Square(1, 7), Color.black), new Knight(this.board, new Square(6, 0), Color.white), new Knight(this.board, new Square(6, 7), Color.black), new Bishop(this.board, new Square(2, 0), Color.white), new Bishop(this.board, new Square(2, 7), Color.black), new Bishop(this.board, new Square(5, 0), Color.white), new Bishop(this.board, new Square(5, 7), Color.black), new Rook(this.board, new Square(0, 0), Color.white), new Rook(this.board, new Square(0, 7), Color.black), new Rook(this.board, new Square(7, 0), Color.white), new Rook(this.board, new Square(7, 7), Color.black), new Queen(this.board, new Square(3, 0), Color.white), new Queen(this.board, new Square(3, 7), Color.black), new King(this.board, new Square(4, 0), Color.white), new King(this.board, new Square(4, 7), Color.black) ]; for (let i = 0; i <= 7; i++) { pieces.push(new Pawn(this.board, new Square(i, 1), Color.white)); pieces.push(new Pawn(this.board, new Square(i, 6), Color.black)); } this.board.pieces = pieces; } makeMove(move) { this.board = this.board.applyMove(move, true); } }
Python
UTF-8
1,592
3.078125
3
[]
no_license
from selenium import webdriver import datetime user_names=[] def attack(): driver = webdriver.Chrome("C:\\Users\\Downloads\\chromedriver.exe") driver.get("https://web.whatsapp.com/") for att in range(0,len(user_names)): user = driver.find_element_by_xpath('//span[@title = "{}"]'.format(user_names[att])) user.click() msg_box = driver.find_element_by_class_name("_13mgZ") for i in range(count): msg_box.send_keys(msg) button = driver.find_element_by_class_name("_3M-N-") button.click() def timer(): while True: current_time=datetime.datetime.now() print(current_time) stringtime=str(current_time) print(stringtime) time_list=list(stringtime) print(time_list) cur_time_hour=str(time_list[11]+time_list[12]) cur_time_minutes=str(time_list[14]+time_list[15]) print(cur_time_hour,cur_time_minutes) if cur_time_hour==set_time_hours and cur_time_minutes==set_time_minutes: attack() set_time_hours=str(input("set time in hours(24-hours format) for message: ")) set_time_minutes=str(input("set time in minutes for message: ")) print(set_time_hours,":",set_time_minutes) no_of_users=int(input("type the number of users: ")) for no in range(0,no_of_users): user_input=str(input("type the names you need to send messages: ")) user_names.append(user_input) msg = input("Enter your message : ") count = int(input("Enter number of messages :")) timer() while True: attack()
C++
UTF-8
6,381
2.921875
3
[]
no_license
#include <string> #include <iostream> #include <iomanip> #include <sstream> #include "Contact.h" //#include "Date.h" void Contact::setGender(string gender) { _gender = gender; } string Contact::getGender() { return _gender; } void Contact::setTitle(string title) { _title = title; } string Contact::getTitle() { return _title; } void Contact::setFirstName(string firstName) { _firstName = firstName; } string Contact::getFirstName() { return _firstName; } void Contact::setMiddleInitial(string middleInitial) { _middleInitial = middleInitial; } string Contact::getMiddleInitial() { return _middleInitial; } void Contact::setLastName(string lastName) { _lastName = lastName; } string Contact::getLastName() { return _lastName; } void Contact::setStreetAddress(string streetAddress) { _streetAddress = streetAddress; } string Contact::getStreetAddress() { return _streetAddress; } void Contact::setCity(string city) { _city = city; } string Contact::getCity() { return _city; } void Contact::setState(string state) { _state = state; } string Contact::getState() { return _state; } void Contact::setZipCode(string zipCode) { _zipCode = zipCode; } string Contact::getZipCode() { return _zipCode; } void Contact::setEmailAddress(string emailAddress) { _emailAddress = emailAddress; } string Contact::getEmailAddress() { return _emailAddress; } void Contact::setBirthday(string birthday) { _birthday = birthday; //_birthday = Date(birthday); } string Contact::getBirthday() { return _birthday; //return _birthday.getDate(); } string Contact::getFullName() { string fullName = ""; fullName.append(getFirstName()); fullName.append(" "); fullName.append(getMiddleInitial()); fullName.append(" "); fullName.append(getLastName()); return fullName; } string Contact::toString() { string newString = ""; newString.append(getGender()); newString.append(", "); newString.append(getTitle()); newString.append(", "); newString.append(getFirstName()); newString.append(", "); newString.append(getMiddleInitial()); newString.append(", "); newString.append(getLastName()); newString.append(", "); newString.append(getStreetAddress()); newString.append(", "); newString.append(getCity()); newString.append(", "); newString.append(getState()); newString.append(", "); newString.append(getZipCode()); newString.append(", "); newString.append(getEmailAddress()); newString.append(", "); newString.append(getBirthday()); return newString; } //void Contact::setBirthdayValues() //{ // string tempLine = _birthday; // string token = ""; // int fieldNumber = 0; // char delimiter = '/'; // int numberOfFields = 3; // int start = 0; // int end = tempLine.find(delimiter); // string fieldsOfBirthday[3]; // // while (end != string::npos) { // token = tempLine.substr(start, (end - start)); // fieldsOfBirthday[fieldNumber] = (token); // fieldNumber++; // start = end + 1; // end = tempLine.find(delimiter, start); // } // token = tempLine.substr(start, (end - start)); // fieldsOfBirthday[fieldNumber] = (token); // // for (int index = 0; index < numberOfFields; index++) { // switch (index) { // case 0: _birthMonth = stoi(fieldsOfBirthday[index]); // break; // case 1: _birthDayOfTheMonth = stoi(fieldsOfBirthday[index]); // break; // case 2: _birthYear = stoi(fieldsOfBirthday[index]); // break; // default: cout << "Invalid field detected" << endl; // break; // } // // } // setAge(); //} void Contact::setAge() { int currentDay = 12; int currentMonth = 11; int currentYear = 2017; //auto t = std::time(nullptr); //auto tm = *std::localtime(&t); //std::ostringstream oss; //oss << std::put_time(&tm, "%d-%m-%Y"); //auto str = oss.str(); //string tempLine = str; //string token = ""; //int fieldNumber = 0; //char delimiter = '/'; //int numberOfFields = 3; //int start = 0; //int end = tempLine.find(delimiter); //int fieldsOfBirthday[3]; //while (end != string::npos) { // token = tempLine.substr(start, (end - start)); // fieldsOfBirthday[fieldNumber] = stoi(token); // fieldNumber++; // start = end + 1; // end = tempLine.find(delimiter, start); //} //token = tempLine.substr(start, (end - start)); //fieldsOfBirthday[fieldNumber] = stoi(token); //for (int index = 0; index < numberOfFields; index++) { // switch (index) { // case 0: currentMonth = fieldsOfBirthday[index]; // break; // case 1: currentDay = fieldsOfBirthday[index]; // break; // case 2: currentYear = fieldsOfBirthday[index]; // break; // default: cout << "Invalid field detected" << endl; // break; // } //} int age = currentYear - _birthYear; _age = age; } int Contact::getAge() { return _age; } int Contact::getMonth() { return _birthMonth; } int Contact::getYear() { return _birthYear; } int Contact::getDayOfTheMonth() { return _birthDayOfTheMonth; } Contact::Contact() { } Contact::Contact(string contactLine) { string tempLine = contactLine; string token = ""; int fieldNumber = 0; char delimiter = ','; int numberOfFields = 11; int start = 0; int end = tempLine.find(delimiter); if (tempLine[0] >= '0' && tempLine[0] <= '9') { start = tempLine.find(delimiter) + 1; end = tempLine.find(delimiter, start); } while (end != string::npos) { token = tempLine.substr(start, (end - start)); _fieldsOfContact[fieldNumber] = token; fieldNumber++; start = end + 1; end = tempLine.find(delimiter, start); } token = tempLine.substr(start, (end - start)); _fieldsOfContact[fieldNumber] = token; for (int index = 0; index < numberOfFields; index++) { switch (index) { case 0: setGender(_fieldsOfContact[index]); break; case 1: setTitle(_fieldsOfContact[index]); break; case 2: setFirstName(_fieldsOfContact[index]); break; case 3: setMiddleInitial(_fieldsOfContact[index]); break; case 4: setLastName(_fieldsOfContact[index]); break; case 5: setStreetAddress(_fieldsOfContact[index]); break; case 6: setCity(_fieldsOfContact[index]); break; case 7: setState(_fieldsOfContact[index]); break; case 8: setZipCode(_fieldsOfContact[index]); break; case 9: setEmailAddress(_fieldsOfContact[index]); break; case 10: setBirthday(_fieldsOfContact[index]); //_birthday = Date(token); break; default: cout << "Invalid field detected" << endl; break; } } //setBirthdayValues(); } Contact::~Contact() { }
Java
UTF-8
377
1.695313
2
[]
no_license
package io.github.binglau; /** * 类Config.java的实现描述:TODO:类实现描述 * * @author bingjian.lbj 2016-04-30 下午6:42 */ public class Config { final static String KAFKA_ADDRESS = "192.168.33.10:9092"; final static String TOPIC = "demo-test"; final static String ZK_CONNECT = "192.168.33.10:2181"; final static String GROUPID = "group1"; }
Markdown
UTF-8
10,532
2.8125
3
[ "Apache-2.0" ]
permissive
<p align="center"> <img src="./img/borgia-logo-light.png" /> </p> # Documentation - Gestion d'un magasin ## Application Build : [4.5.0 + ](https://github.com/borgia-app/Borgia/releases/tag/4.5.0) Licence : [GNU GPL version 3](./license.txt) # Introduction Ce guide a pour objectif d'expliquer le fonctionnement de l'application de vente de Borgia. Il détaillera la gestion des administrateurs d'un magasin, de ses produits et de ses modules de vente. Il ne s'attardera pas sur la gestion complète des stocks, qui fait l'objet d'un [autre guide](./stocks.md). # Administrateurs du magasin Lors de la création d'un magasin, deux groupes d'administrateurs sont également créés automatiquement afin de gérer le magasin. Ces deux groupes sont nommés "Chefs du magasin" et "Associés du magasin". Ils n'ont pas les mêmes fonctionnalités, les mêmes permissions et ne sont pas gérés par le même groupe supérieur. Dans les deux cas, ces administrateurs peuvent accéder au "Workboard" du magasin en changeant de groupe dans le menu latéral (`Groupes / Chefs ou Associés NOM-DU-MAGASIN`). ## Chefs du magasin Le groupe admin le plus important d'un magasin est le groupe des chefs du magasin. Le nom complet est "Chefs _NOM-DU-MAGASIN_ ". La gestion de ce groupe est laissé par défaut aux groupe des présidents et des vice-présidents. C'est donc à eux de définir qui fait partie de ce groupe principal. Pour modifier les membres, cliquer sur `Gestion des groupes / Gestion chefs NOM_DU_MAGASIN` dans le menu latéral. Par défaut, ce groupe a la permission de : * Ajouter, lister et accéder aux détails des utilisateurs. * Ajouter de l'argent à un utilisateur. * Ajouter, modifier, lister, accéder aux détails et modifier les prix des produits (de ce magasin uniquement). * Lister et accéder aux détails d'une vente (de ce magasin uniquement). * Vendre des produits avec le module de vente par opérateur. * Ajouter, lister et accéder aux détails des inventaires et des entrées de stocks (de ce magasin uniquement). * Gérer les membres du groupe des associés de ce magasin. L'ensemble des permissions peuvent être données à ce groupe par le(s) président(s) ou le(s) vice-président(s). Théoriquement, ce groupe ne devrait contenir qu'un petit nombre de membres: uniquement le(s) chef(s) du magasin élu ou choisi au sein des administrateurs de celui-ci. Les autres devraient faire partie du groupe des associés. ## Associés du magasin Ce second groupe est un cran en dessous des chefs en terme d'administration mais peuvent totalement disposer des mêmes permissions. Ce groupe est directement gérés par le groupe des chefs du magasin. Ainsi, il est aisé d'ajouter et de supprimer des membres à ce groupe en cas de besoin (par exemple lors d'une soirée importante qui nécessite un grand nombre de collaborateurs pour la vente). Ce groupe ne peut pas recevoir l'ensemble des permissions, mais seulement celles qui sont appliquées aux chefs du magasin. Ainsi, un associé ne peux pas obtenir une permission dont le chef du même magasin ne dispose pas lui-même. Par défaut, les permissions des associés sont : * Ajouter, lister et accéder aux détails des utilisateurs. * Ajouter de l'argent à un utilisateur. * Ajouter, modifier, lister et accéder aux détails (de ce magasin uniquement). * Lister et accéder aux détails d'une vente (de ce magasin uniquement). * Vendre des produits avec le module de vente par opérateur. * Ajouter, lister et accéder aux détails des inventaires et des entrées de stocks (de ce magasin uniquement). # Gestion des produits Les produits sont les éléments qui sont vendus au magasin à travers les différents modules de vente. Il convient de les utiliser correctement pour s'assurer que la gestion des stocks est cohérente et que le prix de vente correct. ## Ajouter un produit Borgia propose deux types de produits différents pour les magasins : les produits unitaires et les produits vendus à la quantité. La différence est essentielle et fondamentale pour bien utiliser l'application des produits de Borgia: elle doit donc être bien comprise. ### Produit unitaire Un produit unitaire (aussi nommé produit tout court) est le produit de base de Borgia. L'acheteur repart avec l'intégrité du produit en une fois et il disparait physiquement du stock. Par exemple, une bouteille de bière, un écusson ou encore une blouse sont des produits basiques et unitaires. ![Ajout produit simple](./img/new_product.png) L'ajout d'un tel produit ne nécessite qu'un nom de produit (qui sera le nom de vente). ### Produit vendu à la quantité Un produit vendu à la quantité ne disparait pas physiquement du stock lorsqu'il est vendu. En effet, seulement une petite partie de son état est vendu à chaque fois. Par exemple, de la bière provenant d'un fût est un produit vendu à la quantité. De même, le fromage ou le pain vendu au poids en font partie. Bien sûr, ce n'est pas limité aux produits alimentaires. ![Ajout produit vendu à la quantité](./img/new_product_quantity.png) L'ajout d'un tel produit nécessite un nom et aussi une unité de vente : gramme ou centilitre. ### Détails d'un produit L'ensemble des informations d'un produit est disponible en cliquant sur "détails" pour le produit concerné dans la liste des produits du magasin. ![Produit dans la liste](./img/product_in_list.png) La page qui s'affiche indique les informations du produit ainsi que les différentes manipulations possibles à effectuer (voir la suite de ce document). ![Détails d'un produit](./img/product_retrieve.png) ## Activation / suppression Un produit peut être désactivé ou supprimé en cas de besoin. Lors de la désactivation, le produit : * n'est plus visible à la vente, * reste présent dans la liste des produits, * peut être réactivé à tout moment, cette action **est reversible**. Et lors de la suppression, le produit : * disparait purement et simplement de Borgia, * n'est plus modifiable, visible dans les listes ou disponible à la vente, * cette action est **irreversible**. Ainsi, la suppression d'un produit est à réserver si une erreur a été faite concernant ce produit. Si l'objectif est simplement de le retirer de la vente temporairement, la désactivation est à privilégier. ## Gestion du prix de vente Borgia peut gérer automatiquement le prix de vente des produits en utilisant les données d'entrées et de sorties du stocks (voir le tutoriel concernant les stocks pour plus d'informations). Le paramètre qui indique la marge de vente à appliquer est défini dans la configuration de Borgia, et est commun à tout les magasins. Ce paramètre n'est modifiable que par les personnes autorisées (par défaut le(s) président(s), le(s) vice-président(s), et le(s) trésorier(s)) De plus, il est également possible d'utiliser un prix défini manuellement pour chacun des produits en cliquant sur le bouton `Gestion manuelle du prix`. ![Gestion manuelle du prix](./img/manual_price.png) Si c'est le cas, Borgia indique la déviation par rapport au prix qu'il calcule afin d'informer les administrateurs de la cohérence ou non du prix manuel. ![Ajout produit simple](./img/manual_price_deviant.png) **Remarque**: dans les deux cas, si le prix de vente est nul (entré manuellement ou calculé par Borgia), Borgia ne permettra pas de vendre ce produit. ## Stock Cette section fait l'objet d'un [guide à part entière](./stocks.md). Notez simplement qu'un produit ne peut pas être vendu s'il n'y a pas encore eu d'entrée de stocks. Sinon le prix de vente sera nul et Borgia refusera de l'afficher dans les modules. # Modules de ventes L'objectif principal des produits et de l'application magasin est de vendre des choses pour l'association, par l'intermédiaire de Borgia. ## Les deux types de modules de ventes Afin de proposer des produits aux membres et utilisateurs de la solution, deux modules de vente différents sont disponibles. Les deux modules ont des contenus distincts et une fonction différente. Mais leurs configurations sont similaires, et ne sont donc pas différenciées dans ce guide (voir suite du document). Le premier est le module de "vente directe". Il autorise les utilisateurs à indiquer eux-même leurs achats via une interface simplifiée. Tout fonctionne **sans** l'intervention d'un administrateur du magasin et est donc basé sur la confiance entre les membres et l'association. Pour activer et configurer ce module, il faut cliquer sur "Module vente libre service" dans le menu latéral des gestionnaires du magasin. ![Module vente libre service](./img/module_selfsale.png) Le second est un module équivalent mais disponible **uniquement pour et avec** les gestionnaires du magasin. La vente est donc approuvée par un administrateur directement. Ce module est nommé "Module vente par opérateur". ![Module vente par opérateur](./img/module_operator.png) ## Configuration En cliquant sur le lien du module dans le menu latéral, la page de configuration s'ouvre. La section du haut indique les paramètres actuels du module, notamment s'il est activé ou non. ![Configuration du module](./img/module_config.png) Pour modifier ces paramètres, cliquer sur le bouton "Modifier". ## Catégories de vente La seconde section indique les produits qui sont disponibles à la vente. Ils sont organisés par catégories que l'on peut ajouter, modifier et supprimer à la volée. Le nom de la catégorie est associée au nom affiché dans l'onglet sur l'interface utilisée par les utilisateurs. Un produit peut être ajouté à plusieurs catégories en même temps. Si c'est un produit vendu à la quantité, il faut indiquer la quantité vendu à chaque fois. Par exemple 25 cl pour un verre, 50 pour une pinte etc. ![Sélection de la quantité dans une catégorie](./img/quantity_in_cat.png) ## Accès aux modules Une fois activés, les modules de vente sont accessibles par les utilisateurs. Les module de vente font l'objet d'une page de login spécifique qui doit être sélectionnée en cliquant sur le bouton vert "liens directs" sur la page de login usuelle. ![Liens directs](./img/direct_links.png) ![Modal liens directs](./img/direct_links_modal.png) En plus de ces liens, des redirections sont disponibles dans le menu latéral. Par le groupe "Gadz'Arts" via "Vente directe _NOM-DU-MAGASIN_" et "Module vente" par les groupes des chefs et associés du magasin en question. # Bilan de santé
PHP
UTF-8
2,090
2.625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\modules\work\models; use Yii; /** * This is the model class for table "work_progress". * * @property integer $id * @property integer $work_id * @property double $exp * @property integer $phy * @property integer $fin */ class WorkProgress extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'work_progress'; } /** * @inheritdoc */ public function rules() { return [ [['work_id', 'phy', 'fin'], 'integer'], [['exp'], 'string'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'work_id' => 'Work ID', 'exp' => 'Exp', 'phy' => 'Phy', 'fin' => 'Fin', ]; } /* *@return form of individual elements */ public function showForm($form,$attribute) { switch ($attribute) { case 'id': return $form->field($this,$attribute)->textInput(); break; case 'work_id': return $form->field($this,$attribute)->textInput(); break; case 'exp': return $form->field($this,$attribute)->textInput(); break; case 'phy': return $form->field($this,$attribute)->textInput(); break; case 'fin': return $form->field($this,$attribute)->textInput(); break; default: break; } } /* *@return form of individual elements */ public function showValue($attribute) { $name='name_'.Yii::$app->language; switch ($attribute) { case 'id': return $this->id; break; case 'work_id': return $this->work_id; break; case 'exp': return $this->exp; break; case 'phy': return $this->phy; break; case 'fin': return $this->fin; break; default: break; } } }
Markdown
UTF-8
2,774
2.546875
3
[]
no_license
--- authors: - Raphael Brugier tags: - AWS date: 2018-11-28T23:20:07.000Z title: "AWS re:Invent 2018 - Day 1" image: https://raw.githubusercontent.com/ippontech/blog-usa/master/images/2018/11/reinvent2.jpeg --- Hi everyone, AWS re:Invent is huge! And each day has a lot of new announcements. Here are our favorites: # Storage ## Managed SFTP Service for S3 S3 now offers a managed SFTP service. You can integrate with S3 using your “legacy” SFTP commands, and even use the IAM policies to control accesses. A simple service, but one that can simplify the migration of legacy applications. [AWS Transfer for SFTP – Fully Managed SFTP Service for Amazon S3](https://aws.amazon.com/blogs/aws/new-aws-transfer-for-sftp-fully-managed-sftp-service-for-amazon-s3/) ## Optimized agent for data transfer A tool to simplify and optimize your S3 to local or local to S3 data transfers. Very useful to move a lot of data into or from S3. [AWS DataSync – Automated and Accelerated Data Transfer](https://aws.amazon.com/blogs/aws/new-aws-datasync-automated-and-accelerated-data-transfer/) ## New S3 storage class: Intelligent-tiering This new storage class allows to dynamically and automatically change the storage type of your S3 objects. AWS uses machine learning algorithms to switch your objects between the frequent and infrequent access classes depending on how they are accessed. [Automatic Cost Optimization for Amazon S3 via Intelligent Tiering](https://aws.amazon.com/blogs/aws/new-automatic-cost-optimization-for-amazon-s3-via-intelligent-tiering/) # Analytics ## Athena Workload Isolation (Beta) The most important feature of this tool is to be able to limit the amount of data used during the processing and being able to cancel a request. This is especially useful when new users are running long (and costly) requests that may be blocking other resources. # Connectivity ## Transit Gateway Transit Gateway simplifies the connection between all the VPCs. Before that, VPCs did not support transitive peering. Using Transit Gateway you can now to build a hub-and-spoke network topology. [Use an AWS Transit Gateway to Simplify Your Network Architecture](https://aws.amazon.com/fr/blogs/aws/new-use-an-aws-transit-gateway-to-simplify-your-network-architecture/) # Compute ## Firecracker - Lightweight virtualization AWS has open sourced a new virtualization technology - written in Rust - that promises to run microVMs (think serverless functions) in a fraction of a second. Firecracker is the technology behind the Lambda service, so it’s really exciting to see AWS open sourcing it. [Firecracker – Lightweight Virtualization for Serverless Computing](https://aws.amazon.com/blogs/aws/firecracker-lightweight-virtualization-for-serverless-computing/)
JavaScript
UTF-8
2,218
3.0625
3
[]
no_license
function FormValidatorClass(config) { //sample config file //normally states added to an elemnt initially is: //state= {touched: false, filled: false, valid: false} //this state is added to data attribute of all elements in the given form /* config = { name: "my-form", namespaces: [n1, n2], //namespaces reference for validation functions fields: [ { name: "first-input", validationCondition: "fun1 || fun2 && fun3 || fun4", //these functions should be either in some namespace validState: { //anyone of below 4 should be present untouchedFilled: false, //autofill form case touchedFilled: false, //write something and its filled untouchUnfilled: false, //no write and nothing filled - non required field touchUnfilled: false, //wrote and emptied a field //anyone of below 2 should be present filledValid: false, //something is written and its valid unfilledValid: false //nothing is written and its valid - same as 'touchUnfilled' }, warnState: {}, //same properties as validState but will not cause form invalidation chkValidEvents: ["change", "keyup"], onInvalid: callbackFunction, // to be fired when chkValidEvents detect invalidation //on invalid also sends a arguement as Object. This object contains 3 properties, //state, condition and event on which validation was checked, which are array of string. //1) state contains validState options which failed //2) condition contains the name of functions passed in validationConditions properties //due to which invalidation happened. //3) event contains the event on which invalidation occured. This is one the options passed //in chkValidEvents property onWarn: callbackFunction, //same as onInvalid function. no form invalidation though onValid: callbackFunction // to be fired when chkValidEvents detect validation } ], resolve: function //a promise which will execute and will submit function only if it resolves } */ }
Python
UTF-8
379
2.640625
3
[]
no_license
def sign(): from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA key = RSA.generate(2048) public = key.publickey().exportKey('PEM').decode('ascii') private = key.exportKey('PEM').decode('ascii') text = 'abcdefgh'.encode('utf-8') hash = SHA256.new(text).digest() signature = key.sign(hash, '') print('signature=', signature) sign()
Python
UTF-8
371
3.484375
3
[]
no_license
import random try: while True: for i in range(21,30): print(str(i) + " X " + str(i)) answer = int(input()) if(answer == (i*i)): print("SUCCESS!!") else: print("FAIL!! correct answer: " + str(i*i)) except: print("Irrelevent key has been pressed. Exiting Program")
C++
UTF-8
3,639
3
3
[]
no_license
#include "Driver.h" #include "Tracker/KilometersPassedTracker.h" #include "Tracker/SatisfactionTracker.h" /** * Constructor. * @param idNum id number. * @param ageVal age of the driver. * @param status marital status. * @param years years of experience. * @param cabID id number of the driver's cab. * @return Driver object. */ Driver::Driver(int idNum, int ageVal, MaritalStatus status, int years, int cabID) : Recognizable(idNum), age(ageVal), maritalStatus(status), yearsOfExp(years), avgSatisfaction(0), totalPassengers(0), cab(NULL), cabId(cabID), available(true), location(Point(0, 0)) { passengers = list<Passenger *>(); } /** * Default constructor. * @return Driver object. */ Driver::Driver() : Recognizable(0), age(0), maritalStatus(SINGLE), yearsOfExp(0), avgSatisfaction(0), totalPassengers(0), cab(NULL), cabId(0), available(true), location(Point(0, 0)) { passengers = list<Passenger *>(); } /** * Destructor. */ Driver::~Driver() { delete cab; } /** * Get the id of the driver's cab. * @return number. */ int Driver::getCabId() { return cabId; } /** * Get the driver's cab. * @return pointer to cab. */ Cab *Driver::getCab() { return cab; } /** * Set the cab of the driver. * @param cab pointer to some cab. */ void Driver::setCab(Cab *taxi) { cab = taxi; } /** * Get the location of the driver. * @return point. */ Point Driver::getLocation() { return location; } /** * Notify the driver of a certain ride he must take. * @param navigation pointer to navigation, will contain the ride details. */ void Driver::takeRide(Navigation *navigation) { available = false; cab->setNavigation(navigation); } /** * Drive the cab to its next location in the ride, * and notify about the movement. */ void Driver::moveOneStep() { // Drive the cab. int steps = cab->moveOneStep(); location = cab->getLocation(); notifyMovement(steps); if (cab->isArrivedToDestination()) { // This is the end of the ride, Handle listeners and passengers. clearListeners(); passengers.clear(); // Make driver available to another work. available = true; cab->resetNavigation(); } } /** * Add a list of passengers to the driver. * @param passengersList list of pointers to passengers. */ void Driver::addPassengers(std::list<Passenger *> passengersList) { for (std::list<Passenger *>::iterator it = passengersList.begin(); it != passengersList.end(); it++) { passengers.push_back(*it); } } /** * Get the passengers of the driver. * @return list of pointers to passengers. */ list<Passenger *> Driver::getPassengers() { return passengers; } /** * Add the given inspection to the average satisfaction. * @param satisfaction number between 1 to 5. */ void Driver::addInspection(int satisfaction) { int numinator = avgSatisfaction * totalPassengers + satisfaction; avgSatisfaction = numinator / (++totalPassengers); } /** * Get the average satsfaction of the driver. * @return average satisfaction. */ int Driver::getAvgSatisfaction() { return avgSatisfaction; } /** * Add a listeners which associated with the current driver and the given ride. * @param ride pointer to ride. */ void Driver::addListeners(Ride *ride) { MovementListener *wayTracker = new KilometersPassedTracker(this, ride); addListener(wayTracker); MovementListener *satisfactionTracker = new SatisfactionTracker(this, ride); addListener(satisfactionTracker); }
C
UTF-8
6,878
2.921875
3
[]
no_license
// SRmisc_functions.c #include "SRmisc_functions.h" #include <util/delay.h> #include <avr/interrupt.h> #include <stdio.h> // for printf #define kPa2PSI 0.14503774 // 1 kPa = 0.14503774 PSI (approx) // Mean and Standard Deviation Module variables uint16_t M_SD_target_num_samples; uint16_t M_SD_num_samples; float M_SD_mean; float M_SD_variance; // ----- bitwise operations: uint8_t flag_is_on(uint8_t flags, uint8_t flag_num) { if(flags & (1 << (flag_num-1))) return 1; return 0; } uint8_t make_flag(uint8_t prior_flags, uint8_t flag_num) { uint8_t new_flags; new_flags = prior_flags | (1 << (flag_num-1)); return new_flags; } // ----- bytewise operations: uint32_t build_uint32_from_byte_array(uint8_t bytes[], uint8_t num_bytes) { uint32_t big_int; uint8_t i; big_int = 0; for(i = 0; i < num_bytes; i++) { big_int = big_int<<8; big_int += bytes[i]; } return big_int; } int16_t twos_complement_conversion(uint16_t unsigned_value, uint8_t sign_bit_pos) { uint16_t intermediate; int16_t result; uint8_t sign; // extract the sign bit from the bit sequence (the MSB) sign = (unsigned_value>>sign_bit_pos)&0x0001; if(sign != 0) // a nonzero sign bit indicates a negative value { intermediate = unsigned_value &~ (1<<sign_bit_pos); // clear sign bit result = (1<<(sign_bit_pos)) - intermediate; result = result * (-1); } else { result = unsigned_value; } return result; } // ----- unit conversions: float kPa_to_PSI(float kPa) { // 1 kPa = 0.14503774 PSI (approx) return kPa2PSI*kPa; } float mbar_to_PSI(float mbar) { // 1 mbar = 0.1 kPa return 0.1*kPa2PSI*mbar; } float celsius_to_farenheit(float celsius) { return celsius * (9.0/5.0) + 32.0; // exact } float farenheit_to_celsius(float farenheit) { return (farenheit - 32.0) * (5.0/9.0); // exact } // ----- math operations: void OLS_solver(uint8_t x_points[], float y_points[], uint8_t num_points, float *slope_soln, float *yint_soln) { // using Ordinary Least Squares to fit the line to these 2D points, you get // slope = sum[(x_i - x_mean)*(y_i - y_mean)]/sum[(x_i - x_mean)^2] // y_int = y_mean - slope*x_mean float x_sum, y_sum, x_mean, y_mean; float numerator, denominator; x_sum = 0; y_sum = 0; for(uint8_t i = 0; i < num_points; i++) { x_sum += x_points[i]; y_sum += y_points[i]; } for(uint8_t i = 0; i < num_points; i++) { numerator += (x_points[i] - x_mean)*(y_points[i] - y_mean); denominator += (x_points[i] - x_mean)*(x_points[i] - x_mean); } x_mean = x_sum/num_points; y_mean = y_sum/num_points; numerator = 0; //sum[(x_i - x_mean)*(y_i - y_mean)] denominator = 0; //sum[(x_i - x_mean)^2] for(uint8_t i = 0; i < num_points; i++) { numerator += (x_points[i] - x_mean)*(y_points[i] - y_mean); denominator += (x_points[i] - x_mean)*(x_points[i] - x_mean); } *slope_soln = numerator/denominator; *yint_soln = y_mean - (*slope_soln)*x_mean; } uint8_t find_median_of_3(uint8_t* meas) { // Finds the median of 3 numbers by finding the max, finding the min, and returning the other value uint8_t mini = 0; uint8_t maxi = 0; uint8_t medi = 0; uint8_t min = 0; uint8_t max = 0xFF; for (uint8_t i = 0; i < 3; i++) { if(meas[i] < max) { max = meas[i]; maxi = i; } if(meas[i] > min) { min = meas[i]; mini = i; } } for (medi = 0; medi < 3; medi++) { if((medi != maxi) & (medi != mini)) break; } return meas[medi]; } // Mean and Standard Deviation Module void init_M_SD_module(uint8_t goal_num_samples) { M_SD_target_num_samples = goal_num_samples; M_SD_num_samples = 0; M_SD_mean = 0; M_SD_variance = 0; } uint8_t M_SD_module_add_value(float val) { float k = M_SD_num_samples + 1; float next_mean; float next_var; // increment the mean: if(M_SD_num_samples == 0) { next_mean = val; } else { next_mean = (M_SD_mean*(k-1) + val)/k; } // increment the variance: if(M_SD_num_samples >= 2) // k > 2 (third or higher value being added) { //next_var = ((k-2)/(k-1))*M_SD_variance + ((1/k)*(val-M_SD_mean)*(val-M_SD_mean)) next_var = ((k-2)*M_SD_variance)/(k-1) + ((val-M_SD_mean)/k)*(val-M_SD_mean); } else if(M_SD_num_samples == 1) // k == 2 (second value being added) { next_var = (val-M_SD_mean)*(val-M_SD_mean)/2.0; } else // k == 1 (first value being added) { next_var = 0; } M_SD_mean = next_mean; M_SD_variance = next_var; M_SD_num_samples++; // alert user that the mean and variance are ready for sampling: if(M_SD_num_samples >= M_SD_target_num_samples) return 1; else return 0; } float M_SD_module_get_mean(void) { return M_SD_mean; } float M_SD_module_get_stdev(void) { return sqrt(M_SD_variance); } // ----- data printing operations: void print_mathematica_formatted_2column(uint8_t x_points[], float y_points[], uint8_t num_points) { printf("{"); for(uint8_t i = 0; i < num_points; i++) { printf("\r\n{%u,%.6f},", x_points[i], (double)y_points[i]); _delay_ms(5); } printf("\b};\r\n"); } void print_precise_line_equation(float slope, float yint) { printf("line: y = %.6f+%.6f*x\r\n", yint, slope); _delay_ms(5); } // ----- debugging operations: void print_uint8_in_binary(uint8_t num) { if(num < 10) // single digit printf(" %u = ", num); else if(num < 100) // two digit printf(" %u = ", num); else // three digit printf("%u = ", num); for(int8_t i = 7; i >= 0; i--) { printf("%u", (num >> i) & 1); //_delay_ms(2); } printf("\r\n"); } void compare_two_uint64_print(uint64_t num1, uint64_t num2) { uint8_t byte; if(num1 == num2) printf("SAME\r\n"); else printf("DIFFERENT\r\n"); /* for(uint8_t byte = 0; byte < 8; byte++) { printf("%u: ", byte + 1); printf("%u, ", (num1>>(8*byte)) & 0xFF); printf("%u\r\n", (num2>>(8*byte)) & 0xFF); _delay_ms(5); }*/ printf("1: "); for(byte = 8; byte > 0; byte--) { printf("%2x ", (num1>>(8*(byte-1))) & 0xFF); _delay_ms(2); } printf("\r\n"); printf("2: "); for(byte = 8; byte > 0; byte--) { printf("%2x ", (num2>>(8*(byte-1))) & 0xFF); _delay_ms(2); } printf("\r\n"); } void checkpoint_print(uint8_t symbol) { if(ALLOW_CHECKPOINT_PRINT) printf("%c",symbol); } void halt_program() { _delay_ms(50); // LEDs are monitoring interrupts, sometimes //set_LED(1, LED_SATURATION_LOW); //set_LED(2, LED_SATURATION_LOW); printf("HALTED, must reboot, debug your program\r\n"); //fprintf_P(&usart_stream, PSTR("HALTED, must reboot, debug your program\r\n")); _delay_ms(20); cli(); //disable_interrupts while(1==1) {/* infinite fail loop */}; }
Java
UTF-8
333
1.898438
2
[]
no_license
package com.dj.cloud.service; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RestController; @RestController @Service public class OrderServiceImpl implements OrderService{ @Override public String sayOrder(String userName) { return "hello Order,"+userName; } }
C++
UTF-8
17,622
2.53125
3
[]
no_license
#include <graphics/Context.hpp> #include <graphics/Renderer.hpp> #include <graphics/TextureManager.hpp> #include <utils/log.hpp> #include <utils/split.hpp> #include <utils/libgen.hpp> #include <utils/to_string.hpp> #include <algorithm> #include <set> #define check_gl_err() graphics::show_gl_err(__FILE__, __LINE__) namespace graphics { const char* err_str(GLenum errorCode) { static const struct { GLenum code; const char *string; } errors[]= { {GL_NO_ERROR, "no error"}, {GL_INVALID_ENUM, "invalid enumerant"}, {GL_INVALID_VALUE, "invalid value"}, {GL_INVALID_OPERATION, "invalid operation"}, {GL_INVALID_FRAMEBUFFER_OPERATION, "invalid framebuffer operation"}, // {GL_STACK_OVERFLOW, "stack overflow"}, // {GL_STACK_UNDERFLOW, "stack underflow"}, {GL_OUT_OF_MEMORY, "out of memory"}, {0, NULL } }; for (int i = 0; errors[i].string; ++i) { if (errors[i].code == errorCode) { return errors[i].string; } } return NULL; } int show_gl_err(const char *file, int line) { GLenum gl_err; int ret_code = 0; gl_err = glGetError(); if (gl_err != GL_NO_ERROR) { LOG(ERR) << "glError in file " << (file ? utils::base_name(file) : "unknown") << " @ line " << line << ": " << err_str(gl_err); ret_code = 1; } return ret_code; } struct Context::internal { private: typedef std::map<GLenum, GLuint> tex_bindings_t; public: internal(); ~internal(); /** Установить флаги особых расширений в зависимости от наличия того или иного расширения в extensions */ void setup_extensions_flags(); public: color_t clear_color; ///< Текущий цвет очистки рендербуфера color_t color; ///< Текущий цвет графических объектов unsigned char color_mask; ///< маска применения цвета к фрэймбуферу double depth_clear_value; ///< GLenum depth_clear_func; ///< GLenum blend_func[2]; ///< GLenum active_texture; ///< номер текущей активной текстуры GL_TEXTURE0, GL_TEXTURE1... rectangle_t scissor_box; ///< область отсечения рендеринга относительно экрана std::set<std::string> extensions; ///< Cписок особых расширений std::string vendor_string; ///< std::string renderer_string; ///< std::string version_string; ///< bool has_ext_texture_npot; ///< Флаг особых расширений texture_npot bool has_ext_rgb8; ///< std::map<GLenum, GLboolean> server_caps; ///< std::vector<bool> vertex_attrib_arrays_states; ///< Состояния привязок буферов tex_bindings_t tex_bindings; ///< Привязки текстур к текстурным юнитам }; Context::internal::internal() : clear_color() , color() , depth_clear_value(0.0) , depth_clear_func(GL_LESS) , active_texture(0) , extensions() , has_ext_texture_npot(false) , has_ext_rgb8(false) , server_caps() { GLfloat farr[4]; { glGetFloatv(GL_COLOR_CLEAR_VALUE, farr); check_gl_err(); clear_color.r = farr[0]; clear_color.g = farr[1]; clear_color.b = farr[2]; clear_color.a = farr[3]; } { glGetFloatv(GL_SCISSOR_BOX, farr); check_gl_err(); scissor_box.x = farr[0]; scissor_box.y = farr[1]; scissor_box.w = farr[2]; scissor_box.h = farr[3]; } { const GLenum gl_caps[] = { GL_CULL_FACE, GL_BLEND, GL_DITHER, GL_STENCIL_TEST, GL_DEPTH_TEST, GL_SCISSOR_TEST, GL_POLYGON_OFFSET_FILL, GL_SAMPLE_ALPHA_TO_COVERAGE, GL_SAMPLE_COVERAGE }; const int gl_caps_count = sizeof(gl_caps)/sizeof(GLenum); for (int i = 0; i < gl_caps_count; ++i) { server_caps[gl_caps[i]] = glIsEnabled(gl_caps[i]); check_gl_err(); } } { glGetIntegerv(GL_BLEND_SRC_RGB, reinterpret_cast<GLint *>(&blend_func[0])); check_gl_err(); glGetIntegerv(GL_BLEND_DST_RGB, reinterpret_cast<GLint *>(&blend_func[1])); check_gl_err(); } { const GLubyte *vend = glGetString(GL_VENDOR); check_gl_err(); if (vend) { vendor_string = reinterpret_cast<const char *>(vend); LOG(INFO) << "Vendor: " << vendor_string; } const GLubyte *rend = glGetString(GL_RENDERER); check_gl_err(); if (rend) { renderer_string = reinterpret_cast<const char *>(rend); LOG(INFO) << "Renderer: " << renderer_string; } const GLubyte *vers = glGetString(GL_VERSION); check_gl_err(); if (vers) { version_string = reinterpret_cast<const char *>(vers); LOG(INFO) << "Version: " << version_string; } const GLubyte *exts = glGetString(GL_EXTENSIONS); check_gl_err(); if (exts) { std::string extensions_string(reinterpret_cast<const char *>(exts)); std::transform(extensions_string.begin(), extensions_string.end(), extensions_string.begin(), toupper); LOG(INFO) << "Supported OpenGL extensions: " << extensions_string; utils::split(extensions, extensions_string, ' '); setup_extensions_flags(); } const GLubyte *glsl_version = glGetString(GL_SHADING_LANGUAGE_VERSION); check_gl_err(); if (glsl_version) { LOG(INFO) << "GLSL version: " << glsl_version; } } } Context::internal::~internal() { } void Context::internal::setup_extensions_flags() { // расширения GL GL_ARB_TEXTURE_NON_POWER_OF_TWO и GLES GL_OES_TEXTURE_NPOT полностью покрывают требования фреймворка, // поэтому можно их считать одинаковыми has_ext_texture_npot = extensions.count("GL_ARB_TEXTURE_NON_POWER_OF_TWO") || extensions.count("GL_OES_TEXTURE_NPOT"); // проверка, поддерживается ли расширение GL_OES_rgb8_rgba8 - для полноцветного рендербуфера has_ext_rgb8 = extensions.count("GL_OES_RGB8_RGBA8") > 0; } /** \class gl */ ContextSPtr gl::m_ctx(new ContextStub()); rectangle_t gl::m_viewport; dimension_t gl::m_screen_size; bool gl::m_is_tablet = false; void gl::create() { if (m_ctx->is_active()) return; LOG(INFO) << "GL-context created"; // Создаем активный gl-контекст и делаем его текущим m_ctx.reset(new Context()); // Определяем начальное состояние графики m_ctx->enable_server_state(GL_BLEND); m_ctx->set_blend_func(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); m_ctx->set_clear_color(color_t(0.0f, 0.0f, 0.0f, 0.0f)); // Пересоздаем шейдеры и заново линкуем шейдерные программы renderer().load_shaders(); // Восстанавливаем текстуры if (texmgr().is_alive()) texmgr().reload(); } void gl::destroy() { if (!m_ctx->is_active()) return; LOG(INFO) << "GL-context destroyed"; // Разрушаем шейдеры и удаляем шейдерные программы renderer().release_shaders(); // Разрушаем текстуры if (texmgr().is_alive()) texmgr().unload(); // Создаем неактивный gl-контекст и делаем его текущим m_ctx.reset(new ContextStub()); } ContextBase* gl::ctx() { return m_ctx.get(); } void gl::set_viewport(const rectangle_t& value, bool force) { if (value == m_viewport) { if (force) m_ctx->set_viewport(m_viewport); return; } m_viewport = value; m_ctx->set_viewport(m_viewport); } rectangle_t gl::get_viewport() { return m_viewport; } void gl::set_tablet(bool value) { m_is_tablet = value; } bool gl::get_tablet() { return m_is_tablet; } bool gl::set_screen_size(const dimension_t& value) { if (m_screen_size == value) return false; m_screen_size = value; return true; } dimension_t gl::get_screen_size() { return m_screen_size; } /** \class ContextBase */ ContextBase::ContextBase() { } ContextBase::~ContextBase() { } /** \class Context */ Context::Context() : m(new internal) { GLint max_vertex_attribs = 16; glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs); check_gl_err(); m->vertex_attrib_arrays_states.resize(max_vertex_attribs, false); } void Context::set_clear_color(const color_t& value) { if (m->clear_color == value) return; m->clear_color = value; glClearColor(m->clear_color.r, m->clear_color.g, m->clear_color.b, m->clear_color.a); check_gl_err(); } color_t Context::get_clear_color() const { return m->clear_color; } void Context::set_depth_value(GLfloat value) { if (value == m->depth_clear_value) return; glClearDepthf(value); check_gl_err(); m->depth_clear_value = value; } void Context::set_depth_function(GLenum value) { if (value == m->depth_clear_func) return; glDepthFunc(value); check_gl_err(); m->depth_clear_func = value; } void Context::clear_buffers(GLbitfield mask) { glClear(mask); check_gl_err(); } void Context::enable_server_state(const GLenum cap) { if (m->server_caps.count(cap) > 0) { if (m->server_caps[cap]) return; } glEnable(cap); check_gl_err(); m->server_caps[cap] = GL_TRUE; } void Context::disable_server_state(const GLenum cap) { if (m->server_caps.count(cap) > 0) { if (!m->server_caps[cap]) return; } glDisable(cap); check_gl_err(); m->server_caps[cap] = GL_FALSE; } void Context::enable_vertex_attr_array(GLuint index) { if (index < m->vertex_attrib_arrays_states.size()) { if (m->vertex_attrib_arrays_states[index]) return; m->vertex_attrib_arrays_states[index] = true; } glEnableVertexAttribArray(index); check_gl_err(); } void Context::disable_vertex_attr_array(GLuint index) { if (index < m->vertex_attrib_arrays_states.size()) { if (!m->vertex_attrib_arrays_states[index]) return; m->vertex_attrib_arrays_states[index] = false; } glDisableVertexAttribArray(index); check_gl_err(); } void Context::set_blend_func(const GLenum sfactor, const GLenum dfactor) { GLenum * const value = m->blend_func; if (sfactor == value[0] && dfactor == value[1]) return; glBlendFunc(sfactor, dfactor); check_gl_err(); value[0] = sfactor; value[1] = dfactor; } void Context::draw_elements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices) { glDrawElements(mode, count, type, indices); check_gl_err(); } GLuint Context::create_shader(GLenum type, const std::string& source) { // Создаем шейдер GLuint shader_id = 0; shader_id = glCreateShader(type); check_gl_err(); ASSERT(shader_id); // Компилируем шейдер const GLint src_length = source.length(); const char *source_text = source.c_str(); glShaderSource(shader_id, 1, (const GLchar**)&source_text, &src_length); check_gl_err(); glCompileShader(shader_id); check_gl_err(); // Проверяем, что шейдер скомпилировался нормально { GLint status = 0, length = 0; GLchar buffer[1024]; // Получаем статус шейдера glGetShaderiv(shader_id, GL_COMPILE_STATUS, &status); check_gl_err(); if (status != GL_TRUE) { // Ошибка компиляции glGetShaderInfoLog(shader_id, 1024, &length, buffer); check_gl_err(); LOG(ERR) << "Ошибка при создании шейдера OpenGL: " << (const char*)buffer; LOG(ERR) << "Тип: " << shader_type(type) << "; Исходный текст шейдера:\n" << source; } // Если компиляция безуспешна, прекращаем работу программы CHECK(status == GL_TRUE); } return shader_id; } GLuint Context::create_program(GLuint vertex_shader, GLuint fragment_shader) { // Создаём программу GLuint program_id = 0; program_id = glCreateProgram(); check_gl_err(); ASSERT(program_id); // Указываем шейдеры программе glAttachShader(program_id, vertex_shader); check_gl_err(); glAttachShader(program_id, fragment_shader); check_gl_err(); // Линкуем и проверяем результат линковки glLinkProgram(program_id); check_gl_err(); LOG_IF(FATAL, check_program_status(program_id, GL_LINK_STATUS) != GL_TRUE) << "Не удалось слинковать шейдерную программу"; // Проверяем статус программы glValidateProgram(program_id); check_gl_err(); LOG_IF(FATAL, check_program_status(program_id, GL_VALIDATE_STATUS) != GL_TRUE) << "Шейдерная программа не корректна"; return program_id; } void Context::use_program(GLuint program_id) { glUseProgram(program_id); check_gl_err(); } void Context::detach_shader(GLuint program_id, GLuint shader_id) { glDetachShader(program_id, shader_id); check_gl_err(); } void Context::delete_shader(GLuint shader_id) { glDeleteShader(shader_id); check_gl_err(); } void Context::delete_program(GLuint program_id) { glDeleteProgram(program_id); check_gl_err(); } GLint Context::get_uniform_location(GLuint program, const GLchar* name) { GLint ret = glGetUniformLocation(program, name); check_gl_err(); return ret; } GLint Context::get_attrib_location(GLuint program, const GLchar* name) { GLint ret = glGetAttribLocation(program, name); check_gl_err(); return ret; } void Context::set_uniform_matrix(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value, const unsigned char& dimension) { switch (dimension) { case 2: glUniformMatrix2fv(location, count, transpose, value); check_gl_err(); break; case 3: glUniformMatrix3fv(location, count, transpose, value); check_gl_err(); break; case 4: glUniformMatrix4fv(location, count, transpose, value); check_gl_err(); break; default: LOG(ERR) << "Unsupported matrix dimension!"; } } void Context::set_uniform_vector(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3) { glUniform4f(location, v0, v1, v2, v3); check_gl_err(); } void Context::set_uniform_value(GLint location, GLint v0) { glUniform1i(location, v0); check_gl_err(); } void Context::set_uniform_value(GLint location, GLfloat v0) { glUniform1f(location, v0); check_gl_err(); } void Context::set_pointer_vertex_attr(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer) { glVertexAttribPointer(index, size, type, normalized, stride, pointer); check_gl_err(); } void Context::gen_textures(GLsizei n, GLuint *textures) { glGenTextures(n, textures); check_gl_err(); } void Context::del_textures(GLsizei n, const GLuint *textures) { glDeleteTextures(n, textures); check_gl_err(); } void Context::bind_texture(GLuint texture, GLenum unit) { // Выбираем текстурный юнит, к которому будет привязана текстура select_texture(unit); // Если текстура уже привязана к данноме текстурному юниту, ничего не делаем if (m->tex_bindings[unit] == texture) return; // Запоминаем текущую привязку текстуры m->tex_bindings[unit] = texture; // Выполняем привязку текстуры glBindTexture(GL_TEXTURE_2D, texture); check_gl_err(); } bool Context::is_texture_binded(GLuint texture, GLenum unit) { return m->tex_bindings[unit] == texture; } void Context::select_texture(GLenum unit) { // Если указанный текстурый юнит уже активен, ничего не делаем if (m->active_texture == unit) return; // Запоминаем текущий активный текстурный юнит m->active_texture = unit; // Назначаем активный текстурный юнит glActiveTexture(m->active_texture); check_gl_err(); } void Context::set_tex_param(GLenum target, GLenum pname, GLint param) { glTexParameteri(target, pname, param); check_gl_err(); } void Context::load_texture(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data) { glTexImage2D(target, level, internalFormat, width, height, border, format, type, data); check_gl_err(); } void Context::set_viewport(const rectangle_t& value) { glViewport(static_cast<int>(value.x), static_cast<int>(value.y), static_cast<int>(value.w), static_cast<int>(value.h)); check_gl_err(); } GLint Context::check_program_status(GLuint program_id, GLenum param) { GLint status = 0, length = 0; glGetProgramiv(program_id, param, &status); check_gl_err(); if (status != GL_TRUE) { GLchar buffer[1024]; glGetProgramInfoLog(program_id, 1024, &length, buffer); check_gl_err(); LOG(ERR) << "Ошибка шейдерной программы OpenGL: " << (const char*)buffer; } return status; } std::string Context::shader_type(GLenum type) { if (type == GL_VERTEX_SHADER) return "GL_VERTEX_SHADER"; else if (type == GL_FRAGMENT_SHADER) return "GL_FRAGMENT_SHADER"; else return "Unknown (" + utils::to_string(type) + ")"; } Context::~Context() { } }
C++
ISO-8859-1
683
2.609375
3
[]
no_license
#include "Hide.h" #include "components\MoveComponent.h" #include "steering\ObstacleAvoidance.h" Hide::Hide(CVector pos) { position = pos; } Hide::~Hide(void) { } void Hide::apply(MoveComponent *self) { //Steuert so schnell wie mglich einen bestimmten Vektor an CVector currentPosition = self->getPosition(); CVector currentVelocity = self->getVelocity(); CVector desiredPosition = position; CVector desiredVelocity = desiredPosition-currentPosition; CVector accel = (desiredVelocity); accel.normalize(); accel *= self->getMaxAccel(); self->setAccel(accel); ObstacleAvoidance::avoideObstacles(self, true); } void Hide::retarget(CVector pos) { position = pos; }
Rust
UTF-8
3,464
2.78125
3
[ "Apache-2.0" ]
permissive
use super::structs::*; use crate::config::Config; use std::fmt; use std::{collections::HashMap, error::Error, path::PathBuf}; mod fill_intermediate_entries; use fill_intermediate_entries::fill_intermediate_entries; mod fill_stems; use fill_stems::fill_stems; mod fill_containers; use fill_containers::fill_containers; pub mod word_list_generators; use word_list_generators::WordListGenerationError; pub mod intermediate_entry; use intermediate_entry::IntermediateEntry; pub mod nudger; use nudger::Nudger; pub mod frontmatter; extern crate rust_stemmers; #[derive(Debug)] pub enum IndexGenerationError { NoFilesSpecified, FileNotFoundError(PathBuf), WordListGenerationError(WordListGenerationError), } impl Error for IndexGenerationError {} impl fmt::Display for IndexGenerationError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let desc: String = match self { IndexGenerationError::NoFilesSpecified => { "No files specified in config file".to_string() } IndexGenerationError::FileNotFoundError(s) => { format!("File {} not found", s.to_string_lossy()) } IndexGenerationError::WordListGenerationError(e) => e.to_string(), }; write!(f, "{}", desc) } } pub fn build(config: &Config) -> Result<Index, IndexGenerationError> { println!("{}", Nudger::from(config).generate_formatted_output()); let mut intermediate_entries: Vec<IntermediateEntry> = Vec::new(); fill_intermediate_entries(&config, &mut intermediate_entries)?; let mut stems: HashMap<String, Vec<String>> = HashMap::new(); fill_stems(&intermediate_entries, &mut stems); let mut containers: HashMap<String, Container> = HashMap::new(); fill_containers(&config, &intermediate_entries, &stems, &mut containers); let entries: Vec<Entry> = intermediate_entries.iter().map(Entry::from).collect(); let config = PassthroughConfig { url_prefix: config.input.url_prefix.clone(), title_boost: config.input.title_boost.clone(), excerpt_buffer: config.output.excerpt_buffer, excerpts_per_result: config.output.excerpts_per_result, displayed_results_count: config.output.displayed_results_count, }; Ok(Index { entries, containers, config, }) } fn remove_surrounding_punctuation(input: &str) -> String { let mut chars: Vec<char> = input.chars().collect(); while chars.first().unwrap_or(&'a').is_ascii_punctuation() { chars.remove(0); } while chars.last().unwrap_or(&'a').is_ascii_punctuation() { chars.pop(); } chars.into_iter().collect() } #[cfg(test)] mod tests { use super::*; use crate::config::File; use crate::config::*; #[test] fn test_not_present_html_selector_fails_gracefully() { let config = Config { input: InputConfig { files: vec![File { source: DataSource::Contents("".to_string()), title: "Title".to_string(), filetype: Some(Filetype::HTML), html_selector_override: Some(".article".to_string()), ..Default::default() }], ..Default::default() }, ..Default::default() }; build(&config).expect_err("Config didn't error when it should have!"); } }
Python
UTF-8
820
3.140625
3
[]
no_license
import random from gym_hnefatafl.envs import HnefataflEnv class RandomAgent(object): def __init__(self, player): self.player = player self.corners = [(1, 1), (1, 11), (11, 1), (11, 11)] # chooses a random move and returns it # in order for games to finish in a reasonable amount of time, # the agent always sends the king to one of the corners if able # (this causes white to win basically all the time) def make_move(self, env: HnefataflEnv) -> ((int, int), (int, int)): # for pos_from, pos_to in env.action_space: # if pos_to in self.corners: # return pos_from, pos_to return random.choice(env.action_space) # does nothing in this agent, but is here because other agents need it def give_reward(self, reward): pass
Python
UTF-8
9,685
2.765625
3
[]
no_license
import cv2 import numpy as np import time import math import matplotlib.pyplot as plt def to_show(images, titles): length = len(images) rows = 1 if length < 4: columns = length else: rows = round(length / 2) columns = 3 for i in range(len(images)): plt.subplot(rows, columns, i + 1); plt.imshow(images[i]) plt.title(titles[i]) plt.xticks([]), plt.yticks([]) plt.show() def get_param_lines(lines): thetas = [] coords = [] for i in range(0, len(lines)): rho = lines[i][0][0] theta = lines[i][0][1] thetas.append(theta) a = math.cos(theta) b = math.sin(theta) x0 = a * rho y0 = b * rho pt1 = (int(x0 + 1000 * (-b)), int(y0 + 1000 * a)) pt2 = (int(x0 - 1000 * (-b)), int(y0 - 1000 * a)) coords.append((pt1, pt2)) return thetas, coords def group_points(pts): rect = np.zeros((4, 2), dtype=np.float32) s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] return rect def find_intersetion(lines1, lines2): pts = [] for lineV in lines1: for lineH in lines2: xdiff = (lineV[0][0] - lineV[1][0], lineH[0][0] - lineH[1][0]) ydiff = (lineV[0][1] - lineV[1][1], lineH[0][1] - lineH[1][1]) def det(a, b): return a[0] * b[1] - a[1] * b[0] div = det(xdiff, ydiff) if div == 0: print('lines dont have intersect') d = (det(*lineV), det(*lineH)) x = det(d, xdiff) / div y = det(d, ydiff) / div pts.append((int(x), int(y))) length = len(pts) propably_points = np.zeros((length, 2)) for i in range(length): propably_points[i] = pts[i] return propably_points def transform_image(image, rect): (tl, tr, br, bl) = rect width_a = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) width_b = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) max_width = max(int(width_a), int(width_b)) height_a = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) height_b = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) max_height = max(int(height_a), int(height_b)) dst = np.array([ [0, 0], [max_width - 1, 0], [max_width - 1, max_height - 1], [0, max_height - 1]], dtype="float32") m = cv2.getPerspectiveTransform(rect, dst) return cv2.warpPerspective(image, m, (max_width, max_height)) def get_ejection_threshold(array): mean = np.mean(array) std = np.std(array) ejection_threshold = (mean - std, mean + std) return ejection_threshold, mean def get_condition(center_point, points): cond_1 = 0 cond_2 = 0 for point in points: if cond_1 == 0 and center_point[1] > point[1]: cond_1 = 1 elif cond_2 == 0 and center_point[1] < point[1]: cond_2 = 1 return cond_1 and cond_2 def remove_res(*args): for arg in args: arg.clear() class TakingPointsPlate: def __init__(self, image_path=None, stop=100, debug=0): self.image = cv2.imread(image_path) self.stop = stop self.debug = debug self.pts = [] self.contour_points = None # Set vertical borders of lines self.shape = self.image.shape[:2][::-1] c = int(((self.shape[0]) / 2)) self.thr = c if c < 100 else 100 self.half_shape = np.array((self.shape[0] / 2, self.shape[1] / 2), dtype=np.int) self.processing_dict = {'image': cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB), 'images_debug': [], 'titles': [], 'borders': [[(0, 0), (0, self.shape[1])], [(self.shape[0], 0), (self.shape[0], self.shape[1])]]} def image_preprocessing(self): self.processing_dict['gray'] = cv2.cvtColor(self.processing_dict['image'], cv2.COLOR_BGR2GRAY) self.processing_dict['thresh'] = cv2.threshold(self.processing_dict['gray'], 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] self.processing_dict['edges'] = cv2.Canny(self.processing_dict['thresh'], 50, 200, apertureSize=3) if self.debug: self.processing_dict['images_debug'].extend( [self.processing_dict['image'], self.processing_dict['gray'], self.processing_dict['thresh'], self.processing_dict['edges']]) self.processing_dict['titles'].extend(['image', 'gray', 'thresh', 'edges']) def get_attitude(self, points): contour_image = np.array(([0, 0], [self.shape[0], 0], [self.shape[0], self.shape[1]], [0, self.shape[1]])) area_contour = cv2.contourArea(points) area_image = cv2.contourArea(contour_image) return True if area_contour / area_image > 0.3 else False def find_optimal_contour(self): count = 0 while 1: count += 1 if count == self.stop: print(f'search for lines ended at iteration {count}') break self.processing_dict['lines'] = cv2.HoughLines(self.processing_dict['edges'], rho=1, theta=np.pi / 90, threshold=self.thr) if self.processing_dict['lines'] is not None: self.processing_dict['theta'], self.processing_dict['lines'] = get_param_lines( self.processing_dict['lines']) ejection_threshold, mean_theta = get_ejection_threshold(self.processing_dict['theta']) # append best lines self.processing_dict['best_lines'] = [] for t, line in zip(self.processing_dict['theta'], self.processing_dict['lines']): cond = abs(t - mean_theta) if ejection_threshold[0] <= t <= ejection_threshold[1] and cond < 0.1: self.processing_dict['best_lines'].append(line) adequacy = True if len(self.processing_dict['best_lines']) >= 2 else False if adequacy: self.pts = find_intersetion(self.processing_dict['borders'], self.processing_dict['best_lines']) if len(self.pts) == 0: continue cond = get_condition(self.half_shape, self.pts) if cond: self.contour_points = group_points(self.pts) attitude = self.get_attitude(self.contour_points) if attitude: if self.debug: self.processing_dict['lines_draw'] = self.processing_dict['image'].copy() for i in self.processing_dict['best_lines']: cv2.line(self.processing_dict['lines_draw'], i[0], i[1], (0, 0, 255), 1, cv2.LINE_AA) self.processing_dict['images_debug'].append(self.processing_dict['lines_draw']) self.processing_dict['titles'].append('lines_draw') print(f'the optimality condition was satisfied on {count}') break else: self.thr -= 1 remove_res(self.processing_dict["theta"], self.processing_dict['lines'], self.processing_dict['best_lines']) continue else: self.thr -= 1 remove_res(self.processing_dict["theta"], self.processing_dict['lines'], self.processing_dict['best_lines']) continue else: self.thr -= 1 remove_res(self.processing_dict["theta"], self.processing_dict['lines'], self.processing_dict['best_lines']) continue else: self.thr -= 1 def alignment_plates(self): print(f'len order points is {len(self.pts)}') self.processing_dict['warped'] = transform_image(self.image, self.contour_points) if self.debug: self.processing_dict['images_debug'].append(self.processing_dict['warped']) self.processing_dict['titles'].append('warped') to_show(self.processing_dict['images_debug'], self.processing_dict['titles']) return self.processing_dict['warped'] def save_results(self): if self.processing_dict['images_debug'] and self.processing_dict['titles'] != []: for image, title in zip(self.processing_dict['images_debug'], self.processing_dict['titles']): cv2.imwrite(f'results/{title}.png', image) else: pass if __name__ == '__main__': start = time.time() image_path = 'test_images/num-22.png' get_plate = TakingPointsPlate(image_path, debug=0) get_plate.image_preprocessing() get_plate.find_optimal_contour() warped = get_plate.alignment_plates() get_plate.save_results() print(f'inference time is {time.time() - start}')
Python
UTF-8
1,395
2.71875
3
[ "MIT" ]
permissive
from molsysmt._private.exceptions import ArgumentError from molsysmt import pyunitwizard as puw import numpy as np functions_with_boolean = ( 'molsysmt.basic.get.get', 'molsysmt.basic.compare.compare', 'molsysmt.basic.iterator.__init__', 'iterators.__init__', ) def digest_temperature(temperature, caller=None): """ Checks if temperature arguments has the correct type. Parameters --------- temperature: None, integer, list, tuple or ndarray The temperature argument. caller: str, optional Name of the function or method that is being digested. Returns ------- ndarray The temperature with correct type Raises ------- WrongStepError If temperature is not a valid argument. """ if caller.endswith(functions_with_boolean): if isinstance(temperature, bool): return temperature value, unit = puw.get_value_and_unit(temperature) if not puw.check(unit, dimensionality={'[K]':1}): raise ArgumentError('temperature', value=coordinates, caller=caller, message=None) if isinstance(value, (int, np.int64, float, np.float64)): return puw.quantity(value, unit, standardized=True) raise ArgumentError('temperature', value=temperature, caller=caller, message=None)
Shell
UTF-8
1,592
3.671875
4
[]
no_license
#!/bin/bash #chkconfig: 345 70 31 #description: cmsweb_discovery This script runs CMS DBS Data Discovery service if [ -z ${DDHOME} ]; then echo $"The DDHOME environment is not set" 2>&1 1>& /dev/null < /dev/null & . /data/projects/dbs/setup.sh fi cd ${DDHOME} RETVAL=$? port=`cat DBSDD.conf | grep -i "port=" | tail -1 | sed "s/PORT=//g"` base=dbs_discovery if [ -n "$WEBTOOLS_BASEURL" ]; then url="$WEBTOOLS_BASEURL/$base" else url="http://cmsweb.cern.ch/$base" # url=`cat DBSDD.conf | grep -i "^URL=" | tail -1 | sed "s/URL=//g"` fi pid=`ps auxw | grep cmsWeb | grep -v grep | grep ${port} | awk '{print $2}'` cmd="cmsWeb --base-url=${url} --port=${port} --default-page /DDServer" start(){ if [ ! -z ${pid} ]; then kill -9 ${pid} fi echo $"Start Data Discovery Service on port ${port}..." su cmsweb -c "nohup ${cmd} 2>&1 1>& /dev/null < /dev/null &" } stop(){ echo $"Stop Data Discovery Service on port ${port}..." if [ ! -z ${pid} ]; then kill -9 ${pid} fi } restart(){ echo $"Checking for existing cmsWeb app running data discovery..." if [ ! -z ${pid} ]; then echo $"Found data discovery running on pid=${pid}, will restart" kill -9 ${pid} fi echo $"Start Data Discovery Service on port ${port}..." su cmsweb -c "nohup ${cmd} 2>&1 1>& /dev/null < /dev/null &" } case "$1" in start) start ;; stop) stop ;; restart) restart ;; *) echo $"Usage: $0 {start|stop|status|restart}" exit 1 ;; esac exit $RETVAL
Markdown
UTF-8
1,677
2.515625
3
[ "Apache-2.0" ]
permissive
# OBJETIVO: editar la información de la colección o sus cromos de manera sencilla <!-- editar-coleccion.component.ts --> Recibimos la coleccion al iniciar el componente. Los parámetros de nombreColeccion y imagenColeccion los asociamos a los dos inputs que tenemos. Al principio serán iguales a al nombre y la imagen actual de la coleccion, por eso los igualamos. # EditarColeccion() Se hace un PUT de la colección seleccionado para editar # GET_Imagen() Busca la imagen de la colección que tiene el nombre del coleccion.ImagenColeccion y lo carga en imagenColeccion # GET_ImagenCromo() Busca la imagen de todos los cromos que tiene el nombre del cromo.Imagen y lo carga en imagenCromoArray # OrdenarCromos() Ordena los cromos por nombre. # ActivarInput() Mostrar() # AbrirDialogoAgregarCromoColeccion() Tendremos un botón que abre el diálogo para añadir los cromos (agregar-cromo-dialog).Explicación README-agregar-cromo-dialog.md. Al cerrar el diálogo ejecutaremos la función CromosEImagenDeLaColeccion() para actualizar la lista de cromos. # EnviarCromoEditar() Una vez seleccionado un cromo, lo podemos editar o eliminar. Esta función se activará si clicamos en editar. Envía el cromo específico al componente editar-cromo. # AbrirDialogoConfirmacionBorrarCromo() Abrimos el componente para confirmar que quiero eliminar el cromo seleccionado. # BorrarCromo() Utilizamos esta función para eliminar un cromo de la base de datos y actualiza la lista de cromos. # CromosEImagenDeLaColeccion() Esta función ya esta explicada en el README-mis-colecciones.md, y sirve para una vez editado o añadido un cromo si actualize la colección.
Java
UTF-8
2,905
2.09375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.professorjasse.bigsoft.sige.model; import java.io.Serializable; import java.util.Date; import javax.persistence.*; import javax.validation.constraints.NotNull; //import org.hibernate.validator.constraints.Email; /** * * @author Erminio Jasse */ @Entity @Table (name="tb_Educador")/*, uniqueConstraints={ @UniqueConstraint(columnNames={"usu_telefone1", "usu_telefone2"}, name="uk_usuariotelefone") })*/ public class Educador implements Serializable{ @Id @GeneratedValue private Integer id; private String nome; private String senha; private String telefone1; private String genero; String data_nascimento; private String especialidade; private String observacoes; private String nacionalidade; public Educador() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getNacionalidade() { return nacionalidade; } public void setNacionalidade(String nacionalidade) { this.nacionalidade = nacionalidade; } public String getData_nascimento() { return data_nascimento; } public void setData_nascimento(String data_nascimento) { this.data_nascimento = data_nascimento; } public String getEspecialidade() { return especialidade; } public void setEspecialidade(String especialidade) { this.especialidade = especialidade; } public String getObservacoes() { return observacoes; } public void setObservacoes(String observacoes) { this.observacoes = observacoes; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } public String getGenero() { return genero; } public void setGenero(String genero) { this.genero = genero; } public String getTelefone1() { return telefone1; } public void setTelefone1(String telefone1) { this.telefone1 = telefone1; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } @Override public String toString() { return "Educador{" + "id=" + id + ", nome=" + nome + ", senha=" + senha + ", telefone1=" + telefone1 + ", genero=" + genero + ", data_nascimento=" + data_nascimento + ", especialidade=" + especialidade + ", observacoes=" + observacoes + ", nacionalidade=" + nacionalidade + '}'; } }
Java
UTF-8
8,930
3.140625
3
[]
no_license
import java.util.*; import java.io.*; public class USACO{ public static void main(String[] args){ // try every test case, catch if file is invalid try{ System.out.println(bronze("testCases/makelake.1.in")); System.out.println(bronze("testCases/makelake.2.in")); System.out.println(bronze("testCases/makelake.3.in")); System.out.println(bronze("testCases/makelake.4.in")); System.out.println(bronze("testCases/makelake.5.in")); System.out.println(silver("testCases/ctravel.1.in")); System.out.println(silver("testCases/ctravel.2.in")); System.out.println(silver("testCases/ctravel.3.in")); System.out.println(silver("testCases/ctravel.4.in")); System.out.println(silver("testCases/ctravel.5.in")); // System.out.println(silver("ctravel.0.in")); } catch (FileNotFoundException e){ System.out.println("File not found"); } } public static int bronze(String filename) throws FileNotFoundException{ // make new lake and return volume Lake test = new Lake(filename); return test.volume(); } public static int silver(String filename) throws FileNotFoundException{ // instantiate paths pasture and return number of solutions Path test = new Path(filename); int paths = test.generatePaths(); return paths; } } class Path{ private int N; private int M; private int T; private int R1; private int C1; private int R2; private int C2; private char[][] pasture; // given pasture, with trees private int[][] paths; // array of possible solutions from each given square public Path(String filename) throws FileNotFoundException{ // read input file File file = new File(filename); Scanner input = new Scanner(file); String readLine = ""; int line = 0; while (input.hasNextLine()){ readLine = input.nextLine(); /* Read the first line of information for number of rows, columns, final elevation, and number of instructions*/ if (line == 0){ // separate the line into String array of the "numberStr" to be used String[] numberStr = readLine.split(" "); N = Integer.parseInt(numberStr[0]); M = Integer.parseInt(numberStr[1]); T = Integer.parseInt(numberStr[2]); pasture = new char[N][M]; paths = new int[N][M]; } // When reading the lines with the pasture else if (line <= N){ // update current pasture row int r = line - 1; for (int i = 0; i < pasture[0].length; i++){ pasture[r][i] = readLine.charAt(i); } } // When reading the start and end coordinates else if (line > N){ String[] numberStr = readLine.split(" "); // store start and end coordinates R1 = Integer.parseInt(numberStr[0]); C1 = Integer.parseInt(numberStr[1]); R2 = Integer.parseInt(numberStr[2]); C2 = Integer.parseInt(numberStr[3]); } line++; } } // print out the pasture public String toString(){ String pastureStr = ""; for (int r = 0; r < N; r++){ for (int c = 0; c < M; c++){ pastureStr += pasture[r][c]+" "; if (c == M -1){ pastureStr += "\n"; } } } return pastureStr; } // print out array of possible paths public String toStringPaths(){ String pathStr = ""; for (int r = 0; r < N; r++){ for (int c = 0; c < M; c++){ pathStr += paths[r][c]+" "; if (c == M -1){ pathStr += "\n"; } } } return pathStr; } // generate array of possible paths from each given square public int generatePaths(){ // array row, column equivalents of given rows and columns int row1 = R1 - 1; int col1 = C1 - 1; int row2 = R2 - 1; int col2 = C2 - 1; // base: if 0 moves, the only solution is at the end point paths[row2][col2] = 1; // for each second / move for (int t = 0; t < T; t++){ int[][] tempPaths = new int[N][M]; // create temporary paths array /* Loop through paths array and update each square in the temporary array with the sum of the horizonally and vertically adjacent values in the paths array, if the current square is open pasture, i.e. no tree. */ for (int r = 0; r < paths.length; r++){ for (int c = 0; c < paths[0].length; c++){ // Also check if each direction is within bounds of the pasture if (r - 1 >= 0 && pasture[r-1][c] == '.'){ tempPaths[r][c] += paths[r-1][c]; } if (r + 1 < paths.length && pasture[r+1][c] == '.'){ tempPaths[r][c] += paths[r+1][c]; } if (c - 1 >= 0 && pasture[r][c-1] == '.'){ tempPaths[r][c] += paths[r][c-1]; } if (c + 1 < paths[0].length && pasture[r][c+1] == '.'){ tempPaths[r][c] += paths[r][c+1]; } } } // Set paths array as the temporary paths array paths = tempPaths; } // Return the number of possible solutions from starting square return paths[row1][col1]; } } class Lake{ private int R; private int C; private int E; private int N; private int[][] pasture; // 2D array with pasture depths private int[] cowHerd; // 9-squares to be stomped on public Lake(String filename) throws FileNotFoundException{ // read input file File file = new File(filename); Scanner input = new Scanner(file); String readLine = ""; int line = 0; while (input.hasNextLine()){ readLine = input.nextLine(); // separate the line into String array of the "numberStr" to be used String[] numberStr = readLine.split(" "); /* Read the first line of information for number of rows, columns, final elevation, and number of instructions*/ if (line == 0){ R = Integer.parseInt(numberStr[0]); C = Integer.parseInt(numberStr[1]); E = Integer.parseInt(numberStr[2]); N = Integer.parseInt(numberStr[3]); pasture = new int[R][C]; } // When reading the lines with the pasture else if (line <= R){ // update current pasture row int r = line - 1; for (int i = 0; i < pasture[0].length; i++){ pasture[r][i] = Integer.parseInt(numberStr[i]); } } // When reading the instructions else if (line > R && (line - R) <= N){ // call herd to stomp where specified int R_s = Integer.parseInt(numberStr[0]); int C_s = Integer.parseInt(numberStr[1]); int D_s = Integer.parseInt(numberStr[2]); stomp(R_s, C_s, D_s); } line++; } } // for printing pasture public String toString(){ String pastureStr = ""; for (int r = 0; r < R; r++){ for (int c = 0; c < C; c++){ pastureStr += pasture[r][c]+" "; if (c == C -1){ pastureStr += "\n"; } } } return pastureStr; } // stomp on a 9-square space on the pasture given specified row, column, and depth to stomp down public void stomp(int R_s, int C_s, int D_s){ cowHerd = new int[9]; int index = 0; // Check if cow herd can fit on the given area if (1 <= R_s && R_s <= R-2 && 1 <= C_s && C_s <= C-2){ // add the 9 elevations to an array for (int i = R_s-1; i < R_s+2; i++){ cowHerd[index] = pasture[i][C_s-1]; cowHerd[index+1] = pasture[i][C_s]; cowHerd[index+2] = pasture[i][C_s+1]; index += 3; } // sort the array of elevations and store the highest elevation Arrays.sort(cowHerd); int highestElev = cowHerd[8]; int diff = 0; // update the pasture levels for (int i = R_s -1; i < R_s+2; i++){ /* If the difference between elevations of current spot and highest spot is less than or equal to the number of inches to push down, subtract the elevation of the current spot by the difference between the number of inches to push down and the difference between elevations. */ diff = highestElev - pasture[i][C_s-1]; if (diff <= D_s){ pasture[i][C_s-1] -= (D_s - diff); } diff = highestElev - pasture[i][C_s]; if (diff <= D_s){ pasture[i][C_s] -= (D_s - diff); } diff = highestElev - pasture[i][C_s+1]; if (diff <= D_s){ pasture[i][C_s+1] -= (D_s - diff); } } } } // Find the volume of the lake public int volume(){ int totalDepth = 0; for (int r = 0; r < R; r++){ for (int c = 0; c < C; c++){ // If the pasture is under the water, add the depth to total depth if ( (E - pasture[r][c]) > 0){ totalDepth += (E - pasture[r][c]); } } } // Multiply depth by 6 feet by 6 feet to get volume int volume = totalDepth * 72 * 72; return volume; } }
Python
UTF-8
1,250
3.3125
3
[]
no_license
#!/usr/bin/env python # # Luke Southam <luke@devthe.com> # GCJ Problem A. Tic-Tac-Toe-Tomek # T = int(raw_input()) symbols = ["X","O",".","T"] for test_i in xrange(T): board = [[],[],[],[]] unfinished = 0 for i in xrange(4): line = raw_input() for char in line: if char == ".": unfinished += 1 if char in symbols: board[i].append(char) state = None lists = [board[i] for i in xrange(4)] lists.extend([[board[i][j] for i in xrange(4)] for j in xrange(4)]) lists.append([board[i][i] for i in xrange(4)]) lists.append([board[3 - i][i] for i in xrange(4)]) for l in lists: symbols_freq = {symbol:0 for symbol in symbols} for c in l: symbols_freq[c] += 1 if symbols_freq["O"] == 4 or (symbols_freq["T"] == 1 and symbols_freq["O"] == 3): state = "O won" elif symbols_freq["X"] == 4 or (symbols_freq["T"] == 1 and symbols_freq["X"] == 3): state = "X won" if unfinished and not state: state = "Game has not completed" elif not state: state = "Draw" print "Case #%i: %s" % (test_i + 1, state) try: raw_input() except EOFError: pass
C#
UTF-8
2,382
2.65625
3
[]
no_license
using UnityEngine; public class BulletController : MonoBehaviour { // THIS IS THE PLAYER'S PROJECTILE CONTROLLER. public ParticleSystem particles0; public ParticleSystem particles1; public ParticleSystem particles2; public float speed; // This is the speed at which the projectile travels. float bulletBoundary = 20f; // The maximum ceiling of the projectile. private void FixedUpdate() { transform.position += Vector3.up * speed; // Continuously moves the projectile in an upward position. if (transform.position.y >= bulletBoundary) // If the bullet does not hit a target. { destroyBullet(); // It will terminate and destroy itself to prevent a projectile from infintely travelling. } } private void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("Enemy")) // If the projectile hits an enemy { Destroy(other.gameObject); // The enemy will be eliminated. destroyBullet(); // The projectile will be terminated. // These particle effects will play upon hitting the enemy. Instantiate(particles0, transform.position, Quaternion.identity); Instantiate(particles1, transform.position, Quaternion.identity); Instantiate(particles2, transform.position, Quaternion.identity); Invoke("DestroyThis", 7f); // This hopes to destroy the Particle System after 7 seconds. I'm not sure this works. PlayerScore.playerScore++; // Increments the player's score by one, this is currently not used. } else if (other.CompareTag("Base")) // If the projectile hits a base. { destroyBullet(); // The projectile will simply be terminated. } else if (other.CompareTag("Projectile")) // If the projectile hits another projectile { Destroy(other.gameObject); // It will terminate the other projectile. destroyBullet(); // It will also terminate this projectile. } } void destroyBullet() { Destroy(gameObject); // Destroys the projectile. } void destroyThis() { // Destroys the Particle Systems after 7 seconds. Destroy(particles0); Destroy(particles1); Destroy(particles2); } }
Markdown
UTF-8
6,523
2.78125
3
[]
no_license
--- author_image: cc-logo-96dpi.png author: ContentConcepts bio: Manuscript Editing Services at affordable prices title: Predatory Journal - what is it and how to avoid them? date: 2021-02-14T18:30:00.000Z previewImage: predatory-journal.jpg excerpt: "“Predatory journals (also called deceitful or scamming journals) are arraigned of implementing inferior academic standards and practices in their editorial and peer-review processes. They apply poor ethical procedures by skipping peer-review, or do superficial (even bypass internal quality check)”. " tags: - manuscript - predatory - researchpaper seo: title: What is predatory journal? How to avoid predatory journal? description: Detailed guide to predatory journal and how to identify and avoid them keywords: - manuscript - predatory - researchpaper --- ![Predatory journal](predatory-journal.jpg "What is predatory journal") Nowadays, one’s inbox or spam folder deluged with emails soliciting paper submission to journals. These emails are triggered by the recent paper published in a reputed journal, or conference or from email address in projects or other research-related websites. There is also the pressure on budding research to publish with the current research environment adopt “Publish or Perish” policy. Now how to check and know which are legitimate journals, etc. and avoid them. ## What are predatory journals? The label ‘predatory journal’ was conceived by Jeffrey Beall (who systematically analysed a growing number of exploitative academic journals charging author fees without proper quality-check (via peer review) of the submitted and published papers). https://beallslist.net/ These journals act as predators and contemplate the authors (new or inexperienced), as their prey and lure them with a promise of fast-track peer-review and publish. Authors feel attracted by these guarantees to get their work published rapidly, hence amenable to pay for this service. “Predatory journals (also called deceitful or scamming journals) are arraigned of implementing inferior academic standards and practices in their editorial and peer-review processes. They apply poor ethical procedures by skipping peer-review, or do superficial (even bypass internal quality check)”. A novel and newer trend of predatory journals are ‘hijacked journals’; journals impersonating reputed and legitimate journals and purport to be the original journal and cajole the authors to submit to hijacked journals instead of the original. ## A brief summary on the rise of predatory journals Predatory journals gained prominence with the start of the open-access publication concept (pioneered by Hindawi in 1997), due to the bloom of this concept array of new publishers mushroomed and started their journals as online-only, with a grave intentions to capitalise on to make financial profit at the expenses of the publishing system. In 2011, Beall’s list included 18 publishers. By 2016, that number had grown to 923 publishers. The problem had bloomed into a catastrophe. The inclusions based on 52 criteria (Beall), was forced to shut down after almost a decade due to mounting intimidation by various dishonourable publishers. Selected publishers, journals and some also members of the open-access community had objected against Beall’s understanding of predatory journals. Threats of legal proceedings by some of the publishers he had labelled as ‘predatory’ resulted in Beall taking the list down, but amidst the academia, Beall earned a lot of appreciation for his list. Others apart from Beall list; ‘‘The Journal Blacklist’ available for subscription. A good review of the list is also accessible on the Scholarly Kitchen Blog; anonymous group started the initiative ‘Stop Predatory Journals’ listing some 1,300 possible predatory journals, based on Beall’s list, and the number of inclusions is expanding. Currently in Cabell’s Blacklist there are 12,000 plus so-called predatory journals listed.  https://predatoryjournals.com/ https://thinkchecksubmit.org/ ## What do predatory journals perpetuate?  What are the attributes of a predatory journal? Checklist of the abeyant misconduct, unethical practices, and other behaviours of predatory journal(s):  * do not follow a standardised peer-review process (no clarity on the process; single/double blind review, etc.) * may not subject the submission to peer-reviewers or may not apply any editing or improvement of the submission before publishing  * publish a high number of very low-quality articles and manuscripts   * publish fake or hoax papers  * send spam emails to researchers imploring them to contribute   * list members on editorial boards without their knowledge or permission   * make up (fake) names of editorial board members or authors or reviewers   * copy material, design and advertise as reputed and legitimate journal  * hijack credible journals by setting up journals with identical names and similar websites   * inappropriately or fraudulently use ISSN   * make up or fake journal metrics such as impact factors and others   * state wrong or misleading information about the size and the location of the publisher   * no doi (Digital Object Identifier) for the published article additionally * include fake or fraudulent metrices (misleading impact factor) and other such scores (considered credible and important for author) * include less or unknown or fake indexing services ## Why it is paramount to avoid predatory journals? All the features listed above should provide enough reasons to for an ethical and respected scholar not consider publishing in any of the predatory journals. Yet many, notably, young and inexperienced researchers who feel the pressure to publish papers still fall prey to these journals. Pitfalls of publishing in a predatory journal * one might get charged for publishing the paper (without any information available in the website about APC/ open access/ Hybrid). * after acceptance of one’s paper – charge fee to publish (without prior information on APC \[Article processing charges] or Open access policy options. * paper eventually will not be accessible/ available in the future due to poor long-term storage facility/ website/ domain leasing.  * credibility as a scholar/ researcher can be damaged by publishing in these journals. * Also, not useful for finding and attracting research grants or academic positions.
C++
UTF-8
2,283
3.8125
4
[ "Apache-2.0" ]
permissive
#pragma once #include <core/std.h> // Ignores element constructors / destructors! template <typename T> class array_deque { public: array_deque() {} array_deque(uint capacity) : m_data(capacity) {} array_deque(const array_deque& o) { m_data.resize(o.capacity()); m_start = 0; m_size = o.size(); for (uint i = 0; i < m_size; i++) { operator[](i) = o[i]; } } auto operator=(const array_deque& o) { if (this == &o) { return *this; } if (o.size() > capacity()) { m_data.resize(round_up_power2(o.size())); } m_start = 0; m_size = o.size(); for (uint i = 0; i < m_size; i++) { operator[](i) = o[i]; } return *this; } uint size() const { return m_size; } uint capacity() const { return m_data.size(); } bool empty() const { return m_size == 0; } const T& operator[](uint index) const { return (m_start + index < capacity()) ? m_data[m_start + index] : m_data[m_start + index - capacity()]; } T& operator[](uint index) { return (m_start + index < capacity()) ? m_data[m_start + index] : m_data[m_start + index - capacity()]; } void push_back(T value) { if (m_size == m_data.size()) { if (m_data.size() == 0) { m_data.resize(4); } else { vector<T> data(m_data.size() * 2); for (uint i = 0; i < m_size; i++) std::swap(data[i], operator[](i)); m_data.swap(data); } m_start = 0; } uint end = m_start + m_size; if (end >= capacity()) { end -= capacity(); } m_data[end] = value; m_size += 1; } T pop_front() { uint i = m_start++; if (m_start >= capacity()) { m_start -= capacity(); } m_size -= 1; return m_data[i]; } void swap(array_deque& o) { m_data.swap(o.m_data); std::swap(m_start, o.m_start); std::swap(m_size, o.m_size); } void clear() { m_start = 0; m_size = 0; } private: vector<T> m_data; uint m_start = 0; uint m_size = 0; };
Java
UTF-8
268
2.671875
3
[]
no_license
package assign5; public class Context { private AverageInterface avg; public Context (AverageInterface avgI){ this.avg = avgI; } public double findAvg () { return avg.getAverage(); } public void setAvg(AverageInterface avgI){ this.avg = avgI; } }
Markdown
UTF-8
16,923
3.03125
3
[]
no_license
--- published: true organization_id: '2013126' year_submitted: 2013 indicator: ' Health' body_class: strawberry project_id: '3102190' title: >- “Hey I’m Walking Here!”: A Campaign Celebrating Pedestrians in the City of Los Angeles project_summary: "\"The future of the city is walking. Redesigning our cities for walkers and walking will help make our cities places where people want to be. But it’s not something we consciously think about. So every time you’re out there walking I want you to think “Hey, I’m Walking Here!” — Alissa Walker, Journalist and Los Angeles Walks Steering Committee member, at WIRED 2012\r\n\r\nLast December, Alissa’s talk at the WIRED 2012 conference in London became a dinner table discussion at a Los Angeles Walks meeting. We laughed over the clip Alissa referenced from Midnight Cowboy where Dustin Hoffman yells “Hey, I’m Walking Here!” at a fast-moving car rolling into a New York City crosswalk: http://www.youtube.com/watch?v=c412hqucHKw But in all seriousness, shouting “Hey, I’m Walking Here” was far too representative of our own Los Angeles experience—a place where walking doesn’t get enough respect.\r\n\r\nWe found ourselves becoming inspired by other entertaining yet educational stunts that highlighted pedestrians, like a group of pedestrians that actually moved a car which had stopped in the middle of the crosswalk in Brazil: http://www.youtube.com/watch?feature=player_embedded&v=UqhUeDTAyYs Or Peatónito, who takes to the streets in Mexico City as the masked Mexican defender of pedestrians: http://m.theatlanticcities.com/commute/2013/02/if-only-every-city-had-masked-lucha-libre-defender-pedestrians/4804/ We realized we needed the same kind of cultural touchstone for Los Angeles: a movement bringing attention, safety and a bit of fun to walking to help build a healthier, more vibrant Los Angeles\r\n\r\nWalking is a “magic app” for creating a healthy city. As the most common type of physical activity, walking is an easy and effective way to improve fitness. It reduces body fat and bad cholesterol, cutting the risk of some of the leading causes of death in Los Angeles. Walking extends life—walking 75 minutes per week adds 1.8 years of life; walking 2.5 hours per week adds 7 years of life. Walking regularly also improves mood and reduces fatigue.\r\n\r\nThe benefits of walking reach beyond individual fitness to make communities into healthier places to live, work and play. Walking instead of driving, even for short car trips, decreases air pollution and reduces respiratory and cardiovascular ailments as well as some kinds of cancer. Car crashes are the leading cause of death for Angelenos under the age of 5 and the second-leading cause of death for children and young adults ages 5 to 24. Making the city safer for pedestrians can also make the city more equitable: Most pedestrian deaths in L.A. occur in low-income neighborhoods where many residents do not own cars. But the solution is not simply to get more people walking—it also requires that streets and sidewalks be redesigned to protect pedestrians from roadway traffic, slow down cars and trucks, and keep walkers feeling safe.\r\n\r\nWith these ideas in mind, Los Angeles Walks proposes to launch \"Hey, I'm Walking Here!\" (or in Español, “¡Ay, Estoy Caminando!”)—a campaign which will not only increase pedestrian safety, but also highlight and celebrate walking as a conscious act that’s happening all over the city. And by expanding upon our existing Los Angeles Walks work including awareness, events, community meetings and action, we’ll be able to support long-term efforts to build a more walkable Los Angeles by 2050.\r\n\r\nActivities funded through our “Hey, I’m Walking Here!” campaign will include:\r\n\r\n Creating a bilingual “Hey, I’m Walking Here!”/ “¡Ay, Estoy Caminando!” publicity campaign using posters, stickers, public art, infographics and social media.\r\n\r\n Authoring “Hey, I’m Walking Here!”/ “¡Ay, Estoy Caminando!” materials which will highlight the benefits of walking as a healthy and civic-minded action.\r\n\r\n Convening community meetings in three neighborhoods where residents will assess the “good, bad and the ugly” for pedestrian activity, highlighting unsafe or unsavory walking environments to improve on the “Hey, I’m Walking Here” action days.\r\n\r\n Organizing “Hey I’m Walking Here” action days where local communities will be empowered to make temporary, attention-getting improvements to local walking infrastructure (like a Parking Day focused on pedestrians).\r\n\r\n Designing a pilot program for a pedestrian-focused urban wayfinding system that also serves as a publicity campaign throughout the city, to help Angelenos to understand the distance between neighborhoods and landmarks, and see that more places are walkable.\r\n\r\n Holding regular group walks to underscore how walking is a fun way to explore the city and promote healthy lifestyles, where we will provide “Hey I’m Walking Here” materials.\r\n\r\n Promoting pedestrian parades and events during CicLAvias (WalkLAvia) to make sure walkers have a welcoming space when streets are closed to traffic.\r\n\r\n Educating local residents about how to ask for higher-visibility crosswalks and lower speed limits on their streets (especially near schools).\r\n\r\n " project_image: 'https://img.youtube.com/vi/hHXkL2SbXI8/hqdefault.jpg' project_video: 'https://www.youtube.com/embed/hHXkL2SbXI8' What are some of your organization’s most important achievements to date?: "Represented on the City of Los Angeles Pedestrian Advisory Committee; our founder Deborah Murphy has been Chair since 1998\r\n\r\nAdvocated for the City’s first Walkability Checklist that is used by City Planning Staff in their review of new development projects\r\n\r\nOrganized the Great Hollywood Walkabout in 2006\r\n\r\nOrganized the Great Glassell Park/Cypress Park Walkabout in 2007\r\n\r\nOrganized the Downtown Pasadena Walkabout in 2008\r\n\r\nPart of the team that prepared the Nationally recognized Living Street Model Street Design Manual\r\n\r\nPart of the Green LA Coalition Living Streets Campaign\r\n\r\nServed on Mayor James Hahn’s Transportation Task Force\r\n\r\nServed on County of Los Angeles Pedestrian Safety Task Force\r\n\r\nSince 1999 we have been the go-to organization for the press regarding pedestrian safety issues appearing in media including KCRW, KCET, KPCC, LA Times, LA Weekly, Curbed LA, Streetsblog LA and more\r\n\r\nAdvocated for 15 years for Continental Crosswalk installations in the City of Los Angeles\r\n\r\nAdvocated for 20 years for the creation of the Pedestrian Coordinator positions, which were finally created in 2012\r\n\r\nAdvocated with a coalition of Active Transportation advocates for a 5% set-aside of Measure R Local Return funds for pedestrian projects and 5% for bicycle projects in the City of Los Angeles\r\n\r\nAdvocated for pedestrian and bike safety projects in Silver Lake including a Road Diet for Rowena Avenue for six years, which was implemented in 2013\r\n\r\nFacilitated pedestrian safety charrettes in two Los Angeles neighborhoods: Silver Lake community in August 2012 and Leimert Park in November 2012\r\n\r\nConducted pedestrian-related events during CicLAvia including a WalkLAvia in October 2012 on three miles of Figueroa Street\r\n " Please identify any partners or collaborators who will work with you on this project.: "Occidental College Urban and Environmental Policy Institute\r\nColleen Corcoran, Designed by Colleen\r\nLos Angeles County Bicycle Coalition\r\nSafe Routes to School National Partnership\r\nLos Angeles Commons\r\nMulticultural Communities for Mobility\r\nStreetsblog Los Angeles " Please explain how you will evaluate your project. How will you measure success?: "Many Los Angeles residents already enjoy walking and are instinctively drawn to areas good for walking—places like parks, the beach and walkable commercial districts. But most Angelenos have not taken the next step to consider how their neighborhoods can become more walkable. Los Angeles Walks’ “Hey, I’m Walking Here!” campaign is intended to tap into this latent desire to help Angelenos request more pedestrian amenities, build more vibrant communities, and elevate the act of walking in the City of Los Angeles.\r\n\r\nWe plan to work closely alongside existing community efforts, reaching thought leaders, policymakers, and media to help us outline key steps which will not only build safer and more accessible city, but a more fun place to walk as well.\r\n\r\nTo evaluate the immediate goals of our project, we will track the number of events and community forums that Los Angeles Walks holds and the number of participants in these events. We will also capture and quantify the different ways that the campaign shares its “Hey, I’m Walking Here!” message, and count how often campaign slogans and themes are picked up and references in news articles and interviews, like minded organizations, social media likes and shares, political and policy debates and other public forums.\r\n\r\nAnd will evaluate the campaign’s success in the short term by increased attention to walking. Over the long term the project can help improve metrics related to rates of walking, spending on pedestrian infrastructure, walkable land uses, and health outcomes.\r\n\r\nLos Angeles walks blogs regularly with updates on upcoming and past pedestrian-related events and news and produces a year-in-walking round-up of highlights. Comparing past updates with updates if this project is funded can help show whether there is an upsurge in interest in walking in LA, and Los Angeles Walks plans to participate in the Fall 2013 City of Los Angeles Bicycle and Pedestrian Count, led by the Los Angeles County Bicycle Coalition which helps establish much needed data and understanding of current travel patterns in the City.\r\n\r\nAt the same time as we track the strength of our messaging and participate in data collection, we will be laying the groundwork for analyzing longer term improvements in walking-related indicators. We will collect baseline data for rates of walking, funding for pedestrian programs and infrastructure, injuries and fatalities to pedestrians, staffing for pedestrian programs, and land zoned for mixed uses and/or with pedestrian overlays. " How will your project benefit Los Angeles?: "Los Angeles has incredible potential to become one of the world’s most walkable cities. Our mild climate is one obvious advantage, providing us with perfect walking weather almost every day of the year. Even our reputation for sprawl works to our advantage: Los Angeles developed as a series of small towns, meaning that there are multiple historic downtowns and commercial corridors that provide interesting places to walk. We also have the fastest-growing transit system in the United States, providing an extensive “walk extender” because it allows people to walk to a bus or train, take transit, then continue walking to destinations. New rail and bus rapid transit stops can evolve into walkable hubs that can allow more Angelenos to reduce driving or live without a car. Just raising the visibility of walking a little bit will have a tremendous impact with multiple co-benefits, and has potential to support a transformation the way the city thinks about walking and travels.\r\n\r\nThe Los Angeles region is also home to a health-conscious population and to many immigrants from countries with walkable cities where public space is valued. Certain demographic groups like young people and empty nesters of all backgrounds have been shown to be increasingly drawn to walkable neighborhoods. From street food to art walks to stair climbs, Los Angeles is slowly embracing walking as a key component of a great city.\r\n\r\nBut we shouldn't downplay the remaining challenges to creating a more walkable L.A. During the 20th century, Los Angeles was redesigned as a city for automobiles. Our streets were engineered to move as many cars and trucks as possible as fast as possible. Los Angeles was zoned to keep businesses away from homes, so new buildings were required to add parking. As a result, parking lots, driveways, strip malls and drive through restaurants carved up the city, creating barriers to safe, convenient and pleasant walks.\r\n\r\nAlthough the city and region are beginning to support transit, biking and walking, L.A. is still not a safe enough environment for pedestrians. Sidewalks are in a poor state of repair. Speed limits for cars are too high, and because roads and driving lanes are wide, many drivers speed even beyond the legal limit. There are not enough crosswalks. As a result, pedestrians in Los Angeles are disproportionately likely to be victims of fatal car crashes compared to national statistics. Approximately 100 pedestrians are killed each year in Los Angeles by hit-and-run drivers. Drivers who kill pedestrians often escape detection or are given light sentences, sending a message that that we care more about moving cars than we do about human life. Creating more awareness about walking and shifting L.A. to become a more walkable city will save lives through improved safety and extend and save and improve even more lives through the health benefits of a more physically active population.\r\n\r\nA pedestrian advocacy movement is overdue in Los Angeles, yet the timing c" What would success look like in the year 2050 regarding your indicator?: "By 2050, Los Angeles will be known globally as one of the best cities for walking in the world. The biggest change can be easily seen from the air: All of L.A.’s once-famous freeways have been removed, their multiple lanes of traffic replaced with extensive linear parks. Down the center of each of these parks are wide, green boulevards with clean energy rapid buses, protected cycling lanes and excellent walking paths. This network of “urban trails” connects each of L.A.’s neighborhoods so it’s completely possible to get nearly anywhere in the city on dedicated foot or bike infrastructure, although the extensive rail system is usually faster. L.A. City overall health will be significantly improved with most citizens naturally getting in the public health reccomended minimum 10,000 steps a day as they go about their daily living, and collision rates for pedestrians and the city with drastically decrease. Drivers stop, with tender caution for pedestrians as they cross the street. Hit n’ runs are a thing of the past. people take responsibility for their actions and realize that the guilt of running away from the scene of the crime is more harmful to them than owning up to their actions, and individuals will recognize the serious responsibility in their hands while as drivers. 90% of kids walk or bike to school as they attend quality schools close to where they live. Walking Meetings will be a common occurence in the workplace. And streetwalkers will come to take on a whole different meaning in Los Angeles. A remake of “No One Walks in LA,” will be made with the title changed to “We all walk in LA” and mashed up to Randy Newman’s infamous “I Love LA”. Mayor of Los Angeles will champion themselves as “Sidewalk Mayors” and other urban regions will look to Los Angeles with envy and questions for advice for how their neighborhoods can be as awesome as ours.\r\n\r\nAll neighborhoods in the city have been redesigned to be more walkable. A cultural shift has occurred and Angelenos in general choose to live close to where they work and shop. When they want to visit other parts of the city, people walk or bike to a rail station. Or they take a short walk to any commercial street to catch the frequent, convenient, attractive zero emissions buses which are the main form of motorized transportation in 2050. Although cars are still legal, all roads have tolls, surface parking lots are banned, speed limits are 10 mph in residential neighborhoods. Most people don’t own cars and those who do, rarely drive them. Freeway capped park projects will pop up all over the city, reclaiming loved space that had been previously sacrificed.\r\n\r\nMore and more people walk in Los Angeles. The percentage of trips in Los Angeles taken on foot will have increased from 20 percent to 50 percent or more. These shift into trips taken on foot will enjoy multiple co-benefits that will result in better air quality, reduced carbon emissions, and improved public health. The average resident wa" cached_project_image: >- https://archive-assets.la2050.org/images/2013/hey-im-walking-here-a-campaign-celebrating-pedestrians-in-the-city-of-los-angeles/img.youtube.com/vi/hHXkL2SbXI8/hqdefault.jpg youtube_video_identifier: hHXkL2SbXI8 ---
Java
UTF-8
9,065
2.046875
2
[ "Apache-2.0" ]
permissive
package com.oval.app.activities; import java.io.File; import java.util.ArrayList; import java.util.StringTokenizer; import org.mitre.svmp.activities.AppRTCRefreshAppsActivity; import org.mitre.svmp.activities.SvmpActivity; import org.mitre.svmp.common.ConnectionInfo; import org.mitre.svmp.services.SessionService; import com.citicrowd.oval.R; import com.oval.app.fragments.OvalHomeFragment; import com.oval.app.fragments.OvalSearchFragment; import com.oval.slidingmenu.adapter.NavDrawerListAdapter; import com.oval.slidingmenu.model.NavDrawerItem; import com.squareup.picasso.Picasso; import android.app.Fragment; import android.app.FragmentManager; import android.content.Intent; import android.content.res.Configuration; import android.content.res.TypedArray; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.util.Log; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class OvalDrawerActivity extends SvmpActivity { private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; // nav drawer title private CharSequence mDrawerTitle; // used to store app title private CharSequence mTitle; // slide menu items private String[] navMenuTitles; private TypedArray navMenuIcons; private ArrayList<NavDrawerItem> navDrawerItems; private NavDrawerListAdapter adapter; ImageView icProfile; ConnectionInfo connectionInfo; TextView emailTv; private int sendRequestCode; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.activity_drawer); connectionInfo = dbHandler.getConnectionInfo(1); mTitle = mDrawerTitle = getTitle(); // load slide menu items navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // nav drawer icons from resources navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.list_slidermenu); icProfile = (ImageView) findViewById(R.id.icProfile); emailTv = (TextView) findViewById(R.id.emailTv); emailTv.setText(connectionInfo.getUsername()); StringTokenizer strToken = new StringTokenizer(connectionInfo.getPhotoUrl(), "="); String icon = strToken.nextToken() + "=200"; Picasso.with(this).load(icon).placeholder(R.drawable.ic_profile).into(icProfile); navDrawerItems = new ArrayList<NavDrawerItem>(); // adding nav drawer items to array // Home navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1))); // Find People navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1))); // Photos navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1))); // Communities, Will add a counter here /* * navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], * navMenuIcons.getResourceId(3, -1), true, "22")); // Pages * navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], * navMenuIcons.getResourceId(4, -1))); // What's hot, We will add a * counter here navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], * navMenuIcons.getResourceId(5, -1), true, "50+")); */ // Recycle the typed array navMenuIcons.recycle(); mDrawerList.setOnItemClickListener(new SlideMenuClickListener()); // setting the nav drawer list adapter adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems); mDrawerList.setAdapter(adapter); // enabling action bar app icon and behaving it as toggle button /* * getActionBar().setDisplayHomeAsUpEnabled(true); * getActionBar().setHomeButtonEnabled(true); */ // mDrawerLayout.openDrawer(mDrawerList); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_launcher, // nav // menu // toggle // icon R.string.app_name, // nav drawer open - description for // accessibility R.string.app_name // nav drawer close - description for // accessibility ) { public void onDrawerClosed(View view) { // getActionBar().setTitle(mTitle); // calling onPrepareOptionsMenu() to show action bar icons invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { // getActionBar().setTitle(mDrawerTitle); // calling onPrepareOptionsMenu() to hide action bar icons invalidateOptionsMenu(); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { Fragment fragment = new OvalHomeFragment(); if (fragment != null) { FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit(); // update selected item and title, then close the drawer mDrawerLayout.closeDrawer(Gravity.START); } } } public void openDrawer() { mDrawerLayout.openDrawer(Gravity.START); } /** * Slide menu item click listener */ private class SlideMenuClickListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // display view for selected nav drawer item displayView(position); } } public void clearApplicationData() { File cache = getCacheDir(); File appDir = new File(cache.getParent()); if (appDir.exists()) { String[] children = appDir.list(); for (String s : children) { if (!s.equals("lib")) { deleteDir(new File(appDir, s)); Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************"); } } } } public static boolean deleteDir(File dir) { if (dir != null && dir.isDirectory()) { String[] children = dir.list(); for (int i = 0; i < children.length; i++) { boolean success = deleteDir(new File(dir, children[i])); if (!success) { return false; } } } return dir.delete(); } /* * * Called when invalidateOptionsMenu() is triggered */ /** * Diplaying fragment view for selected nav drawer list item */ private void displayView(int position) { // update the main content by replacing fragments Fragment fragment = null; switch (position) { case 0: fragment = new OvalHomeFragment(); break; case 1: // fragment = new OvalSearchFragment(); //refreshApps(connectionInfo); // clearApplicationData(); break; default: break; } mDrawerLayout.closeDrawer(Gravity.START); if (fragment != null) { FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit(); // update selected item and title, then close the drawer mDrawerList.setItemChecked(position, true); mDrawerList.setSelection(position); // setTitle(navMenuTitles[position]); mDrawerLayout.closeDrawer(Gravity.START); } else { // error in creating fragment Log.e("MainActivity", "Error in creating fragment"); } } /* * @Override public void setTitle(CharSequence title) { mTitle = title; * getActionBar().setTitle(mTitle); } */ /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ public void startSearchFragment(String searchStr) { Bundle bundle = new Bundle(); bundle.putString("searchText", searchStr); // set Fragmentclass Arguments Fragment fragment = new OvalSearchFragment(); if (fragment != null) { fragment.setArguments(bundle); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().replace(R.id.frame_container, fragment) .addToBackStack(OvalSearchFragment.TAG).commit(); // update selected item and title, then close the drawer } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Intent stopServiceIntent = new Intent(ACTION_STOP_SERVICE, null, this, SessionService.class); stopService(stopServiceIntent); } }
TypeScript
UTF-8
10,462
2.8125
3
[ "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
import { toQueryString } from "../../utils"; import { SdkClient } from "../common/sdk-client"; import { JobManagerModels } from "./jobmanager-models"; /** * Offers execution mechanisms for running models stored in Model Management module. * A schedule is created based on a model identifier and a cron expression so the model will run one or multiple times. * Each time a model runs a new job is generated. * When the schedule is created it will start according to the cron expression. * If a user wants to stop the executions it can update the status of the schedule and the executions will stop. * Also the user has the possibility to update again the status and trigger again the schedule. * If a user does not want to run a model multiple times or based on a schedule expression * it can start immediately a new job. * * @export * @class JobManagerClient * @extends {SdkClient} */ export class JobManagerClient extends SdkClient { private _baseUrl: string = "/api/jobmanager/v3"; /** * * Jobs * * Retrieves all the job executions within a tenant, sorted by creationDate descendant order, * up to 10.000 items, paged, maximum 100 items per request if no paging parameters are specified. * The service purges all jobs older than 90 days that have one of the final statuses * (e.g. STOPPED, FAILED, SUCCEEDED). * * @param {{ * pageNumber?: number; * pageSize?: number; * filter?: string; * }} [params] * @returns {Promise<JobManagerModels.JobList>} * * @example Filter example: * {"message": {"contains": "Error"},"status": { "or": {{"eq" : "STOPPED"},{"eq" : "FAILED"}}},"creationDate": * {{"after": "2018-06-23T20:09:00"}}} * @memberOf JobManagerClient */ public async GetJobs(params?: { pageNumber?: number; pageSize?: number; filter?: string; }): Promise<JobManagerModels.JobList> { const parameters = params || {}; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/jobs?${toQueryString(parameters)}`, }); return result as JobManagerModels.JobList; } /** * * Jobs * * Creates a new job execution based on the model identifier. * This endpoint offers the possibility of running a model or an algorithms * just one time without the need of providing a schedule string * The inputFolderId and outputFolderId are identifiers of data sources provided by * Data Exchange module. * * @param {JobManagerModels.JobParameters} parameter * @returns {Promise<JobManagerModels.Job>} * * @memberOf JobManagerClient */ public async PostJob(parameter: JobManagerModels.JobParameters): Promise<JobManagerModels.Job> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), body: parameter, baseUrl: `${this._baseUrl}/jobs`, }); return result as JobManagerModels.Job; } /** * * * Jobs * * Retrieves the details regarding a job execution * * @param {string} id * @returns {Promise<JobManagerModels.Job>} * * @memberOf JobManagerClient */ public async GetJob(id: string): Promise<JobManagerModels.Job> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/jobs/${id}`, }); return result as JobManagerModels.Job; } /** * * * Jobs * * Stops a job execution. The call sets the job's status to STOPPING, * while letting the service to internally handle the additional * steps required to get the job into a STOPPED status. * Caller is responsible for polling the status until the job has reached * a final state. In the event that the stop action fails for various * reasons, the job execution can end up with a FAILED status. * Existing results that were resulted from execution will be kept and * provided to Data Exchange following the parameters used to start the * job execution. If no output parameters were defined, any definitive * (or partial) results will be lost and cleaned up during the stopping process. * * @param {string} id * @returns {Promise<JobManagerModels.Job>} * * @memberOf JobManagerClient */ public async StopJob(id: string): Promise<JobManagerModels.Job> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/jobs/${id}/stop`, }); return result as JobManagerModels.Job; } /** * * Schedules * * Retrieves a list with all schedules stored within the same tenant * * @param {{ * pageNumber?: number; * pageSize?: number; * filter?: string; * }} [params] * @returns {Promise<JobManagerModels.ScheduleList>} * @example Schedule Filter * * Complex and flexible filter that can filter by creationDate, name, status, modelId and scheduleString. * All the top fields used in the filter are ANDed, but the searched values can use AND and OR operands, including comparison operators where the values allow. All fields are optional. * The expected filter format is: * ?filter={ * "status": { * "eq": "RUNNING" * },"message": { * "eq": "Insufficient disk space" * },"creationDate": { * "gt": "2018-06-23T20:09:00" * }, * "name": { * "eq": "Every 2 Months" * } * } * * @memberOf JobManagerClient */ public async GetSchedules(params?: { pageNumber?: number; pageSize?: number; filter?: string; }): Promise<JobManagerModels.ScheduleList> { const parameters = params || {}; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/schedules?${toQueryString(parameters)}`, body: {}, additionalHeaders: { "Content-Type": "application/json" }, // ! fix: April 2021 manual fix for the schedules endpoint }); return result as JobManagerModels.ScheduleList; } /** * * Schedules * * Schedules a job for execution specified by its model id and a schedule string. * The model ID is retrieved from Model Management module after uploading a model. * The schedule string follows the cron format. Example 0 15 10 * * ? - will trigger the model at 10:15 am every day * * @param {JobManagerModels.ScheduleParameters} parameters * @returns {Promise<JobManagerModels.ScheduleDetails>} * * @memberOf JobManagerClient */ public async PostSchedule( parameters: JobManagerModels.ScheduleParameters ): Promise<JobManagerModels.ScheduleDetails> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), body: parameters, baseUrl: `${this._baseUrl}/schedules`, }); return result as JobManagerModels.ScheduleDetails; } /** * * Schedules * * Retrieves information about a schedule * * @param {string} id * @returns {Promise<JobManagerModels.ScheduleDetails>} * * @memberOf JobManagerClient */ public async GetSchedule(id: string): Promise<JobManagerModels.ScheduleDetails> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/schedules/${id}`, }); return result as JobManagerModels.ScheduleDetails; } /** * * Schedules * * Removes a schedule * * This endpoint offers the possibility of removing a schedule from the storage * * @param {string} id * * @memberOf JobManagerClient */ public async DeleteSchedule(id: string) { await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/schedules/${id}`, noResponse: true, }); } /** * * * Jobs * * Updates the status of the schedule to started. * If a schedule has been stopped it can be started again using this endpoint. * If a schedule is running, based on the schedule string it creates jobs * * @param {string} id * @returns {Promise<JobManagerModels.ScheduleDetails>} * * @memberOf JobManagerClient */ public async StartSchedule(id: string): Promise<JobManagerModels.ScheduleDetails> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/schedules/${id}/start`, }); return result as JobManagerModels.ScheduleDetails; } /** * * Schedules * * Updates the status of the schedule to stopped. * If a user wants to stop a schedule this endpoint offers the possibility to update the status * of the schedule to stop. When a scheduler is stopped it cannot create new jobs executions * * @param {string} id * @returns {Promise<JobManagerModels.ScheduleDetails>} * * @memberOf JobManagerClient */ public async StopSchedule(id: string): Promise<JobManagerModels.ScheduleDetails> { const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/schedules/${id}/stop`, }); return result as JobManagerModels.ScheduleDetails; } }
Markdown
UTF-8
4,543
2.953125
3
[]
no_license
# Simple Java Sandbox ## Features * Provide 2 http endpoints that accepts JSON base64 encoded binary data on both endpoints `<host>/v1/diff/<ID>/left` and `<host>/v1/diff/<ID>/right` * The provided data needs to be diff-ed and the results shall be available on a third end point `<host>/v1/diff/<ID>` * The results shall provide the following info in JSON format * If equal return that * If not of equal size just return that * If of same size provide insight in where the diffs are, actual diffs are not needed (offsets + length) * Make assumptions in the implementation explicit, choices are good but need to be communicated ## Assumptions * **left** and **right** endpoints are implemented using http **PUT** method since they are implemented as a create/update * **left** or **right** endpoints can be called many times to update the operators values for a given **ID** as long as no diff operation have been called for the given **ID** * when **left** or **right** endpoints are called for an already calculated diff following error response will be returned ``` HTTP/1.1 400 Content-Type: text/plain;charset=UTF-8 Operators cannot be changed for a previously processed Id: "example" ``` * calling **diff** endpoint before calling **left** or **right** will return and error ``` HTTP/1.1 400 Content-Type: text/plain;charset=UTF-8 Not enough parameters to create a comparator: Comparator.right: cannot be null ``` * calling **diff** endpoint before any operator will return and error ``` HTTP/1.1 404 Content-Type: text/plain;charset=UTF-8 Requested Id wasn't found: "example5" ``` * **diff** endpoint returns the diff result in the node `{"result": "____",}` containing one of the following values: `EQUAL`, `NOT_EQUAL_SIZE`, `DIFF` * after successfully calling a **diff** endpoint, the result is saved in a repository. Subsequent calls with the same ID will retrieve the result from the database instead of calculating it again. Since the operator cannot be updated, the result will remain de same after the first calculation. ## Implementation ### Running the application 1. clone the repository 2. run `./gradlew bootRun` 3. Application starts on port 8080 4. Call **left** and **right** endpoints. Example: ``` PUT http://localhost:8080/v1/diff/example/left Content-Type: application/json { "value": "SW50ZWdyYXRpb25UZXN0T3BlcmF0b3I=" } ``` ``` PUT http://localhost:8080/v1/diff/example/right Content-Type: application/json { "value": "SW50Z1dyYX22b25UZ333T3BlcmF0b3I=" } ``` 5. Call **diff** endpoint. Example: ``` GET http://localhost:8080/v1/diff/example HTTP/1.1 200 Content-Type: application/json;charset=UTF-8 { "result": "DIFF", "details": [ { "startIndex": 5, "length": 1 }, { "startIndex": 10, "length": 2 }, { "startIndex": 17, "length": 3 } ] } ``` ### Test Runs using `./gradlew test` #### Unit Tests Implemented using junit, located under folder `.\src\test` #### Integration test Implemented using cucumber, located under folder `.\src\test-integration`. * `co.femago.assignment.it.IntegrationTestRunner` bootstrap class to start the test suite * Functionalities definition example: ```gherkin Feature: Comparing left and right operators returns an expected response Scenario: Both operators are equal Given a left operator with value: "SW50ZWdyYXRpb25UZXN0T3BlcmF0b3I=" for a request with id: "req1" And a right operator with value: "SW50ZWdyYXRpb25UZXN0T3BlcmF0b3I=" for a request with id: "req1" When a diff request with id: "req1" is sent Then the response result is "EQUAL" And no diffs are returned Scenario: Operators have different size Given a left operator with value: "SW50ZWdyYXRpb25UZXN0T3BlcmF0b3I=" for a request with id: "req2" And a right operator with value: "SW50ZWdyYXRpb25UZXN0T3BlcmF0b3JMZW5ndGg=" for a request with id: "req2" When a diff request with id: "req2" is sent Then the response result is "NOT_EQUAL_SIZE" And no diffs are returned Scenario: Operators have diffs Given a left operator with value: "SW50ZWdyYXRpb25UZXN0T3BlcmF0b3I=" for a request with id: "req3" And a right operator with value: "SW50Z1dyYX22b25UZ333T3BlcmF0b3I=" for a request with id: "req3" When a diff request with id: "req3" is sent Then the response result is "DIFF" And 3 diffs are returned: | start index | length | | 5 | 1 | | 10 | 2 | | 17 | 3 | ```
Markdown
UTF-8
6,277
3.609375
4
[ "MIT" ]
permissive
--- layout: post title: Swift 简书- 函数 published: true date: 2015-09-30 16:07 categories: tags: comments: true description: 本来不想写这个,心想不就是函数吗?可是然并卵!Swift的函数太牛掰了!不过这个可能不太适合初学者。废话少叙,开始。 --- ------------------------- > "这些文章都是看苹果的官方《The Swift Programming Language (Swift 2)》,然后自己理解表达简化出来的,肯定有不确切的地方" >[原文链接] [id] [id]: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158 ------------------ 本来不想写这个,心想不就是函数吗?可是然并卵!Swift的函数太牛掰了!不过这个可能不太适合初学者。废话少叙,开始。 ###普通的函数### 如下: + 不带参数和返回值 ``` func sayHello(){} ``` + 不带返回值 ``` func sayHello(hello:String){} ``` + 参数和返回值都带 ``` func sayHello(string: String) -> String { return string } ``` + 多个参数 ``` func sayHello(string: String, string2: String) -> String { return string } ``` **有点不同的来了** + 多个返回值,是的你没看错,多谢tuple类型 ``` func minMax(array: [Int]) -> (min: Int, max: Int)? { if array.isEmpty { return nil } var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) } ``` 没啥说的关于这个,不过你要注意到返回值是 ()? 也就是Option类型,也就是返回值可以是nil。 **不同的来了** + 函数的参数名问题 因为为了和Objective C的函数对应,所以通常当你在XCode里面敲入一个函数的时候第一个函数参数的名字就可以忽略了,第二个带着就行了. 但是可能可读性不强或者某种原因或者Swift作者心情不好就不喜欢,于是Swift 2 里面是这样的: ``` func someFunction(firstParameterName: Int, secondParameterName: Int) { } someFunction(1, secondParameterName: 2) ``` 这是一个正常的函数调用但是 firstParameterName 这是个外部参数名没有了,看上去有点别扭,于是乎你可以这样做: ``` func sayHello(from person: String, to anotherPerson: String) -> String { return "Hello \(person) and \(anotherPerson)!" } sayHello(from: "Bill", to: "Ted") ``` 像不像是读一段话而已呢?也就是可读性增强了。 但是呢作者还不满意,上面类似 from to 这个外部参数名必须写,要是作者就是不想写呢? ``` func someFunction(firstParameterName: Int, _ secondParameterName: Int) { } someFunction(1, 2) ``` ***带有默认参数的函数*** ``` func someFunction(parameterWithDefault: Int = 12) {} someFunction(6) someFunction() //这个就是12了 ``` ***看看可变参数*** 也就是用```...```来传递多个参数。比如 ```(numbers: Doubles ...)```实际上也就是```[Double]``` ``` func arithmeticMean(numbers: Double...) -> Double { var total: Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(1, 2, 3, 4, 5) // 3 ``` **"一个函数最多只能有一个可变参数"** ***常量参数和变量参数*** 函数参数默认都是常量。但是有时候有一个变量的copy就不用在函数里面定义一个新的变量了 ``` func alignRight(var string: String, totalLenght: Int, pad: Charater) -> String { return string } let a = "hello" let b = alignRight(a, totalLength:10, pad: "-") b 的值不回影响a ``` **"如果在函数内部改变可变参数,那么这个改变在函数体外面是不会被看到的,可变函数真的很赞!"** ###In-Out 参数,哇,看上去好深奥### 可变参数的变化只在函数体内,如果你想让一个函数调用之后这个变化依旧保留呢?那就是In-Out参数了。 in-out 参数只能是变量,因为常量不能被修改。也不能有默认值。 ``` func swap(inout a: Int, inout _ b:Int){ let temporaryA = a a = b b = temporaryA } ``` ###函数(型)类型 Function Types### 是的他是一个类型。 官方定义:每个函数都有一个确定的函数类型,由参数类型和返回值类型组成。 ``` func addTwoInts(a: Int, _ b: Int) -> Int { return a + b } ``` 比如这个函数,函数类型就是: ```(Int, Int) -> Int``` ``` func printHelloWorld() { print("hello, world") } ``` 的函数类型就是: ``` () -> Void ``` 函数类型就和起他类型一样,你也可以用它来定义变量: ``` var mathFunction: (Int, Int) -> Int = addTwoInts ``` 他也可以做函数参数: ``` func printMathResult(mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFunction(a, b))") } printMathResult(addTwoInts, 3, 5) // 8 ``` 返回值:自己体会下下面的例子吧,应该不难看懂。 ``` func chooseStepFunction(backwards: Bool) -> (Int) -> Int { return backwards ? stepBackward : stepForward } var currentValue = 3 let moveNearerToZero = chooseStepFunction(currentValue > 0) print("Counting to zero:") // Counting to zero: while currentValue != 0 { print("\(currentValue)... ") currentValue = moveNearerToZero(currentValue) } print("zero!") // 3... // 2... // 1... // zero! ``` ## 嵌套函数 Nested ## 普通的函数作用域都是全局的,嵌套函数默认是被函数体对外隐藏的,例子如下: ``` func chooseStepFunction(backwards: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backwards ? stepBackward : stepForward } var currentValue = -4 let moveNearerToZero = chooseStepFunction(currentValue > 0) // moveNearerToZero now refers to the nested stepForward() function while currentValue != 0 { print("\(currentValue)... ") currentValue = moveNearerToZero(currentValue) } print("zero!") // -4... // -3... // -2... // -1... // zero! ```
Python
UTF-8
3,130
3.921875
4
[]
no_license
""" Реализовать класс LinkedListWithDriver от класса LinkedList. Дочерний класс должен уметь работать с реализованными ранее драйверами. 1. Реализовать свойство driver, которое будет возвращать используемый драйвер и проверять, что устанавливаемый драйвер является экземпляром класса IStructureDriver. 2. Реализовать метод read, который с помощью встроенного драйвера будет получать последовательность элементов и помещать их в самого себя. При вызове метода связанный список должен полностью перезаписываться новыми элементами. 3. Реализовать метод write, который передавать последовательность элементов для записи драйвером. 4. Протестировать паттерн "Стратегия" в ключе независимости работы экземляров LinkedListWithDriver от драйверов IStructureDriver. LinkedListWithDriver должен уметь работать со всеми экземплярами дочерних классов класс IStructureDriver. 5. LinkedListWithDriver должен поддерживать "горячую замену" драйвера, то есть без удаления и создания нового экземпляра LinkedListWithDriver, а замена драйвера существующего экземпляра. """ from py_class.LinketList import LinkedList from lesson_5_driver.driver import IStructureDriver from lesson_5_driver.b_fabric_method import FabricDriverBuilder class LinkedListWithDriver(LinkedList): def __init__(self, data, driver_: IStructureDriver = None): super().__init__(data) self.__driver = driver_ @property def driver(self): return self.__driver @driver.setter def driver(self, driver_: IStructureDriver): if not isinstance(driver_, IStructureDriver) and driver_ is not None: msg = f"Драйвер должен быть экземпляром класса {IStructureDriver}" raise TypeError(msg) self.__driver = driver_ def read(self): """Взять драйвер и считать из него информацию в LinkedList""" data_from_driver = self.__driver.read(self) self.clear() for value in data_from_driver: self.append(value) def write(self): """Взять драйвер и записать в него информацию из LinkedList""" self.__driver.write(self) if __name__ == '__main__': ll = LinkedListWithDriver([1, 2, 3, 4, 57]) ll.driver = FabricDriverBuilder.get_driver() ll.write()
Markdown
UTF-8
12,020
2.71875
3
[]
no_license
# Planning Tools Planning Tools is a set of programs to help with the design planning process. It contains programs to cluster user research data like product features or user needs. It can import data from card sorts, fielded data describing elements of interest, or manually entered pairwise comparisons. It can cluster data using agglomerative ("bottom-up") hierarchical clustering or graph-based methods, and it can output data as CSV spreadsheets for further processing. ## Quickstart ``` $ python3 -m venv planning_tools_env $ cd planning_tools_env $ source bin/activate $ pip install git+https://github.com/johnjung/planning_tools.git ``` ## matrix The matrix command takes an unsorted similarity matrix and clusters it using hierarchical clustering. For small data sets you can compare these values pairwise and enter them into a spreadsheet manually; for an example matrix look at [sample_data/fruits_and_vegetables.csv](./sample_data/fruits_and_vegetables.csv). You can enter pairwise comparisons like this in any spreadsheet. All items being clustered should be listed in row and column headers. These headers should be sorted the same way so that the cells on the diagonal from the top left to the bottom right each receive a 1.0 score, meaning that every element is perfectly similar to itself. A score of 0.0 means that the two elements being compared have nothing in common, while scores in between indicate increasing amounts of similarity. Finally, in input data it's not necessary to include the upper triangle of the matrix (cells above the diagonal) because those cells perfectly mirror the cells in the lower triangle- the matrix script will fill in the blanks. To take a look at an ASCII art visualization of the unsorted data in the terminal: ``` $ matrix to-ascii sample_data/fruits_and_vegetables.csv s r t g a r p c r s a i u a a p c w p b t n c v p b h p b c o r o o e l p b s c s u o l e e e e c a e a t o r m g a e e a p o a q m b c e f r r a e p r b l a c a a p r p t p n i n r u b f e a m r r r c l p r b p i t c n t e a c p t p a n i r a e i a d o u i i h e l i a e m o o g o a p o l u e n a o o s r g n o n i e e e r e e g a e e l e e r e r e c r a c n t h s s s s s t s s s y s s e s s s i s s s s n s e s s h s s s q u a s h @ , = , c u c u m b e r s @ , * , , * , * , , f i g s @ , , = , , , , , , b e a n s , @ , = = , , = a v o c a d o s @ , , l e m o n s @ , * , , g r a p e f r u i t , , @ , , , , , * , , = , r a s p b e r r i e s , , @ , , , * , = , , c h e r r i e s = , , @ , = , , , , , p e a c h e s , , @ = , * , , , c e l e r y * , @ , , = , * , , , a p p l e s , , , = = @ , = , , = s t r a w b e r r i e s , , * , , , @ , = , , c a b b a g e @ , , , p e a s , = , @ * , , , = , , = l i m e s * , @ , , p o t a t o e s , , @ , b r o c c o l i , = , * @ , , , = , , * o r a n g e s , * , @ , , t o m a t o e s * , = , , @ , , * , , , p e a r s , , , , * = , @ = , = g r a p e s , , = , , , = = @ , , c o r n = , , , @ , , , , p i n e a p p l e s , , , = , , , , , , , , , @ = l e t t u c e , , , , , , @ , = , p e p p e r s * , * = = * , , @ , , = b a n a n a s , , , , , , = , , = , = @ s p i n a c h , , , , , , , = , @ , , o n i o n s , , , , , , , , , , @ , c a r r o t s , = , = * , , = , , @ ``` Cluster the data: ``` $ matrix cluster --linkage_method=complete sample_data/fruits_and_vegetables.csv s r t p a r g i s a r c n c p w a u t b a p p e b h b b p o c o p c r v c o l s a e a a e g e e l e r u c m e a o o a t s o e p p a p p n r r r r e l f a m e a p b r c c b a q n t i p c e p a f r a r r m i r n b l t p e r p c a b t u c i t n l h a l n i i p i i o m u g e e o e a o e o d a o a o o u a e e r e a g e e e e n e i e r r e r n t a l o g e s r n c c s s s s s s s s s s s s t s s y s s s s s i s e s h n s e h a p p l e s @ = = , = , = , , , , p e a c h e s = @ * , , , , , , p e a r s = * @ , = , , = , , , p i n e a p p l e s , , , @ = , , , , , , , = , , b a n a n a s = , = = @ , , , , , , , , f i g s , , , , @ = , , , , c h e r r i e s = , , , , = @ , , , , g r a p e s , , = , , , , @ = = , r a s p b e r r i e s , , , , , , , = @ * , s t r a w b e r r i e s , , , , , , , = * @ , l e m o n s , @ * , , l i m e s , * @ , , g r a p e f r u i t , , = , , , , , , , , @ * o r a n g e s , , , , * @ c u c u m b e r s @ * * * , , , , , , c e l e r y * @ = * , , , , , , , t o m a t o e s * = @ * , , , , , , , , p e p p e r s * * * @ , = = = , , , , b e a n s , , , , @ = = = c a r r o t s , , , = = @ = * , , , p e a s , , , = = = @ * , , , , b r o c c o l i , , , = = * * @ , , , , a v o c a d o s , , @ c a b b a g e @ , , , p o t a t o e s , @ , , s q u a s h , @ = , c o r n , , , , , = @ , , o n i o n s , , , , , , , , , @ , , l e t t u c e , , , , , , , , @ = s p i n a c h , , , , , , , , , , = @ ``` ## cardsort This program builds a similarity matrix from card sort data by calculating the [Jaccard index](https://en.wikipedia.org/wiki/Jaccard_index) of each pair of items. For an example of how to structure your data, take a look at [sample_data/beer_flavor_wheel.csv](./sample_data/beer_flavor_wheel.csv). Each line in the file contains three columns. The first is a unique identifier for each test- the sample data contains three tests. You can label these whatever you would like, but here these are labelled 'A', 'B', and 'C'. The second column contains an identifier, unique to that test, for each grouping that a participant created during the ard sort- again, you could label these whatever you would like, but in this case groupings are labelled '01', '02', '03', etc. The third column contains the item itself. So in the sample data, for test 'A', 'sherry' was placed into a group by itself, labelled '01', while 'tobacco' and 'leather' were placed together into a group labelled '02'. To create a similarity matrix from this data, run the following command: ```console $ cardsort to-matrix sample_data/beer_flavor_wheel.csv ``` This script works for both open card sorts, where participants can place items into whatever groups they like, and closed card sorts, where a certain number of groups re pre-selected before the test begins. ## similarity This script takes similarity data, similar to what Charles Owen described in his book Structured Planning, and converts it to a similarity matrix. For an example of how to structure this data, see [sample_data/chairs.csv](./sample_data/chairs.csv). (This example is from p. 146 of Structured Planning.) Data files should contain headers for each column of data, and a label for each element in the first column. At the end of the file, after a blank line, are four rows that describe each data element. The first of those rows is labelled 'field_type', which indicates if the data in this field is discrete (non-orderable, like 'apples', 'oranges' and 'mangos') or continuous (like the numbers 1, 2, 3, 4.) The next row contains a weight for each field, followed by a match_difference and no_match_difference, as described in Structured Planning. To create a similarity matrix based on data like this: ```console $ similarity to-matrix sample_data/chairs.csv ``` ## Contributing There are many ways to contribute to this software- your pull requests, bug reports, feature requests, sample data sets, and use cases are all very welcome. Please contact the author for more information. ## Author John Jung
Python
UTF-8
1,359
3
3
[]
no_license
import xlrd import MySQLdb # read cell value from excel def get_row_col(excel): for row in range (excel.nrows): for col in range (excel.ncols): print row,excel.cell(row,col).value # connect db def read_excel_data_to_db(): conn=MySQLdb.connect(host="127.0.0.1",user="root",passwd="1",db="lilin",charset="utf8") cursor = conn.cursor() # cursor.execute("create table excel1(col int,value char(20),value1 char(20))") cursor.execute("describe excel1") print cursor.fetchall() for row in range (excel.nrows): values = row,excel.cell(row,1).value param = (row,excel.cell(row,0).value,excel.cell(row,1).value) sql = "insert into excel1 (col,value,value1) values(%s,%s,%s)" cursor.execute(sql,param) conn.commit() # read row into database # for row in range (excel.nrows): # for col in range (excel.ncols): # values = row,excel.cell(row,col).value # param = (row,excel.cell(row,col).value) # sql = "insert into excel (row,value) values(%s,%s)" # cursor.execute(sql,param) # conn.commit() cursor.close() conn.close() if __name__ == '__main__': # create index and obtain an worksheet orderly rfile = xlrd.open_workbook("test.xls") for index in range (0,2): excel = rfile.sheet_by_index(index) print excel # get_row_col(excel) read_excel_data_to_db()
Java
UTF-8
1,065
3.671875
4
[]
no_license
package modul_2.array_2; import java.util.Scanner; public class Task_7 { public static void main(String[] args) { int n; Scanner scr = new Scanner(System.in); // 7. System.out.println("Введите переменную/размер матрицы n - "); n = scr.nextInt(); double [][] matr = new double[n][n]; System.out.println("Наша матрица - "); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { matr[i][j] = Math.sin((i * i - j * j) / n); System.out.printf("%10f",matr[i][j]); } System.out.println(); } int k = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (matr[i][j] > 0) { k++; } } } System.out.println("Количество положительных элементов = " +k); } }
C++
UTF-8
4,582
2.5625
3
[]
no_license
/* Copyright 2011 Etay Meiri This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "technique.h" #include <glm/glm.hpp> struct DirectionalLight; struct Material; namespace Animation { struct BaseLight { glm::vec3 color; float ambientIntensity; float diffuseIntensity; BaseLight() { color = glm::vec3(0.0f, 0.0f, 0.0f); ambientIntensity = 0.0f; diffuseIntensity = 0.0f; } }; struct DirectionalLight : public BaseLight { glm::vec3 direction; DirectionalLight() { direction = glm::vec3(0.0f, 0.0f, 0.0f); } }; struct PointLight2 : public BaseLight { glm::vec3 position; struct { float constant; float linear; float exp; } attenuation; PointLight2() { position = glm::vec3(0.0f, 0.0f, 0.0f); attenuation.constant = 1.0f; attenuation.linear = 0.0f; attenuation.exp = 0.0f; } }; struct SpotLight : public PointLight2 { glm::vec3 direction; float cutoff; SpotLight() { direction = glm::vec3(0.0f, 0.0f, 0.0f); cutoff = 0.0f; } }; class SkinningTechnique : public Technique { public: static const unsigned int MAX_POINT_LIGHTS = 2; static const unsigned int MAX_SPOT_LIGHTS = 2; static const unsigned int MAX_BONES = 100; SkinningTechnique(); virtual bool Init() override; void SetWVP(const glm::mat4& WVP); void SetWorldMatrix(const glm::mat4& WVP); void SetLightSpaceMatrix(const glm::mat4& lightSpaceMatrix); void SetRenderingDepth(bool renderingDepth = false); void SetDepthMap(std::string depthMapName, GLuint ShadowMapIndex, GLuint textureID); void SetColorTextureUnit(unsigned int textureUnit); void SetDirectionalLight(const DirectionalLight& light); void SetDirectionalLight(const ::DirectionalLight& light); void SetPointLights(unsigned int numLights, const PointLight2* lights); void SetSpotLights(unsigned int numLights, const SpotLight* lights); void SetEyeWorldPos(const glm::vec3& eyeWorldPos); void SetMatSpecularIntensity(float intensity); void SetMatSpecularPower(float power); void SetMaterial(const Material& material); void SetUseTexture(bool useTexture); void SetBoneTransform(unsigned int index, const glm::mat4& transform); private: GLuint m_WVPLocation; GLuint m_WorldMatrixLocation; GLuint m_lightSpaceMatrix; GLuint m_colorTextureLocation; GLuint m_eyeWorldPosLocation; GLuint m_matSpecularIntensityLocation; GLuint m_matSpecularPowerLocation; GLuint m_numPointLightsLocation; GLuint m_numSpotLightsLocation; struct { GLuint color; GLuint ambientIntensity; GLuint diffuseIntensity; GLuint direction; } m_dirLightLocation; struct { GLuint color; GLuint ambientIntensity; GLuint diffuseIntensity; GLuint position; struct { GLuint constant; GLuint linear; GLuint exp; } atten; } m_pointLightsLocation[MAX_POINT_LIGHTS]; struct { GLuint color; GLuint ambientIntensity; GLuint diffuseIntensity; GLuint position; GLuint direction; GLuint Cutoff; struct { GLuint constant; GLuint linear; GLuint exp; } atten; } m_spotLightsLocation[MAX_SPOT_LIGHTS]; GLuint m_boneLocation[MAX_BONES]; }; }
Markdown
UTF-8
3,014
3.015625
3
[]
no_license
# 动画性能 > 性能影响一切 ## 技术:去除布局颠簸 - 由设置和获取的交替而导致的UI性能降低称为布局颠簸。 - 解决办法:批量操作DOM的设置和获取 ``` // 糟糕的做法 var currentTop = $("element").css("top"); // 获取 $("element").style.top = currentTop + 1; // 设置 var currentLeft = $("element").css("left"); // 获取 $("element").style.left = currentLeft + 1; // 设置 ``` - jQuery元素对象(JEO) ``` // 糟糕做法:未缓存JEO $("#element").css("opacity", 1); // ...... 一些中间代码...... // 再次将JEO实例化 $("#element").css("opacity", 0); ``` ``` // 恰当优化做法: // 缓存jQuery元素对象 var $element = $("#element"); $element.css("opacity", 1); // ...... 一些中间代码 ...... // 复用了缓存的JEO,避免了一次DOM查询 $element.css("opacity”, 0); ``` - 强制给值:明确地为动画设置初始值,避免一开始对页面进行获取的操作 ``` // 设置translateX从初始值0变动至500像素的动画 $element.velocity({ translateX: [ 500, 0 ] }); // 设置opacity从初始值1变动至0的动画 $element.velocity({ opacity: [ 0, 1 ]); ``` ## 批量添加DOM ``` var $body = $("body"); var $newElements = [ "<div>Div 1</div>", "<div>Div 2</div>", "<div>Div 3</div>" ]; var html = ""; $newElements.each(function(i, element) { html += element; }); // 一次性添加 $(html).appendTo($body); ``` ## 技巧:避免影响临近的元素 > 很多CSS属性,一经改变,就会造成临近元素尺寸或位置的调整,包括: top 、 right 、 bottom 和 left ,所有的 margin 和 padding 属性, border 厚度,以及 width 和 height 尺寸 尽可能设置CSS的 transform 属性( translateX 、translateY 、 scaleX 、 scaleY 、 rotateZ 、 rotateX 和 rotateY )的动画 ``` $element.velocity({ top: "100px" }); // 更快:使用translateY $element.velocity({ translateY: "100px" }); ``` ## 技巧:减少并发加载 - 错开动画 ``` $elements.velocity({ opacity: 1 }, { stagger: 300 }); ``` - 多动画序列 ``` $images .velocity({ opacity: 1 }) .velocity({ boxShadowBlur: "50px" }); ``` ## 技巧:不用持续响应滚动(scroll)和调整大小(resize)事件 - 问题 ``` // 当滚动浏览器窗口时,执行一个行为 $(window).scroll(function() { // 这里写的任何行为都会在用户滚动时,每秒钟触发多次 }); // 当浏览器窗口的大小改变时,执行一个行为 $(window).resize(function() { // 这里写的任何行为都会在用户调整窗口大小时,每秒钟触发多次 }); ``` - 解决方法:对事件句柄进行反跳(debounce) 定义一个时间间隔,在此时间间隔内,事件句柄回调将仅会被调用一次 ## 技巧:减少图片渲染 - 尽可能将基于图形的图片转成SVG元素 - 减少要渲染的图片 - 多图时,错开切换可见性的动画时间 ## 在旧浏览器上降级动画 - 产品决策:减少整个网站的动画 - 技术决策:只针对低端设备减少动画(使用全局动画乘数技术)
C#
UTF-8
3,688
2.5625
3
[ "MIT" ]
permissive
using System; using PivotalTrackerDotNet.Domain; using NUnit.Framework; namespace PivotalTrackerDotNet.Tests { [TestFixture] public class StoryServiceTest { private StoryService storyService = null; const int projectId = 456301; [TestFixtureSetUp] public void TestFixtureSetUp() { storyService = new StoryService(AuthenticationService.Authenticate(TestCredentials.Username, TestCredentials.Password)); } [Test] public void CanRetrieveSingleStory() { const int storyId = 23590427; var story = storyService.GetStory(projectId, storyId); Assert.NotNull(story); Assert.AreEqual(projectId, story.ProjectId); Assert.AreEqual(storyId, story.Id); Assert.AreEqual("feature", story.StoryType); Assert.AreEqual("Single Task", story.Name); Assert.AreEqual(2, story.Estimate); Assert.AreEqual(1, story.Tasks.Count); Assert.AreEqual(storyId, story.Tasks[0].ParentStoryId); } [Test] public void CanRettrieveMultipleStories() { var stories = storyService.GetCurrentStories(projectId); Assert.NotNull(stories); Assert.AreEqual(2, stories.Count); } [Test] public void CanRetrieveIceBoxStories() { var stories = storyService.GetIceboxStories(projectId); Assert.NotNull(stories); Assert.AreEqual(2, stories.Count); } [Test] public void CanAddAndDeleteStores(){ var story = new Story{Name="Nouvelle histoire", RequestedBy="pivotaltrackerdotnet",StoryType= StoryType.Feature , Description="bla bla bla and more bla", ProjectId=projectId}; var savedStory = storyService.AddNewStory(projectId,story); Assert.AreEqual(story.Name, savedStory.Name); Assert.AreEqual(projectId, savedStory.ProjectId); Assert.AreEqual(story.RequestedBy, savedStory.RequestedBy); Assert.AreEqual(story.StoryType, savedStory.StoryType); Assert.AreEqual(story.Description, savedStory.Description); var deletedStory = storyService.RemoveStory(projectId, savedStory.Id); Assert.AreEqual(savedStory.Id, deletedStory.Id); Assert.AreEqual(savedStory.Name, deletedStory.Name); Assert.AreEqual(projectId, deletedStory.ProjectId); Assert.AreEqual(savedStory.RequestedBy, deletedStory.RequestedBy); Assert.AreEqual(savedStory.StoryType, deletedStory.StoryType); Assert.AreEqual(savedStory.Description, deletedStory.Description); } [Test] public void CanSaveTask() { var guid = Guid.NewGuid().ToString(); var stories = storyService.GetCurrentStories(projectId); var task = stories[0].Tasks[0]; task.Description = guid; storyService.SaveTask(task); stories = storyService.GetCurrentStories(projectId); Assert.AreEqual(guid, stories[0].Tasks[0].Description); } [Test] public void CanAddGetAndDeleteNewTasks(){ var story = new Story{Name="Nouvelle histoire", RequestedBy="pivotaltrackerdotnet",StoryType=StoryType.Feature, Description="bla bla bla and more bla", ProjectId=projectId}; var savedStory = storyService.AddNewStory(projectId,story); var task = new Task{Description="stuff stuff stuff", ParentStoryId=savedStory.Id, ProjectId=projectId }; var savedTask = storyService.AddNewTask(task); Assert.AreEqual(task.Description, savedTask.Description); var retrievedTask = storyService.GetTask(projectId, savedTask.ParentStoryId, savedTask.Id); Assert.NotNull(retrievedTask); var deletedTask = storyService.RemoveTask(task.ProjectId, task.ParentStoryId, savedTask.Id); Assert.NotNull(deletedTask); Assert.AreEqual(savedTask.Description, deletedTask.Description); Assert.AreEqual(savedTask.Id, deletedTask.Id); storyService.RemoveStory(projectId, savedStory.Id); } } }
C++
UTF-8
1,263
3.203125
3
[]
no_license
#define relayPin 13 //定義繼電器接腳為13 #define IN1 12 //定義IN1接腳為12 #define OnPin 2 //定義ON按鈕開關接腳為2 #define OffPin 3 //定義OFF按鈕開關接腳為3 int val = 0; //變數val用來儲存按鈕狀態 int val1 = 0; //變數val1用來儲存按鈕狀態 int state = 0; //1表示ON按鍵按下,0表示OFF按下 void setup(){ pinMode(relayPin, OUTPUT); //設定繼電器接腳為輸出狀態 pinMode(IN1, OUTPUT); //設定IN1接腳為輸出狀態 pinMode (OnPin,INPUT); //設定按鈕ON接腳為輸入狀態 pinMode (OffPin,INPUT); //設定按鈕OFF接腳為輸入狀態 } void loop(){ val = digitalRead(OnPin); //讀取ON按鈕狀態並儲存 if((val == LOW)&&(state== 0)){ //檢查按鈕的變化情況 state =1; digitalWrite(relayPin,HIGH); digitalWrite(IN1,HIGH); delay(40); //延時抗按鈕彈跳 } val1 = digitalRead(OffPin); //讀取按鈕OFF狀態並儲存 if((val1 == LOW)&&(state == 1)){ //檢查按鈕的變化情況 state =0; digitalWrite(relayPin,LOW); digitalWrite(IN1,LOW); delay(40); //延時抗按鈕彈跳 } }
Shell
UTF-8
842
3.703125
4
[]
no_license
#!/bin/bash RUNS=5 SIZE="80 84 88 92 96 100 104 108 112 116 120 124 128 132 136 140 144 148 152 156 160 164 168 172 176 180 184 188 192 196 200 204 208 212 216 220 224 228 232 236 240 244 248 252 256 260 264 268 272 276" FILE="stats.csv" # Chek for program arguments if [ $# == 0 ]; then echo "Usage: $0 FILE [RUNS]" exit 1 else if [ $# == 2 ]; then RUNS=$2 echo "Setting run number to $RUNS" fi FILE=$1 fi echo "Running statistical Krylov tests. Writing results to file $FILE." # All tests for t in `seq 1 5`; do echo "Running Test $t ... " for i in $SIZE; do echo " Test $t with n = $i ..." for run in `seq 1 $RUNS`; do ./bicgstab_cl --gpu --stats -t $t -n $i >>$FILE STATUS=$? if [ $STATUS != 0 ]; then echo "ERROR Solver exited with status $STATUS" exit $STATUS fi done done done
Java
UTF-8
941
3.1875
3
[]
no_license
package JAVA_APP; import java.util.*; import java.util.stream.Collectors; import static java.util.Collections.*; import static java.util.stream.Collectors.*; public class Demo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Set set = new HashSet(); int n = sc.nextInt(); int[] arr = new int[n]; String[] name = new String[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); name[i] = sc.next(); } Map maplist = new HashMap(); List keyList = Arrays.asList(arr); List valueList = Arrays.asList(name); maplist.put(keyList, valueList); Iterator iterator = maplist.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry key = (Map.Entry) iterator.next(); System.out.println(key.getKey().toString() + " " + key.getValue()); } } }
Java
UTF-8
847
2.03125
2
[]
no_license
package s.po; import java.io.Serializable; public class GoodsPictureInfo implements Serializable { private static final long serialVersionUID = 1L; private Integer pkid; private byte[] GoodsPictureData; private String GoodsPictureName; private Integer GoodsId; public Integer getPkid() { return pkid; } public void setPkid(Integer pkid) { this.pkid = pkid; } public byte[] getGoodsPictureData() { return GoodsPictureData; } public void setGoodsPictureData(byte[] goodsPictureData) { GoodsPictureData = goodsPictureData; } public String getGoodsPictureName() { return GoodsPictureName; } public void setGoodsPictureName(String goodsPictureName) { GoodsPictureName = goodsPictureName; } public Integer getGoodsId() { return GoodsId; } public void setGoodsId(Integer goodsId) { GoodsId = goodsId; } }
Markdown
UTF-8
622
2.765625
3
[]
no_license
[funky](../../index.md) / [org.funky.option](../index.md) / [kotlin.Array](index.md) / [firstOption](.) # firstOption `fun <A> `[`Array`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)`<out A>.firstOption(): `[`Option`](../-option/index.md)`<A>` `fun <A> `[`Array`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)`<out A>.firstOption(p: (A) -> `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)`): `[`Option`](../-option/index.md)`<A>` Extracts the first element and wraps it in an Option. Returns None is the receiver has no elements.
Java
UTF-8
879
2.15625
2
[]
no_license
package com.pl.bg.javamasproject.demo.adapter; import com.pl.bg.javamasproject.demo.model.Tomograph; import org.springframework.data.domain.Example; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Optional; public interface TomographRepository extends JpaRepository<Tomograph, Integer> { @Override List findAll(); @Override Optional findById(Integer integer); @Override boolean existsById(Integer integer); @Override void deleteById(Integer integer); @Override <S extends Tomograph> S save(S s); @Query(value = "select t from Tomograph t where t.serial_number = :serial_number") boolean findBySerialNumberTomo(@Param("serial_number")String serial_number); }
Java
UTF-8
1,234
2.609375
3
[]
no_license
/** * Project : Classify URLs */ package xlong.classifyURL.main; import weka.core.Instances; import weka.core.converters.ConverterUtils.DataSink; import xlong.classifyURL.core.FilesToInstances; public class GetOriginalArff { public static void getOriginalArff(int nAll) throws Exception{ Instances data; String dir = "temp/URLsHaveSameType/"; String[] allFiles = new String[nAll]; for (int i=0;i<nAll;i++){ allFiles[i] = dir + (i+1); } data = FilesToInstances.createInstances("URLClasses", allFiles); //DataSink.write("results/URLAll_Ori.arff", data); // Randomize data.randomize(new java.util.Random()); // Percentage split int percent = 66; int trainSize = (int) Math.round(data.numInstances() * percent/ 100); int testSize = data.numInstances() - trainSize; Instances train = new Instances(data, 0, trainSize); Instances test = new Instances(data, trainSize, testSize); DataSink.write("temp/URLAll_Train.arff", train); DataSink.write("temp/URLAll_Test.arff", test); } public static void getOriginalArff() throws Exception{ getOriginalArff(337); } public static void run() throws Exception { System.out.println("Get Orignal Arff..."); getOriginalArff(200); } }
Python
UTF-8
144
2.71875
3
[]
no_license
n=int(input()) s=list(map(int,input().split())) ans=0 for i in range(n-1): ans+=max(s[i]-s[i+1],0) s[i+1]=max(s[i+1],s[i]) print(ans)
C#
UTF-8
1,267
2.828125
3
[]
no_license
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.ServiceBus.Messaging; using System; using System.Collections.Generic; using System.Text; namespace ServiceBusQueueTriggerFunction { public static class ServiceBusQueueTriggeredFunction { [FunctionName("ServiceBusQueueTriggeredFunction")] public static void Run([ServiceBusTrigger("sortingsqueue", AccessRights.Manage, Connection = "ServiceBusConnection")]string myQueueItem, [Queue("outqueue", Connection = "MyOutQueue")] out string outQueue, TraceWriter log) { log.Info($"C# ServiceBus queue trigger function processed message: {myQueueItem}"); myQueueItem = myQueueItem ?? throw new ArgumentNullException(nameof(myQueueItem)); var arrayToSort = Parsing.ParseQueueMessage(myQueueItem); Sorting.MergeSort(arrayToSort); StringBuilder sortedString = new StringBuilder(); foreach (var number in arrayToSort) { sortedString.Append(number); sortedString.Append(','); } outQueue = sortedString.ToString(); log.Info($"Out queue message: {outQueue}"); } } }
Markdown
UTF-8
756
2.53125
3
[]
no_license
Deployed version [here](http://fideligard.surge.sh/) Fideligard allows clients to test the historical performance of stock portfolios. Buy and sell stocks based on past performance and Fidelagard will keep track of your transactions and portfolio at any given date. Fideligard is an Angular JS Javascript single-page web application using services, direcrives, ui-router and multi-view states. Historical data comes from Yahoo Finance. Fideligard also includes a stock-trading game. Start on day 1 and make trades one day at a time. The goal is to have the best-performing portfolio at the end of the simulation. ![Trading view](screenshots/trade_screen.png "Trading view. Choose from stocks on ticker on the left and change the date using the slider.")
Markdown
UTF-8
4,257
2.875
3
[]
no_license
--- layout: default title: Quelques astuces pour travailler avec des chiffres section: pages --- * La meilleure façon de travailler avec des données, c’est d’y prendre plaisir. Les données peuvent sembler rébarbatives, mais si vous les laisser vous intimider, vous n’arriverez à rien. Voyez-les comme un jouet, un territoire à explorer, et elles révéleront souvent des secrets et des histoires avec une facilité déconcertante. Traitez les simplement comme n’importe quel autre élément de preuve, sans crainte ni partialité. Mais voyez surtout cela comme un exercice d’imagination. Soyez créatif en songeant aux angles alternatifs que les données peuvent receler et confrontez-les à d’autres éléments de preuve. « Quel autre angle peut expliquer ceci ? » est une bonne question à se poser pour vérifier tel nombre manifestement trop beau pour être vrai ou telle preuve apparemment claire, qui ne sont peut-être rien de la sorte. * Ne confondez pas cynisme et scepticisme. Le scepticisme est une qualité ; être cynique, c’est baisser les bras. Si vous croyez au datajournalisme (et c’est probablement le cas puisque vous lisez ce livre), alors vous devez croire que les données ont mieux à offrir que des mensonges ou des caricatures. Utilisées avec discernement, elles peuvent nous apporter un profond savoir. Nous ne devons être ni cynique, ni naïfs, mais alertes. * Si je vous dis que la consommation d’alcool a augmenté pendant la récession, vous me direz peut-être que c’est parce que tout le monde est déprimé. Si je vous dis qu’elle a baissé, vous me répondrez que c’est parce que tout le monde est fauché. En d’autres termes, ce que disent les données ne changera rien à l’interprétation que vous avez décidé d’en faire, à savoir que dans un cas comme dans l’autre, tout va mal. Si vous croyez aux données, essayez de les laisser s’exprimer avant d’y imprimer votre humeur, vos croyances ou vos attentes. Il y a tellement de données dans la nature qu’il vous suffira de chercher un peu pour en trouver qui confirment vos préjugés. En clair, le datajournalisme, selon moi, présente peu d’intérêt si vous n’êtes pas ouvert d’esprit. Les chiffres n’ont aucune vertu intrinsèque ; vous seul êtes le garant de l’objectivité. * Vous avez le droit d’avoir des doutes. Nous avons trop tendance à associer les chiffres à l’autorité et à la certitude. Bien souvent, la meilleure réponse consiste à dire qu’il n’y a pas de réponse du tout, ou à offrir la meilleure interprétation possible tout en sachant qu’il ne s’agit que d’une grossière approximation. Je pense que nous devons dire ces choses-là. Cela peut sembler être la meilleure façon de tuer une histoire dans l’œuf, mais c’est également une excellente manière de soulever de nouvelles questions. De même, il y a bien souvent plusieurs manières légitimes d’interpréter des données. Les chiffres ne sont pas nécessairement vrais ou faux. * L’enquête elle-même est un angle intéressant et peut faire l’objet d’un article dans lequel vous exposez les éléments de preuve un par un – et cela s’applique tout particulièrement aux chiffres, qui viennent rarement seuls. Des sources différentes peuvent offrir de nouveaux angles, de nouvelles idées et une compréhension plus riche. Je crois que nous avons trop tendance à vouloir être autoritaire et à donner la réponse aux gens – et que nous manquons ainsi l’occasion de détailler le processus d’investigation. * Les plus vieilles questions sont souvent les meilleures : ce chiffre est-il vraiment trop élevé ? D’où provient-il ? Êtes-vous sûr qu’il compte pour autant que vous le pensez ? Voilà quelques questions à se poser pour penser au-delà des données, prendre en compte les informations qui sont passées inaperçues à force de se focaliser sur un seul chiffre, la complexité de la vraie vie, la diversité des comparaisons possibles au fil du temps, par groupe ou par région géographique ; en bref, le contexte. _Michael Blastland, journaliste indépendant_
Shell
UTF-8
214
2.71875
3
[ "MIT" ]
permissive
#!/bin/bash source ../spec.sh source ./module_spec.sh # Clean up vlc, if we dont have Qt5 if [ "${INCVLC}" == "Y" ] && [ "${INCQTFIVE}" != "Y" ]; then rm ${DIR}/usr/${LIBDIR}/vlc/plugins/gui/libqt_plugin.so fi
Java
UTF-8
4,620
2.71875
3
[]
no_license
package akydroid.galactic.bunny.gameworld; import java.util.ArrayList; import akydroid.galactic.bunny.objects.BoundaryFrame; import akydroid.galactic.bunny.objects.EnemyBall; import akydroid.galactic.bunny.objects.MyBG; import akydroid.galactic.bunny.objects.MyPlayer; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; public class MyGameWorld { final int INITIAL_BALL_SIZE = 8; float screenHeight, screenWidth, gameHeight, gameWidth; float scaleX, scaleY; MyGameRenderer myGameRenderer; static MyPlayer myPlayer; BoundaryFrame myFrame; MyBG myBG; ArrayList<EnemyBall> myEnemyBallArray; Rectangle circleLimits; final int BOUNDARYSCALER = 18; final int PLAYERSCALER = 9; public MyGameWorld(float screenHeight, float screenWidth, float gameHeight, float gameWidth, float scaleX, float scaleY) { this.screenHeight = screenHeight; this.screenWidth = screenWidth; this.gameHeight = gameHeight; this.gameWidth = gameWidth; this.scaleX = scaleX; this.scaleY = scaleY; circleLimits = new Rectangle(gameWidth / BOUNDARYSCALER, gameHeight/ BOUNDARYSCALER, gameWidth - (2 * gameWidth / BOUNDARYSCALER),gameHeight - (2 * gameHeight / BOUNDARYSCALER)); myBG = new MyBG(gameHeight, gameWidth); myFrame = new BoundaryFrame(gameHeight, gameWidth, gameHeight / BOUNDARYSCALER, gameWidth / BOUNDARYSCALER); myPlayer = new MyPlayer(gameHeight, gameWidth,(gameHeight * (BOUNDARYSCALER - 1)) / BOUNDARYSCALER, PLAYERSCALER, gameWidth / BOUNDARYSCALER, gameHeight / BOUNDARYSCALER); myEnemyBallArray = new ArrayList<EnemyBall>(); myEnemyBallArray.add(0, new EnemyBall(0, INITIAL_BALL_SIZE, new Vector2(gameWidth / 2, gameHeight / 2), new Vector2(1, 1),circleLimits,-1)); myEnemyBallArray.add(1, new EnemyBall(1, INITIAL_BALL_SIZE, new Vector2(gameWidth / 2, gameHeight / 2), new Vector2(1, 1),circleLimits,-1)); } public void update(float delta) { myPlayer.update(delta); int killIt = -1; for (int i = 0; i < myEnemyBallArray.size(); i++) { myEnemyBallArray.get(i).update(delta); if (myPlayer.getBullet() != null) { if (Intersector.overlaps(myEnemyBallArray.get(i).getMyCircle(), myPlayer.getBullet().getMyBoundingRectangle())) { killIt = i; } } } if (killIt != -1) { IMKilled(killIt); killIt = -1; } } public void IMKilled(int killed) { if (myEnemyBallArray.get(killed).getMyCircle().radius > 2) { int newIndex = myEnemyBallArray.size(); myEnemyBallArray.add(newIndex, new EnemyBall(newIndex, myEnemyBallArray.get(killed).getMyCircle().radius / 2, new Vector2(myEnemyBallArray.get(killed).getMyCircle().x, myEnemyBallArray.get(killed).getMyCircle().y), new Vector2(1, 1), circleLimits,myEnemyBallArray.get(killed).getMoveDirection())); newIndex += 1; myEnemyBallArray.add(newIndex, new EnemyBall(newIndex, myEnemyBallArray.get(killed).getMyCircle().radius / 2, new Vector2(myEnemyBallArray.get(killed).getMyCircle().x, myEnemyBallArray.get(killed).getMyCircle().y), new Vector2(1, 1), circleLimits,calculateNewDirectionsOfNewEnemies(killed))); } myEnemyBallArray.remove(killed); myPlayer.setBullet(null); } private int calculateNewDirectionsOfNewEnemies(int killed) { int newDirection = myEnemyBallArray.get(killed).getMoveDirection(); if (newDirection % 2 == 0) newDirection -= 1; else if (newDirection % 2 == 1) newDirection += 1; return newDirection; } public MyPlayer getPlayer() { return myPlayer; } public MyBG getMyBG() { return myBG; } public BoundaryFrame getBoundaryFrame() { return myFrame; } public MyGameRenderer getRenderer() { return myGameRenderer; } public void setRenderer(MyGameRenderer tempRenderer) { myGameRenderer = tempRenderer; } public float getScreenHeight() { return screenHeight; } public void setScreenHeight(float screenHeight) { this.screenHeight = screenHeight; } public float getScreenWidth() { return screenWidth; } public void setScreenWidth(float screenWidth) { this.screenWidth = screenWidth; } public float getGameHeight() { return gameHeight; } public void setGameHeight(float gameHeight) { this.gameHeight = gameHeight; } public float getGameWidth() { return gameWidth; } public void setGameWidth(float gameWidth) { this.gameWidth = gameWidth; } public ArrayList<EnemyBall> getEnemyBall() { return myEnemyBallArray; } }
TypeScript
UTF-8
340
2.78125
3
[]
no_license
export class Credentials { public username: string; public password: string; constructor(username: string, password: string) { this.username = username; this.password = password; } public getJson():string { return '{"username":"'+this.username+'", "password":"'+this.password+'"}'; } }
Ruby
UTF-8
526
2.578125
3
[]
no_license
class HogwartAsAService def get_students(house1) house_id = get_json('house').select do |house| house[:name] == house1 end.first[:id] get_json("house/#{house_id}") end def get_json(url) response = conn.get(url) JSON.parse(response.body, symbolize_names: true) end def conn Faraday.new(url: 'https://hogwarts-as-a-service.herokuapp.com/api/v1/') do |faraday| faraday.headers['x_api_key'] = ENV['hogwarts_service_api'] faraday.adapter Faraday.default_adapter end end end
PHP
UTF-8
587
2.8125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace App\Configuration; use App\Version\VersionInterface; interface ConfigurationInterface { public function __construct(array $paths, VersionInterface $version, ?string $changelog); public static function parseFile(string $filename, string $versioning): ConfigurationInterface; public function save(string $filename): void; public function getChangelog(): ?string; public function getPaths(): array; public function getVersion(): ?VersionInterface; public function setVersion(VersionInterface $version): void; }
TypeScript
UTF-8
369
2.703125
3
[]
no_license
interface Option { label: string; value: any; } interface IRegiao { id: number; nome: string; sigla: string; } export interface IEstado { id: number; nome: string; regiao: IRegiao; sigla: string; } export interface ICidade { id: number; nome: string; } export type ICidadeWithPicker = ICidade & Option; export type IEstadoWithPicker = IEstado & Option;
C#
UTF-8
631
3.359375
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace LamdaDemo { class LambdaArray { static void Sample_Select_Lambda_Indexed() { string[] words = { "one", "two", "three" }; var result = words.Select((w, i) => new { Index = i, Value = w }); Debug.WriteLine("Words with index and value:"); foreach (var word in result) Debug.WriteLine(String.Format("Index {0} is {1}", word.Index, word.Value)); } } }
C++
UTF-8
821
3.03125
3
[]
no_license
#include <iostream> #include <conio.h> #include <iomanip> #include <stdlib.h> using namespace std; int main () { int Mat_A[4][4]; int i,j,k, baris, kolom; do { system("cls"); cout<< "Baris dan kolom tidak boleh lebih dari 4!\n\n"; cout<< "Masukkan banyak baris matrik A : "; cin>> baris; cout<< "Masukkan banyak kolom matrik A : "; cin>> kolom; } while (baris>4||kolom>4); //membaca elemen - elemen matrik A for(i = 0; i < baris; i++) { for(j = 0; j < kolom; j++) { cout<<"Index "<<i<<", "<<j<<" = "; cin>>Mat_A[i][j]; } } cout<<endl; //Mencetak elemen A cout<< "\nMatrik A ("<<baris<<"x"<<kolom<<")\n"; for(i = 0; i < baris; i++) { for(j = 0; j < kolom; j++) { cout<<setw(3)<<Mat_A[i][j]; } cout<<endl; } getch (); return 0; }
Java
UHC
767
2.453125
2
[]
no_license
import java.awt.event.MouseListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class puzzle{ public static void main(String[] args) { MainFrame mf = new MainFrame(); //Ŭ, ҷ } } class MainFrame extends JFrame implements MouseListener, Runnable{ // Ŭ private JLabel lb_title = new JLabel(); // ŸƲ ǥÿ private JLabel lb_time = new JLabel(); //ð ǥÿ private JButton bt_start = new JButton("START"); // ư private JButton bt_reset = new JButton("RESET"); // ư SimpleDateFormat time_format; //ð ޾Ƶ }
Java
UTF-8
1,670
2.328125
2
[]
no_license
package com.cdkj.gchf; import java.io.IOException; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class PostFilter implements Filter { Logger logger = LoggerFactory.getLogger(getClass()); private FilterConfig filterConfig = null; public void destroy() { this.filterConfig = null; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; Enumeration<String> names = request.getParameterNames(); StringBuilder output = new StringBuilder(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); output.append(name).append("="); String values[] = request.getParameterValues(name); for (int i = 0; i < values.length; i++) { if (i > 0) { output.append("' "); } output.append(values[i]); } if (names.hasMoreElements()) output.append("&"); } request.setAttribute("postdata", output); logger.info("postdata: " + output); chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } }
PHP
UTF-8
614
2.828125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /* * This file is part of Matrices. * * (c) Graham Campbell <graham@alt-three.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace GrahamCampbell\Matrices\Iterators; /** * This is the collection column iterator class. * * @author Graham Campbell <graham@alt-three.com> */ class CollectionColumnIterator extends AbstractCollectionIterator { public function __construct(array $matrices, $index) { foreach ($matrices as $matrix) { $this->iterators[] = $matrix->column($index); } } }
Markdown
UTF-8
3,644
3.125
3
[]
no_license
前面我们实现了通过网络端口来访问运行在docker容器内的服务。下面我们来实现通过端口连接到一个docker容器 ---------- # 网络端口映射 我们创建了一个 python 应用的容器。 ``` docker run -d -P training/webapp python app.py ``` 另外,我们可以指定容器绑定的网络地址,比如绑定 127.0.0.1。 我们使用 `-P` 参数创建一个容器,使用 docker ps 来看到端口5000绑定主机端口32768。 ``` runoob@runoob:~$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES fce072cc88ce training/webapp "python app.py" 4 minutes ago Up 4 minutes 0.0.0.0:32768->5000/tcp grave_hopper ``` 我们也可以使用 -p 标识来指定容器端口绑定到主机端口。 两种方式的区别是: - `-P` :是容器内部端口随机映射到主机的高端口。 - `-p` : 是容器内部端口绑定到指定的主机端口。 ``` docker run -d -p 5000:5000 training/webapp python app.py ``` ``` runoob@runoob:~$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 33e4523d30aa training/webapp "python app.py" About a minute ago Up About a minute 0.0.0.0:5000->5000/tcp berserk_bartik fce072cc88ce training/webapp "python app.py" 8 minutes ago Up 8 minutes 0.0.0.0:32768->5000/tcp grave_hopper ``` 另外,我们可以指定容器绑定的网络地址,比如绑定127.0.0.1。 ``` docker run -d -p 127.0.0.1:5001:5002 training/webapp python app.py runoob@runoob:~$ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 95c6ceef88ca training/webapp "python app.py" 6 seconds ago Up 6 seconds 5000/tcp, 127.0.0.1:5001->5002/tcp adoring_stonebraker 33e4523d30aa training/webapp "python app.py" 3 minutes ago Up 3 minutes 0.0.0.0:5000->5000/tcp berserk_bartik fce072cc88ce training/webapp "python app.py" 10 minutes ago Up 10 minutes 0.0.0.0:32768->5000/tcp grave_hopper ``` 这样我们就可以通过访问127.0.0.1:5001来访问容器的5002端口。 上面的例子中,默认都是绑定 tcp 端口,如果要绑定 UDP 端口,可以在端口后面加上 `/udp`。 ``` docker run -d -p 127.0.0.1:5000:5000/udp training/webapp python app.py ``` `docker port` 命令可以让我们快捷地查看端口的绑定情况。 ``` runoob@runoob:~$ docker port adoring_stonebraker 5002 127.0.0.1:5001 ``` # Docker容器连接 端口映射并不是唯一把 docker 连接到另一个容器的方法。 docker有一个连接系统允许将多个容器连接在一起,共享连接信息。 docker连接会创建一个父子关系,其中父容器可以看到子容器的信息。 ---------- ## 容器命名 当我们创建一个容器的时候,docker会自动对它进行命名。另外,我们也可以使用`--name`标识来命名容器,例如: ``` docker run -d -P --name runoob training/webapp python app.py ``` 我们可以使用 docker ps 命令来查看容器名称。 ``` runoob@runoob:~$ docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 43780a6eabaa training/webapp "python app.py" 3 minutes ago Up 3 minutes 0.0.0.0:32769->5000/tcp runoob ```
Python
UTF-8
685
2.53125
3
[ "MIT" ]
permissive
from rest_framework.response import Response from rest_framework.views import status """ Decorador definido para que valide que algunos campos de la sentencia que llegan en la petición no estén vacíos """ def validate_request_data(fn): def decorated(*args, **kwargs): # args[0] == GenericView Object input_code = args[0].request.data.get("input_code", "") if not input_code : return Response( data={ "message": "Input Code is required!" }, status=status.HTTP_400_BAD_REQUEST ) return fn(*args, **kwargs) return decorated
C#
UTF-8
1,414
2.71875
3
[]
no_license
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Buzz.Client { /// <summary> /// Client Function - user interaction /// provide Post and Delete API to create and delete load clusters /// </summary> public static class PostClusterClient { [FunctionName("PostClusterClient")] public static async Task<HttpResponseMessage> PostCluster([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, [OrchestrationClient] DurableOrchestrationClient starter, ILogger log) { // Get request body dynamic data = await req.Content.ReadAsAsync<object>(); var scale = (int)data?.scale; var name = (string)data?.name; if (scale == 0 || string.IsNullOrEmpty(name)) { return req.CreateResponse(HttpStatusCode.BadRequest, $"Bad input. please supply name and scale > 0"); } log.LogInformation($"post cluster client: {name} scale: {scale}"); var response = starter.StartNewAsync("CreateCluster", new Tuple<string, int>(name, scale)); return req.CreateResponse(HttpStatusCode.OK, $"started create process id:{response.Id}"); } } }
Markdown
UTF-8
832
3.078125
3
[]
no_license
# Redux Feedback Loop ## Description For this project I built a feedback app. The user answers a list of questions (each located on their own route) and submits their feedback. For the questions I chose to use a dropdown with the values 1-5. When the feedback is submitted it is Posted to a SQL database. Upon completion the user is able to click a button to leave additional feedback which will bring them back to the home page to start the process again. Tech used: * React * Redux * HTML * CSS * javaScript * Node.js * SQL ![](public/images/pic1.png) ![](public/images/pic2.png) ![](public/images/pic3.png) ![](public/images/pic4.png) ## Thank You I would like to give a special shoutout to dEv Jana and my other instructors at Prime Academy for teaching me the skills and creating the requirements for this project.
Rust
UTF-8
1,050
3.78125
4
[ "MIT" ]
permissive
fn main() { let a = String::from("hello"); run1(&a).unwrap(); run2(&a).unwrap(); } fn run1(a: &String) -> Result<(), String> { let b = match foo(a) { Ok(x) => x, Err(x) => return Err(x), }; let c = match bar(a) { Ok(x) => x, Err(x) => return Err(x), }; let d = match baz(&b, c) { Ok(x) => x, Err(x) => return Err(x), }; println!("{:?}", d); Ok(()) } fn run2(a: &String) -> Result<(), String> { let b = foo(a)?; let c = bar(a)?; let d = baz(&b, c)?; println!("{:?}", d); Ok(()) } fn foo(s: &String) -> Result<&String, String> { if s.is_empty() { Err(String::from("foo")) } else { Ok(s) } } fn bar(s: &String) -> Result<i32, String> { if s.is_empty() { Err(String::from("bar")) } else { Ok(s.len() as i32) } } fn baz(s: &String, i: i32) -> Result<(&String, i32), String> { if s.is_empty() || i == 0 { Err(String::from("baz")) } else { Ok((s, i)) } }
Java
UTF-8
7,210
2.53125
3
[]
no_license
package com.ing.connector.interfaces; //import com.eds.cio.model.Model; //import com.eds.cio.server.interfaces.persistence.NailbaPending2XSegTDB; import java.util.Hashtable; import java.util.Vector; import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParsePosition; import com.ing.connector.interfaces.WLineHelper; /** * The NailbaPending2XSegT object represents a INFPOL outbound row used by Interfaces for outbound * processing. * This object works with an PMFFileProcessor to complete the construction and * execution of a INFPOL interface. * * This class extends Model to implement persistency related behavior. At this time, * the class does not implement a deferrable interface since this object is not deferrable. * * NailbaPending2XSegTobjects can be constructed in one of two ways. First a default constructor * constructs an "empty" NailbaPending2XSegT object that is then populated, most likely by the * NailbaPending2XSegTRH. The second form is by passing the overloaded constructor a STRING which * is parsed and places values in the instance variables. This technique is used to * implement behavior related to constructing the object from ASCII input files. * * Since most of the conversion related functionality is currently in the FileProcessor * classes, only basic getter/setter and parsing routines are implemented here. * * @since Iteration 3 - 6/98 */ //public class NailbaPending2XSegT extends Model { public class NailbaPending2XSegT{ // VARIABLES, STATIC THEN INSTANCE //instance variables occur in the order they are expected on the inbound file //rather than in alphabetical order. This is to help the SE in the parse( ) //and toString() method. private String m_freeFormText; // CONSTRUCTORS /** * construct an empty NailbaPending2XSegT Object * @since Iteration 3 - 6/98 */ public NailbaPending2XSegT() { } /** * construct an NailbaPending2XSegT object and load instance variables by parsing the value * held in a String. This code supports the passing of ASCII file contents * to the object for processing. This serves as a work around for processing * from flat files instead of database tables. * * If the line fails to parse properly, an instantiation exception is thrown * * @param aString String containg a value for each instance variable * @since Iteration 3 - 6/98 */ public NailbaPending2XSegT(String aStr) throws InstantiationException { try { this.parse(aStr); // this.makedirty(); } catch (Exception e) { System.out.println("NailbaPending2XSegT:Unable to parse routine against String "); System.out.println(" line value is: "); System.out.println(aStr); throw new InstantiationException(aStr); } } // STATIC METHODS // INSTANCE METHODS /* objectAt( ) is used to assist subclasses of FileProcessor * that have not been converted to directly use the getters and setters * on this object. It is in place to help the FileProcessors that have * have been coded with the Record/RecordField object structure. When * possible, this method should not be used because of the overhead * associated with it -- USE GETTERS DIRECTLY. * * This method returns values directly w/out using getters to improve * Java performance. Other objects must use the public getter * * @param String - a String indicating which instance variable to return * @return Object - instance of the object the variable returns */ // public Object objectAt(String aStr) // throws Exception { // return null; // } /* parse( ) takes a string, as if it were an ASCII file, and places * values into the instance variables. The string is parsed using the * substring method. Position in the string is VERY IMPORTANT due to * the order in which fields fall out. * * This routine directly sets instance variables to improve Java performance * * @param aStr - String representing an ASCII line */ private void parse(String aStr) throws Exception { } /* toString() converts the object back to its original ASCII * file value by using a WLineHelper class to handle leading * zeroes and padding with blanks. This method is mainly used * when writing this object out and requiring the data to be * in a fixed length format. * * To improve Java performance, this routine directly accesses instance * variables * * @return String - Fixed Length string representing ASCII output line value */ public String toString() { return this.toStringDelimited(""); } /* * @return String - Field Delimited string representing ASCII output line value. * If the delimiter is empty, a fixed length version of the string is returned. * * The same call is used for fixed or delimited to allow single declaration of * the output record no matter if fixed length or field delimited. */ public String toStringDelimited(String delim) { WLineHelper aHelper = new WLineHelper(); // if a delimiter is empty, a fixed-length-field string of fields is returned, // otherwise a delimited-field string of fields is returned, delimited with the // requested character. aHelper.setFieldDelimiter(delim); String d = new String("D,yyMMdd"); //Date (Send as Date) String d2 = new String("D,yyyyMMdd"); //Date (Send as Date) String i = new String("I"); //Number (Send as Integer) String j = new String("J"); //signed number (Send as Integer) String m = new String("M"); //money (Send as Double) String n = new String("N"); //signed money (Send as Double) String s = new String("S"); //String (Send as String) String aStr = null; // typ, Object, size, decimal places try { aStr = aHelper.toStringFixed(s,m_freeFormText,26,0); } catch (Exception e) { com.ing.connector.Registrar.logError("NailbaPending2XSegT:toString(): Error converting data to String"); aStr = null; } return aStr; } // INTERFACE IMPLEMENTATIONS // Super Overrides and extensions /** M O D E L O B J E C T O V E R R I D E * persistenceBroker() returns the .class name of the DatabaseBroker that * handles the I/O for this class. Used by DatabaseTransaction to commit * an object that extends Model. * @return Class DatabaseBroker Class Name */ // protected Class persistenceBrokerClass() { // return NailbaPending2XSegTDB.class; // } // end persistenceBrokerClass // SUPERCLASS INTERFACE IMPLEMENTATIONS // ACCESSORS public String getFreeFormText() { return m_freeFormText; } public void setFreeFormText(String aString) { m_freeFormText = aString; } } // end of class
JavaScript
UTF-8
2,210
2.53125
3
[]
no_license
import { put, takeLatest, all } from 'redux-saga/effects'; import axios from 'axios'; // Function sends get request to get all challenge photos and puts in reducer listening for 'SET_CHALLENGE_PHOTOS' function* fetchChallengePhotosSaga(action){ let response = yield axios({ method: 'GET', url: `/api/challengephotos`, }); console.log('CHALLENGEPHOTOS', response.data); yield put({ type: 'SET_CHALLENGE_PHOTOS', payload: response.data }); }; // Function sends photo creation data function* createPhotosSaga(action) { console.log('ACTION PAYLOAD', action.payload); let response = yield axios({ method: 'POST', url: '/api/photos', data: action.payload }); console.log('Response', response); }; // Function runs a delete request with action.payload.photo_id upon success throws back into fetch_captain_team_photos with action.payload.team_id function* denyPhotosSaga(action){ console.log('this is action dot payload DAVID ', action.payload) ; let response = yield axios({ method: 'DELETE', url: `/api/photos/${action.payload.photo_id}`, }); console.log('DELETEPHOTOS', response.data); yield put({ type: 'FETCH_CAPTAIN_TEAM_PHOTOS', payload: action.payload.team_id }); }; // Function runs a put request with action.payload.photo_id upon success throws back into fetch_captain_team_photos with action.payload.team_id function* approvePhotosSaga(action){ console.log('in approvephotos this is action.payload', action.payload); let response = yield axios({ method: 'PUT', url: `/api/photos/${action.payload.photo_id}`, }); console.log('APPROVEPHOTOS', response.data); yield put({ type: 'FETCH_CAPTAIN_TEAM_PHOTOS', payload: action.payload.team_id }); }; function* photosSaga() { yield takeLatest('CREATE_PHOTOS', createPhotosSaga); yield takeLatest('FETCH_CHALLENGE_PHOTOS', fetchChallengePhotosSaga); yield takeLatest('DELETE_PHOTOS', denyPhotosSaga); yield takeLatest('APPROVE_PHOTOS', approvePhotosSaga); }; export default photosSaga;
Markdown
UTF-8
2,702
3.296875
3
[ "MIT" ]
permissive
# AI in AEC - artificial intelligence in architecture, engineering and construction There is a dream that artificial intelligence could be very useful and productive in helping the built environment be updated faster, cheaper and better. The tools, the people, and the expertise are all available to make this dream happen. Why isn't it happening? The reason - as is so frequently the case with technology - the United States of America. Major CAD vendors are based in America and the biggest CAD market is America. Whatever works in America is what the vendors build. Whatever can't work in America is what the vendors avoid. Let's double click into this thought. The first idea that comes to mind with using AI and building is to use AI to help with designing according to the building codes. If we are talking about United Kingdom or Germany or a normal country. this would be in a eminently doable. But of market size has been too small for the vendors to venture into this field. In the United States, however, the market has been bin enough but there is no national building code that is actually national. Instead there are tens of thousands local codes - and most of those codes are behind paywalls. it would be a huge process to gather up all those codes and synthesize them into a reasonable AI-based workflow. A second idea would be to use AI to help with designing certain building types. AI systems could be very helpful in designing better schools. Again the issue is United States. There are 10,000 or school boards and each has its own peculiar megalomania. Beyond that the federal government and the states of government and local governments all have different ideas about supporting private or public schools. And so on. A third idea would be to drop down to a building products and component level. Heere it kind of gets interesting. the US market is dominated by slab on grade plasterboard on stud construction - with most designs being created by copying and pasting items from catalogs or selecting from spreadsheets. if you want a cheap building you go to America; if you want fine architecture you go to Europe. There may be AI possibilities in the American form of construction but it's hard to guess what that might be. Maybe teams of AI people can figure this out. ;-) if AI is to be helpful in the built environment * It is likely to be designed and first implemented outside of United States * It will be able to access a sufficiently large set of building codes and standards across large numbers of properties in order to generate income for the creators * The AI must be able to generate outcomes that are faster, cheaper and better then what we have now
JavaScript
UTF-8
11,991
2.609375
3
[]
no_license
// Store frame for motion functions var previousFrame = null; var paused = false; var waitGesture = true; var waitNavigate = false; var frameCount = 0; var prevSelect = 0; var circleCount = 0; var selected = false; var swipe = false; //var selection = ""; // Setup Leap loop with frame callback function var controllerOptions = {enableGestures: true}; //variables for webpages var swipe = 0; var inputNum = 0; var inputArray = [0, 0, 0, 0, 0, 0, 0, 0, 0]; var thumbsUp = 0; var thumbsDown = 0; var thumbConfirm = ""; var inputString = ""; var urls = ["index.html", "welcome.html", "account.html", "withdraw.html", "Deposit.html", "transactions.html", "success.html", "exit.html"]; // to use HMD mode: // controllerOptions.optimizeHMD = true; Leap.loop(controllerOptions, function(frame) { //get the current page var currentPage = getIndex(window.location.pathname.split("/").pop()); if (currentPage == 6 || currentPage == 7) { waitNavigate = true; } console.log(frameCount); selected = false; if (frameCount > 50) { waitGesture = false; } if (frameCount < 100 && (currentPage == 6 || currentPage == 7)) { waitNavigate = true; } else { waitNavigate = false; } console.log(waitNavigate); autoNavigate(currentPage); frameCount++; // Display Frame object data var frameOutput = document.getElementById("frameData"); var frameString = "Frame ID: " + frame.id + "<br />" + "Timestamp: " + frame.timestamp + " &micro;s<br />" + "Hands: " + frame.hands.length + "<br />" + "Fingers: " + frame.fingers.length + "<br />" + "Tools: " + frame.tools.length + "<br />" + "Gestures: " + frame.gestures.length + "<br />"; // Frame motion factors if (previousFrame && previousFrame.valid) { var translation = frame.translation(previousFrame); frameString += "Translation: " + vectorToString(translation) + " mm <br />"; var rotationAxis = frame.rotationAxis(previousFrame); var rotationAngle = frame.rotationAngle(previousFrame); frameString += "Rotation axis: " + vectorToString(rotationAxis, 2) + "<br />"; frameString += "Rotation angle: " + rotationAngle.toFixed(2) + " radians<br />"; var scaleFactor = frame.scaleFactor(previousFrame); frameString += "Scale factor: " + scaleFactor.toFixed(2) + "<br />"; } if (currentPage != 6 && currentPage != 7) frameOutput.innerHTML = "<div style='width:300px; float:left; padding:5px'>" + frameString + "</div>"; // var extendedOutput = document.getElementById("extended"); // var extendedString = ""; var extendedFingers = 0; // var inputOutput = document.getElementById("inputData"); //loop through hand and count extended fingers if (frame.hands.length > 0) { for (var i = 0; i < frame.hands.length; i++) { var hand = frame.hands[i]; extendedFingers = countExtended(hand); if (hand.type == "right") { if (hand.palmNormal[0] <= -.3) { var thumbPosition = "Thumbs Up"; thumbsUp += 1 } else if (hand.palmNormal[0] >= .3) { thumbPosition = "Thumbs Down"; thumbsDown += 1 } else { thumbPosition = "Fail"; } } else { if (hand.palmNormal[0] <= -.3) { thumbPosition = "Thumbs Down"; thumbsDown ++; } else if (hand.palmNormal[0] >= .3) { thumbPosition = "Thumbs Up"; thumbsUp ++; } else { thumbPosition = "Fail"; } } if (currentPage != 0) { var inputNum = findMax(); // var foo = document.getElementById("inputmax"); // foo.innerHTML = inputNum; if (currentPage != 3 && currentPage != 6 && currentPage != 4 && currentPage != 5 && currentPage != 7) { switch (inputNum) { case 1: if (prevSelect != 1) { reset(currentPage); var select = document.getElementById("select1"); select.innerHTML = "<img class='options' src='images/RightHand-1-select.svg'/>"; } break; case 2: if (prevSelect != 2) { reset(currentPage); var select = document.getElementById("select2"); select.innerHTML = "<img class='options' src='images/RightHand-2-select.svg'/>"; } break; case 3: if (prevSelect != 3) { reset(currentPage); var select = document.getElementById("select3"); select.innerHTML = "<img class='options' src='images/RightHand-3-select.svg'/>"; } break; } } //set previously selected option prevSelect = inputNum; if (confirmThumbs() == 1) { confirmSelection(currentPage); } else { if (extendedFingers > 0) { inputArray[extendedFingers - 1]++; } } checkInput(currentPage); } console.log(thumbsUp); } } // if (currentPage != 0) // extendedOutput.innerHTML = extendedFingers; if (frame.gestures.length > 0) { if (!waitGesture) { for (var i = 0; i < frame.gestures.length; i++) { var gesture = frame.gestures[i]; switch (gesture.type) { case "circle": circleCount++; if (circleCount > 60) exit(currentPage); break; case "swipe": swipe = true; navigate(currentPage); break; case "screenTap": break; case "keyTap": break; default: } } } } // Store frame for motion functions previousFrame = frame; }) function navigate(currentPage) { if (!waitNavigate) { console.log("navigating"); var newPageNum = 0; inputString = ""; if (swipe) { if (currentPage > 0) { if (currentPage != 3 && currentPage != 5 && currentPage != 6) { newPageNum = currentPage - 1; } if (currentPage == 5) { newPageNum = 2; } } else { newPageNum = currentPage + 1; } } else { if (confirmThumbs() == 1) { console.log("thumbs") console.log(currentPage); switch (currentPage) { case 1: console.log("got here"); newPageNum = 2; break; case 2: newPageNum = currentPage + prevSelect; break; case 3: newPageNum = 6; break; case 4: newPageNum = 6; break; } } } console.log("Current: " + currentPage); console.log(newPageNum); //reset and navigate if (newPageNum > 0) { reset(currentPage); window.location = urls[newPageNum]; } } } function confirmSelection(currentPage) { selected = true; switch (prevSelect) { case 1: window.name = "593882e4ceb8abe242517839"; break; case 2: window.name = "59389eaeceb8abe24251788e"; break; case 3: window.name = "59380fd0a73e4942cdafd723"; break; } if (currentPage != 3 || (currentPage == 3 && inputString.length >= 3)) { navigate(currentPage); } updateBoxes(currentPage); reset(currentPage); } function getIndex(url) { switch (url) { case "index.html": return 0; case "welcome.html": return 1; case "account.html": return 2; case "withdraw.html": return 3; case "Deposit.html": return 4; case "transactions.html": return 5; case "success.html": return 6; case "exit.html": return 7; default: return 0; } } function countExtended(hand) { var extended = 0; for(var f = 0; f < hand.fingers.length; f++){ var finger = hand.fingers[f]; if(finger.extended) extended++; } return extended; } function confirmThumbs() { if (thumbsUp >= 100) { console.log("thumbs confirmed") return 1; } else if (thumbsDown >= 100) { return -1; } else { return 0; } } function findMax() { var maxCount = 0; var maxIndex = 0; for (var i = 0; i < inputArray.length; i++) { if (maxCount < inputArray[i]) { maxCount = inputArray[i]; maxIndex = i; } } return maxIndex+1; } function autoNavigate(currentPage) { if (currentPage == 7 || currentPage == 6) { if (frameCount > 200) { switch (currentPage) { case 6: window.location = urls[2]; break; case 7: window.location = urls[0]; break; } } } } function vectorToString(vector, digits) { if (typeof digits === "undefined") { digits = 1; } return "(" + vector[0].toFixed(digits) + ", " + vector[1].toFixed(digits) + ", " + vector[2].toFixed(digits) + ")"; } function togglePause() { paused = !paused; // if (paused) { // document.getElementById("pause").innerText = "Resume"; // } else { // document.getElementById("pause").innerText = "Pause"; // } } function pauseForGestures() { if (document.getElementById("pauseOnGesture").checked) { pauseOnGesture = true; } else { pauseOnGesture = false; } } function reset(currentPage) { //reset counting array for (var i = 0; i < inputArray.length; i++) { inputArray[i] = 0; } //reset counting variables thumbsUp = 0; thumbsDown = 0; circleCount = 0; if (currentPage == 1 || currentPage == 2) { var select1 = document.getElementById("select1"); select1.innerHTML = "<img class='options' src='images/RightHand-1-tilt.svg'/>"; var select2 = document.getElementById("select2"); select2.innerHTML = "<img class='options' src='images/RightHand-2-tilt.svg'/>"; var select3 = document.getElementById("select3"); select3.innerHTML = "<img class='options' src='images/RightHand-3-tilt.svg'/>"; } } function updateBoxes(currentPage) { if (currentPage == 3) { //access elements w0put = document.getElementById("w0"); w1put = document.getElementById("w1"); w2put = document.getElementById("w2"); console.log(inputString.length); console.log(inputString); switch (inputString.length) { case 1: w2put.innerHTML = inputString; break; case 2: w2put.innerHTML = inputString.charAt(1); w1put.innerHTML = inputString.charAt(0); break; case 3: w2put.innerHTML = inputString.charAt(2); w1put.innerHTML = inputString.charAt(1); w0put.innerHTML = inputString.charAt(0); console.log("Amount: " + inputString); deposit(window.name, Number(inputString)); break; } } } function checkInput(currentPage) { if (currentPage == 3) { var difference = 0; for (var i = 0; i < inputArray.length - 1; i++) { if (difference < Math.abs(inputArray[i] - inputArray[i+1])) difference = Math.abs(inputArray[i] - inputArray[i+1]); } } if (difference > 100) { inputString += findMax().toString(); updateBoxes(currentPage); reset(); } } function exit(currentPage) { if (currentPage != 3) { reset(currentPage); window.location = "exit.html"; } } function displaySelected(){ var nick = document.getElementById("nick"); getNickname(window.name, nick); var balance = document.getElementById("balance"); getBalance(window.name,balance); } var curPage = window.location.pathname.split("/").pop(); if(curPage === "account.html" && window.name != ""){ displaySelected(); } //New code if(curPage === "success.html" && window.name != ""){ var rembal = document.getElementById("rembalance"); getBalance(window.name, rembal); } if(curPage == "transactions.html" && window.name != ""){ var table = document.getElementById("trans"); getPurchases(window.name, table); var nick = document.getElementById("nick"); getNickname(window.name, nick); }
Python
UTF-8
6,974
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- import urllib from bs4 import BeautifulSoup import urllib.request as request import re import sqlite3 import os from datetime import datetime class Crawler(object): def __init__(self, db_path, use_proxies=False): self.con = sqlite3.connect(db_path) self.cursor = self.con.cursor() self.ignore_words = {'the', 'of', 'to', 'and', 'a', 'in', 'is', 'it'} self.headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36' } proxies = { 'https': 'https://127.0.0.1:1087', 'http': 'http://127.0.0.1:1087' } self.opener = request.build_opener(request.ProxyHandler( proxies)) if use_proxies else request.build_opener() request.install_opener(self.opener) def __del__(self): self.cursor.close() self.con.close() def db_commit(self): self.con.commit() def creat_db_tables(self): self.cursor.execute( 'create table url_list(id integer primary key autoincrement, \ url varchar(200) not null)') self.cursor.execute( 'create table word_list(id integer primary key autoincrement, \ word varchar(50) not null)') self.cursor.execute( 'create table word_location(id integer primary key autoincrement, \ url_id integer,\ word_id integer,\ location integer)') self.cursor.execute( 'create table link(id integer primary key autoincrement,\ from_id integer,\ to_id integer)') self.cursor.execute( 'create table link_words(id integer primary key autoincrement,\ word_id integer,\ link_id integer)') self.cursor.execute('create index word_idx on word_list(word)') self.cursor.execute('create index url_idx on url_list(url)') self.cursor.execute( 'create index word_url_idx on word_location(word_id)') self.cursor.execute('create index url_to_idx on link(to_id)') self.cursor.execute('create index url_from_idx on link(from_id)') self.db_commit() def add_to_index(self, url, soup): if self.has_indexed(url): return # print('Indexing %s' % url) # 获取每个单词 text = self.get_text_only(soup) words = self.separate_words(text) # 得到URL的id url_id = self.get_entry_id('url_list', 'url', url) # 将每个单词与该url关联 for i in range(len(words)): word = words[i] if word in self.ignore_words: continue word_id = self.get_entry_id('word_list', 'word', word) self.cursor.execute( "insert into word_location(url_id,word_id,location) values (?,?,?)", (url_id, word_id, i)) def get_text_only(self, soup): v = soup.string if v == None: c = soup.contents if c != []: resulttext = '' for t in c: subtext = self.get_text_only(t) resulttext += subtext + '\n' return resulttext else: return '' else: return v.strip() def separate_words(self, text): return [s.lower() for s in re.split(r'\W*', text) if s != ''] def has_indexed(self, url): u = self.cursor.execute("select id from url_list where url=?", (url, )).fetchone() if u != None: v = self.cursor.execute( "select * from word_location where url_id=?", (u[0], )).fetchone() if v != None: return True return False def get_entry_id(self, table, field, value, create_new=True): self.cursor.execute("select rowid from {} where {}=?".format( table, field), (value, )) res = self.cursor.fetchone() if res == None: self.cursor.execute("insert into {}({}) values(?)".format( table, field), (value, )) return self.cursor.lastrowid else: return res[0] def add_link_ref(self, urlFrom, urlTo, linkText): words = self.separate_words(linkText) from_id = self.get_entry_id('url_list', 'url', urlFrom) to_id = self.get_entry_id('url_list', 'url', urlTo) if from_id == to_id: return cur = self.cursor.execute( "insert into link(from_id,to_id) values (?,?)", (from_id, to_id)) link_id = cur.lastrowid for word in words: if word in self.ignore_words: continue word_id = self.get_entry_id('word_list', 'word', word) self.cursor.execute( "insert into link_words(link_id,word_id) values (?,?)", (link_id, word_id)) def crawl(self, init_url, depth=1): pages = [init_url] for i in range(depth): new_layer_pages = set() print('-----------layer %s has %s pages-----------' % (i, len(pages))) for j, page in enumerate(pages): try: req = request.Request(page, headers=self.headers) c = request.urlopen(req) except Exception as e: print('could not open %s\nBecause:' % page, e) continue soup = BeautifulSoup(c.read(), 'lxml') self.add_to_index(page, soup) print('has indexed %3.2f %%:' % ((j + 1) / len(pages) * 100), page) links = soup('a') for k, link in enumerate(links): if 'href' in link.attrs: url = urllib.parse.urljoin(page, link['href']).split('#')[0] country = re.search(r'(\w{2}).wikipedia.org', url) if country == None or (country != None and country.group(1) != 'en' ) or url.find("'") != -1: continue if i<2 and url[:4] == 'http' and not self.has_indexed(url): new_layer_pages.add(url) linkText = self.get_text_only(link) self.add_link_ref(page, url, linkText) self.db_commit() pages = new_layer_pages self.db_commit() return
Shell
UTF-8
382
3.625
4
[]
no_license
#!/bin/bash git_status_improved__() { local filename="$1" gitstatus_result="$(git status -s --ignored $filename)" if [[ -z "$gitstatus_result" ]]; then git_tracked_files=$(git ls-files | grep $filename) if [[ -z "$git_tracked_files" ]]; then echo "?? $filename" else echo "[Good] $filename" fi else echo "$gitstatus_result" fi } git_status_improved__ "$@"
Python
UTF-8
1,133
3.96875
4
[]
no_license
""" 142:环形链表2 https://leetcode-cn.com/problems/linked-list-cycle-ii/ 判断环形链表是不是会相交 快慢指针,如果两个链表相交,那么让快的指针指向头节点 两个指针速度一样往前走,碰面的地方就是交点. """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: if not head:return None if head==head.next:return head slow=fast=head i=0 meet=False while fast and fast.next: slow=slow.next fast=fast.next.next if slow==fast: meet=True break if slow==fast and meet: ###为了判断是哪一种情况跳出循环的,证明确实相遇之后,而不是因为fast到头了. fast=head else: return None while fast: if fast==slow: return fast else: fast=fast.next slow=slow.next i+=1
Java
UTF-8
2,299
2.0625
2
[]
no_license
package cn.piesat.minemonitor.mapdata.base; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; import butterknife.Unbinder; public abstract class BaseFragment extends Fragment { Unbinder unbinder; public abstract int getLayoutId(); public abstract void loadingData(); @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = View.inflate(getContext(), getLayoutId(), null); unbinder = ButterKnife.bind(this, rootView); loadingData(); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); } public void toActivity(Class<?> toClsActivity) { toActivity(toClsActivity, null); } public void toActivity(Class<?> toClsActivity, Bundle bundle) { Intent intent = new Intent(getContext(), toClsActivity); if (bundle != null) { intent.putExtras(bundle); } startActivity(intent); } public void toActivityForResult(Class<?> toClsActivity,int requestCode){ toActivityForResult(toClsActivity,null,requestCode); } public void toActivityForResult(Class<?> toClsActivity, Bundle bundle,int requestCode){ Intent intent = new Intent(getContext(), toClsActivity); if (bundle != null) { intent.putExtras(bundle); } getActivity().startActivityForResult(intent,requestCode); } public void setResult(Class<?> toClsActivity,int requestCode){ toActivityForResult(toClsActivity,null,requestCode); } public void setResult(Class<?> toClsActivity, Bundle bundle,int resultCode){ Intent intent = new Intent(getContext(), toClsActivity); if (bundle != null) { intent.putExtras(bundle); } getActivity().setResult(resultCode,intent); } }