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
JavaScript
UTF-8
3,065
2.71875
3
[ "MIT" ]
permissive
'use babel'; import { Point, TextEditor } from 'atom'; class GoToLineView { constructor() { this.miniEditor = new TextEditor({ mini: true }); this.miniEditor.element.addEventListener('blur', this.close.bind(this)); this.message = document.createElement('div'); this.message.classList.add('message'); this.element = document.createElement('div'); this.element.classList.add('go-to-line'); this.element.appendChild(this.miniEditor.element); this.element.appendChild(this.message); this.panel = atom.workspace.addModalPanel({ item: this, visible: false }); atom.commands.add('atom-text-editor', 'go-to-line:toggle', () => { this.toggle(); return false; }); atom.commands.add(this.miniEditor.element, 'core:confirm', () => { this.navigate(); }); atom.commands.add(this.miniEditor.element, 'core:cancel', () => { this.close(); }); this.miniEditor.onWillInsertText(arg => { if (arg.text.match(/[^0-9:]/)) { arg.cancel(); } }); this.miniEditor.onDidChange(() => { this.navigate({ keepOpen: true }); }); } toggle() { this.panel.isVisible() ? this.close() : this.open(); } close() { if (!this.panel.isVisible()) return; this.miniEditor.setText(''); this.panel.hide(); if (this.miniEditor.element.hasFocus()) { this.restoreFocus(); } } navigate(options = {}) { const lineNumber = this.miniEditor.getText(); const editor = atom.workspace.getActiveTextEditor(); if (!options.keepOpen) { this.close(); } if (!editor || !lineNumber.length) return; const currentRow = editor.getCursorBufferPosition().row; const rowLineNumber = lineNumber.split(/:+/)[0] || ''; const row = rowLineNumber.length > 0 ? parseInt(rowLineNumber) - 1 : currentRow; const columnLineNumber = lineNumber.split(/:+/)[1] || ''; const column = columnLineNumber.length > 0 ? parseInt(columnLineNumber) - 1 : -1; const position = new Point(row, column); editor.setCursorBufferPosition(position); editor.unfoldBufferRow(row); if (column < 0) { editor.moveToFirstCharacterOfLine(); } editor.scrollToBufferPosition(position, { center: true }); } storeFocusedElement() { this.previouslyFocusedElement = document.activeElement; return this.previouslyFocusedElement; } restoreFocus() { if ( this.previouslyFocusedElement && this.previouslyFocusedElement.parentElement ) { return this.previouslyFocusedElement.focus(); } atom.views.getView(atom.workspace).focus(); } open() { if (this.panel.isVisible() || !atom.workspace.getActiveTextEditor()) return; this.storeFocusedElement(); this.panel.show(); this.message.textContent = 'Enter a <row> or <row>:<column> to go there. Examples: "3" for row 3 or "2:7" for row 2 and column 7'; this.miniEditor.element.focus(); } } export default { activate() { return new GoToLineView(); } };
Java
UTF-8
1,736
2.65625
3
[]
no_license
package com.aoa.springwebservice.dto; import com.aoa.springwebservice.domain.Menu; import com.aoa.springwebservice.domain.Store; import java.io.Serializable; public class MenuDTO implements Serializable { protected String name; protected int price; protected String description; protected String imageUrl; public MenuDTO() { } public MenuDTO(String name, int price, String description, String imageUrl) { this.name = name; this.price = price; this.description = description; this.imageUrl = imageUrl; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public Menu toDomain() { return toDomain(null); } public Menu toDomain(Store store) { return toDomain(store, imageUrl); } public Menu toDomain(Store store, String imageUrl) { return new Menu(name, price, description, imageUrl, store); } @Override public String toString() { return "MenuDTO{" + "name='" + name + '\'' + ", price=" + price + ", description='" + description + '\'' + ", imageUrl='" + imageUrl + '\'' + '}'; } }
JavaScript
UTF-8
601
2.828125
3
[]
no_license
function update_username() { var username = document.getElementById('username').value; var user_id = document.getElementById('user_id').innerHTML; var user = { username: username }; var xhttp = new XMLHttpRequest(); xhttp.open('PUT', '/user/' + user_id, true); xhttp.setRequestHeader('Content-Type', 'application/json') xhttp.onreadystatechange = function () { if (xhttp.readyState == 4) { if (xhttp.status == 200) { window.location = "/profile"; } else { console.log("post failed"); } } } xhttp.send(JSON.stringify(user)); }
Java
UTF-8
863
2.578125
3
[]
no_license
package edu.pucmm; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Created by anyderre on 04/06/17. */ public class ConnectionDB { private final String url="jdbc:h2:./practica3db"; private final String username="sa"; private final String password=""; public ConnectionDB(){ RegistrarDriver(); } public Connection getConnection(){ Connection connection= null; try { connection = DriverManager.getConnection(this.url, this.username, this.password); } catch (SQLException e) { e.printStackTrace(); } return connection; } public void RegistrarDriver (){ try { Class.forName("org.h2.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
Markdown
UTF-8
585
3.5625
4
[]
no_license
## 分而治之 ### 分而治之是什么? - 分而治之是算法设计中的一种方法。 - 它将一个问题分成多个和原问题相似的小问题,递归解决小问题,再将结果合并以解决原来的问题。 ### 场景一:归并排序 - 分: 把数组从中间一分为二。 - 解: 递归地对两个子数组进行归并排序。 - 合: 合并有序子数组。 ### 场景二:快速排序 - 分:选基准,按基准把数组分成两个子数组。 - 解:递归地两个子数组进行快速排序。 - 合:对两个子数组进行合并。
JavaScript
UTF-8
1,620
2.8125
3
[ "MIT" ]
permissive
import React, { Component } from "react"; import "./background.css"; import imageSources from './images.json'; let container = null; let images = imageSources let _images = [] let imgLoc = "" let index = 0 let screenWidth = 0 export class Background extends Component { componentDidMount() { screenWidth = window.screen.width; container = document.getElementById("background"); this.loadImages(); window.requestAnimationFrame(() => { this.moveImages() }); } getRandomInRange = (min, max) => { return Math.floor(Math.random() * (max - min + 1)) + min; } preloadImage = (filename) => { let img = new Image(300, 500); img.xPlane = this.getRandomInRange(-500, screenWidth - 1000); img.yPlane = this.getRandomInRange(500, 1000); img.zPlane = this.getRandomInRange(300, 2000); img.style = "transform: translate3d(" + img.xPlane + "px, " + img.yPlane + "px, -" + img.zPlane + "px);"; container.appendChild(img); imgLoc = ""; img.src = imgLoc + filename; img.alt = ""; _images[index] = img; index++; } loadImages = () => { for (let i = 0; i < images.length; ++i) { let filename = images[i]; this.preloadImage(filename); } } moveImages = () => { _images.forEach((image) => { image.yPlane = image.yPlane - 2; image.style.cssText = "transform: translate3d(" + image.xPlane + "px, " + image.yPlane + "px, -" + image.zPlane + "px); z-index: " + image.zIndex; }); window.requestAnimationFrame(() => { this.moveImages() }); } render() { return ( <div id="background"></div> ) } }
Shell
UTF-8
1,354
3.796875
4
[ "ISC" ]
permissive
#!/bin/sh RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' # No Color okMsg="[${GREEN}OK${NC}]" errorMsg="[${RED}ERR${NC}]" for file in ./store/DEV/*; do input=$(echo "$file"| sed -E "s/\.\/store\/DEV\///g" | sed -E "s/\.\///g"); output=$(echo "$input" | sed -E "s/ DEV$//g"); echo ":: $input"; if $(markdown-pp "$file/$input.mdpp" -o "$file/$input.md" 2> /dev/null) then echo $okMsg "Transpiling..." #-- Add MD name into the local .gitignore # cd "$file"; # gitignore=".gitignore" # if [ ! -f $gitignore ] || [ ! -s $gitignore ]; then # echo "$input.md" > $gitignore # echo $okMsg "MD gitignore created..." # else # flag=false # while IFS="" read -r p || [ -n "$p" ] # do # line=$(printf '%s\n' "$p") # if [[ "$line" == "$input.md" ]] # then # flag=true # fi # done < $gitignore # if [[ "$flag" == false ]] # then # if [[ ! $(tail -c1 $gitignore | wc -l) -gt 0 ]] # then # echo "" >> $gitignore # fi # echo "$input.md" >> $gitignore # echo $okMsg "MD gitignored updated..." # fi # fi # cd ~- #-- Move file in the release folder if mv "./store/DEV/$input/$input.md" "./store/$output/$output.md" 2> /dev/null then echo $okMsg "Releasing..." else echo $errorMsg "Releasing..." fi else echo $errorMsg "Transpiling..." fi echo "" done
C++
UTF-8
2,624
2.609375
3
[ "Artistic-2.0", "MIT" ]
permissive
/* * Copyright (c) 2003-2023 Rony Shapiro <ronys@pwsafe.org>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ /** * \file Linux-specific implementation of utf8conv.h */ #include "../typedefs.h" #include "../utf8conv.h" #include <cstdlib> #include <clocale> #include <langinfo.h> #include <cassert> #include <cstring> #include <string> #include <unistd.h> using namespace std; class Startup { public: Startup() { // Since this can fail before main(), we can't rely on cerr etc. // being initialized. At least give the user a clue... char *gl = setlocale(LC_ALL, nullptr); char *sl = setlocale(LC_ALL, ""); if (sl == nullptr) { // Couldn't get environment-specified locale, warn user // and punt to default "C" char wrnmess[] = "Couldn't load locale, falling back to default\n"; (void) write(STDERR_FILENO, wrnmess, sizeof(wrnmess)/sizeof(*wrnmess)-1); sl = setlocale(LC_ALL, gl); } if (sl == nullptr) { // If we can't get the default, we're really FUBARed char errmess[] = "Couldn't initialize locale - bailing out\n"; (void) write(STDERR_FILENO, errmess, sizeof(errmess)/sizeof(*errmess)-1); _exit(2); } if (strcmp(nl_langinfo(CODESET), "UTF-8")){ char errmess[] = "Current locale doesn't support UTF-8\n"; (void) write(STDERR_FILENO, errmess, sizeof(errmess)/sizeof(*errmess)-1); } } }; static Startup startup; size_t pws_os::wcstombs(char *dst, size_t maxdstlen, const wchar_t *src, size_t , bool ) { return ::wcstombs(dst, src, maxdstlen) + 1; } size_t pws_os::mbstowcs(wchar_t *dst, size_t maxdstlen, const char *src, size_t , bool ) { return ::mbstowcs(dst, src, maxdstlen) + 1; } wstring pws_os::towc(const char *val) { wstring retval(L""); assert(val != nullptr); size_t len = strlen(val); int wsize; const char *p = val; wchar_t wvalue; while (len > 0) { wsize = mbtowc(&wvalue, p, MB_CUR_MAX); if (wsize <= 0) break; retval += wvalue; p += wsize; len -= wsize; }; return retval; } std::string pws_os::tomb(const stringT& val) { if (!val.empty()) { const size_t N = std::wcstombs(nullptr, val.c_str(), 0); assert(N > 0); char* szstr = new char[N+1]; szstr[N] = 0; std::wcstombs(szstr, val.c_str(), N); std::string retval(szstr); delete[] szstr; return retval; } else return string(); }
PHP
UTF-8
12,493
2.78125
3
[]
no_license
<?php class Exposicion_model extends CI_Model { public $NOMBRE_TABLA = "exposicion"; private $sql; public function __construct() { parent::__construct(); $this->load->database(); $this->sql = "SELECT *, year(fecha_inicio) 'ano', ( SELECT 1 + (-0.1*(TRUNCATE((DATEDIFF(CURDATE(), fecha_inicio) /365),0) )) ) 'alfa' FROM " . $this->NOMBRE_TABLA; } public function getTodos($idCondicion = NULL, $orden = NULL) { $where = " where 1=1"; if($idCondicion !== NULL) $where.= " and id_condicion=$idCondicion"; $order_by = ""; if($orden !== NULL) $order_by =" order by fecha_fin asc"; $sql = $this->sql." $where $order_by"; return $this->db->query($sql)->result(); } public function getVisibles($idCondicion = NULL) { $where = " where visible=1"; if($idCondicion !== NULL) $where.= " and id_condicion=$idCondicion"; $order_by = " order by fecha_fin asc"; $sql = $this->sql." $where $order_by"; return $this->db->query($sql)->result(); } public function get($id) { return $this->db->query($this->sql . " where id=$id")->row(); } /** * Agrega una exposición basado en los datos de la ficha técnica * @param \FichaTecnica $ficha * @return int Id de la exposición creada */ public function agregar($ficha) { $datos = array( "nombre" => $ficha->nombreExpo, "descripcion" => $ficha->descExpo, "nota" => $ficha->notaExpo, "id_disciplina" => $ficha->idDisciplina, "id_condicion" => $ficha->idCondicion, "id_disponibilidad" => $ficha->idDisponibilidad, "id_sede" => $ficha->idSede, "id_usuario" => 0, //TODO ); if (!empty($ficha->fechaInicioExpo)) $datos["fecha_inicio"] = $ficha->fechaInicioExpo; if (!empty($ficha->fechaFinExpo)) $datos["fecha_fin"] = $ficha->fechaFinExpo; $this->db->insert($this->NOMBRE_TABLA, $datos); return $this->db->insert_id(); } /** * Actualiza la exposición con los datos proporcionados * @param int $idExpo Id de la exposición a actualizar * @param array $datos Datos a actualizar */ public function actualizar($idExpo, $datos) { return $this->db->update($this->NOMBRE_TABLA, $datos, array("id" => $idExpo)); } /** * Actualiza visibilidad del registro * @param int $idExpo * @return type */ public function publicar($idExpo){ $datos["visible"] = 1; return $this->actualizar($idExpo, $datos); } /** * Actualiza visibilidad del registro * @param int $idExpo * @return type */ public function ocultar($idExpo){ $datos["visible"] = 0; return $this->actualizar($idExpo, $datos); } /** * Devuelve un arreglo con estructuras de información con detalles básicos de las exposiciones * @param int $idCondicion Filtro por condición * @return array Arreglo con arreglos que detallan exposiciones encontradas con la condición especificada */ public function getDetalles($idCondicion){ /*$this->output->set_header('Content-Type: application/json; charset=utf-8');*/ $salida = array(); $tagError = "error"; $this->load->model("disciplina_model"); $this->load->model("condicion_model"); $this->load->model("sede_model"); $this->load->model("disponibilidad_model"); $this->load->model("autor_model"); $this->load->model("obra_model"); $this->load->model("obra_x_multimedio_model"); $this->load->model("multimedio_model"); //Consulta exposiciones y valida si hay resultados $exposiciones = $this->getVisibles($idCondicion); foreach ($exposiciones as $exposicion) { $disciplina = $this->disciplina_model->get($exposicion->id_disciplina); if (empty($disciplina)) { $salida = array($tagError => "No existe disciplina con id " . $exposicion->id_disciplina); //$this->escribirJson($salida); return $salida; } $condicion = $this->condicion_model->get($exposicion->id_condicion); if (empty($condicion)) { $salida = array($tagError => "No existe condición con id " . $exposicion->id_condicion); //$this->escribirJson($salida); return $salida; } $sede = $this->sede_model->get($exposicion->id_sede); if (empty($sede)) { $salida = array($tagError => "No existe sede con id " . $exposicion->id_sede); //$this->escribirJson($salida); return $salida; } $disponibilidad = $this->disponibilidad_model->get($exposicion->id_disponibilidad); if (empty($disponibilidad)) { $salida = array($tagError => "No existe disponibilidad con id " . $exposicion->id_disponibilidad); //$this->escribirJson($salida); return $salida; } $alfaFinal = (double) $exposicion->alfa; if ($alfaFinal > 1) $alfaFinal = 1; if ($alfaFinal < 0.1) $alfaFinal = 0.1; //Llenado de datos Exposición $exposicionSalida = array("id" => $exposicion->id, "nombre" => $exposicion->nombre, "descripcion" => $exposicion->descripcion, "nota" => $exposicion->nota, "idDisciplina" => $exposicion->id_disciplina, "disciplina" => $disciplina->nombre, "idCondicion" => $exposicion->id_condicion, "condicion" => $condicion->nombre, "idSede" => $exposicion->id_sede, "sede" => $sede->nombre, "disponibilidad" => $disponibilidad->nombre, "ano" => $exposicion->ano, "inicio" => $exposicion->fecha_inicio, "fin" => $exposicion->fecha_fin, "color" => $disciplina->color, "alfa" => $alfaFinal, "borde" => $condicion->borde, "carpeta_multimedios" => $exposicion->carpeta_multimedios, "icono" => $sede->icono); if ($exposicion->archivo_thumbnail != '') $exposicionSalida["archivo_thumbnail"] = $this->getInfoArchivo($exposicion->archivo_thumbnail); if ($exposicion->archivo_portada != '') $exposicionSalida["archivo_portada"] = $this->getInfoArchivo($exposicion->archivo_portada); $salida[] = $exposicionSalida; }//fin ciclo exposiciones //$this->escribirJson($salida); return $salida; } /** * Devuelve una estructura de información con detalles profundos de la exposición * @param int $idExpo id de la exposición * @return array Detalles de la exposición ó detalles de error */ public function getDetallesExposicion($idExpo = 0){ //$this->output->set_header('Content-Type: application/json; charset=utf-8'); $salida = array(); $tagError = "error"; $this->load->model("disciplina_model"); $this->load->model("condicion_model"); $this->load->model("sede_model"); $this->load->model("disponibilidad_model"); $this->load->model("autor_model"); $this->load->model("obra_model"); $this->load->model("obra_x_multimedio_model"); $this->load->model("multimedio_model"); $this->load->model("articulo_model"); $this->load->model("hoja_model"); if ($idExpo == 0 || !is_numeric($idExpo)) { $salida = array($tagError => "No se especificó id numérico de exposición"); //$this->escribirJson($salida); return $salida; } //Consulta exposiciones y valida si hay resultados $exposicion = $this->get($idExpo); if (empty($exposicion)) { $salida = array($tagError => "Exposición con id $idExpo no existe"); //$this->escribirJson($salida); return $salida; } $disciplina = $this->disciplina_model->get($exposicion->id_disciplina); if (empty($disciplina)) { $salida = array($tagError => "No existe disciplina con id " . $exposicion->id_disciplina); //$this->escribirJson($salida); return $salida; } $condicion = $this->condicion_model->get($exposicion->id_condicion); if (empty($condicion)) { $salida = array($tagError => "No existe condición con id " . $exposicion->id_condicion); //$this->escribirJson($salida); return $salida; } $sede = $this->sede_model->get($exposicion->id_sede); if (empty($sede)) { $salida = array($tagError => "No existe sede con id " . $exposicion->id_sede); //$this->escribirJson($salida); return $salida; } $disponibilidad = $this->disponibilidad_model->get($exposicion->id_disponibilidad); if (empty($disponibilidad)) { $salida = array($tagError => "No existe disponibilidad con id " . $exposicion->id_disponibilidad); //$this->escribirJson($salida); return $salida; } $alfaFinal = (double) $exposicion->alfa; if ($alfaFinal > 1) $alfaFinal = 1; if ($alfaFinal < 0.1) $alfaFinal = 0.1; //Llenado de datos Exposición $salida = array("id" => $idExpo, "nombre" => $exposicion->nombre, "descripcion" => $exposicion->descripcion, "nota" => $exposicion->nota, "idDisciplina" => $exposicion->id_disciplina, "disciplina" => $disciplina->nombre, "idCondicion" => $exposicion->id_condicion, "condicion" => $condicion->nombre, "idSede" => $exposicion->id_sede, "sede" => $sede->nombre, "disponibilidad" => $disponibilidad->nombre, "ano" => $exposicion->ano, "inicio" => $exposicion->fecha_inicio, "fin" => $exposicion->fecha_fin, "color" => $disciplina->color, "alfa" => $alfaFinal, "borde" => $condicion->borde, "carpeta_multimedios" => $exposicion->carpeta_multimedios, "icono" => $sede->icono); if ($exposicion->archivo_thumbnail != '') $salida["archivo_thumbnail"] = $this->getInfoArchivo($exposicion->archivo_thumbnail); if ($exposicion->archivo_portada != '') $salida["archivo_portada"] = $this->getInfoArchivo($exposicion->archivo_portada); if ($exposicion->archivo_contraportada != '') $salida["archivo_contraportada"] = $this->getInfoArchivo($exposicion->archivo_contraportada); if ($exposicion->archivo_pieza_principal_1 != '') $salida["archivo_pieza_principal_1"] = $this->getInfoArchivo($exposicion->archivo_pieza_principal_1); if ($exposicion->archivo_pieza_principal_2 != '') $salida["archivo_pieza_principal_2"] = $this->getInfoArchivo($exposicion->archivo_pieza_principal_2); if ($exposicion->archivo_pieza_principal_3 != '') $salida["archivo_pieza_principal_3"] = $this->getInfoArchivo($exposicion->archivo_pieza_principal_3); if ($exposicion->archivo_pieza_principal_4 != '') $salida["archivo_pieza_principal_4"] = $this->getInfoArchivo($exposicion->archivo_pieza_principal_4); if ($exposicion->archivo_pieza_principal_5 != '') $salida["archivo_pieza_principal_5"] = $this->getInfoArchivo($exposicion->archivo_pieza_principal_5); //Consulta autores y valida si hay resultados $autores = $this->autor_model->getEnExposicion($idExpo); if (empty($autores)) { $salida = array($tagError => "No existen autores en la exposición $idExpo"); //$this->escribirJson($salida); return $salida; } $listaAutores = array(); //Recorre autores foreach ($autores as $autor) { $autorSalida = array("nombre" => $autor->nombre); $listaObras = array(); //Recorremos obras del autor $obras = $this->obra_model->getConAutor($autor->id); foreach ($obras as $obra) { $obraSalida = array("titulo" => $obra->titulo, "comentario" => $obra->comentario, "elaboracion" => $obra->elaboracion, "tecnica" => $obra->tecnica, "dimensiones" => $obra->dimensiones); $listaMultimedios = array(); //Recorremos multimedios de la obra $multimedios = $this->obra_x_multimedio_model->getConObra($obra->id); foreach ($multimedios as $multimedio) $listaMultimedios[] = $this->getInfoArchivo($multimedio->id_multimedio); $obraSalida["multimedios"] = $listaMultimedios; $listaObras[] = $obraSalida; } $autorSalida["obras"] = $listaObras; $listaAutores[] = $autorSalida; } $salida["autores"] = $listaAutores; //Consulta artículos $articulos_x_expo = $this->articulo_model->getEnExposicion($idExpo); $listaArticulos = array(); //Recorre articulos foreach ($articulos_x_expo as $articulo_expo) { $articulo = $this->articulo_model->get($articulo_expo->id_articulo); $articuloSalida = array("nombre" => $articulo->nombre, "autor" => $articulo->autor, "referencia" => $articulo->referencia); $listaHojas = array(); //Recorremos hojas del articulo $hojas = $this->hoja_model->getConArticulo($articulo->id); foreach ($hojas as $hoja) { $listaHojas[] = $hoja->html; } $articuloSalida["hojas"] = $listaHojas; $listaArticulos[] = $articuloSalida; } $salida["articulos"] = $listaArticulos; //$this->escribirJson($salida); return $salida; } private function getInfoArchivo($idArchivo, $incluirPath = FALSE) { $archivo = $this->multimedio_model->get($idArchivo); if (empty($archivo)) return NULL; $salida = array("nombre" => $archivo->nombre_archivo, "tipo" => $archivo->tipo_archivo); if ($incluirPath === TRUE) $salida["carpeta"] = $archivo->path; return $salida; } }
Java
UTF-8
91,234
2.1875
2
[ "Apache-2.0" ]
permissive
package io.reactiverse.pgclient; import io.reactiverse.pgclient.data.Interval; import io.reactiverse.pgclient.data.Json; import io.reactiverse.pgclient.data.Numeric; import io.reactiverse.pgclient.data.Point; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import org.junit.Test; import java.math.BigDecimal; import java.time.*; import java.time.format.DateTimeFormatter; import java.util.*; import java.util.function.BiFunction; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author <a href="mailto:emad.albloushi@gmail.com">Emad Alblueshi</a> */ public class DataTypeExtendedEncodingTest extends DataTypeTestBase { @Override protected PgConnectOptions options() { return new PgConnectOptions(options).setCachePreparedStatements(false); } @Test public void testDecodeBoolean(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Boolean\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Boolean") .returns(Tuple::getValue, Row::getValue, true) .returns(Tuple::getBoolean, Row::getBoolean, true) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeBoolean(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Boolean\" = $1 WHERE \"id\" = $2 RETURNING \"Boolean\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addBoolean(Boolean.FALSE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Boolean") .returns(Tuple::getValue, Row::getValue, false) .returns(Tuple::getBoolean, Row::getBoolean, false) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeEnum(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"currentMood\" FROM \"EnumDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "currentMood") .returns(Tuple::getValue, Row::getValue, "ok") .returns(Tuple::getString, Row::getString, "ok") .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeEnum(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"EnumDataType\" SET \"currentMood\" = $1 WHERE \"id\" = $2 RETURNING \"currentMood\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("happy") .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "currentMood") .returns(Tuple::getValue, Row::getValue, "happy") .returns(Tuple::getString, Row::getString, "happy") .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeInt2(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Short\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, (short) 32767) .returns(Tuple::getShort, Row::getShort, Short.MAX_VALUE) .returns(Tuple::getInteger, Row::getInteger, 32767) .returns(Tuple::getLong, Row::getLong, 32767L) .returns(Tuple::getFloat, Row::getFloat, 32767f) .returns(Tuple::getDouble, Row::getDouble, 32767d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(32767)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(32767)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInt2(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Short\" = $1 WHERE \"id\" = $2 RETURNING \"Short\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(Short.MIN_VALUE, 2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, (short) -32768) .returns(Tuple::getShort, Row::getShort, Short.MIN_VALUE) .returns(Tuple::getInteger, Row::getInteger, -32768) .returns(Tuple::getLong, Row::getLong, -32768L) .returns(Tuple::getFloat, Row::getFloat, -32768f) .returns(Tuple::getDouble, Row::getDouble, -32768d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(-32768)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(-32768)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeInt4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Integer\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, Integer.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, Integer.MAX_VALUE) .returns(Tuple::getLong, Row::getLong, 2147483647L) .returns(Tuple::getFloat, Row::getFloat, 2147483647f) .returns(Tuple::getDouble, Row::getDouble, 2147483647d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(2147483647)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(2147483647)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInt4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Integer\" = $1 WHERE \"id\" = $2 RETURNING \"Integer\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(Integer.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, Integer.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, Integer.MIN_VALUE) .returns(Tuple::getLong, Row::getLong, -2147483648L) .returns(Tuple::getFloat, Row::getFloat, -2147483648f) .returns(Tuple::getDouble, Row::getDouble, -2147483648d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(-2147483648)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(-2147483648)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeInt8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Long\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, Long.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, -1) .returns(Tuple::getLong, Row::getLong, Long.MAX_VALUE) .returns(Tuple::getFloat, Row::getFloat, 9.223372E18f) .returns(Tuple::getDouble, Row::getDouble, 9.223372036854776E18d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(Long.MAX_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(Long.MAX_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInt8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Long\" = $1 WHERE \"id\" = $2 RETURNING \"Long\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addLong(Long.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, Long.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, Long.MIN_VALUE) .returns(Tuple::getFloat, Row::getFloat, -9.223372E18f) .returns(Tuple::getDouble, Row::getDouble, -9.223372036854776E18d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal(Long.MIN_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.create(Long.MIN_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeCustomType(TestContext ctx) { Async async = ctx.async(); String actual = "('Othercity',\" 'Second Ave'\",f)"; PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CustomDataType\" SET \"address\" = $1 WHERE \"id\" = $2 RETURNING \"address\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("('Othercity', 'Second Ave', false)") .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "address") .returns(Tuple::getValue, Row::getValue, actual) .returns(Tuple::getString, Row::getString, actual) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeFloat4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Float\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, Float.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, 2147483647) .returns(Tuple::getLong, Row::getLong, 9223372036854775807L) .returns(Tuple::getFloat, Row::getFloat, Float.MAX_VALUE) .returns(Tuple::getDouble, Row::getDouble, 3.4028234663852886E38d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Float.MAX_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Float.MAX_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeFloat4(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Float\" = $1 WHERE \"id\" = $2 RETURNING \"Float\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addFloat(Float.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, Float.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, 0L) .returns(Tuple::getFloat, Row::getFloat, Float.MIN_VALUE) .returns(Tuple::getDouble, Row::getDouble, 1.401298464324817E-45d) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Float.MIN_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Float.MIN_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeFloat8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Double\" FROM \"NumericDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, Double.MAX_VALUE) .returns(Tuple::getShort, Row::getShort, (short) -1) .returns(Tuple::getInteger, Row::getInteger, 2147483647) .returns(Tuple::getLong, Row::getLong, 9223372036854775807L) .returns(Tuple::getFloat, Row::getFloat, Float.POSITIVE_INFINITY) .returns(Tuple::getDouble, Row::getDouble, Double.MAX_VALUE) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Double.MAX_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Double.MAX_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeFloat8(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"NumericDataType\" SET \"Double\" = $1 WHERE \"id\" = $2 RETURNING \"Double\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addDouble(Double.MIN_VALUE) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, Double.MIN_VALUE) .returns(Tuple::getShort, Row::getShort, (short) 0) .returns(Tuple::getInteger, Row::getInteger, 0) .returns(Tuple::getLong, Row::getLong, 0L) .returns(Tuple::getFloat, Row::getFloat, 0f) .returns(Tuple::getDouble, Row::getDouble, Double.MIN_VALUE) .returns(Tuple::getBigDecimal, Row::getBigDecimal, new BigDecimal("" + Double.MIN_VALUE)) .returns(Tuple::getNumeric, Row::getNumeric, Numeric.parse("" + Double.MIN_VALUE)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeDateBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Date\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); LocalDate ld = LocalDate.parse("1981-05-30"); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Date") .returns(Tuple::getValue, Row::getValue, ld) .returns(Tuple::getLocalDate, Row::getLocalDate, ld) .returns(Tuple::getTemporal, Row::getTemporal, ld) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeDateBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Date\" = $1 WHERE \"id\" = $2 RETURNING \"Date\"", ctx.asyncAssertSuccess(p -> { LocalDate ld = LocalDate.parse("1981-06-30"); p.execute(Tuple.tuple() .addLocalDate(ld) .addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Date") .returns(Tuple::getValue, Row::getValue, ld) .returns(Tuple::getLocalDate, Row::getLocalDate, ld) .returns(Tuple::getTemporal, Row::getTemporal, ld) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeDateAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Date\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); LocalDate ld = LocalDate.parse("2017-05-30"); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Date") .returns(Tuple::getValue, Row::getValue, ld) .returns(Tuple::getLocalDate, Row::getLocalDate, ld) .returns(Tuple::getTemporal, Row::getTemporal, ld) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeDateAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Date\" = $1 WHERE \"id\" = $2 RETURNING \"Date\"", ctx.asyncAssertSuccess(p -> { LocalDate ld = LocalDate.parse("2018-05-30"); p.execute(Tuple.tuple() .addLocalDate(ld) .addInteger(4) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Date") .returns(Tuple::getValue, Row::getValue, ld) .returns(Tuple::getLocalDate, Row::getLocalDate, ld) .returns(Tuple::getTemporal, Row::getTemporal, ld) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTime(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Time\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { LocalTime lt = LocalTime.parse("17:55:04.905120"); ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Time") .returns(Tuple::getValue, Row::getValue, lt) .returns(Tuple::getLocalTime, Row::getLocalTime, lt) .returns(Tuple::getTemporal, Row::getTemporal, lt) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeTime(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Time\" = $1 WHERE \"id\" = $2 RETURNING \"Time\"", ctx.asyncAssertSuccess(p -> { LocalTime lt = LocalTime.parse("22:55:04.905120"); p.execute(Tuple.tuple() .addLocalTime(lt) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Time") .returns(Tuple::getValue, Row::getValue, lt) .returns(Tuple::getLocalTime, Row::getLocalTime, lt) .returns(Tuple::getTemporal, Row::getTemporal, lt) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTimeTz(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"TimeTz\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); OffsetTime ot = OffsetTime.parse("17:55:04.905120+03:07"); ColumnChecker.checkColumn(0, "TimeTz") .returns(Tuple::getValue, Row::getValue, ot) .returns(Tuple::getOffsetTime, Row::getOffsetTime, ot) .returns(Tuple::getTemporal, Row::getTemporal, ot) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeTimeTz(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"TimeTz\" = $1 WHERE \"id\" = $2 RETURNING \"TimeTz\"", ctx.asyncAssertSuccess(p -> { OffsetTime ot = OffsetTime.parse("20:55:04.905120+03:07"); p.execute(Tuple.tuple() .addOffsetTime(ot) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimeTz") .returns(Tuple::getValue, Row::getValue, ot) .returns(Tuple::getOffsetTime, Row::getOffsetTime, ot) .returns(Tuple::getTemporal, Row::getTemporal, ot) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTimestampBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Timestamp\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(3), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); LocalDateTime ldt = LocalDateTime.parse("1800-01-01T23:57:53.237666"); ColumnChecker.checkColumn(0, "Timestamp") .returns(Tuple::getValue, Row::getValue, ldt) .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt) .returns(Tuple::getTemporal, Row::getTemporal, ldt) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeTimestampBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Timestamp\" = $1 WHERE \"id\" = $2 RETURNING \"Timestamp\"", ctx.asyncAssertSuccess(p -> { LocalDateTime ldt = LocalDateTime.parse("1900-02-01T23:57:53.237666"); p.execute(Tuple.tuple() .addLocalDateTime(ldt) .addInteger(4), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Timestamp") .returns(Tuple::getValue, Row::getValue, ldt) .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt) .returns(Tuple::getTemporal, Row::getTemporal, ldt) .forRow(row); async.complete(); })); })); })); } static final LocalDateTime ldt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); @Test public void testDecodeTimestampAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Timestamp\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Timestamp") .returns(Tuple::getValue, Row::getValue, ldt) .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt) .returns(Tuple::getTemporal, Row::getTemporal, ldt) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeTimestampAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Timestamp\" =$1 WHERE \"id\" = $2 RETURNING \"Timestamp\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addLocalDateTime(LocalDateTime.parse("2017-05-14T19:35:58.237666")) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); LocalDateTime ldt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Timestamp") .returns(Tuple::getValue, Row::getValue, ldt) .returns(Tuple::getLocalDateTime, Row::getLocalDateTime, ldt) .returns(Tuple::getTemporal, Row::getTemporal, ldt) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeTimestampTzBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(v -> { conn.prepare("SELECT \"TimestampTz\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(3), ctx.asyncAssertSuccess(result -> { OffsetDateTime odt = OffsetDateTime.parse("1800-01-02T02:59:59.237666Z"); ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimestampTz") .returns(Tuple::getValue, Row::getValue, odt) .returns(Tuple::getOffsetDateTime, Row::getOffsetDateTime, odt) .returns(Tuple::getTemporal, Row::getTemporal, odt) .forRow(row); async.complete(); })); })); })); })); } @Test public void testEncodeTimestampTzBeforePgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(v -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"TimestampTz\" =$1 WHERE \"id\" = $2 RETURNING \"TimestampTz\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addOffsetDateTime(OffsetDateTime.parse("1800-02-01T23:59:59.237666-03:00")) .addInteger(3) , ctx.asyncAssertSuccess(result -> { OffsetDateTime odt = OffsetDateTime.parse("1800-02-02T02:59:59.237666Z"); ctx.assertEquals(1, result.rowCount()); ctx.assertEquals(1, result.size()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimestampTz") .returns(Tuple::getValue, Row::getValue, odt) .returns(Tuple::getOffsetDateTime, Row::getOffsetDateTime, odt) .returns(Tuple::getTemporal, Row::getTemporal, odt) .forRow(row); async.complete(); })); })); })); })); } @Test public void testDecodeTimestampTzAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(v -> { conn.prepare("SELECT \"TimestampTz\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); OffsetDateTime odt = OffsetDateTime.parse("2017-05-15T02:59:59.237666Z"); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimestampTz") .returns(Tuple::getValue, Row::getValue, odt) .returns(Tuple::getOffsetDateTime, Row::getOffsetDateTime, odt) .returns(Tuple::getTemporal, Row::getTemporal, odt) .forRow(row); async.complete(); })); })); })); })); } @Test public void testEncodeTimestampTzAfterPgEpoch(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.query("SET TIME ZONE 'UTC'", ctx.asyncAssertSuccess(v -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"TimestampTz\" = $1 WHERE \"id\" = $2 RETURNING \"TimestampTz\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addOffsetDateTime(OffsetDateTime.parse("2017-06-14T23:59:59.237666-03:00")) .addInteger(1) , ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); OffsetDateTime odt = OffsetDateTime.parse("2017-06-15T02:59:59.237666Z"); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "TimestampTz") .returns(Tuple::getValue, Row::getValue, odt) .returns(Tuple::getOffsetDateTime, Row::getOffsetDateTime, odt) .returns(Tuple::getTemporal, Row::getTemporal, odt) .forRow(row); async.complete(); })); })); })); })); } static final UUID uuid = UUID.fromString("6f790482-b5bd-438b-a8b7-4a0bed747011"); @Test public void testDecodeUUID(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"uuid\" FROM \"CharacterDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "uuid") .returns(Tuple::getValue, Row::getValue, uuid) .returns(Tuple::getUUID, Row::getUUID, uuid) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeUUID(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"uuid\" = $1 WHERE \"id\" = $2 RETURNING \"uuid\"", ctx.asyncAssertSuccess(p -> { UUID uuid = UUID.fromString("92b53cf1-2ad0-49f9-be9d-ca48966e43ee"); p.execute(Tuple.tuple() .addUUID(uuid) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "uuid") .returns(Tuple::getValue, Row::getValue, uuid) .returns(Tuple::getUUID, Row::getUUID, uuid) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeInterval(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Interval\" FROM \"TemporalDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { // 10 years 3 months 332 days 20 hours 20 minutes 20.999999 seconds Interval expected = Interval.of() .years(10) .months(3) .days(332) .hours(20) .minutes(20) .seconds(20) .microseconds(999999); p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getInterval, Row::getInterval, expected) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeInterval(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"TemporalDataType\" SET \"Interval\" = $1 WHERE \"id\" = $2 RETURNING \"Interval\"", ctx.asyncAssertSuccess(p -> { // 2000 years 1 months 403 days 59 hours 35 minutes 13.999998 seconds Interval expected = Interval.of() .years(2000) .months(1) .days(403) .hours(59) .minutes(35) .seconds(13) .microseconds(999998); p.execute(Tuple.tuple() .addInterval(expected) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getInterval, Row::getInterval, expected) .forRow(row); async.complete(); })); })); })); } @Test public void testNumeric(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: NUMERIC)) AS t (c)", new Numeric[]{ Numeric.create(10), Numeric.create(200030004), Numeric.create(-500), Numeric.NaN }, Tuple::getNumeric); } @Test public void testNumericArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: NUMERIC[])) AS t (c)", new Numeric[][]{new Numeric[]{Numeric.create(10), Numeric.create(200030004), null, Numeric.create(-500), Numeric.NaN, null}}, Tuple::getNumericArray); } @Test public void testJSON(TestContext ctx) { testJson(ctx, "JSON"); } @Test public void testJSONB(TestContext ctx) { testJson(ctx, "JSONB"); } private void testJson(TestContext ctx, String jsonType) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: " + jsonType + ")) AS t (c)", new Json[]{ Json.create(10), Json.create(true), Json.create("hello"), Json.create(new JsonObject().put("foo", "bar")), Json.create(new JsonArray().add(0).add(1).add(2)) }, Tuple::getJson); } @Test public void testJSONArray(TestContext ctx) { testJsonArray(ctx, "JSON"); } @Test public void testJSONBArray(TestContext ctx) { testJsonArray(ctx, "JSONB"); } private void testJsonArray(TestContext ctx, String jsonType) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: " + jsonType + "[])) AS t (c)", new Json[][]{ new Json[]{Json.create(10), Json.create(true), Json.create("hello"), Json.create(new JsonObject().put("foo", "bar")), Json.create(new JsonArray().add(0).add(1).add(2))} }, Tuple::getJsonArray); } @Test public void testBooleanArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: BOOL[])) AS t (c)", new Boolean[][]{new Boolean[]{true, null, false}}, Tuple::getBooleanArray); } @Test public void testShortArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: INT2[])) AS t (c)", new Short[][]{new Short[]{0, -10, null, Short.MAX_VALUE}}, Tuple::getShortArray); } @Test public void testIntegerArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: INT4[])) AS t (c)", new Integer[][]{new Integer[]{0, -10, null, Integer.MAX_VALUE}}, Tuple::getIntegerArray); } @Test public void testLongArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: INT8[])) AS t (c)", new Long[][]{new Long[]{0L, -10L, null, Long.MAX_VALUE}}, Tuple::getLongArray); } @Test public void testFloatArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: FLOAT4[])) AS t (c)", new Float[][]{new Float[]{0f, -10f, Float.MAX_VALUE}}, Tuple::getFloatArray); } @Test public void testPoint(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: POINT)) AS t (c)", new Point[]{new Point(0, 0), new Point(10.45, 20.178)}, Tuple::getPoint); } @Test public void testPointArray(TestContext ctx) { testGeneric(ctx, "SELECT c FROM (VALUES ($1 :: POINT[])) AS t (c)", new Point[][]{new Point[]{new Point(4, 5), null, new Point(3.4, -4.5), null}}, Tuple::getPointArray); } private static <T> void compare(TestContext ctx, T expected, T actual) { if (expected != null && expected.getClass().isArray()) { ctx.assertNotNull(actual); ctx.assertTrue(actual.getClass().isArray()); List expectedList = Arrays.asList((Object[]) expected); List actualList = Arrays.asList((Object[]) actual); ctx.assertEquals(expectedList, actualList); } else { ctx.assertEquals(expected, actual); } } private <T> void testGeneric(TestContext ctx, String sql, T[] expected, BiFunction<Row, Integer, T> getter) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { List<Tuple> batch = Stream.of(expected).map(Tuple::of).collect(Collectors.toList()); conn.preparedBatch(sql, batch, ctx.asyncAssertSuccess(result -> { for (T n : expected) { ctx.assertEquals(result.size(), 1); Iterator<Row> it = result.iterator(); Row row = it.next(); compare(ctx, n, getter.apply(row, 0)); compare(ctx, n, row.getValue(0)); result = result.next(); } ctx.assertNull(result); async.complete(); })); })); } @Test public void testDecodeJson(TestContext ctx) { testDecodeJson(ctx, "JsonDataType"); } @Test public void testDecodeJsonb(TestContext ctx) { testDecodeJson(ctx, "JsonbDataType"); } private void testDecodeJson(TestContext ctx, String tableName) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"JsonObject\", \"JsonArray\", \"Number\", \"String\", \"BooleanTrue\", \"BooleanFalse\", \"Null\" FROM \"" + tableName + "\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); JsonObject object = new JsonObject("{\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : []}"); JsonArray array = new JsonArray("[1,true,null,9.5,\"Hi\"]"); ColumnChecker.checkColumn(0, "JsonObject") .returns(Tuple::getValue, Row::getValue, Json.create(object)) .returns(Tuple::getJson, Row::getJson, Json.create(object)) .forRow(row); ColumnChecker.checkColumn(1, "JsonArray") .returns(Tuple::getValue, Row::getValue, Json.create(array)) .returns(Tuple::getJson, Row::getJson, Json.create(array)) .forRow(row); ColumnChecker.checkColumn(2, "Number") .returns(Tuple::getValue, Row::getValue, Json.create(4)) .returns(Tuple::getJson, Row::getJson, Json.create(4)) .forRow(row); ColumnChecker.checkColumn(3, "String") .returns(Tuple::getValue, Row::getValue, Json.create("Hello World")) .returns(Tuple::getJson, Row::getJson, Json.create("Hello World")) .forRow(row); ColumnChecker.checkColumn(4, "BooleanTrue") .returns(Tuple::getValue, Row::getValue, Json.create(true)) .returns(Tuple::getJson, Row::getJson, Json.create(true)) .forRow(row); ColumnChecker.checkColumn(5, "BooleanFalse") .returns(Tuple::getValue, Row::getValue, Json.create(false)) .returns(Tuple::getJson, Row::getJson, Json.create(false)) .forRow(row); ColumnChecker.checkColumn(6, "Null") .returns(Tuple::getValue, Row::getValue, Json.create(null)) .returns(Tuple::getJson, Row::getJson, Json.create(null)) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeJson(TestContext ctx) { testEncodeJson(ctx, "JsonDataType"); } @Test public void testEncodeJsonb(TestContext ctx) { testEncodeJson(ctx, "JsonbDataType"); } private void testEncodeJson(TestContext ctx, String tableName) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"" + tableName + "\" SET " + "\"JsonObject\" = $1, " + "\"JsonArray\" = $2, " + "\"Number\" = $3, " + "\"String\" = $4, " + "\"BooleanTrue\" = $5, " + "\"BooleanFalse\" = $6, " + "\"Null\" = $7 " + "WHERE \"id\" = $8 RETURNING \"JsonObject\", \"JsonArray\", \"Number\", \"String\", \"BooleanTrue\", \"BooleanFalse\", \"Null\"", ctx.asyncAssertSuccess(p -> { JsonObject object = new JsonObject("{\"str\":\"blah\", \"int\" : 1, \"float\" : 3.5, \"object\": {}, \"array\" : []}"); JsonArray array = new JsonArray("[1,true,null,9.5,\"Hi\"]"); p.execute(Tuple.tuple() .addJson(Json.create(object)) .addJson(Json.create(array)) .addJson(Json.create(4)) .addJson(Json.create("Hello World")) .addJson(Json.create(true)) .addJson(Json.create(false)) .addJson(Json.create(null)) .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); ColumnChecker.checkColumn(0, "JsonObject") .returns(Tuple::getValue, Row::getValue, Json.create(object)) .returns(Tuple::getJson, Row::getJson, Json.create(object)) .forRow(row); ColumnChecker.checkColumn(1, "JsonArray") .returns(Tuple::getValue, Row::getValue, Json.create(array)) .returns(Tuple::getJson, Row::getJson, Json.create(array)) .forRow(row); ColumnChecker.checkColumn(2, "Number") .returns(Tuple::getValue, Row::getValue, Json.create(4)) .returns(Tuple::getJson, Row::getJson, Json.create(4)) .forRow(row); ColumnChecker.checkColumn(3, "String") .returns(Tuple::getValue, Row::getValue, Json.create("Hello World")) .returns(Tuple::getJson, Row::getJson, Json.create("Hello World")) .forRow(row); ColumnChecker.checkColumn(4, "BooleanTrue") .returns(Tuple::getValue, Row::getValue, Json.create(true)) .returns(Tuple::getJson, Row::getJson, Json.create(true)) .forRow(row); ColumnChecker.checkColumn(5, "BooleanFalse") .returns(Tuple::getValue, Row::getValue, Json.create(false)) .returns(Tuple::getJson, Row::getJson, Json.create(false)) .forRow(row); ColumnChecker.checkColumn(6, "Null") .returns(Tuple::getValue, Row::getValue, Json.create(null)) .returns(Tuple::getJson, Row::getJson, Json.create(null)) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeName(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Name\" FROM \"CharacterDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "What is my name ?"; ColumnChecker.checkColumn(0, "Name") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeName(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"Name\" = upper($1) WHERE \"id\" = $2 RETURNING \"Name\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("vert.x") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "VERT.X"; ColumnChecker.checkColumn(0, "Name") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeChar(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"SingleChar\" FROM \"CharacterDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String singleChar = "A"; ColumnChecker.checkColumn(0, "SingleChar") .returns(Tuple::getValue, Row::getValue, singleChar) .returns(Tuple::getString, Row::getString, singleChar) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeChar(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"SingleChar\" = upper($1) WHERE \"id\" = $2 RETURNING \"SingleChar\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("b") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String singleChar = "B"; ColumnChecker.checkColumn(0, "SingleChar") .returns(Tuple::getValue, Row::getValue, singleChar) .returns(Tuple::getString, Row::getString, singleChar) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeFixedChar(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"FixedChar\" FROM \"CharacterDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "YES"; ColumnChecker.checkColumn(0, "FixedChar") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeFixedChar(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"FixedChar\" = upper($1) WHERE \"id\" = $2 RETURNING \"FixedChar\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("no") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "NO "; ColumnChecker.checkColumn(0, "FixedChar") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeText(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Text\" FROM \"CharacterDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "Hello World"; ColumnChecker.checkColumn(0, "Text") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeText(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"Text\" = upper($1) WHERE \"id\" = $2 RETURNING \"Text\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("Hello World") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "HELLO WORLD"; ColumnChecker.checkColumn(0, "Text") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testDecodeVarCharacter(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"VarCharacter\" FROM \"CharacterDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple().addInteger(1), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "Great!"; ColumnChecker.checkColumn(0, "VarCharacter") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeVarCharacter(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"CharacterDataType\" SET \"VarCharacter\" = upper($1) WHERE \"id\" = $2 RETURNING \"VarCharacter\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addString("Great!") .addInteger(2), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(1, result.size()); ctx.assertEquals(1, result.rowCount()); Row row = result.iterator().next(); String name = "GREAT!"; ColumnChecker.checkColumn(0, "VarCharacter") .returns(Tuple::getValue, Row::getValue, name) .returns(Tuple::getString, Row::getString, name) .forRow(row); async.complete(); })); })); })); } @Test public void testEncodeLargeVarchar(TestContext ctx) { int len = 2048; StringBuilder builder = new StringBuilder(); for (int i = 0; i < len; i++) { builder.append((char) ('A' + (i % 26))); } String value = builder.toString(); Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1::VARCHAR(" + len + ")", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(value), ctx.asyncAssertSuccess(result -> { ctx.assertEquals(value, result.iterator().next().getString(0)); async.complete(); })); })); })); } @Test public void testBytea(TestContext ctx) { Random r = new Random(); int len = 2048; byte[] bytes = new byte[len]; r.nextBytes(bytes); Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT $1::BYTEA \"Bytea\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(Buffer.buffer(bytes)), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Bytea") .returns(Tuple::getValue, Row::getValue, Buffer.buffer(bytes)) .returns(Tuple::getBuffer, Row::getBuffer, Buffer.buffer(bytes)) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeBooleanArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Boolean\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Boolean") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new boolean[]{Boolean.TRUE})) .returns(Tuple::getBooleanArray, Row::getBooleanArray, ColumnChecker.toObjectArray(new boolean[]{Boolean.TRUE})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeBooleanArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Boolean\" = $1 WHERE \"id\" = $2 RETURNING \"Boolean\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addBooleanArray(new Boolean[]{Boolean.FALSE, Boolean.TRUE}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Boolean") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new boolean[]{Boolean.FALSE, Boolean.TRUE})) .returns(Tuple::getBooleanArray, Row::getBooleanArray, ColumnChecker.toObjectArray(new boolean[]{Boolean.FALSE, Boolean.TRUE})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeShortArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Short\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new short[]{1})) .returns(Tuple::getShortArray, Row::getShortArray, ColumnChecker.toObjectArray(new short[]{1})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeShortArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Short\" = $1 WHERE \"id\" = $2 RETURNING \"Short\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addShortArray(new Short[]{2, 3, 4}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Short") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new short[]{2, 3, 4})) .returns(Tuple::getShortArray, Row::getShortArray, ColumnChecker.toObjectArray(new short[]{2, 3, 4})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeIntArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Integer\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new int[]{2})) .returns(Tuple::getIntegerArray, Row::getIntegerArray, ColumnChecker.toObjectArray(new int[]{2})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeIntArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Integer\" = $1 WHERE \"id\" = $2 RETURNING \"Integer\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addIntegerArray(new Integer[]{3, 4, 5, 6}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Integer") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new int[]{3, 4, 5, 6})) .returns(Tuple::getIntegerArray, Row::getIntegerArray, ColumnChecker.toObjectArray(new int[]{3, 4, 5, 6})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeLongArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Long\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, new Long[]{3L}) .returns(Tuple::getLongArray, Row::getLongArray, new Long[]{3L}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeLongArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Long\" = $1 WHERE \"id\" = $2 RETURNING \"Long\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addLongArray(new Long[]{4L, 5L, 6L, 7L, 8L}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Long") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new long[]{4, 5, 6, 7, 8})) .returns(Tuple::getLongArray, Row::getLongArray, ColumnChecker.toObjectArray(new long[]{4, 5, 6, 7, 8})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeFloatArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Float\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new float[]{4.1f})) .returns(Tuple::getFloatArray, Row::getFloatArray, ColumnChecker.toObjectArray(new float[]{4.1f})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeFloatArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Float\" = $1 WHERE \"id\" = $2 RETURNING \"Float\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addFloatArray(new Float[]{5.2f, 5.3f, 5.4f}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Float") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new float[]{5.2f, 5.3f, 5.4f})) .returns(Tuple::getFloatArray, Row::getFloatArray, ColumnChecker.toObjectArray(new float[]{5.2f, 5.3f, 5.4f})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeDoubleArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Double\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new double[]{5.2})) .returns(Tuple::getDoubleArray, Row::getDoubleArray, ColumnChecker.toObjectArray(new double[]{5.2})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeDoubleArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Double\" = $1 WHERE \"id\" = $2 RETURNING \"Double\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addDoubleArray(new Double[]{6.3}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new double[]{6.3})) .returns(Tuple::getDoubleArray, Row::getDoubleArray, ColumnChecker.toObjectArray(new double[]{6.3})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEmptyArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Double\" = $1 WHERE \"id\" = $2 RETURNING \"Double\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addDoubleArray(new Double[]{}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Double") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(new double[]{})) .returns(Tuple::getDoubleArray, Row::getDoubleArray, ColumnChecker.toObjectArray(new double[]{})) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeStringArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Text\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Text") .returns(Tuple::getValue, Row::getValue, new String[]{"Knock, knock.Who’s there?very long pause….Java."}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{"Knock, knock.Who’s there?very long pause….Java."}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeStringArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Text\" = $1 WHERE \"id\" = $2 RETURNING \"Text\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{"Knock, knock.Who’s there?"}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Text") .returns(Tuple::getValue, Row::getValue, new String[]{"Knock, knock.Who’s there?"}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{"Knock, knock.Who’s there?"}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeEnumArray(TestContext ctx) { final String[] expected = new String[]{"ok", "unhappy", "happy"}; Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Enum\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getStringArray, Row::getStringArray, expected) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEnumArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Enum\" = $1 WHERE \"id\" = $2 RETURNING \"Enum\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{"unhappy"}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, new String[]{"unhappy"}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{"unhappy"}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEnumArrayMultipleValues(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Enum\" = $1 WHERE \"id\" = $2 RETURNING \"Enum\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{"unhappy", "ok"}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, new String[]{"unhappy", "ok"}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{"unhappy", "ok"}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeEnumArrayEmptyValues(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Enum\" = $1 WHERE \"id\" = $2 RETURNING \"Enum\", \"Boolean\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addStringArray(new String[]{}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Enum") .returns(Tuple::getValue, Row::getValue, new String[]{}) .returns(Tuple::getStringArray, Row::getStringArray, new String[]{}) .forRow(result.iterator().next()); ColumnChecker.checkColumn(1, "Boolean") .returns(Tuple::getValue, Row::getValue, new Boolean[]{true}) .returns(Tuple::getBooleanArray, Row::getBooleanArray, new Boolean[]{true}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeLocalDateArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"LocalDate\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { final LocalDate dt = LocalDate.parse("1998-05-11"); ColumnChecker.checkColumn(0, "LocalDate") .returns(Tuple::getValue, Row::getValue, new Object[]{dt, dt}) .returns(Tuple::getLocalDateArray, Row::getLocalDateArray, new Object[]{dt, dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeLocalDateArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalDate\" = $1 WHERE \"id\" = $2 RETURNING \"LocalDate\"", ctx.asyncAssertSuccess(p -> { final LocalDate dt = LocalDate.parse("1998-05-12"); p.execute(Tuple.tuple() .addLocalDateArray(new LocalDate[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "LocalDate") .returns(Tuple::getValue, Row::getValue, new LocalDate[]{dt}) .returns(Tuple::getLocalDateArray, Row::getLocalDateArray, new LocalDate[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSS"); static final LocalTime lt = LocalTime.parse("17:55:04.90512", dtf); @Test public void testDecodeLocalTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"LocalTime\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "LocalTime") .returns(Tuple::getValue, Row::getValue, new LocalTime[]{lt}) .returns(Tuple::getLocalTimeArray, Row::getLocalTimeArray, new LocalTime[]{lt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeLocalTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalTime\" = $1 WHERE \"id\" = $2 RETURNING \"LocalTime\"", ctx.asyncAssertSuccess(p -> { final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss.SSSSS"); final LocalTime dt = LocalTime.parse("17:55:04.90512", dtf); p.execute(Tuple.tuple() .addLocalTimeArray(new LocalTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "LocalTime") .returns(Tuple::getValue, Row::getValue, new LocalTime[]{dt}) .returns(Tuple::getLocalTimeArray, Row::getLocalTimeArray, new LocalTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } static final OffsetTime dt = OffsetTime.parse("17:55:04.90512+03:00"); @Test public void testDecodeOffsetTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"OffsetTime\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "OffsetTime") .returns(Tuple::getValue, Row::getValue, new OffsetTime[]{dt}) .returns(Tuple::getOffsetTimeArray, Row::getOffsetTimeArray, new OffsetTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeOffsetTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"OffsetTime\" = $1 WHERE \"id\" = $2 RETURNING \"OffsetTime\"", ctx.asyncAssertSuccess(p -> { final OffsetTime dt = OffsetTime.parse("17:56:04.90512+03:07"); p.execute(Tuple.tuple() .addOffsetTimeArray(new OffsetTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "OffsetTime") .returns(Tuple::getValue, Row::getValue, new OffsetTime[]{dt}) .returns(Tuple::getOffsetTimeArray, Row::getOffsetTimeArray, new OffsetTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeLocalDateTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"LocalDateTime\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { final LocalDateTime dt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); ColumnChecker.checkColumn(0, "LocalDateTime") .returns(Tuple::getValue, Row::getValue, new LocalDateTime[]{dt}) .returns(Tuple::getLocalDateTimeArray, Row::getLocalDateTimeArray, new LocalDateTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeLocalDateTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"LocalDateTime\" = $1 WHERE \"id\" = $2 RETURNING \"LocalDateTime\"", ctx.asyncAssertSuccess(p -> { final LocalDateTime dt = LocalDateTime.parse("2017-05-14T19:35:58.237666"); p.execute(Tuple.tuple() .addLocalDateTimeArray(new LocalDateTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "LocalDateTime") .returns(Tuple::getValue, Row::getValue, new LocalDateTime[]{dt}) .returns(Tuple::getLocalDateTimeArray, Row::getLocalDateTimeArray, new LocalDateTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } static final OffsetDateTime odt = OffsetDateTime.parse("2017-05-15T02:59:59.237666Z"); @Test public void testDecodeOffsetDateTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"OffsetDateTime\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "OffsetDateTime") .returns(Tuple::getValue, Row::getValue, new OffsetDateTime[]{odt}) .returns(Tuple::getOffsetDateTimeArray, Row::getOffsetDateTimeArray, new OffsetDateTime[]{odt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeOffsetDateTimeArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"OffsetDateTime\" = $1 WHERE \"id\" = $2 RETURNING \"OffsetDateTime\"", ctx.asyncAssertSuccess(p -> { final OffsetDateTime dt = OffsetDateTime.parse("2017-05-14T19:35:58.237666Z"); p.execute(Tuple.tuple() .addOffsetDateTimeArray(new OffsetDateTime[]{dt}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "OffsetDateTime") .returns(Tuple::getValue, Row::getValue, new OffsetDateTime[]{dt}) .returns(Tuple::getOffsetDateTimeArray, Row::getOffsetDateTimeArray, new OffsetDateTime[]{dt}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeUUIDArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"UUID\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { final UUID uuid = UUID.fromString("6f790482-b5bd-438b-a8b7-4a0bed747011"); ColumnChecker.checkColumn(0, "UUID") .returns(Tuple::getValue, Row::getValue, new UUID[]{uuid}) .returns(Tuple::getUUIDArray, Row::getUUIDArray, new UUID[]{uuid}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeUUIDArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"UUID\" = $1 WHERE \"id\" = $2 RETURNING \"UUID\"", ctx.asyncAssertSuccess(p -> { final UUID uuid = UUID.fromString("6f790482-b5bd-438b-a8b7-4a0bed747011"); p.execute(Tuple.tuple() .addUUIDArray(new UUID[]{uuid}) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "UUID") .returns(Tuple::getValue, Row::getValue, new UUID[]{uuid}) .returns(Tuple::getUUIDArray, Row::getUUIDArray, new UUID[]{uuid}) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testDecodeNumericArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Numeric\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { Numeric[] expected = { Numeric.create(0), Numeric.create(1), Numeric.create(2), Numeric.create(3) }; ColumnChecker.checkColumn(0, "Numeric") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getNumericArray, Row::getNumericArray, expected) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeNumericArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Numeric\" = $1 WHERE \"id\" = $2 RETURNING \"Numeric\"", ctx.asyncAssertSuccess(p -> { Numeric[] expected = { Numeric.create(0), Numeric.create(10000), }; p.execute(Tuple.tuple() .addNumericArray(expected) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Numeric") .returns(Tuple::getValue, Row::getValue, expected) .returns(Tuple::getNumericArray, Row::getNumericArray, expected) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testBufferArray(TestContext ctx) { Random r = new Random(); int len = 2048; byte[] bytes = new byte[len]; r.nextBytes(bytes); Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT ARRAY[$1::BYTEA] \"Bytea\"", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.of(Buffer.buffer(bytes)), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Bytea") .returns(Tuple::getValue, Row::getValue, new Buffer[]{Buffer.buffer(bytes)}) .returns(Tuple::getBufferArray, Row::getBufferArray, new Buffer[]{Buffer.buffer(bytes)}) .forRow(result.iterator().next()); async.complete(); })); })); })); } static final Interval[] intervals = new Interval[] { Interval.of().years(10).months(3).days(332).hours(20).minutes(20).seconds(20).microseconds(999991), Interval.of().minutes(20).seconds(20).microseconds(123456), Interval.of().years(-2).months(-6) }; @Test public void testDecodeIntervalArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("SELECT \"Interval\" FROM \"ArrayDataType\" WHERE \"id\" = $1", ctx.asyncAssertSuccess(p -> { p.execute(Tuple.tuple() .addInteger(1), ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(intervals)) .returns(Tuple::getIntervalArray, Row::getIntervalArray, ColumnChecker.toObjectArray(intervals)) .forRow(result.iterator().next()); async.complete(); })); })); })); } @Test public void testEncodeIntervalArray(TestContext ctx) { Async async = ctx.async(); PgClient.connect(vertx, options, ctx.asyncAssertSuccess(conn -> { conn.prepare("UPDATE \"ArrayDataType\" SET \"Interval\" = $1 WHERE \"id\" = $2 RETURNING \"Interval\"", ctx.asyncAssertSuccess(p -> { Interval[] intervals = new Interval[] { Interval.of().years(10).months(3).days(332).hours(20).minutes(20).seconds(20).microseconds(999991), Interval.of().minutes(20).seconds(20).microseconds(123456), Interval.of().years(-2).months(-6), Interval.of() }; p.execute(Tuple.tuple() .addIntervalArray(intervals) .addInteger(2) , ctx.asyncAssertSuccess(result -> { ColumnChecker.checkColumn(0, "Interval") .returns(Tuple::getValue, Row::getValue, ColumnChecker.toObjectArray(intervals)) .returns(Tuple::getIntervalArray, Row::getIntervalArray, ColumnChecker.toObjectArray(intervals)) .forRow(result.iterator().next()); async.complete(); })); })); })); } }
Java
UTF-8
4,007
2.375
2
[]
no_license
package dev.brighten.example.commands; import cc.funkemunky.api.Atlas; import cc.funkemunky.api.commands.ancmd.Command; import cc.funkemunky.api.commands.ancmd.CommandAdapter; import cc.funkemunky.api.utils.Color; import cc.funkemunky.api.utils.Init; import cc.funkemunky.api.utils.MiscUtils; import cc.funkemunky.api.utils.Tuple; import lombok.val; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @Init(commands = true) public class ExampleCommand { @Command(name = "example", description = "an example command", display = "example", usage = "/<command>", permission = "atlas.command.example", aliases = "atlasexample") public void onCommand(CommandAdapter cmd) { Atlas.getInstance().getCommandManager(Atlas.getInstance()).runHelpMessage(cmd, cmd.getSender(), Atlas.getInstance().getCommandManager(Atlas.getInstance()).getDefaultScheme()); } @Command(name = "example.execute", description = "execute a test message", display = "execute", usage = "/<command> <arg>", permission = "atlas.command.example.execute", aliases = "atlasexample.execute") public void onExecute(CommandAdapter cmd) { cmd.getSender().sendMessage(Color.translate("#9F8DFAYou have initiated the test command.")); } @Command(name = "testjson", playerOnly = true) public void onTestJson(CommandAdapter cmd) { Player sender = cmd.getPlayer(); List<TextComponent> components = new ArrayList<>(); TextComponent types = new TextComponent(Color.translate(sender.getWorld().getEntities().stream() .map(ent -> ent.getType().getName()) .filter(Objects::nonNull) .sorted(Comparator.comparing(v -> v)) .map(n -> Color.Yellow + MiscUtils.injectColor(n, Color.Yellow)) .collect(Collectors.joining("&8, &e")) + "&7: ")); components.add(types); List<Tuple<Entity, String>> names = new ArrayList<>(); sender.getWorld().getEntities().stream().sorted(Comparator.comparing(ent -> ent.getType().name())) .map(ent -> new Tuple<>(ent, ent.getName())).forEach(names::add); for (int i = 0; i < names.size(); i++) { Tuple<Entity, String> tuple = names.get(i); Entity ent = tuple.one; String name = ent.getName(); boolean livingEntity = ent instanceof LivingEntity; val component = new TextComponent(Color.Gray + MiscUtils.injectColor(Color.strip(name), Color.Gray) + (i + 1 < names.size() ? Color.Dark_Gray + ", " + Color.Gray : "")); if(livingEntity) { LivingEntity living = (LivingEntity) ent; component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{ new TextComponent(Color.translate("&eType&7: &f" + ent.getType().name())), new TextComponent(Color.translate("\n&eLiving&7: &ftrue")), new TextComponent(Color.translate("\n&eHealth&7: &f" + living.getHealth()))})); } else { component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new BaseComponent[]{ new TextComponent(Color.translate("\n&eType&7: &f" + ent.getType().name())), new TextComponent(Color.translate("\n&eLiving&7: &ffalse"))})); } components.add(component); } sender.spigot().sendMessage(components.stream().toArray(TextComponent[]::new)); } }
Ruby
UTF-8
424
2.703125
3
[]
no_license
require './lib/enigma' require 'date' require './lib/generator' require './lib/abc_index' enigma = Enigma.new handle = File.open(ARGV[0], "r") incoming_text = handle.read handle.close decrypted_text = enigma.decrypt(incoming_text, ARGV[2], ARGV[3]) writer = File.open(ARGV[1], "w") writer.write(decrypted_text[:encryption]) writer.close puts "Created '#{ARGV[1]}' with #{decrypted_text[:key]} and #{decrypted_text[:date]}"
JavaScript
UTF-8
1,484
2.59375
3
[ "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-ecma-no-patent" ]
permissive
// Copyright (C) 2016 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-%typedarray%.prototype.slice description: Preservation of bit-level encoding info: | [...] 15. Else if count > 0, then [...] e. NOTE: If srcType and targetType are the same, the transfer must be performed in a manner that preserves the bit-level encoding of the source data. f. Let srcByteOffet be the value of O's [[ByteOffset]] internal slot. g. Let targetByteIndex be A's [[ByteOffset]] internal slot. h. Let srcByteIndex be (k × elementSize) + srcByteOffet. i. Let limit be targetByteIndex + count × elementSize. j. Repeat, while targetByteIndex < limit i. Let value be GetValueFromBuffer(srcBuffer, srcByteIndex, "Uint8"). ii. Perform SetValueInBuffer(targetBuffer, targetByteIndex, "Uint8", value). iii. Increase srcByteIndex by 1. iv. Increase targetByteIndex by 1. includes: [nans.js, compareArray.js, testTypedArray.js] features: [TypedArray] ---*/ function body(FloatArray) { var subject = new FloatArray(NaNs); var sliced, subjectBytes, slicedBytes; sliced = subject.slice(); subjectBytes = new Uint8Array(subject.buffer); slicedBytes = new Uint8Array(sliced.buffer); assert(compareArray(subjectBytes, slicedBytes)); } testWithTypedArrayConstructors(body, [Float32Array, Float64Array]);
Python
UTF-8
1,191
3.859375
4
[]
no_license
import string def invert_text(text_tobe_inverted): inverted_text = text_tobe_inverted[::-1] return inverted_text def remove_punctuations(text_tobe_stripped): removed_punct = text_tobe_stripped.translate(string.maketrans("",""), string.punctuation) return removed_punct def check_Palindrome(Palindrome_file): with open(Palindrome_file) as Pfile: content = Pfile.readlines() num_line = int(content.pop(0)) i = 0 while i < num_line: content[i] = content[i].strip('\n') i = i + 1 Ptext = ''.join(content[0:num_line]) Ptext = Ptext.lower() Ptext = Ptext.replace(" ","") Ptext_nopunct = remove_punctuations(Ptext) Ptext_inv = invert_text(Ptext_nopunct) if Ptext_inv == Ptext_nopunct: return True else: return False def main(): file_name =raw_input("Enter the name of the file to be check if it is a Palindrome:") if check_Palindrome(file_name): print ("This is a Palindrome") else: print ("This is not a Palindrome") main()
Python
UTF-8
569
2.71875
3
[]
no_license
import sys import MySQLdb as mysql def main(): # create a connection object connection = mysql.connect(host="localhost", user="root", passwd="123456", db="menu") # create a cursor object cursor = connection.cursor() try: sql = "SELECT * FROM fish" result = cursor.execute(sql) print result results = cursor.fetchall() print results finally: connection.close() if __name__ == "__main__": main()
Shell
UTF-8
1,572
3.390625
3
[]
no_license
#!/bin/bash # Exit on any failure set -e # Check for uninitialized variables set -o nounset ctrlc() { killall -9 python mn -c exit } trap ctrlc SIGINT start=`date` exptid=`date +%b%d-%H:%M` rootdir=ddos-$exptid iperf=/usr/bin/iperf rm -f last ln -s $rootdir last ./http/generator.py --dir ./http/Random_objects dir=$rootdir/http python tcp_dos.py \ --bw-host 15 \ --bw-net 1.5 \ --delay 6 \ --dir $dir \ --period 1 \ --iperf $iperf \ --burst 0.3 \ --minRTO 900 \ --tcp-n 1 \ --http ./util/plot-http.py --dir $dir --out $dir/result.png for tcp_n in 1 10; do for minRTO in 900 300; do for period in 0.5 0.6 0.7 0.8 0.9 0.95 1 1.05 1.1 1.15 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2 2.5 3 3.5 4 4.5 5; do dir=$rootdir/rto-$minRTO-tcp_n-$tcp_n/interval-$period/ rm -f last ln -s $rootdir last python tcp_dos.py \ --bw-host 15 \ --bw-net 1.5 \ --delay 6 \ --dir $dir \ --period $period \ --iperf $iperf \ --burst 0.3 \ --minRTO $minRTO \ --tcp-n $tcp_n ./util/plot-rto.py --dir $dir --out $dir/result.png done ./util/plot.py --dir $rootdir/rto-$minRTO-tcp_n-$tcp_n/ --out $rootdir/rto-$minRTO-tcp_n-$tcp_n/result.png done done cp bootstrap/result.html last/ echo "Started at" $start echo "Ended at" `date` echo "Run: python -m SimpleHTTPServer &" domain=`curl -s -m 2 http://169.254.169.254/latest/meta-data/public-hostname` if [ -z $domain ]; then domain="IP" fi echo "Result is located at http://$domain:8000/last/result.html"
JavaScript
UTF-8
1,401
3.453125
3
[ "Apache-2.0" ]
permissive
(function() { "use strict"; function insert(element, array, compare) { array.splice(locationOf(element, array, compare) + 1, 0, element); return array; } // performs binary search in a sorted array function locationOf(element, array, compare, start, end) { if (array.length === 0) return -1; start = start || 0; end = end || array.length; var pivot = (start + end) >> 1; var c = compare(element, array[pivot]); if (end - start <= 1) return c == -1 ? pivot - 1 : pivot; switch (c) { case -1: return locationOf(element, array, compare, start, pivot); case 0: return pivot; case 1: return locationOf(element, array, compare, pivot, end); }; }; var EventCalendar = function() { this.values = []; this.offset = 0; }; EventCalendar.prototype.push = function(value) { insert(value, this.values, function(lhs, rhs) { if (lhs.time < rhs.time) return -1; if (lhs.time > rhs.time) return 1; return 0; }); }; EventCalendar.prototype.pop = function() { if (this.values.length == 0) { return undefined; } var queue = this.values; var item = queue[this.offset]; this.offset++; if (this.offset * 2 >= queue.length) { this.values = queue.slice(this.offset); this.offset = 0; } return item; }; EventCalendar.prototype.empty = function() { return this.values.length == 0; }; window.EventCalendar = EventCalendar; })();
JavaScript
UTF-8
2,168
2.546875
3
[]
no_license
import { createAction, createReducer } from 'redux-act'; const REDUCER = 'app'; const NS = `@@${REDUCER}/`; export const setUserState = createAction(`${NS}SET_USER_STATE`); export const addSubmitForm = createAction(`${NS}ADD_SUBMIT_FORM`); export const deleteSubmitForm = createAction(`${NS}DELETE_SUBMIT_FORM`); export const getParamsFromQuery = url => { let query = url.split('?'); let params = {}; if (query.length > 1) { let queryStr = query[1]; let paramStrs = queryStr.split('&'); if (paramStrs.length > 0) { paramStrs.forEach(paramStr => { let paramFields = paramStr.split('='); if (paramFields.length > 1) { params[paramFields[0]] = decodeURIComponent(paramFields[1]); } }); } } return params; }; export const getQueryFromParams = (params = {}) => { var query = ''; for (let i = 0; i < Object.keys(params).length; i++) { let field = Object.keys(params)[i]; if (i > 0) { query += '&'; } query += `${field}=${params[field]}`; } return query; }; export const dateFormat = date => { var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; if (!date) { return ''; } var day = date.getDate(); var monthIndex = date.getMonth(); var year = date.getFullYear(); return day + ' ' + monthNames[monthIndex] + ' ' + year; }; export const timeFormat = date => { if (!date) { return ''; } var hour = date.getUTCHours(); var minute = date.getUTCMinutes(); var apm = 'am'; if (hour > 12) { hour = hour - 12; apm = 'pm'; } return hour + ':' + minute + ' ' + apm; }; const initialState = { // APP STATE submitForms: {}, // USER STATE user: {}, }; export default createReducer({ [setUserState]: (state, { user }) => ({ ...state, user }), [addSubmitForm]: (state, id) => { const submitForms = { ...state.submitForms, [id]: true }; return { ...state, submitForms }; }, [deleteSubmitForm]: (state, id) => { const submitForms = { ...state.submitForms }; delete submitForms[id]; return { ...state, submitForms }; }, }, initialState);
C++
UTF-8
2,960
3.28125
3
[]
no_license
Password (20) To prepare for PAT, the judge sometimes has to generate random passwords for the users. The problem is that there are always some confusing passwords since it is hard to distinguish 1 (one) from l (L in lowercase), 0 (zero) from O (o in uppercase). One solution is to replace 1 (one) by @, 0 (zero) by %, l by L, and O by o. Now it is your job to write a program to check the accounts generated by the judge, and to help the juge modify the confusing passwords. Input Specification: Each input file contains one test case. Each case contains a positive integer N (<= 1000), followed by N lines of accounts. Each account consists of a user name and a password, both are strings of no more than 10 characters with no space. Output Specification: For each test case, first print the number M of accounts that have been modified, then print in the following M lines the modified accounts info, that is, the user names and the corresponding modified passwords. The accounts must be printed in the same order as they are read in. If no account is modified, print in one line "There are N accounts and no account is modified" where N is the total number of accounts. However, if N is one, you must print "There is 1 account and no account is modified" instead. Sample Input 1: 3 Team000002 Rlsp0dfa Team000003 perfectpwd Team000001 R1spOdfa Sample Output 1: 2 Team000002 RLsp%dfa Team000001 R@spodfa Sample Input 2: 1 team110 abcdefg332 Sample Output 2: There is 1 account and no account is modified Sample Input 3: 2 team110 abcdefg222 team220 abcdefg333 Sample Output 3: There are 2 accounts and no account is modified 1 by @ 0 by % l by L O by o #include <cstdio> #include <cstring> const int MAXN = 10010; int N, num = 0, num2 = 0, tag[MAXN]; struct node{ char userName[MAXN]; char passWord[MAXN]; } Node[MAXN]; bool check(int i) { int flag = 0; int len = strlen(Node[i].passWord); for(int j=0; j<len; j++) { if(Node[i].passWord[j] == '1') { Node[i].passWord[j] = '@'; flag = 1; } if(Node[i].passWord[j] == '0') { Node[i].passWord[j] = '%'; flag = 1; } if(Node[i].passWord[j] == 'l') { Node[i].passWord[j] = 'L'; flag = 1; } if(Node[i].passWord[j] == 'O') { Node[i].passWord[j] = 'o'; // flag = 1; } } if(flag == 1) return true; else return false; } int main() { // 输入 scanf("%d",&N); for(int i=0; i<N; i++) { scanf("%s %s",Node[i].userName,Node[i].passWord); ////// %s %s间有空格; //////Node[i].userName前无& } // 查找并替换 for(int i=0; i<N; i++) { if(check(i)) { num++; tag[i] = 1; } } // 输出 if(num == 0) { printf("There is %d account and no account is modified",N); return 0; } printf("%d\n",num); for(int i=0; i<N; i++) { if(tag[i] == 1) { printf("%s %s",Node[i].userName,Node[i].passWord); num2 ++; if(num2 != num) printf("\n"); } } return 0; } 17' 一个测试点出错 ???
Java
UTF-8
6,699
1.773438
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2017, Rockwell Collins * All rights reserved. * * This software may be modified and distributed under the terms * of the 3-clause BSD license. See the LICENSE file for details. * */ package fuzzm.lustre.evaluation; import java.util.List; import fuzzm.poly.PolyBool; import fuzzm.util.Debug; import fuzzm.util.EvaluatableSignal; import fuzzm.util.EvaluatableVector; import fuzzm.util.ID; import fuzzm.util.IDString; import fuzzm.util.ProofWriter; import fuzzm.util.StringMap; import fuzzm.util.TypedName; import fuzzm.value.hierarchy.EvaluatableValue; import fuzzm.value.poly.BooleanPoly; import fuzzm.value.poly.GlobalState; import fuzzm.value.poly.PolyEvaluatableValue; import jkind.lustre.BinaryExpr; import jkind.lustre.BinaryOp; import jkind.lustre.Equation; import jkind.lustre.Expr; import jkind.lustre.IdExpr; import jkind.lustre.IfThenElseExpr; import jkind.lustre.NamedType; import jkind.lustre.Node; import jkind.lustre.Program; import jkind.lustre.Type; import jkind.lustre.UnaryExpr; import jkind.lustre.UnaryOp; import jkind.lustre.values.Value; import jkind.lustre.visitors.TypeReconstructor; import jkind.util.Util; public abstract class DepthFirstSimulator extends BaseEvaluatableValueEvaluator { //private final int k; protected final StringMap<Type> types; private final StringMap<Expr> equations = new StringMap<Expr>(); private final List<Expr> assertions; private final TypeReconstructor tx; protected int step = 0; private EvaluatableSignal state; private int thms = 0; protected DepthFirstSimulator(FunctionLookupEV fns, Program prog) { super(fns); Node node = prog.getMainNode(); for (Equation eq : node.equations) { equations.put(((IdExpr) eq.lhs.get(0)).id,eq.expr); } assertions = node.assertions; types = new StringMap<Type>(Util.getTypeMap(node)); tx = new TypeReconstructor(prog); tx.setNodeContext(node); } public PolyBool simulateProperty(EvaluatableSignal state, String name, IDString property) { assert(step == 0); int k = state.size(); System.out.println(ID.location() + "Counterexample Depth : " + k); this.state = new EvaluatableSignal(state); EvaluatableValue accumulatedAssertions = BooleanPoly.TRUE; EvaluatableValue nextAccumulator; for (int time = 0; time < k; time++) { step = time; for (Expr asrt: assertions) { PolyEvaluatableValue asv = (PolyEvaluatableValue) eval(asrt); assert(asv.cex().signum() != 0); nextAccumulator = accumulatedAssertions.and(asv); assert(((PolyEvaluatableValue) accumulatedAssertions).cex().signum() != 0); if (Debug.isEnabled()) { System.out.println(ID.location() + "Assertion " + asrt + " evaluated to " + asv + " [" + asv.cex() + "]"); System.out.println(ID.location() + "Accumulated Assertions [" + thms + "] " + nextAccumulator); String asvString = asv.toACL2(); String preString = ((PolyEvaluatableValue) accumulatedAssertions).toACL2(); String postString = ((PolyEvaluatableValue) nextAccumulator).toACL2(); ProofWriter.printAndTT(ID.location(),String.valueOf(thms),asvString,preString,postString); System.out.println(ID.location() + "Accumulated Assertions [" + thms + "] " + nextAccumulator); thms++; } accumulatedAssertions = nextAccumulator; assert(step == time); } } step = k-1; Expr propExpr = equations.get(property.name()); PolyEvaluatableValue propVal = (PolyEvaluatableValue) eval(propExpr); if (Debug.isEnabled()) System.out.println(ID.location() + name + " = " + propExpr + " evaluated to " + propVal + " [" + propVal.cex() + "]"); PolyEvaluatableValue constraintVal = (PolyEvaluatableValue) propVal.not(); assert(constraintVal.cex().signum() != 0); EvaluatableValue accumulatedConstraints = accumulatedAssertions.and(constraintVal); if (Debug.isEnabled()) { System.out.println(ID.location() + "Constraint not(" + propExpr + ") evaluated to " + constraintVal + " [" + constraintVal.cex() + "]"); System.out.println(ID.location() + "Final Constraint [" + thms + "] " + accumulatedConstraints); String propString = constraintVal.toACL2(); String preString = ((PolyEvaluatableValue) accumulatedAssertions).toACL2(); String postString = ((PolyEvaluatableValue) accumulatedConstraints).toACL2(); ProofWriter.printAndTT(ID.location(),String.valueOf(thms),propString,preString,postString); System.out.println(ID.location() + "Accumulated Constriant [" + thms + "] " + accumulatedConstraints); thms++; } PolyBool polyConstraint = ((BooleanPoly) accumulatedConstraints).value; PolyBool globalInvariants = GlobalState.getInvariants(); PolyBool finalConstraint = polyConstraint.and(globalInvariants); if (Debug.isEnabled()) { System.err.println(ID.location() + "Accumulated Constraints : " + polyConstraint); System.err.println(ID.location() + "Global Invariants : " + globalInvariants); ProofWriter.printAndTT(ID.location(),String.valueOf(thms),polyConstraint.toACL2(),globalInvariants.toACL2(),finalConstraint.toACL2()); System.out.println(ID.location() + "Final Constraint [" + thms + "] " + finalConstraint); thms++; } return finalConstraint; } @Override public abstract Value visit(IfThenElseExpr e); @Override public Value visit(IdExpr e) { EvaluatableVector v = state.get(step); TypedName tname = new TypedName(e.id,(NamedType) types.get(e.id)); if (v.containsKey(tname)) { PolyEvaluatableValue res = (PolyEvaluatableValue) v.get(tname); if (Debug.isEnabled()) System.out.println(ID.location() + e.id + " evaluated to " + res + " [" + res.cex() + "] in time step " + step); return res; } Expr expr = equations.get(e.id); if (expr == null) { System.out.println(ID.location() + "Warning: using default value for " + e); return getDefaultValue(e); } PolyEvaluatableValue value = (PolyEvaluatableValue) eval(expr); if (Debug.isEnabled()) System.out.println(ID.location() + e.id + " = " + expr + " evaluated to " + value + " [" + value.cex() + "] in time step " + step); state.set(new TypedName(e.id,(NamedType) types.get(e.id)),step,value); return value; } abstract protected Value getDefaultValue(IdExpr e); protected Type typeOf(Expr expr) { return expr.accept(tx); } @Override public Value visit(BinaryExpr e) { if (e.op == BinaryOp.ARROW) { if (step == 0) { return e.left.accept(this); } else { return e.right.accept(this); } } else { return super.visit(e); } } @Override public Value visit(UnaryExpr e) { if (e.op == UnaryOp.PRE) { assert(step > 0); step--; Value value = e.expr.accept(this); step++; return value; } else { return super.visit(e); } } }
Markdown
UTF-8
1,678
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# React : Design Patterns Ce dossier Repository est lié au cours React : Design Patterns. Le cours est accessible sur [LinkedIn Learning](https://www.linkedin.com/learning/react-design-patterns-10416007). Dans cette formation qui s'adresse aux développeurs d'application web, vous découvrirez l'usage des design patterns de la bibliothèque React. En compagnie de Sandy Ludosky, vous découvrirez en quoi consistent les design patterns, comment ils permettent de partager et composer le code, et comment assurer la maintenabilité et la scalabilité. Puis, toujours avec des exemples concrets, vous aborderez les props de rendu, la mise en œuvre des composants d'ordre supérieur (HOC) et des interfaces de programmation (API). À la fin de cette formation, vous aurez assimilé toutes les bonnes pratiques pour vos projets React. ## Instructions Ce dossier Repository a des branches pour chacune des vidéos du cours. Vous pouvez utiliser le menu des Branches sur GitHub afin d’accéder aux passages qui vous intéressent. Vous pouvez également rajouter `/tree/BRANCH_NAME` à l’URL afin d’accéder à la branche qui vous intéresse. ## Branches Les branches sont structurées de manière à correspondre aux vidéos du cours. La convention de nommage est : `CHAPITRE#_VIDEO#`. Par exemple, la branche nommée `02_03` correspond au second chapitre, et à la troisième vidéo de ce chapitre. Certaines branches ont un état de départ et de fin. La branche `02_03b (beginning)` correspond au code du début de la vidéo. La branche `02_03e (ending)` correspond au code à la fin de la vidéo. La branche master correspond au code à la fin de la formation.
Java
UTF-8
4,259
1.914063
2
[]
no_license
package com.eposapp.service.impl; import com.eposapp.common.constant.JsonConstans; import com.eposapp.common.constant.ResponseCodeConstans; import com.eposapp.common.constant.SysConstants; import com.eposapp.common.util.EntityUtil; import com.eposapp.common.util.JsonResult; import com.eposapp.common.util.StringUtils; import com.eposapp.common.util.ValidationUtils; import com.eposapp.entity.SysDepartmentEntity; import com.eposapp.entity.SysOrganizationEntity; import com.eposapp.repository.mysql.SysDepartmentRepository; import com.eposapp.repository.mysql.SysOrganizationRepository; import com.eposapp.service.SysDepartmentService; import com.eposapp.service.SysOrganizationService; import com.eposapp.threadlocal.SystemSession; import org.hibernate.transform.Transformers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * @author eiven * */ @Service public class SysDepartmentServiceImpl implements SysDepartmentService { @Autowired private SysDepartmentRepository sysDepartmentRepository; @Override public JsonResult doSaveOrUpdate(Map paramsMap) { try { String isVali= ValidationUtils.validation(paramsMap); if(!isVali.equals(ResponseCodeConstans.SUCCESS)){ return JsonResult.putFail(isVali); } String id = StringUtils.getMapKeyValue(paramsMap,"id"); String code = StringUtils.getMapKeyValue(paramsMap,"code"); boolean isExistCode = sysDepartmentRepository.isExistCode(SysDepartmentEntity.class,code,id); if(isExistCode){ return JsonResult.putFail(JsonConstans.ERR_CODE_EXISTS); } SysDepartmentEntity sysDepartmentEntity = null; boolean isSave = false; if(StringUtils.isNotBlank(id)){ sysDepartmentEntity = sysDepartmentRepository.findById(new SysDepartmentEntity(),id); if(sysDepartmentEntity==null){ return JsonResult.putFail(JsonConstans.ERR_NOT_EXISTED); } EntityUtil.putMapDataIntoEntity(paramsMap,sysDepartmentEntity); isSave = sysDepartmentRepository.update(sysDepartmentEntity); }else{ sysDepartmentEntity = new SysDepartmentEntity(); EntityUtil.putMapDataIntoEntity(paramsMap,sysDepartmentEntity); isSave = sysDepartmentRepository.save(sysDepartmentEntity); } if(isSave){ return JsonResult.putSuccess(); }else{ return JsonResult.putFail(JsonConstans.OPERATION_FAILURE); } } catch (Exception e) { e.printStackTrace(); return JsonResult.putFail(JsonConstans.OPERATION_FAILURE); } } @Override public boolean delete(Class clazz, String id) { return sysDepartmentRepository.delete(clazz,id); } @Override public Map<String, Object> findDeptList(Map paramsMap) { String cnName = StringUtils.getMapKeyValue(paramsMap,"cnName"); String pageNoStr = StringUtils.getMapKeyValue(paramsMap,"pageNo"); String pageSizeStr = StringUtils.getMapKeyValue(paramsMap,"pageSize"); String sql = "SELECT depart.id,depart.parentId,depart2.cnName AS parentName,\n" + " depart.`code`,depart.cnName,depart.enName,depart.sequence,\n" + " depart.phone,depart.fax,depart.principal,depart.remarks,depart.version,\n" + " depart.isDelete,depart.isUse,depart.createId,depart.createTime,u.cnName AS createName\n" + " FROM sys_department depart \n" + "LEFT JOIN sys_department depart2 ON depart2.id = depart.id\n" + "LEFT JOIN sys_user u ON u.id = depart.createId" ; String orgId= SystemSession.getOrgId(); boolean isHasWhere = false; if(StringUtils.isNotBlank(orgId)&& !SysConstants.ROOT_ID.equals(orgId)){ sql+=" WHERE depart.orgId ='"+ orgId +"'"; isHasWhere = true; } Map<String,String> conditionParams = new HashMap<>(3); if(StringUtils.isNotBlank(cnName)){ if(isHasWhere){ sql +=" AND depart.cnName =:cnName "; }else{ sql +=" WHERE depart.cnName =:cnName "; } conditionParams.put("cnName",cnName); } Integer pageNo =null; Integer pageSize =null; if(StringUtils.isNotBlank(pageNoStr)){ pageNo = Integer.valueOf(pageNoStr); } if(StringUtils.isNotBlank(pageSizeStr)){ pageSize = Integer.valueOf(pageSizeStr); } return sysDepartmentRepository.findByNativeQuery(sql,conditionParams,Transformers.ALIAS_TO_ENTITY_MAP,pageNo,pageSize); } }
C++
UTF-8
8,600
2.75
3
[ "MIT" ]
permissive
// CIX C++ library // Copyright (c) Jean-Charles Lefebvre // SPDX-License-Identifier: MIT namespace cix { namespace path { template <typename Char> inline constexpr bool is_sep(Char c) noexcept { #ifdef _WIN32 return c == win_sep<Char> || c == unix_sep<Char>; #else return c == unix_sep<Char> || c == win_sep<Char>; #endif } template <typename Char> constexpr bool is_drive_letter(Char c) noexcept { // Not positive string::char_is() strictly matches alpha characters in the // ASCII range *only*. We do not want alpha unicode characters, so go for // the explicit manual way. // return string::char_is(c, string::ctype_alpha); return (c >= Char('A') && c <= Char('Z')) || (c >= Char('a') && c <= Char('z')); } template <typename String> inline std::enable_if_t< string::is_string_viewable_v<String>, bool> is_absolute(const String& path) noexcept { const auto view = string::to_string_view(path); const auto len = view.length(); if (len > 0) { if (is_sep(view[0])) return true; if (len >= 2 && view[1] == decltype(view)::value_type(':') && is_drive_letter(view[0])) { return true; } } return false; } #if 0 template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> root(const String& path) noexcept { // supported forms: // <drive_letter>: // <drive_letter>:\ // \ (relative to current working directory root) // \\<server>\<sharename>\ // \\?\<drive_spec>:\ // \\.\<physical_device>\ // \\?\<server>\<sharename>\ // \\?\UNC\<server>\<sharename>\ // // ref: // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx // <- especially the "Namespaces" section // https://msdn.microsoft.com/en-us/library/aa365247.aspx // https://en.wikipedia.org/wiki/Path_(computing) auto view = string::to_string_view(path); if (view.empty()) return view; if (view.size() >= 2 && view[1] == Char(':') && is_drive_letter(view[0])) { std::size_t root_len = 2; if (view.size() >= 3) { root_len = view.find_first_not_of(all_sep_str<Char>, 2); if (root_len == view.npos) root_len = view.size(); } return std::basic_string_view<Char>(view.data(), root_len); } CIXTODO; // see wstr::path_root() } #endif // template < // typename String, // typename Char> // inline std::enable_if_t< // string::is_string_viewable_v<String>, // std::basic_string_view<Char>> // nonroot(const String& path) noexcept // { // CIXTODO; // } template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> basename(const String& path) noexcept { // POSIX compliance: // input dirname basename // "/usr/lib" "/usr" "lib" // "/usr/" "/" "usr" // "usr" "." "usr" // "/" "/" "/" // "." "." "." // ".." ".." ".." // "" "." "" // TODO: split root part first in case of an absolute path static constexpr auto sep = native_sep_str<Char>; auto view = string::to_string_view(path); if (view.empty()) return view; // trim trailing separators view = string::rtrim_if(view, is_sep<Char>); if (view.empty()) return sep; // there was only separator(s) in path // search for the last separator in the string auto rit = std::find_if(view.rbegin(), view.rend(), is_sep<Char>); if (rit == view.rend()) return view; // no separator // strip prefix up to the last found separator view.remove_prefix(std::distance(view.begin(), rit.base())); return view; } template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> dirname(const String& path) noexcept { // POSIX compliance: // input dirname basename // "/usr/lib" "/usr" "lib" // "/usr/" "/" "usr" // "usr" "." "usr" // "/" "/" "/" // "." "." "." // ".." ".." ".." // "" "." "" // TODO: split root part first in case of an absolute path static constexpr auto sep = native_sep_str<Char>; static constexpr auto dot_arr = std::array<Char, 1>{ Char('.') }; static constexpr auto dot = string::to_string_view(dot_arr); auto view = string::to_string_view(path); if (view.empty()) return dot; // trim trailing separators view = string::rtrim_if(view, is_sep<Char>); if (view.empty()) return sep; // there was only separator(s) in path // search for the last separator in the string auto rit = std::find_if(view.rbegin(), view.rend(), is_sep<Char>); if (rit == view.rend()) return dot; // no separator // strip basename view.remove_suffix(std::distance(rit.base(), view.end())); // trim trailing separators view = string::rtrim_if(view, is_sep<Char>); if (view.empty()) return sep; // there was only separator(s) remaining return view; } template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> title(const String& path) noexcept { return trim_ext(basename(path)); } template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> trim_ext(const String& path) noexcept { const auto name_ = basename(path); const auto pos = name_.find_last_of(Char('.')); if (pos == name_.npos || pos == 0) return string::to_string_view(path); auto view = string::to_string_view(path); view.remove_suffix(name_.length() - pos); return view; } template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> trim_all_ext(const String& path) noexcept { auto result = trim_ext(path); for (;;) { auto tmp = trim_ext(result); if (tmp.size() == result.size()) break; result.swap(tmp); } return result; } template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> ltrim_sep(const String& path) noexcept { auto view = string::to_string_view(path); if (!view.empty()) view = string::ltrim_if(view, is_sep<Char>); return view; } template < typename String, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string_view<Char>> rtrim_sep(const String& path) noexcept { auto view = string::to_string_view(path); if (!view.empty()) view = string::rtrim_if(view, is_sep<Char>); return view; } template < typename String, typename... Args, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string<Char>> join(const String& head, Args&&... args) noexcept { return string::melt_trimmed( native_sep_str<Char>, head, std::forward<Args>(args)...); } template < typename Container, typename Char> inline std::enable_if_t< string::is_container_of_strings_v<Container>, std::basic_string<Char>> join(const Container& elements) noexcept { return string::melt_trimmed(native_sep_str<Char>, elements); } template < typename String, typename... Args, typename Char> inline std::enable_if_t< string::is_string_viewable_v<String>, std::basic_string<Char>> join_with(Char sep, const String& head, Args&&... args) noexcept { const Char sep_str[2] = { sep, Char(0) }; return string::melt_trimmed( sep_str, head, std::forward<Args>(args)...); } template < typename Container, typename Char> inline std::enable_if_t< string::is_container_of_strings_v<Container>, std::basic_string<Char>> join_with(Char sep, const Container& elements) noexcept { const Char sep_str[2] = { sep, Char(0) }; return string::melt_trimmed(sep_str, elements); } } // namespace path } // namespace cix
Python
UTF-8
3,576
2.90625
3
[]
no_license
import os import re from collections import namedtuple Service = namedtuple('Service', ['number', 'status', 'transport_protocol', 'application_protocol']) Host = namedtuple('Host', ['addr', 'hostname', 'status', 'services']) HOST_WITH_SERVICES = re.compile(r'Host:\s\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s\(.*\)\sPorts\:.*') HOST_WITHOUT_SERVICES = re.compile(r'Host:\s\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s\(.*\)\sStatus:\s.*') class Parser: hosts = [] web_protocols = { 'http':'http', 'http-proxy':'http', 'https':'https', 'ssl/http':'https', 'ssl/https':'https', 'ssl/https?':'https', 'ssl/http-proxy':'https' } delimiter = '\n' def __init__(self, nmap_file): self.display_functions = { 'hosts':self.display_hosts, 'webhosts':self.display_webhosts, 'webports':self.display_webports } self.nmap_file = nmap_file self.parse_hosts() def parse_hosts(self): if not os.path.exists(self.nmap_file): print(f'{self.nmap_file} does not exist.') return None with open(self.nmap_file, 'r') as fd: for line in fd: _line_values = line.split() if HOST_WITH_SERVICES.match(line): addr = _line_values[1] hostname = _line_values[2] status = 'Up' services = ''.join(_line_values[4:]).split('/,') services = self.parse_services(services) self.hosts.append(Host(addr, hostname, status, services)) continue if HOST_WITHOUT_SERVICES.match(line): addr = _line_values[1] hostname = _line_values[2] status = _line_values[4] self.hosts.append(Host(addr, hostname, status, [])) continue def parse_services(self, services): _services = [] for service in services: _service_values = service.split('/') number = _service_values[0] status = _service_values[1] transport_protocol = _service_values[2] application_protocol = _service_values[4] _services.append(Service(number, status, transport_protocol, application_protocol)) return _services def display_hosts(self): for host in self.hosts: print(f'{host.addr} {host.hostname} {host.status}', end=' ') if not host.services: print(end=self.delimiter) continue for service in host.services: print(f'{service.application_protocol} {service.number} {service.transport_protocol} {service.status}', end=', ') print(end=self.delimiter) def display_webhosts(self): for host in self.hosts: if not host.services: continue for service in host.services: if service.application_protocol in self.web_protocols: web_protocol = self.web_protocols[service.application_protocol] print(f'{web_protocol}://{host.addr}:{service.number}', end=self.delimiter) def display_webports(self): for host in self.hosts: if not host.services: continue for service in host.services: if service.application_protocol in self.web_protocols: print(f'{service.number}', end=self.delimiter)
Java
UTF-8
584
2.203125
2
[]
no_license
package Test; import java.sql.Connection; import java.sql.SQLException; import Connection.OracleConnection; import Domain.BankAccountException; public class A_TestConnection { public static void main(String[] args) { try { OracleConnection oracon = new OracleConnection(); oracon.open(); Connection con = oracon.getConnection(); System.out.println(con.getMetaData().getDatabaseMajorVersion()); oracon.close(); } catch (BankAccountException | SQLException e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); } } }
Java
UTF-8
4,993
2.125
2
[]
no_license
package com.tsp3.stashcards; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import com.android.volley.*; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import static android.provider.AlarmClock.EXTRA_MESSAGE; public class Library extends AppCompatActivity { private Spinner spinner; public ArrayList<String> libraryContents = new ArrayList<String>(); public ArrayList<String> sets = new ArrayList<String>(); public ArrayList<String> creators = new ArrayList<String>(); private JSONArray result; private TextView textViewName; private TextView textViewCourse; private TextView textViewSession; public ArrayAdapter<String> adapter; private ListView listview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_library); getWindow().getDecorView().setBackgroundColor(Color.parseColor("#6495ED")); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent create = new Intent(Library.this, CreateCard.class); startActivity(create); } }); getData(); libraryContents = sets; listview = (ListView) findViewById(R.id.list); Intent intent = new Intent(this, DisplayCard.class); listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { int intPosition = position; String clickedValue = listview.getItemAtPosition(intPosition).toString(); goToCards(Integer.toString(intPosition+1)); } }); } void goToCards(String setinfo){ Toast.makeText(getApplicationContext(), setinfo, Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, DisplayCard.class); String message = setinfo; intent.putExtra("SetID", message); startActivity(intent); } private void setLibrary(){ } private void getData(){ result = new JSONArray(); StringRequest stringRequest = new StringRequest("http://tsp3.000webhostapp.com/SetJson.php", new Response.Listener<String>() { @Override public void onResponse(String response) { JSONObject j = null; try { j = new JSONObject(response); result = j.getJSONArray("result"); Library.this.runOnUiThread(new Runnable() { public void run() { getSets(result); } }); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } private void getSets(JSONArray j){ //Traversing through all the items in the json array for(int i=0;i<j.length();i++){ try { //Getting json object JSONObject json = j.getJSONObject(i); //Adding the name of the student to array list sets.add(json.getString("Set_Name")); creators.add(json.getString("creator")); } catch (JSONException e) { e.printStackTrace(); } } //create adaptor to add array to list ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1, sets); //assign adapter to list view listview.setAdapter(adapter); } }
PHP
UTF-8
969
2.5625
3
[]
no_license
<?php /* * 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. */ /** * Description of Serie * * @author Fernando */ class Zend_View_Helper_Serie extends Zend_View_Helper_Abstract { public function serie($serie) { $text = ""; switch ($serie) { case 1: $text = "Brasileirão Série A"; break; case 2: $text = "Brasileirão Série B"; break; case 3: $text = "Brasileirão Série C"; break; case 4: $text = "Brasileirão Série D"; break; default: break; } return $text; } }
Markdown
UTF-8
2,022
2.546875
3
[]
no_license
# uqueue ### Created by Shawn Fotsch and John Rocha ##Screenshots ![screen1](screenshots/playlists.png) ![screen2](screenshots/player.png) ![screen3](screenshots/queue.png) ![screen4](screenshots/broadcasted.png) ##Proof of Concept We originally intended to use Spotify's iOS API to take care of all of the music playing aspects of this app while we focused on establishing a means of communication between the users. Unfortunately, the documentation and framework was deprecated, so we instead had to spend a majority of our time building the music player from the ground up. This included the ability to create/save custom playlists. After creating a reasonable player interface, we implemented user authentication using Facebook and Firebase. The use of Facebook makes it easy to connect to your Facebook friends who also have the app. The user can either choose to broadcast their own playlist so that their friends can follow along, or if a friend is broadcasting and they have been invited, the user can view that friend's playlist. User's have the ability to like/dislike songs on a playlist being broadcasted to them, and these numbers will be updated in real-time across all devices currently viewing the same playlist. We also implemented a basic song request feature where a user could send a host a song suggestion. All broadcasted information is stored in a Firebase database allowing information to flow between users. Ultimately, the application is not in a state to be used widely, but it serves as a proof of concept for our idea to take the stress of a party's host/dj and serves as an effective means of aggregating user feedback. ####Features Not Implemented (Yet) - The ability for the queue to automatically rearrange songs based on number of likes/dislikes - Ability to add a song directly from the song request list - Broadcast doesn't update if a new song is added, it only keeps the list of songs present when the broadcast button was pressed - Push notifications for invites
Python
UTF-8
9,897
2.578125
3
[]
no_license
import django import os import time,statistics os.environ['DJANGO_SETTINGS_MODULE'] = 'helloword.settings' django.setup() class TimeTestTool: # 计算函数运行的时间 @classmethod def calc_func_time(cls, func): start = time.perf_counter() func() end = time.perf_counter() return end - start # 统计时间 @classmethod def statistic_run_time(cls, func, n): data = [cls.calc_func_time(func) for i in range(n)] mean = statistics.mean(data) sd = statistics.stdev(data, xbar=mean) return [data, mean, sd, max(data), min(data)] # 对比 @classmethod def compare(cls, func1, func2, n): result1 = cls.statistic_run_time(func1, n) result2 = cls.statistic_run_time(func2, n) print('对比\t 没有预加载 \t 预加载') print('平均值\t', result1[1], '\t', result2[1]) from juheapp.models import User,App # 懒加载 def lazy_load(): for user in User.objects.all(): print(user.menu.all()) # 预加载 def pre_load(): for user in User.objects.prefetch_related('menu'): print(user.menu.all()) TimeTestTool.compare(lazy_load,pre_load,1000) # from django.test import TestCase # # # Create your tests here. # # # # 先配置django的环境 # import os # import django # # # dajngo黄静的模型 # django.setup() # # from juheapp.models import User,App # # os.environ['DJANGO_SETTINGS_MODULE'] = 'helloword.settings' # # # user1 = User.objects.all()[0] # print(user1.menu) # # import os # import time # import django # import random # import hashlib # # import time, statistics # # from django.utils import timezone # # # from backend import settings # # os.environ.setdefault('DJANGO_SETTINGS_MODULE','backend.settings') # django.setup() # # # from . import lazy_load # # # class TimeTestTool: # # 计算函数运行时间 # @classmethod # def calc_func_time(cls,func): # start = time.perf_counter() # func() # end = time.perf_counter() # return end - start # # # # 统计时间 # @classmethod # def statistic_run_time(cls,func,n): # data = [cls.calc_func_time(func)for i in range(n)] # mean = statistics.mean(data) # sd = statistics.stdev(data,xbar=mean) # return [data, mean, sd, max(data), min(data)] # # # # 对比 # @classmethod # def compare(cls,func1,func2,n): # result1 = cls.statistic_run_time(func1, n) # result2 = cls.statistic_run_time(func2, n) # print('对比\t 没有预加载 \t 预加载') # print('平均值\t', result1[1], '\t',result2[1]) # # # # # # 懒加载 # def lazy_load(): # for user in User.objects.all(): # print(user.menu.all()) # # # 预加载 # def pre_load(): # for user in User.objects.prefetch_related('menu'): # print(user.menu.all) # # TimeTestTool.compare(lazy_load,pre_load,1000) # if __name__ == '__main__': # TimeTestTool.compare(lazy_load.lazy_load,lazy_load.pre_load,100) # import yaml # # # # filepath = r'D:\PycharmProjects\dj_three\helloword\helloword\myappconfig.yaml' # # with open(filepath,'r',encoding='utf8') as f: # # res = yaml.load(f, Loader=yaml.FullLoader) # # print(res) # # print(type(res)) # # # # # # from django.conf import settings # # # # os.environ['DJANGO_SETTINGS_MODULE']='helloword.settings' # # # static_file_path = os.path.join(settings.BASE_DIR,'static') # # # # # # print('static_file_path',static_file_path) # # # filename=r'/abc.png' # # # filepath= os.path.join(static_file_path,filename) # # # print(filepath) # # # # print('basedir:',settings.BASE_DIR) # # # # static_filedir = settings.STATIC_URL # # # print('static_filedir',static_filedir) # # print('static_filedir',os.path.join(settings.BASE_DIR,'static')) # # print(settings.STATIC_ROOT_SELF) # # # # 查询某个对象 # # 导入django的模型 # from juheapp.models import User # # # r = User.objects.filter(nickName__contains='ch') # # r = User.objects.get(nickName='charon@') # # print(r) # # import random # # def ranstr(length): # CHS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' # salt = '' # for i in range(length): # salt += random.choice(CHS) # return salt # # # print(ranstr(8)) # # # 增删改查 # # # 单个增加 # def add_one(): # # 1 # # user = User(openid = 'test_open_id', nickName='test_nickname') # # user.save() # # # 2 # User.objects.create(openid = 'test_open_id2', nickName='test_nickname2') # # # add_one() # # def add_batch(): # new_user_list = [] # for i in range(10): # open_id = ranstr(32) # nickname = ranstr(10) # user = User(openid=open_id, nickName=nickname) # new_user_list.append(user) # User.objects.bulk_create(new_user_list) # # # add_batch() # # # 查询 # # 精确查询 属性+值 # def get_one(): # try: # user = User.objects.get(openid='阿斯弗') # print(user) # except Exception as e: # print(e) # # # # get_one() # # # 数据过滤 模糊查询 # def get_filter(): # # 属性__哪种类型的模糊查询 __contains包含 __exact 精确 # users = User.objects.filter(openid__startswith='test') # # open_id__startswith # # 大于: open_id__gt(greater than) # # 小于: open_id__lt(little than) # # 大于等于:open_id__gte(greater than equal) # # 小于等于:open_id__lte(little than equal) # print(users) # # # get_filter() # # # # 数据排序 # def get_order(): # users = User.objects.order_by('nickName') # print(users) # # # # get_order() # # # # 连锁查询 # # 和管道符类似 # def get_chain(): # users = User.objects.filter(openid__contains='test_').order_by('openid') # print(users) # # # get_chain() # # # 改一个 # def modify_one(): # user = User.objects.get(openid = 'test_open_id') # user.nickName = 'modify_username' # user.save() # # print(user) # # # modify_one() # # # 批量改 # def modify_batch(): # User.objects.filter(openid__contains='test_').update(nickName='modify_uname') # # # # modify_batch() # # # 删除 一个 # def delete_one(): # User.objects.get(openid='test_open_id').delete() # # # delete_one() # # # 批量删除 # # # 批量删除 # def delete_batch(): # User.objects.filter(openid__contains='test_').delete() # # # delete_batch() # # # 全部删除 # def delete_all(): # User.objects.all().delete() # # # 数据库函数 # # 字符串拼接:Concat # # from django.db.models import Value # from django.db.models.functions import Concat # # annotate创建对象的一个属性, Value可以随便写,如果不是对象中原有属性会报错 # def concat_function(): # users = User.objects.filter(openid='test_open_id').annotate( # # open_id=(open_id), nickName=(nickname) # # screen_name = Concat( # # Value('openid='), # # 'openid', # # Value(', '), # # Value('nickName='), # # 'nickName') # # ) # screen_name = Concat( # Value('openid='),'nickName' # )) # print('screen_name = ', users[0].screen_name) # # # # concat_function() # # # 字符串长度 # from django.db.models.functions import Length # # def length_function(): # user = User.objects.filter(openid='test_open_id').annotate( # openid_length = Length('openid'))[0] # # print(user.openid_length) # # # length_function() # # # # 大小写函数 # from django.db.models.functions import Upper, Lower # # def case_function(): # user = User.objects.filter(openid='test_open_id').annotate( # upper_openid=Upper('openid'), # lower_openid=Lower('openid') # )[0] # print('upper_openid:', user.upper_openid, ', lower_openid:', user.lower_openid) # pass # # # case_function() # # # # 日期处理函数 # # Now() # # from blog.models import Article # from django.db.models.functions import Now # from datetime import datetime,timedelta # dt = datetime(day=29,year=2020,month=2) # print(dt) # def now_function(): # # 当前日期之前发布的所有应用 # # gt 大于 # # lt 小于 # # 有 e equel== # articles = Article.objects.filter(publist_date__gt=dt) # for article in articles: # print(article) # # # now_function() # # # 时间截断函数 # # Trunc # from django.db.models import Count # from django.db.models.functions import Trunc # # # def trunc_function(): # # 打印每一天发布的应用数量 # # articel_per_day = Article.objects.annotate(publish_day=Trunc('publist_date', 'month'))\ # # .values('publist_date')\ # # .annotate(publish_num=Count('article_id')) # # # # for article in articel_per_day: # # print('date:', article['publist_date'], ', publish num:', article['publish_num']) # # article_per_day = Article.objects.annotate(publish_day = Trunc('publist_date','month'))\ # .values('publish_day')\ # .annotate(publish_num = Count('content')) # # .annotate(publish_num = Count('article_id')) # # for article in article_per_day: # print('date:',article['publish_day'],',publish nums:',article['publish_num']) # # # # trunc_function() # # # def addarticle(): # # Article.objects.create(title='zzz',brief_content='zxx',content='sdfagfg rgasd',publist_date=dt) # # addarticle() # # # from django.db.models import Q # from django.db.models import F # # # Q 用于构造复杂的查询条件 如 & | 操作 # # ~Q 全部 # def getfilter2(): # users = User.objects.filter(Q(openid__contains='IeELdFoPqBOdB4tJkktg6gJ9N1ihrjWB') & Q(nickName__contains='test') | Q(nickName__contains='names')) # # users = User.objects.filter(~Q(nickName__contains='test')) # print(users) # # # # getfilter2()
Java
UTF-8
3,635
2.390625
2
[]
no_license
package com.lin.controller.user; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.lin.model.user.User; import com.lin.service.user.UserService; @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @Autowired private HttpSession session; @RequestMapping(value = "/modifyPayPasswordInit", method = RequestMethod.GET) public String modifyPayPasswordInit(Model model) { System.out.println("进入modifyPayPasswordInit方法"); User user = (User) session.getAttribute("user"); /*if(user == null) { return "redirect:/init"; } */ if(StringUtils.isBlank(user.getPayPassword())) { model.addAttribute("isNewUser", true); } else { model.addAttribute("isNewUser", false); } return "user/password_edit"; } @RequestMapping(value = "/modifyPayPassword", method = RequestMethod.POST) @ResponseBody public Map<String, Object> modifyPayPassword(String oldPayPassword, String newPayPassword, String truePayPassword) { System.out.println("进入modifyPayPassword方法"); User user = (User) session.getAttribute("user"); Map<String,Object> map = new HashMap<String, Object>(); map.put("result", false); if(user == null) { map.put("msg", "用户未登录"); return map; } if(!StringUtils.isBlank(oldPayPassword) && oldPayPassword.equals(userService.selectUserById(user.getId()).getPayPassword())) { return map; } if (StringUtils.isBlank(newPayPassword) || StringUtils.isBlank(truePayPassword)) { map.put("msg", "密码不能为空"); } else { if(newPayPassword.equals(truePayPassword)) { user.setPayPassword(newPayPassword); if(userService.modifyPayPassword(user)) { map.put("result", true); map.put("msg", "支付密码设置成功"); } else { map.put("result", false); map.put("msg", "支付密码设置失败,请重试"); } } else { map.put("msg", "两次输入的密码不相同"); } } return map; } @RequestMapping(value = "/rechargeInit", method = RequestMethod.GET) public String rechargeInit(Model model) { System.out.println("进入rechargeInit方法"); User account = userService.selectUserById(((User) session.getAttribute("user")).getId()); model.addAttribute("user", account); return "user/recharge"; } @RequestMapping(value = "/recharge", method = RequestMethod.POST) @ResponseBody public Map<String, Object> recharge(double balance) { System.out.println("进入recharge方法"); User user = (User) session.getAttribute("user"); Map<String,Object> map = new HashMap<String, Object>(); map.put("result", false); if(user == null) { map.put("msg", "用户未登录"); return map; } if(balance > 0) { if(userService.recharge(user, balance)) { System.out.println("充值成功"); map.put("result", true); map.put("msg", "充值成功"); } else { System.out.println("充值失败"); map.put("msg", "充值失败,请重试"); } } else { map.put("msg", "充值失败,充值金额不能为0"); } return map; } }
Java
UTF-8
3,392
2.171875
2
[ "Apache-2.0" ]
permissive
package com.asus.robotdevsample; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.asus.robotframework.API.RobotCallback; import com.asus.robotframework.API.RobotCmdState; import com.asus.robotframework.API.RobotErrorCode; import com.robot.asus.robotactivity.RobotActivity; import org.json.JSONObject; public class MotionActivity extends RobotActivity { private ListView listView; private String[] listViewitems; private ArrayAdapter listAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_listview_menu); //title TextView mTextViewTitle = (TextView)findViewById(R.id.textview_title); mTextViewTitle.setText(getString(R.string.toolbar_title_subclass_motion_title)); listViewitems = getResources().getStringArray(R.array.subclasses_motion); listView = (ListView)findViewById(R.id.list_view); listAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, listViewitems); listView.setAdapter(listAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent subExample; switch(position) { case 0: //.moveBody & moveHead subExample = new Intent(MotionActivity.this, MotionMoveBodyHead.class); startActivity(subExample); break; case 1: //.remoteControlBody & remoteControlHead subExample = new Intent(MotionActivity.this, MotionRemoteControlBodyHead.class); startActivity(subExample); break; } } }); } public static RobotCallback robotCallback = new RobotCallback() { @Override public void onResult(int cmd, int serial, RobotErrorCode err_code, Bundle result) { super.onResult(cmd, serial, err_code, result); } @Override public void onStateChange(int cmd, int serial, RobotErrorCode err_code, RobotCmdState state) { super.onStateChange(cmd, serial, err_code, state); } @Override public void initComplete() { super.initComplete(); } }; public static RobotCallback.Listen robotListenCallback = new RobotCallback.Listen() { @Override public void onFinishRegister() { } @Override public void onVoiceDetect(JSONObject jsonObject) { } @Override public void onSpeakComplete(String s, String s1) { } @Override public void onEventUserUtterance(JSONObject jsonObject) { } @Override public void onResult(JSONObject jsonObject) { } @Override public void onRetry(JSONObject jsonObject) { } }; public MotionActivity() { super(robotCallback, robotListenCallback); } }
TypeScript
UTF-8
1,105
2.515625
3
[ "MIT" ]
permissive
import {Component} from '@angular/core'; import {FormGroup, FormControl, FormArray, Validators} from '@angular/forms'; @Component({ moduleId: module.id, selector: 'data-driven', templateUrl: './data-driven.component.html' }) export class DataDrivenComponent{ f: FormGroup; constructor(){ this.f = new FormGroup({ 'userData': new FormGroup({ 'username': new FormControl('Caro', Validators.required), 'email': new FormControl('mail@mail.com', [ Validators.required, Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?") ]) }), 'password': new FormControl('', Validators.required), 'gender': new FormControl('male') }); } genders = [ 'male', 'female' ]; likes = [ 'dog', 'cat', 'bird', 'lizard', 'wale' ]; onSubmit(){ console.log(this.f); } }
Java
UTF-8
8,820
1.945313
2
[]
no_license
package org.techtown.menu_app; import android.app.AlarmManager; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Hashtable; import java.util.List; import java.util.Map; public class Setting extends AppCompatActivity { public static Context CONTEXT; private FirebaseDatabase firebaseDatabase, database; private DatabaseReference firebaseReference, reference, userReference, alarmReference; private Calendar cal, alarmCal; public AlarmManager am; Button Home, Setting_menu, sync; String username, email, menu_name; int nowDay, alarmDay; List<String> menus = new ArrayList<String>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.setting); CONTEXT = this; Intent intent = getIntent(); username = intent.getStringExtra("username").trim(); email = intent.getStringExtra("email").trim(); Home = findViewById(R.id.homebutton); Setting_menu = findViewById(R.id.Setting_menu); sync = findViewById(R.id.synchronization); am = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Home.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((home)home.HCONTEXT).onResume(); finish(); } }); Setting_menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Setting.this, Setting_menu.class); intent.putExtra("username", username); intent.putExtra("email", email); startActivity(intent); } }); sync.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cal = Calendar.getInstance(); nowDay = cal.get(Calendar.DAY_OF_WEEK); firebaseDatabase = FirebaseDatabase.getInstance(); userReference = firebaseDatabase.getReference("user"); userReference.child(username).child("alarm").setValue(null); firebaseReference = firebaseDatabase.getReference("user/"+username+"/Food"); firebaseReference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { // 파이어베이스 데이터베이스의 데이터를 받아오는 곳 for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // 반복문으로 데이터 list를 추 Food food = snapshot.getValue(Food.class); menu_name = food.getName(); menus.add(menu_name); } for (final String food : menus) { final List<String> whens = Arrays.asList("일", "월", "화", "수", "목", "금", "토"); List<Integer> week = Arrays.asList(1, 2, 3, 4, 5, 6, 7); List<String> places = Arrays.asList("금정회관교직원식당", "금정회관학생식당", "문창회관교직원식당", "문창회관학생식당", "샛벌회관식당", "학생회관교직원식당", "학생회관학생식당"); List<String> times = Arrays.asList("조식", "중식", "석식"); database = FirebaseDatabase.getInstance(); for (final Integer day : week) { if (day >= nowDay) { //(day > nowDay || ((day == nowDay) && cal.get(Calendar.HOUR_OF_DAY) <= 6)) { 원래는 동기화 시간에 따라 알람 등록 for (final String place : places) { for (final String time : times) { reference = database.getReference(whens.get(day - 1) + "/" + place + "/" + time); reference.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot in_dataSnapshot) { for (DataSnapshot in_snapshot : in_dataSnapshot.getChildren()) { String menu = (String) in_snapshot.getValue(); if (food.equals(menu)) { String alarm_cont = whens.get(day - 1) + "요일 '" + place + "'에서 '" + time + "'으로 '" + menu + "'이/가 나옵니다."; // DB 등록 Alarm update_alarm = new Alarm(alarm_cont); Map<String, Object> alarm_updates = new Hashtable<>(); alarm_updates.put(whens.get(day - 1) + place + time + menu, update_alarm); userReference.child(username).child("alarm").updateChildren(alarm_updates); // 알람 설정 alarmCal = Calendar.getInstance(); alarmCal.set(Calendar.DATE, cal.get(Calendar.DATE) + (day - nowDay)); alarmCal.set(Calendar.HOUR_OF_DAY, 13); alarmCal.set(Calendar.MINUTE, 59); alarmCal.set(Calendar.SECOND, 00); Intent alarmIntent = new Intent(Setting.this, AlarmReceiver.class); alarmIntent.putExtra("tag", alarm_cont); PendingIntent sender = PendingIntent.getBroadcast(Setting.this, 0, alarmIntent,0); am.set(AlarmManager.RTC, alarmCal.getTimeInMillis(), sender); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("sync", "alarm addition error"); } }); } } } } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { // 디비를 가져오던 중 에러 발생 시 Log.e("Setting", String.valueOf(databaseError.toException())); } }); Toast.makeText(Setting.this, "알람 동기화를 완료하였습니다.", Toast.LENGTH_SHORT).show(); ((home)home.HCONTEXT).onResume(); } }); } }
Java
UTF-8
1,109
3.578125
4
[]
no_license
public class SingliLinkedListObjects { Node head; // basic structure of the list public SingliLinkedListObjects(Student newEntry){ head = new Node(); head.std = newEntry; head.link = null; } public void addSingliLinkedListObjectsBeforeHead(Student newEntry){ Node n = new Node(); n.std = newEntry; n.link = head; head = n; } public void addSingliLinkedListObjectsAfter(Student newEntry){ Node n = new Node(); Node curr = head; while(true){ if(curr.link == null){ n.std = newEntry; n.link = null; curr.link = n; break; } curr = curr.link; } } public void deleteSingliLinkedListObjects(String toBeDeleted){ Node prev = head; Node curr = head.link; while(true){ if(curr.link == null || curr.std.Name == toBeDeleted){ break; } prev = curr; curr = curr.link; } if(curr.link != null){ prev.link = curr.link; } } public void displaySingliLinkedListObjects(){ Node curr = head; while(curr !=null){ System.out.println(curr.std.displayStudent()); curr = curr.link; } } class Node{ Student std; Node link; } }
Java
UTF-8
396
2.078125
2
[]
no_license
package com.project.apptruistic.persistence.repository; import com.project.apptruistic.persistence.domain.Volunteer; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.Optional; public interface VolunteerRepository extends MongoRepository<Volunteer, String> { Optional<Volunteer> findOneByEmail(String email); Boolean existsByEmail(String email); }
Python
UTF-8
672
3.25
3
[]
no_license
# 쉽고 빠르게 배우는 파이썬 GUI 프로그래밍(2020.12) # 1 차시 : 파이썬 GUI Programming & widget import tkinter as tk win = tk.Tk() ent1 = tk.Entry(win, relief='ridge', borderwidth=3, highlightcolor='red', highlightthickness=3, highlightbackground='yellow', takefocus=True) ent1.pack() ent2 = tk.Entry(win, relief='ridge', borderwidth=3, highlightcolor='red', highlightthickness=3, highlightbackground='yellow', takefocus=True) ent2.pack() win.mainloop()
C++
UTF-8
6,376
2.515625
3
[]
no_license
#include <zlib.h> #include "tools/zlib/Worker.hpp" namespace Tools { namespace Zlib { namespace { inline unsigned int _Min(unsigned int a, unsigned int b) { if (a < b) return a; return b; } } Worker::Worker(int compressionLevel) { if (compressionLevel < -1) this->_compressionLevel = -1; else if (compressionLevel > 9) this->_compressionLevel = 9; else this->_compressionLevel = compressionLevel; } void Worker::Deflate(void const* _src, unsigned int srcLength, void*& _dst, unsigned int& dstLenght) { int ret, flush; unsigned int have; z_stream strm; unsigned char* src = (unsigned char*)_src; std::vector<unsigned char> dst; /* allocate deflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = deflateInit2(&strm, this->_compressionLevel, Z_DEFLATED, -15, 9, Z_DEFAULT_STRATEGY); if (ret != Z_OK) { throw std::runtime_error(std::string("FAIL: ") + this->_GetError(ret) + "\n");; } /* compress until end of file */ do { strm.avail_in = _Min(_chunkSize, srcLength); //strm.avail_in = fread(in, 1, CHUNK, source); //if (ferror(source)) { // (void)deflateEnd(&strm); // return Z_ERRNO; //} strm.next_in = src; src += strm.avail_in; srcLength -= strm.avail_in; //flush = feof(source) ? Z_FINISH : Z_NO_FLUSH; flush = srcLength == 0 ? Z_FINISH : Z_NO_FLUSH; /* run deflate() on input until output buffer not full, finish compression if all of source has been read in */ do { strm.avail_out = _chunkSize; strm.next_out = _out; ret = deflate(&strm, flush); /* no bad return value */ assert(ret != Z_STREAM_ERROR); /* state not clobbered */ have = _chunkSize - strm.avail_out; size_t curIndex = dst.size(); dst.resize(dst.size() + have); std::memcpy(dst.data() + curIndex, _out, have); //if (fwrite(out, 1, have, dest) != have || ferror(dest)) { // (void)deflateEnd(&strm); // return Z_ERRNO; //} } while (strm.avail_out == 0); assert(strm.avail_in == 0); /* all input will be used */ /* done when last data in file processed */ } while (flush != Z_FINISH); assert(ret == Z_STREAM_END); /* stream will be complete */ /* clean up and return */ (void)deflateEnd(&strm); _dst = new unsigned char[dst.size()]; std::memcpy(_dst, dst.data(), dst.size()); dstLenght = (unsigned int)dst.size(); } void Worker::Inflate(void const* _src, unsigned int srcLength, void*& _dst, unsigned int& dstLenght) { int ret; unsigned int have; z_stream strm; unsigned char* src = (unsigned char*)_src; std::vector<unsigned char> dst; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit2(&strm, -15); if (ret != Z_OK) { throw std::runtime_error(std::string("FAIL: ") + this->_GetError(ret) + "\n");; } /* decompress until deflate stream ends or end of file */ do { strm.avail_in = _Min(_chunkSize, srcLength); //strm.avail_in = fread(in, 1, CHUNK, source); //if (ferror(source)) //{ // (void)inflateEnd(&strm); // return Z_ERRNO; //} if (strm.avail_in == 0) break; strm.next_in = src; srcLength -= strm.avail_in; src += strm.avail_in; /* run inflate() on input until output buffer not full */ do { strm.avail_out = _chunkSize; strm.next_out = _out; ret = inflate(&strm, Z_NO_FLUSH); assert(ret != Z_STREAM_ERROR); /* state not clobbered */ switch (ret) { case Z_NEED_DICT: ret = Z_DATA_ERROR; /* and fall through */ case Z_DATA_ERROR: case Z_MEM_ERROR: (void)inflateEnd(&strm); throw std::runtime_error(std::string("FAIL: ") + this->_GetError(ret) + "\n");; } have = _chunkSize - strm.avail_out; size_t curIndex = dst.size(); dst.resize(dst.size() + have); std::memcpy(dst.data() + curIndex, _out, have); //if (fwrite(out, 1, have, dest) != have || ferror(dest)) //{ // (void)inflateEnd(&strm); // return Z_ERRNO; //} } while (strm.avail_out == 0); /* done when inflate() says it's done */ } while (ret != Z_STREAM_END); /* clean up and return */ (void)inflateEnd(&strm); _dst = new unsigned char[dst.size()]; std::memcpy(_dst, dst.data(), dst.size()); dstLenght = (unsigned int)dst.size(); } std::string Worker::_GetError(int ret) { switch (ret) { case Z_ERRNO: return "unknown error"; case Z_STREAM_ERROR: return "invalid compression level"; case Z_DATA_ERROR: return "invalid or incomplete deflate data"; case Z_MEM_ERROR: return "out of memory"; case Z_VERSION_ERROR: return "zlib version mismatch!"; default: return "fail"; } } }}
Java
UTF-8
1,892
4.25
4
[]
no_license
package com.tts; import java.util.ArrayList; import java.util.Scanner; import java.util.List; import java.util.ArrayList; import java.util.Collections; public class Numbers { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); //Asking the user for 5 numbers and stores the values in 5 different variabels. System.out.println("Pick 5 numbers: "); int number1 = userInput.nextInt(); int number2 = userInput.nextInt(); int number3 = userInput.nextInt(); int number4 = userInput.nextInt(); int number5 = userInput.nextInt(); //Store the inputted numbers into an array list List <Integer> numberList = new ArrayList<Integer>(); numberList.add(number1); numberList.add(number2); numberList.add(number3); numberList.add(number4); numberList.add(number5); //Get the sum, product, max, and min //Initialize the sum value int sum = 0; //for (Integer number: myArrayVariableName) for (int number: numberList) { sum += number; } //Initialize the product value. int product = 1; for (int number: numberList) { product = product * number; } //Getting the max and min via Collections object int largest = Collections.max(numberList); int smallest = Collections.min(numberList); //Optional -- you can always sort the array (numberList) and then retrieve the first position for the lowest and the last position for the greatest. System.out.println("List of numbers: " + numberList); System.out.println("Sum: " + sum); System.out.println("Product: " + product); System.out.println("Largest number: " +largest); System.out.println("Smallest = " + smallest); } }
Java
UTF-8
5,379
2.046875
2
[]
no_license
package com.sblm.bean; public class Columna { private String rep_ordentotal; private String rep_ordenxdistrito; private String rep_clave; private String rep_direccion; private String rep_numero; private String rep_mazlote; private String rep_stand; private String rep_uso; private String rep_distrito; private double importeupa01; private double importeupa02; private double importeupa03; private double importeupa04; private double importeupa05; private double importeupa06; private double importeupa07; private double importeupa08; private double importeupa09; private double importeupa10; private double importeupa11; private double importeupa12; private double importeupa13; private double importeupa14; private double importeupa15; private double importeupa16; private double importeupatotal; private String rep_cbeneficio; private String rep_observacion; public String getRep_ordentotal() { return rep_ordentotal; } public void setRep_ordentotal(String rep_ordentotal) { this.rep_ordentotal = rep_ordentotal; } public String getRep_ordenxdistrito() { return rep_ordenxdistrito; } public void setRep_ordenxdistrito(String rep_ordenxdistrito) { this.rep_ordenxdistrito = rep_ordenxdistrito; } public String getRep_clave() { return rep_clave; } public void setRep_clave(String rep_clave) { this.rep_clave = rep_clave; } public String getRep_direccion() { return rep_direccion; } public void setRep_direccion(String rep_direccion) { this.rep_direccion = rep_direccion; } public String getRep_numero() { return rep_numero; } public void setRep_numero(String rep_numero) { this.rep_numero = rep_numero; } public String getRep_mazlote() { return rep_mazlote; } public void setRep_mazlote(String rep_mazlote) { this.rep_mazlote = rep_mazlote; } public String getRep_stand() { return rep_stand; } public void setRep_stand(String rep_stand) { this.rep_stand = rep_stand; } public String getRep_uso() { return rep_uso; } public void setRep_uso(String rep_uso) { this.rep_uso = rep_uso; } public String getRep_distrito() { return rep_distrito; } public void setRep_distrito(String rep_distrito) { this.rep_distrito = rep_distrito; } public double getImporteupa01() { return importeupa01; } public void setImporteupa01(double importeupa01) { this.importeupa01 = importeupa01; } public double getImporteupa02() { return importeupa02; } public void setImporteupa02(double importeupa02) { this.importeupa02 = importeupa02; } public double getImporteupa03() { return importeupa03; } public void setImporteupa03(double importeupa03) { this.importeupa03 = importeupa03; } public double getImporteupa04() { return importeupa04; } public void setImporteupa04(double importeupa04) { this.importeupa04 = importeupa04; } public double getImporteupa05() { return importeupa05; } public void setImporteupa05(double importeupa05) { this.importeupa05 = importeupa05; } public double getImporteupa06() { return importeupa06; } public void setImporteupa06(double importeupa06) { this.importeupa06 = importeupa06; } public double getImporteupa07() { return importeupa07; } public void setImporteupa07(double importeupa07) { this.importeupa07 = importeupa07; } public double getImporteupa08() { return importeupa08; } public void setImporteupa08(double importeupa08) { this.importeupa08 = importeupa08; } public double getImporteupa09() { return importeupa09; } public void setImporteupa09(double importeupa09) { this.importeupa09 = importeupa09; } public double getImporteupa10() { return importeupa10; } public void setImporteupa10(double importeupa10) { this.importeupa10 = importeupa10; } public double getImporteupa11() { return importeupa11; } public void setImporteupa11(double importeupa11) { this.importeupa11 = importeupa11; } public double getImporteupa12() { return importeupa12; } public void setImporteupa12(double importeupa12) { this.importeupa12 = importeupa12; } public double getImporteupa13() { return importeupa13; } public void setImporteupa13(double importeupa13) { this.importeupa13 = importeupa13; } public double getImporteupa14() { return importeupa14; } public void setImporteupa14(double importeupa14) { this.importeupa14 = importeupa14; } public double getImporteupa15() { return importeupa15; } public void setImporteupa15(double importeupa15) { this.importeupa15 = importeupa15; } public double getImporteupa16() { return importeupa16; } public void setImporteupa16(double importeupa16) { this.importeupa16 = importeupa16; } public double getImporteupatotal() { return importeupatotal; } public void setImporteupatotal(double importeupatotal) { this.importeupatotal = importeupatotal; } public String getRep_cbeneficio() { return rep_cbeneficio; } public void setRep_cbeneficio(String rep_cbeneficio) { this.rep_cbeneficio = rep_cbeneficio; } public String getRep_observacion() { return rep_observacion; } public void setRep_observacion(String rep_observacion) { this.rep_observacion = rep_observacion; } }
Rust
UTF-8
5,794
2.765625
3
[]
no_license
#![allow(dead_code)] use std::fs::File; use std::io::BufWriter; use std::path::Path; use png::HasParameters; use rand::prelude::*; mod camera; mod geometry; mod material; mod ray; mod vec3; use crate::camera::Camera; use crate::geometry::{HitInfo, Hitable, Sphere}; use crate::material::Material::*; use crate::ray::Ray; use crate::vec3::Vec3; fn main() { const WIDTH: u32 = 800; const HEIGHT: u32 = 600; const NUMBER_OF_STEPS: u32 = 100; let look_from = Vec3::new(11.0, 2.0, 2.5); let look_at = Vec3::new(0.0, 0.0, 0.0); let apertune = 0.05; let dist_to_focus = (look_from - look_at).lenght(); let camera = Camera::new( look_from, look_at, Vec3::up(), 25.0, WIDTH as f32 / HEIGHT as f32, apertune, dist_to_focus, ); let mut rng = rand::thread_rng(); let world = random_scene(&mut rng); let data = raytrace(&world, &camera, WIDTH, HEIGHT, NUMBER_OF_STEPS, &mut rng); write_image("test.png", WIDTH, HEIGHT, &data); } fn raytrace( world: &[Box<Hitable>], camera: &Camera, width: u32, height: u32, samples: u32, rng: &mut rand::RngCore, ) -> Vec<u8> { let mut data = Vec::<u8>::with_capacity((4 * width * height) as usize); for y in (0..height).rev() { for x in 0..width { let mut col = Vec3::zero(); for _ in 0..samples { let jitter_x: f32 = rng.gen(); let jitter_y: f32 = rng.gen(); let u = ((x as f32) + jitter_x) / width as f32; let v = ((y as f32) + jitter_y) / height as f32; let ray = camera.get_ray(u, v, rng); col += color(&ray, &world, rng, 0); } col /= samples as f32; data.push((255.0 * col.r().sqrt()) as u8); data.push((255.0 * col.g().sqrt()) as u8); data.push((255.0 * col.b().sqrt()) as u8); data.push(255); print!("\r"); print!( "{:.2}% Completed ", (data.len() * 25) as f32 / (width * height) as f32 ); } } data } fn color(ray: &Ray, world: &[Box<Hitable>], rng: &mut rand::RngCore, depth: i32) -> Vec3 { if let Some(hit) = world.hit(ray, 0.001, std::f32::MAX) { let scatter_data = hit.material.scatter(ray, &hit, rng); if depth < 50 && scatter_data.is_some() { let (scatter, attenuation) = scatter_data.unwrap(); return attenuation * color(&scatter, world, rng, depth + 1); } else { return Vec3::zero(); } } let dir = ray.direction; // Puts t in the range 0..1 let t = 0.5 * (dir.y() + 1.0); // Gradient from blue to white (1.0 - t) * Vec3::new(1.0, 1.0, 1.0) + t * Vec3::new(0.5, 0.7, 1.0) } fn write_image(path: &str, width: u32, height: u32, data: &[u8]) { let path = Path::new(path); let file = File::create(path).unwrap(); let w = &mut BufWriter::new(file); let mut encoder = png::Encoder::new(w, width, height); encoder.set(png::ColorType::RGBA).set(png::BitDepth::Eight); let mut writer = encoder.write_header().unwrap(); writer.write_image_data(data).unwrap(); } fn random_scene(rng: &mut rand::RngCore) -> Vec<Box<Hitable>> { let mut world = Vec::<Box<Hitable>>::new(); world.push(Box::new(Sphere::new( Vec3::new(0.0, -1000.0, 0.0), 1000.0, Lambertian { albedo: Vec3::new(0.5, 0.5, 0.5), }, ))); for a in -11..11 { for b in -11..11 { let mat_choice: f32 = rng.gen(); let center = Vec3::new( a as f32 + 0.9 * rng.gen::<f32>(), 0.2, b as f32 + 0.9 * rng.gen::<f32>(), ); if (center - Vec3::new(4.0, 0.2, 0.0)).lenght() > 0.9 { if mat_choice < 0.8 { world.push(Box::new(Sphere::new( center, 0.2, Lambertian { albedo: Vec3::new( rng.gen::<f32>() * rng.gen::<f32>(), rng.gen::<f32>() * rng.gen::<f32>(), rng.gen::<f32>() * rng.gen::<f32>(), ), }, ))); } else if mat_choice < 0.95 { world.push(Box::new(Sphere::new( center, 0.2, Metal { albedo: Vec3::new( 0.5 * (1.0 + rng.gen::<f32>()), 0.5 * (1.0 + rng.gen::<f32>()), 0.5 * (1.0 + rng.gen::<f32>()), ), fuzz: 0.5 * rng.gen::<f32>(), }, ))); } else { world.push(Box::new(Sphere::new( center, 0.2, Dielectric { ref_idx: 1.5 }, ))); } } } } world.push(Box::new(Sphere::new( Vec3::new(0.0, 1.0, 0.0), 1.0, Dielectric { ref_idx: 1.5 }, ))); world.push(Box::new(Sphere::new( Vec3::new(-4.0, 1.0, 0.0), 1.0, Lambertian { albedo: Vec3::new(0.1, 0.2, 0.4), }, ))); world.push(Box::new(Sphere::new( Vec3::new(4.0, 1.0, 0.0), 1.0, Metal { albedo: Vec3::new(0.7, 0.6, 0.5), fuzz: 0.0, }, ))); world }
C++
UTF-8
673
3.109375
3
[]
no_license
class Solution { public: bool stoneGame(vector<int> &piles) { // return func1(piles); return func2(piles); } // ** greedy algorithm // ** wrong case: 3 2 10 4 bool func1(vector<int> &piles) { int alex = 0; int lee = 0; int i = 0, j = piles.size() - 1; while (i < j) { if (piles[i] > piles[j]) { alex += piles[i]; i++; } else { alex += piles[j]; j--; } if (piles[i] > piles[j]) { lee += piles[i]; i++; } else { lee += piles[j]; j--; } } return alex > lee; } // ** reference bool func2(vector<int> &piles) { return true; } };
C#
UTF-8
6,379
2.671875
3
[ "MIT" ]
permissive
using Bottleships.Logic; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace Bottleships.Communication { public class Client { private string _serverUrl; private ICaptain _myCaptain; private HttpTransmitter _transmitter; private HttpListenerClass _listener; private static object _lock = new object(); public bool IsGameRunning { get; private set; } public Client(string serverUrl) { _serverUrl = serverUrl; _myCaptain = new MyCaptain(); _transmitter = new HttpTransmitter(); _listener = new HttpListenerClass(3); } public void PlayGame() { _listener.Start(6999); _listener.ProcessRequest += HttpListener_ProcessRequest; lock (_lock) { this.IsGameRunning = true; } } private void HttpListener_ProcessRequest(System.Net.HttpListenerContext context) { string body = null; StreamReader sr = new StreamReader(context.Request.InputStream); using (sr) { body = sr.ReadToEnd(); } var method = context.Request.Url.AbsolutePath.Replace("/", "").ToLower(); if (method.Equals("getplacements")) { var data = JsonConvert.DeserializeObject<PlacementRequest>(body); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/plain"; var allClasses = Clazz.AllClasses; var requestedClasses = new List<Clazz>(); foreach(var clazz in data.Classes) { var matchingClass = allClasses.SingleOrDefault(c => c.Name.Equals(clazz, StringComparison.CurrentCultureIgnoreCase)); if(matchingClass != null) { requestedClasses.Add(matchingClass); } } var placements = _myCaptain.GetPlacements(requestedClasses); using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine(JsonConvert.SerializeObject(placements)); } } if (method.Equals("getshots")) { var data = JsonConvert.DeserializeObject<ShotRequest>(body); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/plain"; var placements = _myCaptain.GetShots(data.EnemyFleets, data.NumberOfShots); using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine(JsonConvert.SerializeObject(placements)); } } if (method.Equals("shotresult")) { var data = JsonConvert.DeserializeObject<IEnumerable<ShotResult>>(body); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/plain"; _myCaptain.RespondToShots(data); using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine(JsonConvert.SerializeObject(new { DataReceived = true })); } } if (method.Equals("startgame")) { var data = JsonConvert.DeserializeObject<GameStartNotification>(body); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/plain"; _myCaptain.StartGameNotification(data); if (!IsGameRunning) { lock (_lock) { this.IsGameRunning = true; } } using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine(JsonConvert.SerializeObject(new { DataReceived = true })); } } if (method.Equals("endgame")) { var data = JsonConvert.DeserializeObject<GameEndNotification>(body); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/plain"; _myCaptain.EndGameNotification(data); using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine(JsonConvert.SerializeObject(new { DataReceived = true })); } } if (method.Equals("endround")) { var data = JsonConvert.DeserializeObject<RoundEndNotification>(body); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/plain"; _myCaptain.EndRoundNotification(data); using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine(JsonConvert.SerializeObject(new { DataReceived = true })); } lock (_lock) { this.IsGameRunning = false; } } if (method.Equals("hitnotification")) { var data = JsonConvert.DeserializeObject<IEnumerable<HitNotification>>(body); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/plain"; _myCaptain.NotifyOfBeingHit(data); using (StreamWriter sw = new StreamWriter(context.Response.OutputStream)) { sw.WriteLine(JsonConvert.SerializeObject(new { DataReceived = true })); } } } public void EndGame() { _listener?.Stop(); _listener?.Dispose(); } } }
Java
UTF-8
6,362
1.679688
2
[ "Apache-2.0" ]
permissive
// // Copyright 2011 EXANPE <exanpe@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package fr.exanpe.t5.lib.mixins; import org.apache.commons.collections.CollectionUtils; import org.apache.tapestry5.BindingConstants; import org.apache.tapestry5.ComponentEventCallback; import org.apache.tapestry5.ComponentResources; import org.apache.tapestry5.ContentType; import org.apache.tapestry5.Link; import org.apache.tapestry5.MarkupWriter; import org.apache.tapestry5.SelectModel; import org.apache.tapestry5.ValueEncoder; import org.apache.tapestry5.annotations.AfterRender; import org.apache.tapestry5.annotations.Events; import org.apache.tapestry5.annotations.Import; import org.apache.tapestry5.annotations.InjectContainer; import org.apache.tapestry5.annotations.OnEvent; import org.apache.tapestry5.annotations.Parameter; import org.apache.tapestry5.annotations.RequestParameter; import org.apache.tapestry5.corelib.components.Select; import org.apache.tapestry5.internal.util.Holder; import org.apache.tapestry5.internal.util.SelectModelRenderer; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.json.JSONObject; import org.apache.tapestry5.services.MarkupWriterFactory; import org.apache.tapestry5.services.ResponseRenderer; import org.apache.tapestry5.services.ValueEncoderSource; import org.apache.tapestry5.services.javascript.JavaScriptSupport; import org.apache.tapestry5.util.TextStreamResponse; import org.slf4j.Logger; import fr.exanpe.t5.lib.constants.ExanpeEventConstants; /** * A mixin for a select component that populates related data in an other select via Ajax on change.<br/> * As an example, a first select displays country, while a second one will automatically populate * its cities regarding the country selected. <br/> * The container is responsible for providing an event handler for event * {@link ExanpeEventConstants#SELECTLOADER_EVENT} (or "selectLoaderAction"). The context will be * the value of the select sent from the client. The return value should be a {@link SelectModel} * object holding the data to display, null is nothing to populate.<br/> * JavaScript : This component is bound to a class Exanpe.SelectLoader.<br/> * * @author jmaupoux */ @Import(library = { "${exanpe.yui2-base}/yahoo-dom-event/yahoo-dom-event.js", "${exanpe.yui2-base}/connection/connection-min.js", "${exanpe.asset-base}/js/exanpe-t5-lib.js" }) @Events(ExanpeEventConstants.SELECTLOADER_EVENT) public class SelectLoader { /** * Event sent by the client */ private static final String EVENT_NAME = "loadSelect"; /** * Param containing the value sent by the client */ private static final String PARAM_NAME = "value"; /** * Defines the target select id to populate */ @Parameter(defaultPrefix = BindingConstants.LITERAL, required = true, allowNull = false) private String targetId; /** * Defines a specific value encoder for the target select */ @Parameter @SuppressWarnings("rawtypes") private ValueEncoder targetEncoder; /** * The select component to which this mixin is attached. */ @InjectContainer private Select select; @Inject private Logger log; @Inject private ComponentResources resources; @Inject private ValueEncoderSource valueEncoderSource; @Inject private MarkupWriterFactory factory; @Inject private ResponseRenderer responseRenderer; @Inject private JavaScriptSupport javaScriptSupport; @AfterRender void end() { JSONObject data = buildJSONData(); javaScriptSupport.addInitializerCall("selectLoaderBuilder", data); } private JSONObject buildJSONData() { String id = select.getClientId(); Link link = resources.createEventLink(EVENT_NAME); JSONObject data = new JSONObject(); data.accumulate("id", id); data.accumulate("targetId", targetId); data.accumulate("url", link.toURI()); return data; } @OnEvent(value = EVENT_NAME) public Object populateSelect(@RequestParameter(value = PARAM_NAME, allowBlank = true) String value) { log.debug("Ajax value received : {}", value); final Holder<SelectModel> holder = Holder.create(); ComponentEventCallback<SelectModel> callback = new ComponentEventCallback<SelectModel>() { public boolean handleResult(SelectModel result) { holder.put(result); return true; } }; log.debug("Triggering event to container..."); resources.triggerEvent(ExanpeEventConstants.SELECTLOADER_EVENT, new Object[] { value }, callback); ContentType contentType = responseRenderer.findContentType(this); SelectModel model = holder.get(); if (model == null || CollectionUtils.isEmpty(model.getOptions())) { log.debug("Received null SelectModel. Sending empty select to client."); return new TextStreamResponse(contentType.toString(), ""); } MarkupWriter writer = factory.newPartialMarkupWriter(contentType); writer.element("root"); model.visit(new SelectModelRenderer(writer, getValueEncoder(model.getOptions().get(0).getValue()))); writer.end(); String reponse = writer.toString(); if (log.isDebugEnabled()) { log.debug("Sending options to client : {}", reponse); } // substract the prefix <root> and suffix </root> return new TextStreamResponse(contentType.toString(), reponse); } ValueEncoder<?> getValueEncoder(Object o) { if (targetEncoder != null) return targetEncoder; return valueEncoderSource.getValueEncoder(o.getClass()); } }
Java
UTF-8
906
2.0625
2
[]
no_license
package com.foxconn.service.impl.trafficcosts; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.foxconn.dao.trafficcosts.TrafficCostsDao; import com.foxconn.pojo.trafficcosts.TrafficCosts; import com.foxconn.service.trafficcosts.TrafficCostsService; @Service("trafficCostsServiceImpl") public class TrafficCostsServiceImpl implements TrafficCostsService { @Resource(name = "trafficCostsDao") private TrafficCostsDao trafficCostsDao; @Override public List<TrafficCosts> getTrafficCostsList(TrafficCosts trafficCosts) { return trafficCostsDao.getTrafficCostsList(trafficCosts); } @Override public void editTrafficCosts(TrafficCosts trafficCosts) { trafficCostsDao.editTrafficCosts(trafficCosts); } @Override public void addTrafficCosts(TrafficCosts trafficCosts) { trafficCostsDao.addTrafficCosts(trafficCosts); } }
Markdown
UTF-8
1,286
2.71875
3
[ "MIT" ]
permissive
# Financial Portfolio Manager This is a code repository for the capstone project for COMP3900 (Computer Science Project) by our team HRDM. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development/testing/viewing purposes. ### Prerequisites * Node.js * Python ### Installation 1. Download or clone this repository to your local machine. ``` git clone https://github.com/alvinwong7/portfolio-manager.git ``` 2. Move into the git repo directory. ``` cd portfolio-manager ``` 3. Setup the virtual env. ``` virtualenv Env ``` 4. Start the virtual env. ``` ./Env/Scripts/activate ``` 5. Install the required python packages. ``` pip install -r requirements.txt ``` 6. Install dependant JS packages. ``` npm install ``` 7. Start the python server in a separate terminal. ``` cd PythonServer Python api.py ``` 8. Start the React Webapp in the original terminal. ``` npm start ``` ## Running 1. Start the React Webapp in the original terminal. ``` npm start ``` 2. Start the python server in a separate terminal. ``` cd PythonServer Python api.py ``` 3. Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits. You will also see any lint errors in the console.
Python
UTF-8
526
3.21875
3
[]
no_license
''' Created on 6 Apr 2018 @author: Robert ''' class files: def __init__(self, value): self._v = value print("constructor") def move(self): print('move data', self._v) def copy(self): print("copy data", self._v) def delete(self): print("delete data", self._v) def main(): mktg=files(99) mktg.move() mktg.copy() mktg.delete() execs=files(77) execs.move() execs.copy() execs.delete() main()
Java
UTF-8
853
2.515625
3
[]
no_license
package tranditional.strategy.company.business; import tranditional.bean.business.JavaDevDirEnum; import java.util.HashMap; import java.util.Map; public class StrategyCreator { final static Map<JavaDevDirEnum.ReportType,IGetDataServiceStrategy> reportServiceMap = new HashMap<>(); static { reportServiceMap.put(JavaDevDirEnum.ReportType.Logictis,new GetLogictisStrategy()); reportServiceMap.put(JavaDevDirEnum.ReportType.Stock,new GetStockStrategy()); } public static GetLogictisStrategy createLogictisStra(){ return new GetLogictisStrategy(); } public static GetStockStrategy createStockStra(){ return new GetStockStrategy(); } public static IGetDataServiceStrategy getServiceByType(JavaDevDirEnum.ReportType reportType){ return reportServiceMap.get(reportType); } }
Python
UTF-8
398
2.578125
3
[]
no_license
#!/usr/bin/python import RPi.GPIO as GPIO import time def init_gpio(): # Set pin 4 to low GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.OUT) GPIO.output(4, GPIO.HIGH) def gate_toggle(): # time to sleep between operations in the main loop GPIO.output(4, GPIO.LOW) time.sleep(1); GPIO.output(4, GPIO.HIGH) def cleanup_gpio(): GPIO.cleanup()
Markdown
UTF-8
987
3.78125
4
[]
no_license
magine that you have an array of 3 integers each representing a different person. Each number can be 0, 1, or 2 which represents the number of hands that person holds up. Now imagine there is a sequence which follows these rules: None of the people have their arms raised at first Firstly, a person raises 1 hand; then they raise the second hand; after that they put both hands down - these steps form a cycle Person #1 performs these steps all the time, person #2 advances only after person #1 puts their hands down, and person #3 advances only after person #2 puts their hands down The first 10 steps of the sequence represented as a table are: Step P1 P2 P3 -------------------- 0 0 0 0 1 1 0 0 2 2 0 0 3 0 1 0 4 1 1 0 5 2 1 0 6 0 2 0 7 1 2 0 8 2 2 0 9 0 0 1 Given a number, return an array with the number of hands raised by each person at that step.
C++
UTF-8
936
3.078125
3
[]
no_license
// // Created by optimus on 19/2/18. // # include <iostream> #include <vector> using namespace std; int main (){ int n ; cin >> n ; while ( n --){ string s; cin >> s; int size = s.size() - 4; int count = 0; for ( int i = 0; i < size; i ++){ if ( s.at(i) == 'c' || s.at(i+1) == 'c' || s.at(i+2) == 'c' || s.at(i+3) == 'c' ){ if ( s.at(i) == 'h' || s.at(i+1) == 'h' || s.at(i+2) == 'h' || s.at(i+3) == 'h' ){ if ( s.at(i) == 'e' || s.at(i+1) == 'e' || s.at(i+2) == 'e' || s.at(i+3) == 'e' ){ if ( s.at(i) == 'f' || s.at(i+1) == 'f' || s.at(i+2) == 'f' || s.at(i+3) == 'f' ){ count ++; } } } } } cout << ( count ? "lovely " + to_string(count) : "normal") << endl; } return 0; }
JavaScript
UTF-8
2,796
3.203125
3
[]
no_license
// Date comparation export const isSooner = (d1, d2) => { var arr1 = d1.split("-").map((item) => parseInt(item)); var arr2 = d2.split("-").map((item) => parseInt(item)); if (arr1[2] === arr2[2]) { if (arr1[1] === arr2[1]) { return arr2[0] - arr1[0]; } return arr2[1] - arr1[1]; } return arr2[2] - arr1[2]; }; // Capitalize string (used for categories) export const capitalizeString = (s) => { if (s !== "") { return s[0].toUpperCase() + s.slice(1); } return ""; }; // calculate balance export const calculateBalance = (transactionData) => { const budgetData = transactionData.filter( (item) => item.type === "budget" ); const expenseData = transactionData.filter( (item) => item.type === "expense" ); var budgetMoney = 0; if (budgetData) { for (var i = 0; i < budgetData.length; i++) { budgetMoney += budgetData[i].amount; } } var expenseMoney = 0; if (expenseData) { for (var j = 0; j < expenseData.length; j++) { expenseMoney += expenseData[j].amount; } } return [budgetMoney, expenseMoney] }; export const costsSum = (cateAllTransactions) => { let sum = 0; for (let i = 0; i < cateAllTransactions.length; i++) { sum += cateAllTransactions[i].value; } return sum; } export const calculatePercentage = (cateAllTransactions, sumOfCosts) => { for (let i = 0; i < cateAllTransactions.length; i++) { cateAllTransactions[i].percentage = parseFloat((cateAllTransactions[i].value / sumOfCosts)); } } export const removeZeroValueTransactions = (transactions) => { const newTransactions = transactions.filter((transaction) => transaction.value !== 0); return newTransactions } export const cateTransactions = (transactions, categories, colors) => { let cateAllTransactions = []; for (const key in categories) { let CateData = transactions.filter((transaction) => transaction.category === categories[key]); let sum = 0; for (let i = 0; i < CateData.length; i++) { sum += CateData[i].amount } let cateObject = { title: capitalizeString(categories[key]), value: sum, color: colors[key] } cateAllTransactions.push(cateObject); } return cateAllTransactions } // Sort transactions value from large to small export const sortTransactions = (transactions) => { let newTransactions = []; newTransactions = transactions.sort((a , b) => b.amount - a.amount); return newTransactions } // Filter transactions by month from format MMM/YYYY e.g Aug 2021 export const filterMonthTransaction = (transactions, date) => { var mon = `${date.format("MM")}-${date.format("YYYY")}`; // Filter transactions based on each month return transactions.filter( (transaction) => transaction.spentAt.slice(3, 10) === mon ); }
C++
UTF-8
449
2.8125
3
[]
no_license
#ifndef BARBOT_SPEECHSYNTHESIS_H #define BARBOT_SPEECHSYNTHESIS_H #include <iostream> /** * Uses Google Speech and an sh script to synthesise speech */ class SpeechSynthesis { public: static const std::string TAG; /** * Excecutes a bash script that pronounces the text given as parameter. * @param text The text you want the robot to say */ static void speak(std::string text); }; #endif //BARBOT_SPEECHSYNTHESIS_H
JavaScript
UTF-8
5,980
3.15625
3
[]
no_license
window.onload = function() { game.init(); } var game = { /** * @parmas {string} canvasId canvas 画布 id * @parmas {Number} canvasWidth 、canvasHeight canvas画布 宽 、高 * @parmas {Object} context 绘制上下文环境 * @parmas {Number} frameWidth 边框宽度 * @parmas {String} frameColor 边框颜色 * @parmas {String} user 用户数组 * @parmas {Number} foodsMaxLength / stoneMaxLength 食物最大数量 石头最大数量 */ canvasId: 'canvas', canvasWidth: 1000, canvasHeight: 600, context: '', frameWidth: 0, frameColor: 'red', user: [], foodsMaxLength: 800, stoneMaxLength: 20, deletTime: 20, init: function() { var canvas = document.getElementById(this.canvasId); canvasWidth = this.canvasWidth; canvasHeight = this.canvasHeight; canvas.width = canvasWidth; canvas.height = canvasHeight; this.frameWidth = this.canvasWidth / 200; frameWidth = this.frameWidth; this.context = canvas.getContext('2d'); var r = 25; for (var i = 0; i < 1; i++) { obj = { x: this.getRandom(r + frameWidth, canvasWidth - r - frameWidth), y: this.getRandom(r + frameWidth, canvasHeight - r - frameWidth), r: r, color: 'blue', name: 'xiao' } this.user.push(obj); } var that = this; this.timer = setInterval(function() { that.drawActive(); },20) this.drawActive(); this.food.init(); this.stone.init(); }, drawActive: function() { this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight); this.drawFrame(); this.food.draw(); this.stone.draw(); this.drawUser(); }, drawUser: function() { var user = this.user; var context = this.context; context.save(); for(var i = 0,len = user.length; i < len; i++) { var ball = user[i]; context.beginPath(); context.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI, false); context.fillStyle = ball.color; context.fill(); context.font = ball.r / 5 + 'px sans-serif'; context.strokeStyle='red'; context.textAlign = 'center'; context.strokeText(ball.name, ball.x, ball.y + ball.r / 5 / 2, 50); } context.restore(); }, food: { arr: [], time: 0, r: 5, init: function() { for (var i = 0; i < 100; i++) { this.add(); } }, add: function() { var r = this.r; obj = { x: game.getRandom(r + frameWidth, canvasWidth - r - frameWidth), y: game.getRandom(r + frameWidth, canvasHeight - r - frameWidth), r: r, color: 'purple' } this.arr.push(obj); }, delete: function(i) { this.arr.splice(i, 1); }, draw: function() { var arr = this.arr; this.time += game.deletTime; if(this.time > 200 && this.arr.length < game.foodsMaxLength) { this.time = 0; this.add(); } var context = game.context; context.save(); for(var i = 0, len = arr.length; i < len; i ++) { var ball = arr[i]; context.beginPath(); context.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false); context.fillStyle = ball.color; context.fill(); } context.restore(); } }, // 石头 stone: { arr: [], r: 25, time: 0, init: function() { for(var i = 0; i < 10;i ++) { this.add(); } }, add: function() { var r = this.r; var obj = { x: game.getRandom(r + frameWidth, canvasWidth - r - frameWidth), y: game.getRandom(r + frameWidth, canvasHeight - r - frameWidth), r: r, color: 'black' } this.arr.push(obj); }, delete: function(i) { this.arr.splice(i, 1); }, draw: function() { var context = game.context; this.time += game.deletTime; if(this.time > 5000 && this.arr.length < game.stoneMaxLength) { this.time = 0; this.add(); } context.save(); for (var i = 0,len = this.arr.length; i < len; i++) { var STONE = this.arr[i]; context.beginPath(); context.arc(STONE.x, STONE.y, STONE.r, 0, Math.PI * 2, false); context.fillStyle = STONE.color; context.fill(); } context.restore(); } }, /** * 绘制边框 */ drawFrame: function() { var context = this.context; var canvasWidth = this.canvasWidth; var canvasHeight = this.canvasHeight; var frameWidth = this.frameWidth; context.save(); context.beginPath(); context.moveTo(frameWidth / 2, frameWidth / 2); context.lineTo(canvasWidth - frameWidth / 2, frameWidth / 2); context.lineTo(canvasWidth - frameWidth / 2, canvasHeight - frameWidth / 2); context.lineTo(frameWidth / 2, canvasHeight - frameWidth / 2); context.closePath(); context.lineWidth = frameWidth; context.lineCap = 'round'; context.lineJoin = 'round'; context.strokeStyle = this.frameColor; context.stroke(); context.restore(); }, getRandom: function(min, max) { return Math.random() * (max - min) + min; } }
C++
UTF-8
395
3.28125
3
[]
no_license
/* * Task #1: * Write a program in CPP to convert the distance in meters entered by the user into * distance in feet and inch using the concept of basic to user defined data conversion. */ #include "Distance.hpp" int main(){ Distance *distance = new Distance; distance->getDistance(); distance->convert(); distance->printDistance(); delete distance; return 0; }
C
UTF-8
1,632
3.03125
3
[]
no_license
#ifndef SUCCESSORS_QUEUE_H #define SUCCESSORS_QUEUE_H struct successors_cell { //each cell contains a word, it's number of occurence and a pointer toward a standard queue containing it's successors and their number of occureces (attribute "was_read_by_statistician") char word[MAX_WORD_LENGTH+1]; int nb_of_occ; struct queue successors; struct successors_cell* next; }; struct successors_queue { struct successors_cell* first; struct successors_cell* last; }; void init_successors_queue(struct successors_queue* succ_queue); int is_successors_queue_empty(struct successors_queue succ_queue); void add_in_successors_queue(struct successors_cell* to_add, struct successors_queue* source); struct successors_cell* read_successors_queue(struct successors_queue source); void remove_in_successors_queue(struct successors_queue* source); struct successors_cell pop_successors_queue(struct successors_queue* source); struct successors_cell* research_word_in_successors_queue(struct successors_queue source, char* word); void purge_successors_queue(struct successors_queue* to_purge); //Purge an entire queue struct successors_cell* research_successors_cell(struct successors_queue*, int position); //return the cell at the given position, NULL if doesn't exist int length_successors_queue(struct successors_queue stats_queue); //Return the length of the queue (i.e the number of cells) void successors_cell_cpy(struct successors_cell* source, struct successors_cell* dest); //Copy a successor cell properly void print_successors_queue(struct successors_queue queue_to_print); //Print the whole queue #endif
Java
UTF-8
299
2.34375
2
[]
no_license
package com.jutem.sort; import java.util.Arrays; import org.junit.Test; public class KSortTest { @Test public void SortIncrease(){ KSort.SortIncreaseInsertion(numbers, 3); System.out.println(Arrays.toString(numbers)); } private int[] numbers={3,5,6,3,1,4,7,8,2}; }
TypeScript
UTF-8
1,346
3.15625
3
[]
no_license
export interface IMessage { text: string; authorID: number; recipientID: number; timestamp: number; isRead: boolean; } export class Message { static parse(proto: IMessage): Message { return new Message( proto.text, proto.authorID, proto.recipientID, proto.timestamp, proto.isRead, ); } static deparse(message: Message): IMessage { return ({ text: message.text, authorID: message.authorID, recipientID: message.recipientID, timestamp: message.timestamp, isRead: message.isRead, }); } public get text(): string { return this._text; } public get authorID(): number { return this._authorID; } public get recipientID(): number { return this._recipientID; } public get timestamp(): number { return this._timestamp; } public get displayDate(): string { const time = new Date(this._timestamp); return time.toLocaleDateString(); } public get displayTime(): string { const time = new Date(this._timestamp); return time.toLocaleTimeString(); } public get isRead(): boolean { return this._isRead; } constructor( private _text: string, private _authorID: number, private _recipientID: number, private _timestamp: number, private _isRead: boolean, ) {} }
C++
UTF-8
1,278
3.625
4
[]
no_license
#include <bits/stdc++.h> #define N 10 using namespace std; class Stack{ int top; public: int a[N]; Stack(){ top=-1; } //push function bool push(int x) { if (top>=(N-1)) { cout<<"Stack Overflow"; return false; } else { a[top++]=x; return true; } } //pop function int pop() { if (top<0) { cout<<"Stack Underflow"; return 0; } else{ int x=a[top--]; return x; } } //peek function int peek(){ if(top<0){ return 0; } else{ int x=a[top]; return x; } } //empty function bool isEmpty(){ return (top<0); } //reversing here! void reverseStack(Stack s2,Stack s3){ while(!isEmpty()){ s2.push(pop()); } while(!s2.isEmpty()){ s3.push(s2.pop()); } while(!s3.isEmpty()){ push(s3.pop()); } } void display(){ while(!isEmpty()){ cout<<" "<<pop(); } } }; int main() { Stack s,s2,s3; int n,val; cout<<"Enter Number Elements for Stack 1:"<<endl; cin>>n; cout<<"Enter Elements for Stack 1:"<<endl; for(int i=0;i<n;i++){ cin>>val; s.push(val); } s.reverseStack(s2,s3); cout<<"After Reversing: "<<endl; s.display(); }
Python
UTF-8
383
3.171875
3
[]
no_license
# -*- coding: utf-8 -*- # -*- coding in this time : utf-8 -*- """ Created on Sat Oct 05 03:36:04 2019 @author: Ajm joha """ days =int(input("Enter days: ")) years = days/365 #weeks = (days -(years * 365)) /7 weeks = int((days % 365) /7) #day = days - ((years * 365) + (weeks * 7)) day = (days % 365) % 7 print(days,"days = %.f "%years,"year/s, ",weeks,"week/s ""and",day,"day/s ")
Markdown
UTF-8
21,898
2.640625
3
[ "CC-BY-4.0", "MIT", "CC-BY-3.0" ]
permissive
<properties pageTitle="Partizione tabelle SQL Data Warehouse | Microsoft Azure" description="Guida introduttiva partizione della tabella Data warehouse di SQL Azure." services="sql-data-warehouse" documentationCenter="NA" authors="jrowlandjones" manager="barbkess" editor=""/> <tags ms.service="sql-data-warehouse" ms.devlang="NA" ms.topic="article" ms.tgt_pltfrm="NA" ms.workload="data-services" ms.date="07/18/2016" ms.author="jrj;barbkess;sonyama"/> # <a name="partitioning-tables-in-sql-data-warehouse"></a>Partizione tabelle SQL Data Warehouse > [AZURE.SELECTOR] - [Panoramica][] - [Tipi di dati][] - [Distribuire][] - [Indice][] - [Partizione][] - [Statistiche][] - [Temporaneo][] Partizione è supportato in tutti i tipi di tabella di SQL Data Warehouse; inclusi columnstore raggruppate, indice cluster e heap. Partizione è supportata anche in tutti i tipi di distribuzione, ad esempio hash o circolari distribuito. Partizione consente di dividere i dati in gruppi più piccoli dei dati e nella maggior parte dei casi, partizione viene effettuati su una colonna di date. ## <a name="benefits-of-partitioning"></a>Vantaggi delle partizioni Partizione possono trarre vantaggio le prestazioni di manutenzione e query di dati. Se dei vantaggi entrambi o solo uno dipende dalla modalità di caricamento di dati e se possibile utilizzare la stessa colonna per entrambi gli scopi, poiché partizione può essere eseguita solo in una colonna. ### <a name="benefits-to-loads"></a>Vantaggi caricamento Il vantaggio principale delle partizioni SQL Data warehouse è migliorare l'efficienza e le prestazioni di caricamento dati dall'uso dell'eliminazione partizione, il passaggio e l'unione. Nella maggior parte dei casi dati sono suddiviso in una colonna di data che è strettamente collegata alla sequenza che i dati vengono caricati nel database. Uno dei principali vantaggi dell'utilizzo di partizioni per mantenere i dati evitare registrazione delle transazioni. Mentre è sufficiente l'inserimento, aggiornamento o eliminazione dei dati può essere l'approccio più semplice, con un piccolo pensiero e fatica, utilizzando partizioni durante il processo di caricamento in modo sostanziale le prestazioni. Cambio di partizione è utilizzabile per rimuovere o sostituire una sezione di una tabella rapidamente. Ad esempio, una tabella dei fatti vendite può contenere solo i dati degli ultimi 36 mesi. Alla fine di ogni mese, il mese di dati di vendita meno recente viene eliminato dalla tabella. Questi dati possono essere eliminati tramite un'istruzione delete per eliminare i dati per il mese meno recente. Tuttavia, l'eliminazione di una grande quantità di dati da righe con un'istruzione delete può richiedere molto tempo, nonché creare il rischio di transazioni di grandi dimensioni che potrebbe richiedere molto tempo per eseguire il ripristino in caso di errori. Un approccio più ottimale consiste nel è sufficiente eliminare la partizione meno recente di dati. Eliminazione delle singole righe in cui potrebbe richiedere ore, l'eliminazione di un'intera partizione potrebbe richiedere secondi. ### <a name="benefits-to-queries"></a>Vantaggi alle query Partizione può anche essere utilizzato per migliorare le prestazioni delle query. Se una query si applica un filtro in una colonna partizionata, questa operazione possibile limitare l'elemento digitalizzato a solo le partizioni idonei che possono essere dei dati, come evitare un'analisi della tabella completo ridotto. Con l'introduzione degli indici columnstore raggruppate, le prestazioni di eliminazione predicati sono meno utili, ma in alcuni casi può essere dei vantaggi alle query. Ad esempio, se la tabella dei fatti vendite suddiviso in 36 mesi utilizzando il campo Data di vendita e quindi una query che filtra alla data di vendita possibile ignorare la ricerca in partizioni che non corrispondono al filtro. ## <a name="partition-sizing-guidance"></a>Guida di ridimensionamento partizione Mentre partizione possono essere utilizzati per migliorare le prestazioni alcuni scenari, creare una tabella con le partizioni **troppi** può influire negativamente sulle prestazioni in alcuni casi. Questi problemi sono particolarmente veri per le tabelle columnstore raggruppate. Per partizione per essere utile, è importante tenere presente quando utilizzare partizioni e il numero delle partizioni da creare. Nessuna regola rapida difficili da quante partizioni sono troppi, dipende i dati e il numero di partizioni vengono caricati a contemporaneamente. Ma come un generale, dell'aggiunta 10s a 100s delle partizioni, non 1000s. Quando si creano partizioni nelle tabelle **columnstore raggruppate** , è importante tenere presente il numero di righe verrà inserita in ogni partizione. Per la compressione ottimale e prestazioni delle tabelle columnstore raggruppate, è necessario un minimo di 1 milione di righe per partizione e distribuzione. Prima che vengano create partizioni, SQL Data Warehouse divide già tutte le tabelle in 60 database distribuiti. Qualsiasi partizione aggiunta a una tabella è oltre alle distribuzioni create in background. Utilizzare questo esempio, se la tabella dei fatti di vendita contenuti 36 partizioni mensile e dato che SQL Data Warehouse include 60 distribuzioni, quindi nella tabella dei fatti di vendita deve contenere 60 milioni di righe al mese o 2,1 miliardi quando vengono inseriti tutti i mesi. Se una tabella contiene righe in modo significativo inferiore a quello il numero minimo di righe per partizione consigliato, è preferibile partizioni meno per aumentare il numero di righe per partizione. Vedere anche l'articolo di[indice] di [indicizzazione]che include le query che possono essere eseguite su SQL Data Warehouse per valutare la qualità degli indici columnstore cluster. ## <a name="syntax-difference-from-sql-server"></a>Differenza di sintassi da SQL Server SQL Data Warehouse introduce una definizione semplificata delle partizioni leggermente diversa da SQL Server. Partizioni funzioni e gli schemi non vengono utilizzati in SQL Data Warehouse come in SQL Server. Se, tuttavia, è sufficiente è identificare partizionata colonna e i punti di bordo. La sintassi delle partizioni potrebbe essere leggermente diversa da SQL Server, i concetti di base sono le stesse. SQL Server e SQL Data Warehouse supporta una colonna di partizione per tabella, che può essere partizione nell'intervallo. Per ulteriori informazioni sulle partizioni, vedere [partizioni tabelle e indici][]. L'esempio seguente di un'istruzione SQL Data Warehouse suddiviso [creazione tabella][] , la tabella FactInternetSales sulla colonna OrderDateKey partizioni: ```sql CREATE TABLE [dbo].[FactInternetSales] ( [ProductKey] int NOT NULL , [OrderDateKey] int NOT NULL , [CustomerKey] int NOT NULL , [PromotionKey] int NOT NULL , [SalesOrderNumber] nvarchar(20) NOT NULL , [OrderQuantity] smallint NOT NULL , [UnitPrice] money NOT NULL , [SalesAmount] money NOT NULL ) WITH ( CLUSTERED COLUMNSTORE INDEX , DISTRIBUTION = HASH([ProductKey]) , PARTITION ( [OrderDateKey] RANGE RIGHT FOR VALUES (20000101,20010101,20020101 ,20030101,20040101,20050101 ) ) ) ; ``` ## <a name="migrating-partitioning-from-sql-server"></a>Eseguire la migrazione partizioni da SQL Server Per eseguire la migrazione le definizioni di partizione di SQL Server SQL Data warehouse semplicemente: - Eliminare la [schema di partizione][]di SQL Server. - Aggiungere la definizione di [funzione partition][] alla tabella creare. Se si esegue la migrazione di una tabella partizionata da un'istanza di SQL Server la sotto SQL può essere utile per analizzare il numero di righe presenti in ogni partizione. Tenere presente che se la stessa granularità partizione viene utilizzata in SQL Data Warehouse, il numero di righe per partizione ridurrà di un fattore di 60. ```sql -- Partition information for a SQL Server Database SELECT s.[name] AS [schema_name] , t.[name] AS [table_name] , i.[name] AS [index_name] , p.[partition_number] AS [partition_number] , SUM(a.[used_pages]*8.0) AS [partition_size_kb] , SUM(a.[used_pages]*8.0)/1024 AS [partition_size_mb] , SUM(a.[used_pages]*8.0)/1048576 AS [partition_size_gb] , p.[rows] AS [partition_row_count] , rv.[value] AS [partition_boundary_value] , p.[data_compression_desc] AS [partition_compression_desc] FROM sys.schemas s JOIN sys.tables t ON t.[schema_id] = s.[schema_id] JOIN sys.partitions p ON p.[object_id] = t.[object_id] JOIN sys.allocation_units a ON a.[container_id] = p.[partition_id] JOIN sys.indexes i ON i.[object_id] = p.[object_id] AND i.[index_id] = p.[index_id] JOIN sys.data_spaces ds ON ds.[data_space_id] = i.[data_space_id] LEFT JOIN sys.partition_schemes ps ON ps.[data_space_id] = ds.[data_space_id] LEFT JOIN sys.partition_functions pf ON pf.[function_id] = ps.[function_id] LEFT JOIN sys.partition_range_values rv ON rv.[function_id] = pf.[function_id] AND rv.[boundary_id] = p.[partition_number] WHERE p.[index_id] <=1 GROUP BY s.[name] , t.[name] , i.[name] , p.[partition_number] , p.[rows] , rv.[value] , p.[data_compression_desc] ; ``` ## <a name="workload-management"></a>Gestione di carico di lavoro Una considerazione finale tenere in considerazione per la decisione partizione tabella è [del carico di lavoro][]. Gestione di carico di lavoro in SQL Data Warehouse è principalmente la gestione di memoria e concorrenza. In SQL Data Warehouse la memoria massima allocata per ogni distribuzione durante l'esecuzione di query è le classi di risorse gestite. Ideale delle partizioni verranno ridimensionate in considerazione altri fattori quali le esigenze di memoria della creazione di indici columnstore raggruppate. Raggruppate columnstore indici vantaggio notevolmente quando viene assegnata memoria. Verrà pertanto si desidera assicurarsi che la ricostruzione dell'indice una partizione non è insufficiente di memoria. Aumentare la quantità di memoria disponibile per la query è possibile ottenere passando dal ruolo predefinito, smallrc, a uno degli altri ruoli, ad esempio largerc. Informazioni sull'assegnazione di memoria per distribuzione sono disponibile eseguendo le viste a gestione dinamica gestore delle risorse. In realtà la concessione di memoria sarà minore di cifre riportata di seguito. Tuttavia, in questo modo un livello di indicazioni utilizzato durante il ridimensionamento delle partizioni per le operazioni di gestione dati. Tentare di evitare che il ridimensionamento delle partizioni oltre la concessione di memoria disponibili per la classe di risorse molto grandi. Se le partizioni crescita in questa figura si corre il rischio pressione della memoria che a sua conduce ad minore compressione ottimale. ```sql SELECT rp.[name] AS [pool_name] , rp.[max_memory_kb] AS [max_memory_kb] , rp.[max_memory_kb]/1024 AS [max_memory_mb] , rp.[max_memory_kb]/1048576 AS [mex_memory_gb] , rp.[max_memory_percent] AS [max_memory_percent] , wg.[name] AS [group_name] , wg.[importance] AS [group_importance] , wg.[request_max_memory_grant_percent] AS [request_max_memory_grant_percent] FROM sys.dm_pdw_nodes_resource_governor_workload_groups wg JOIN sys.dm_pdw_nodes_resource_governor_resource_pools rp ON wg.[pool_id] = rp.[pool_id] WHERE wg.[name] like 'SloDWGroup%' AND rp.[name] = 'SloDWPool' ; ``` ## <a name="partition-switching"></a>Cambio di partizione SQL Data Warehouse supporta partizione divisione, l'unione e passaggio. Ognuna di queste funzioni è excuted con l'istruzione [ALTER TABLE][] . Per cambiare le partizioni tra due tabelle è necessario assicurarsi che le partizioni allineare ai loro rispettivi limiti e che corrispondono alle definizioni delle tabelle. Come vincoli di controllo non sono disponibili per applicare l'intervallo di valori in una tabella nella tabella di origine deve contenere gli stessi limiti partizione come tabella di destinazione. In questo caso non cambia partizione riuscirà come i metadati partizione non verranno sincronizzati. ### <a name="how-to-split-a-partition-that-contains-data"></a>Come dividere una partizione che contiene dati Il modo più efficace per dividere una partizione che contiene già dati consiste nell'utilizzare un `CTAS` istruzione. Se la tabella partizionata è un cluster columnstore quindi partizione tabella deve essere vuota prima che possa essere suddiviso. Tabella di seguito sono esempio columnstore partizionata contenente una riga in ogni partizione: ```sql CREATE TABLE [dbo].[FactInternetSales] ( [ProductKey] int NOT NULL , [OrderDateKey] int NOT NULL , [CustomerKey] int NOT NULL , [PromotionKey] int NOT NULL , [SalesOrderNumber] nvarchar(20) NOT NULL , [OrderQuantity] smallint NOT NULL , [UnitPrice] money NOT NULL , [SalesAmount] money NOT NULL ) WITH ( CLUSTERED COLUMNSTORE INDEX , DISTRIBUTION = HASH([ProductKey]) , PARTITION ( [OrderDateKey] RANGE RIGHT FOR VALUES (20000101 ) ) ) ; INSERT INTO dbo.FactInternetSales VALUES (1,19990101,1,1,1,1,1,1); INSERT INTO dbo.FactInternetSales VALUES (1,20000101,1,1,1,1,1,1); CREATE STATISTICS Stat_dbo_FactInternetSales_OrderDateKey ON dbo.FactInternetSales(OrderDateKey); ``` > [AZURE.NOTE] Creando l'oggetto statistico è verificare che i metadati della tabella sono più preciso. Se si omette la creazione di statistiche, SQL Data Warehouse utilizzerà i valori predefiniti. Per informazioni dettagliate sulle statistiche esaminare [le statistiche][]. Possiamo quindi eseguire una query per il numero di riga utilizzando i `sys.partitions` visualizzazione catalogo: ```sql SELECT QUOTENAME(s.[name])+'.'+QUOTENAME(t.[name]) as Table_name , i.[name] as Index_name , p.partition_number as Partition_nmbr , p.[rows] as Row_count , p.[data_compression_desc] as Data_Compression_desc FROM sys.partitions p JOIN sys.tables t ON p.[object_id] = t.[object_id] JOIN sys.schemas s ON t.[schema_id] = s.[schema_id] JOIN sys.indexes i ON p.[object_id] = i.[object_Id] AND p.[index_Id] = i.[index_Id] WHERE t.[name] = 'FactInternetSales' ; ``` Se si tenta di dividere in questa tabella, si verificherà un errore: ```sql ALTER TABLE FactInternetSales SPLIT RANGE (20010101); ``` Msg 35346, Level 15 stato 1, riga 44 divisa clausola dell'istruzione ALTER partizione non riuscita perché la partizione non è vuota. Solo partizioni vuote possono essere suddivise presenza di un indice columnstore della tabella. È consigliabile disabilitare l'indice columnstore prima istruzione ALTER partizione e quindi ricostruire l'indice columnstore al termine partizione modificare. Tuttavia, è possibile utilizzare `CTAS` per creare una nuova tabella per contenere i dati. ```sql CREATE TABLE dbo.FactInternetSales_20000101 WITH ( DISTRIBUTION = HASH(ProductKey) , CLUSTERED COLUMNSTORE INDEX , PARTITION ( [OrderDateKey] RANGE RIGHT FOR VALUES (20000101 ) ) ) AS SELECT * FROM FactInternetSales WHERE 1=2 ; ``` Come vengono allineati dei limiti delle partizioni è consentito un parametro. Tale etichetta definisce la tabella di origine con una partizione vuota che è possibile successivamente divisa. ```sql ALTER TABLE FactInternetSales SWITCH PARTITION 2 TO FactInternetSales_20000101 PARTITION 2; ALTER TABLE FactInternetSales SPLIT RANGE (20010101); ``` Tutti gli elementi ancora da svolgere sia per allineare i dati al nuovo dei limiti delle partizioni con `CTAS` e cambia nuovamente i dati alla tabella principale ```sql CREATE TABLE [dbo].[FactInternetSales_20000101_20010101] WITH ( DISTRIBUTION = HASH([ProductKey]) , CLUSTERED COLUMNSTORE INDEX , PARTITION ( [OrderDateKey] RANGE RIGHT FOR VALUES (20000101,20010101 ) ) ) AS SELECT * FROM [dbo].[FactInternetSales_20000101] WHERE [OrderDateKey] >= 20000101 AND [OrderDateKey] < 20010101 ; ALTER TABLE dbo.FactInternetSales_20000101_20010101 SWITCH PARTITION 2 TO dbo.FactInternetSales PARTITION 2; ``` Dopo aver completato lo spostamento dei dati è utile anche per aggiornare le statistiche nella tabella di destinazione per assicurarsi che riflettano accuratamente nuova lista di distribuzione dei dati nel loro rispettivi partizioni: ```sql UPDATE STATISTICS [dbo].[FactInternetSales]; ``` ### <a name="table-partitioning-source-control"></a>Tabella suddivisione del controllo origine Per evitare la definizione di una tabella da **rusting** nel sistema di controllo di origine è consigliabile prendere in considerazione la procedura seguente: 1. Creare la tabella come una tabella partizionata ma senza valori partizione ```sql CREATE TABLE [dbo].[FactInternetSales] ( [ProductKey] int NOT NULL , [OrderDateKey] int NOT NULL , [CustomerKey] int NOT NULL , [PromotionKey] int NOT NULL , [SalesOrderNumber] nvarchar(20) NOT NULL , [OrderQuantity] smallint NOT NULL , [UnitPrice] money NOT NULL , [SalesAmount] money NOT NULL ) WITH ( CLUSTERED COLUMNSTORE INDEX , DISTRIBUTION = HASH([ProductKey]) , PARTITION ( [OrderDateKey] RANGE RIGHT FOR VALUES () ) ) ; ``` 2. `SPLIT`la tabella come parte del processo di distribuzione: ```sql -- Create a table containing the partition boundaries CREATE TABLE #partitions WITH ( LOCATION = USER_DB , DISTRIBUTION = HASH(ptn_no) ) AS SELECT ptn_no , ROW_NUMBER() OVER (ORDER BY (ptn_no)) as seq_no FROM ( SELECT CAST(20000101 AS INT) ptn_no UNION ALL SELECT CAST(20010101 AS INT) UNION ALL SELECT CAST(20020101 AS INT) UNION ALL SELECT CAST(20030101 AS INT) UNION ALL SELECT CAST(20040101 AS INT) ) a ; -- Iterate over the partition boundaries and split the table DECLARE @c INT = (SELECT COUNT(*) FROM #partitions) , @i INT = 1 --iterator for while loop , @q NVARCHAR(4000) --query , @p NVARCHAR(20) = N'' --partition_number , @s NVARCHAR(128) = N'dbo' --schema , @t NVARCHAR(128) = N'FactInternetSales' --table ; WHILE @i <= @c BEGIN SET @p = (SELECT ptn_no FROM #partitions WHERE seq_no = @i); SET @q = (SELECT N'ALTER TABLE '+@s+N'.'+@t+N' SPLIT RANGE ('+@p+N');'); -- PRINT @q; EXECUTE sp_executesql @q; SET @i+=1; END -- Code clean-up DROP TABLE #partitions; ``` Con questo approccio il codice sorgente rimane in statico e i valori limite partizioni possono essere dinamico; in evoluzione con il warehouse nel tempo. ## <a name="next-steps"></a>Passaggi successivi Per ulteriori informazioni, vedere gli articoli nella [Tabella Panoramica][Panoramica]di [Tipi di dati di tabella][Tipi di dati], [la distribuzione di una tabella][Distribuisci], [l'indicizzazione di una tabella di][indice], [Mantenendo le statistiche delle tabelle][statistiche] e [Tabelle temporanee][temporaneo]. Per ulteriori informazioni sulle procedure consigliate, vedere [SQL dati Warehouse procedure consigliate][]. <!--Image references--> <!--Article references--> [Panoramica]: ./sql-data-warehouse-tables-overview.md [Tipi di dati]: ./sql-data-warehouse-tables-data-types.md [Distribuire]: ./sql-data-warehouse-tables-distribute.md [Indice]: ./sql-data-warehouse-tables-index.md [Partizione]: ./sql-data-warehouse-tables-partition.md [Statistiche]: ./sql-data-warehouse-tables-statistics.md [Temporaneo]: ./sql-data-warehouse-tables-temporary.md [gestione di carico di lavoro]: ./sql-data-warehouse-develop-concurrency.md [Procedure consigliate Warehouse dati SQL]: ./sql-data-warehouse-best-practices.md <!-- MSDN Articles --> [Gli indici e tabelle partizionate]: https://msdn.microsoft.com/library/ms190787.aspx [ISTRUZIONE ALTER TABLE]: https://msdn.microsoft.com/en-us/library/ms190273.aspx [CREA TABELLA]: https://msdn.microsoft.com/library/mt203953.aspx [funzione Partition]: https://msdn.microsoft.com/library/ms187802.aspx [schema di partizione]: https://msdn.microsoft.com/library/ms179854.aspx <!-- Other web references -->
Java
UTF-8
1,070
2.3125
2
[]
no_license
package com.example.user.mcalc; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class EntryForm extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mortgage_layout); } public void buttonClicked(View v){ EditText principleView = (EditText) findViewById(R.id.principleBox); String principle = principleView.getText().toString(); EditText amortView = (EditText) findViewById(R.id.amortBox); String amort = amortView.getText().toString(); EditText interestView = (EditText) findViewById(R.id.interestBox); String interest = interestView.getText().toString(); MortgageModel myModel = new MortgageModel(principle, amort, interest); String payment = myModel.computePayment(); ((TextView) findViewById(R.id.result)).setText(payment); } }
SQL
UTF-8
261
3.046875
3
[]
no_license
DROP TABLE IF EXISTS collaborators CASCADE; CREATE TABLE collaborators ( id serial PRIMARY KEY NOT NULL, map_id integer REFERENCES maps(id) NOT NULL, user_id integer REFERENCES users(id) NOT NULL, active boolean NOT NULL, unique (map_id, user_id) );
Markdown
UTF-8
2,605
2.703125
3
[]
no_license
<!-- Title: Saving cows with the help of Lord Krishna, Gunny Sacks and Potassium permanganate! Culture Jam #01 Scripts: - //s.imgur.com/min/embed.js --> <!-- > <i>This is a part of "[These are Our Cows](/?p=ourcows)" initiative.</i> An effort to improve the quality of life for abandoned cows and bulls in India. --> ![photo756377654343608414.jpg](/markdown/photo756377654343608414.jpg) > Jan 03, 2016 Farm, don't harm. ====== > <i>Cows are abandoned.</i><br/> > <i>Cows get in fields.</i><br/> > <i>Cows get beaten.</i><br/> > <i>Cows get healed. **By us.**</i> This is what we deal with. And frankly, we are a little tired of it. So, we decided that we need to change how farmers act towards stray cows. Farmers do have a choice to chase away cows with water and that is the only legal choice. Still, they use sticks and sickles and cows lose horns and cows get fractures and maggot wounds. This is not right. We thought if they are not afraid of the law, maybe they will be afraid of the Lord. Today it begins. We have put sweaters made out of gunny sacks on them. The markings on the sweater are the picture of Lord Krishna (who is the savior of cows) and a quote "This cow is mine", in Hindi. Hopefully, when the farmers are chasing away stray cows from their fields, they won't at least hit them with rocks or sticks or sickles. It does not have to stay in our little village. This should spread all over India and only you can help spread it. This should become trendy, and you can be the trend setter. Either pick up a paintbrush and some sacks, or **SHARE** this ‪culture jam‬ with other hactivists. <center><blockquote class="imgur-embed-pub" lang="en" data-id="a/RYsIN"></blockquote></center> Media Links --- > * [Facebook](https://www.facebook.com/worldlywags/posts/1025847224120182) <br/> > * [The better India "This team just came up with an ingenious way of preventing cow abuse"](http://www.thebetterindia.com/41739/badmash-peepal-stray-cows-gunny-sacks-krishna/) > * [India Times "Meet 'Badmash Peepal', A Community Initiative That Prevents Cow Abuse And Changes Human Behaviour"](http://www.indiatimes.com/news/india/meet-badmash-peepal-a-community-initiative-that-prevents-cow-abuse-and-changes-human-behaviour-249151.html) > * [Catch News "The Badmash Peepal: Saving cows with a little help from Lord Krishna"](http://www.catchnews.com/life-society-news/the-badmash-peepal-saving-cows-with-a-little-help-from-lord-krishna-1452257141.html) > * [Punjab Kesari Newspaper](http://epaper.punjabkesari.in/688929/punjab-kesari-himachal-kangra-kesari/Kangra-kesari#page/2/2)
PHP
UTF-8
733
2.703125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { /** * Vaciando tabla antes de llenarla de nuevo */ $this->truncateTables([ 'cities' ]); $this->call(CitiesSeeder::class); } protected function truncateTables(array $tables) { DB::statement('SET FOREIGN_KEY_CHECKS = 0;'); //ignorar llaves foraneas foreach($tables as $table){ DB::table($table)->truncate(); //vaciar la tabla } DB::statement('SET FOREIGN_KEY_CHECKS = 1;'); //reactivar validacion dellave foranea } }
Java
UTF-8
1,843
2.25
2
[]
no_license
package ucll.project.ui.controller; import ucll.project.domain.model.Lector; import ucll.project.domain.model.Lesson; import ucll.project.domain.model.Rol; import ucll.project.domain.service.ApplicationService; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; public class LectorLessen extends RequestHandler { public LectorLessen(String command, ApplicationService applicationService) { super(command, applicationService); } @Override public String handleRequest(HttpServletRequest request, HttpServletResponse response) { LinkedHashMap<Date, List<Lesson>> lessenPerDag = new LinkedHashMap<>(); List<Lesson> lessenLijst; Rol[] roles = new Rol[]{Rol.LECTOR}; Utility.checkRoles(request, roles); Lector lector = (Lector) request.getSession().getAttribute("loggedIn"); String nummer = lector.getLectorennummer(); int id = getApplicationService().getLectorId(nummer); List<Date> datums = getApplicationService().getAllDatumsLector(); Collections.sort(datums); for (Date d : datums){ lessenLijst = getApplicationService().getLessonForLector(id, d); lessenPerDag.put(d, lessenLijst); } request.setAttribute("lessenPerDag", lessenPerDag); List<List<String>> groeplijstperdag = new ArrayList<>(); for (Date d: datums){ List<Lesson> lessen = lessenPerDag.get(d); List<String> groepen = new ArrayList<>(); for (Lesson les: lessen) { groepen.add(getApplicationService().getGroep(les)); } groeplijstperdag.add(groepen); } request.setAttribute("groeplijstperdag", groeplijstperdag); return "lectorLessen.jsp"; } }
Python
UTF-8
2,075
3.21875
3
[]
no_license
"""Lab 1. Approximation of reachable set. Considered model is x'(t) = A(t)*x(t) + C(t)u(t). t belongs to [t0, t1] x(t0) belongs to start set M0, which is ellipsoid u(t) - control function, which belongs to U(t) which is also ellipsoid for any non-negative t """ import numpy as np from approximation import solve from operable import Operable from plot_utils import plot_approximation_result def main(): # pylint: disable=C0103 """Entry point for the app.""" # dimension N = 4 # set up model parameters # weights M1 = 2 M2 = 3 # friction forces B = 4 B1 = 3 B2 = 5 # stiffnesses K = 2 K1 = 2 K2 = 2 # set up start set M0 A0 = [1, 1, 1, 1] QV1 = [1, 0, 0, 0] QV2 = [0, 1, 0, 0] QV3 = [0, 0, 1, 0] QV4 = [0, 0, 0, 1] Q0_SEMI_AXES = [1, 2, 3, 4] Q0_LAMBDA = [ [ (0 if j != i else 1/Q0_SEMI_AXES[i]**2) for j in range(N) ] for i in range(N) ] Q0_EIGEN_VECTORS_MATRIX = np.transpose([QV1, QV2, QV3, QV4]) Q0_EIGEN_VECTORS_MATRIX_INV = np.linalg.inv(Q0_EIGEN_VECTORS_MATRIX) Q0 = np.dot(Q0_EIGEN_VECTORS_MATRIX, Q0_LAMBDA) Q0 = np.dot(Q0, Q0_EIGEN_VECTORS_MATRIX_INV) # set up shape matrix for bounding ellipsoid for u(t) G = [ [Operable(lambda t: t**2+t*16), Operable(lambda t: t**2+t*8)], [Operable(lambda t: t**2+t*8), Operable(lambda t: 4*t**2 + t)] ] # set up matrix of the system (i. e. matrix A(t)) A = [ [0, 1, 0, 0], [-(K + K1)/M1, -(B + B1)/M1, K/M1, B/M1], [0, 0, 0, 1], [K/M2, B/M2, -(K + K2)/M2, -(B + B2)/M2] ] C = [ [0, 0], [1/M1, 0], [0, 0], [0, -1/M2] ] T_START = 0 # T_START - start of time T_END = 10 # T_END - end of time T_COUNT = 50 # T_COUNT - number of timestamps on [t_start, t_end] t_array, center, shape_matrix = solve(A, A0, Q0, C, G, T_START, T_END, T_COUNT) plot_approximation_result(t_array, center, shape_matrix, [0, 1], 'T', 'Y1', 'Y2') main()
Java
UTF-8
396
1.632813
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 ctig; import placedata.ReligionID; /** * Class used for picking religious affiliation * @author RollerSimmer */ public class AffiliationPicker extends EnumPicker<ReligionID> { }
Rust
UTF-8
19,972
2.875
3
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
use super::Timed; use crate::event::EventHandler; #[cfg(test)] use crate::test_utilities::{DummyEventHandler, TestPlugin}; use crate::ContextualAudioRenderer; use std::cmp::Ordering; use std::collections::VecDeque; use std::ops::{Deref, Index, IndexMut}; use vecstorage::{VecGuard, VecStorage}; pub struct EventQueue<T> { queue: VecDeque<Timed<T>>, } pub enum EventCollisionHandling { InsertNewBeforeOld, InsertNewAfterOld, IgnoreNew, RemoveOld, } pub trait HandleEventCollision<T> { fn decide_on_collision(&self, old_event: &T, new_event: &T) -> EventCollisionHandling; } pub struct AlwaysInsertNewBeforeOld; impl<T> HandleEventCollision<T> for AlwaysInsertNewBeforeOld { #[inline(always)] fn decide_on_collision(&self, _old_event: &T, _new_event: &T) -> EventCollisionHandling { EventCollisionHandling::InsertNewBeforeOld } } pub struct AlwaysInsertNewAfterOld; impl<T> HandleEventCollision<T> for AlwaysInsertNewAfterOld { #[inline(always)] fn decide_on_collision(&self, _old_event: &T, _new_event: &T) -> EventCollisionHandling { EventCollisionHandling::InsertNewAfterOld } } pub struct AlwaysIgnoreNew; impl<T> HandleEventCollision<T> for AlwaysIgnoreNew { #[inline(always)] fn decide_on_collision(&self, _old_event: &T, _new_event: &T) -> EventCollisionHandling { EventCollisionHandling::IgnoreNew } } pub struct AlwaysRemoveOld; impl<T> HandleEventCollision<T> for AlwaysRemoveOld { #[inline(always)] fn decide_on_collision(&self, _old_event: &T, _new_event: &T) -> EventCollisionHandling { EventCollisionHandling::RemoveOld } } impl<T> Index<usize> for EventQueue<T> { type Output = Timed<T>; fn index(&self, index: usize) -> &Self::Output { &self.queue[index] } } impl<T> IndexMut<usize> for EventQueue<T> { fn index_mut(&mut self, index: usize) -> &mut Self::Output { &mut self.queue[index] } } impl<T> EventQueue<T> { #[cfg(test)] pub fn from_vec(events: Vec<Timed<T>>) -> Self { Self { queue: events.into(), } } /// # Panics /// Panics if `capacity == 0`. pub fn new(capacity: usize) -> Self { assert!(capacity > 0); Self { queue: VecDeque::with_capacity(capacity), } } /// Queue a new event. /// When the buffer is full, an element may be removed from the queue to make some room. /// This element is returned. pub fn queue_event<H>(&mut self, new_event: Timed<T>, collision_decider: H) -> Option<Timed<T>> where H: HandleEventCollision<T>, { let mut new_event = new_event; let result; if self.queue.len() >= self.queue.capacity() { // Note: self.queue.capacity() > 0, so self.queue is not empty. // TODO: Log an error. // We remove the first event to come, in this way, // we are sure we are not skipping the "last" event, // because we assume that the state of the first event // is only temporarily, and the state of the last event // may remain forever. For this reason, it is safer to // remove the first event if new_event.time_in_frames > self.queue[0].time_in_frames { result = self.queue.pop_front(); } else { return Some(new_event); } } else { result = None; } // If we are at this point, we can assume that we can insert at least one more event. debug_assert!(self.queue.len() < self.queue.capacity()); let mut insert_index = 0; for read_event in self.queue.iter_mut() { match read_event.time_in_frames.cmp(&new_event.time_in_frames) { Ordering::Less => { insert_index += 1; } Ordering::Equal => { match collision_decider.decide_on_collision(&read_event.event, &new_event.event) { EventCollisionHandling::IgnoreNew => { return Some(new_event); } EventCollisionHandling::InsertNewBeforeOld => { break; } EventCollisionHandling::InsertNewAfterOld => { insert_index += 1; } EventCollisionHandling::RemoveOld => { std::mem::swap(&mut read_event.event, &mut new_event.event); return Some(new_event); } } } Ordering::Greater => { break; } } } self.queue.insert(insert_index, new_event); result } /// Remove all events before, but not on, this threshold. /// /// # Note about usage in real-time context /// If `T` implements drop, the elements that are removed are dropped. /// This may cause memory de-allocation, which you want to avoid in /// the real-time part of your library. pub fn forget_before(&mut self, threshold: u32) where T: Copy, { self.queue.retain(|x| x.time_in_frames >= threshold); } /// Remove all events from the queue. /// /// # Note about usage in real-time context /// If `T` implements drop, the elements that are removed are dropped. /// This may cause memory de-allocation, which you want to avoid in /// the real-time part of your library. pub fn clear(&mut self) { self.queue.clear() } /// Shift time forward by `new_zero_time` frames. /// /// # Panics /// Panics in debug mode when at least one event has a `time_in_frames` /// that is < `new_zero_time`. pub fn shift_time(&mut self, new_zero_time: u32) { for event in self.queue.iter_mut() { event.time_in_frames -= new_zero_time; } } pub fn get_last_before(&self, time: u32) -> Option<&Timed<T>> { if let Some(index) = self.queue.iter().rposition(|e| e.time_in_frames < time) { self.queue.get(index) } else { None } } pub fn first(&self) -> Option<&Timed<T>> { self.queue.get(0) } fn render<'storage, 's, 'chunk, S, R, C>( start: usize, stop: usize, input_storage: &'storage mut VecStorage<&'static [S]>, output_storage: &'storage mut VecStorage<&'static mut [S]>, inputs: &[&[S]], outputs: &mut [&mut [S]], renderer: &mut R, context: &mut C, ) where S: 'static, R: ContextualAudioRenderer<S, C>, { let input_guard = mid(input_storage, inputs, start, stop); let mut output_guard = mid_mut(output_storage, outputs, start, stop); renderer.render_buffer(&input_guard, &mut output_guard, context); } pub fn split<'storage, 's, 'chunk, S, R, C>( &mut self, input_storage: &'storage mut VecStorage<&'static [S]>, output_storage: &'storage mut VecStorage<&'static mut [S]>, inputs: &[&[S]], outputs: &'s mut [&'s mut [S]], renderer: &mut R, context: &mut C, ) where S: 'static, R: ContextualAudioRenderer<S, C> + EventHandler<T>, T: std::fmt::Debug, { let buffer_length = if inputs.len() > 0 { inputs[0].len() } else if outputs.len() > 0 { outputs[0].len() } else { todo!(); }; let mut last_event_time = 0; loop { if let Some(ref first) = self.queue.get(0) { if first.time_in_frames as usize >= buffer_length { break; } } else { break; }; let Timed { time_in_frames: event_time, event, } = self.queue.pop_front().expect("event queue is not empty"); if event_time == last_event_time { renderer.handle_event(event); continue; } Self::render( last_event_time as usize, event_time as usize, input_storage, output_storage, inputs, outputs, renderer, context, ); renderer.handle_event(event); last_event_time = event_time; } if (last_event_time as usize) < buffer_length { Self::render( last_event_time as usize, buffer_length, input_storage, output_storage, inputs, outputs, renderer, context, ); }; } } #[test] fn split_works() { let mut test_plugin = TestPlugin::new( vec![ audio_chunk![[11, 12], [21, 22]], audio_chunk![[13, 14], [23, 24]], ], vec![ audio_chunk![[110, 120], [210, 220]], audio_chunk![[130, 140], [230, 240]], ], vec![vec![1, 2], vec![3, 4]], vec![vec![], vec![]], (), ); let input = audio_chunk![[11, 12, 13, 14], [21, 22, 23, 24]]; let mut output = audio_chunk![[0, 0, 0, 0], [0, 0, 0, 0]]; let events = vec![ Timed { time_in_frames: 0, event: 1, }, Timed { time_in_frames: 0, event: 2, }, Timed { time_in_frames: 2, event: 3, }, Timed { time_in_frames: 2, event: 4, }, Timed { time_in_frames: 4, event: 5, }, ]; let mut queue = EventQueue::from_vec(events); let mut input_storage = VecStorage::with_capacity(2); let mut output_storage = VecStorage::with_capacity(2); let mut result_event_handler = DummyEventHandler; queue.split( &mut input_storage, &mut output_storage, &input.as_slices(), &mut output.as_mut_slices(), &mut test_plugin, &mut result_event_handler, ) } #[test] fn split_works_with_empty_event_queue() { let mut test_plugin = TestPlugin::<_, (), _>::new( vec![audio_chunk![[11, 12, 13, 14], [21, 22, 23, 24]]], vec![audio_chunk![[110, 120, 130, 140], [210, 220, 230, 240]]], vec![vec![]], vec![vec![]], (), ); let input = audio_chunk![[11, 12, 13, 14], [21, 22, 23, 24]]; let mut output = audio_chunk![[0, 0, 0, 0], [0, 0, 0, 0]]; let events: Vec<()> = vec![]; let mut queue = EventQueue::new(1); let mut input_storage = VecStorage::with_capacity(2); let mut output_storage = VecStorage::with_capacity(2); let mut result_event_handler = DummyEventHandler; queue.split( &mut input_storage, &mut output_storage, &input.as_slices(), &mut output.as_mut_slices(), &mut test_plugin, &mut result_event_handler, ) } impl<T> Deref for EventQueue<T> { type Target = VecDeque<Timed<T>>; fn deref(&self) -> &Self::Target { &self.queue } } // TODO: Move to a better place in the module hierarchy. pub fn mid<'storage, 'chunk, 's, S>( storage: &'storage mut VecStorage<&'static [S]>, chunk: &'chunk [&'s [S]], start: usize, end: usize, ) -> VecGuard<'storage, &'static [S], &'chunk [S]> { let mut remaining_chunk = chunk; let mut guard = storage.vec_guard(); let mut len = remaining_chunk.len(); while len > 0 { let (first_channel, other_channels) = remaining_chunk.split_at(1); let channel = &(first_channel[0]); let (first, _) = channel.split_at(end); let (_, middle) = first.split_at(start); guard.push(middle); remaining_chunk = other_channels; len = remaining_chunk.len(); } guard } // TODO: Move to a better place in the module hierarchy. /// /// ## Panics /// Panics if `start` > `end` or if `end` > the length of any item in `chunk`. pub fn mid_mut<'storage, 'chunk, 's, S>( storage: &'storage mut VecStorage<&'static mut [S]>, chunk: &'chunk mut [&'s mut [S]], start: usize, end: usize, ) -> VecGuard<'storage, &'static mut [S], &'chunk mut [S]> { let mut remaining_chunk = chunk; let mut guard = storage.vec_guard(); let mut len = remaining_chunk.len(); while len > 0 { let (first_channel, other_channels) = remaining_chunk.split_at_mut(1); let channel = &mut (first_channel[0]); let (first, _) = channel.split_at_mut(end); let (_, middle) = first.split_at_mut(start); guard.push(middle); remaining_chunk = other_channels; len = remaining_chunk.len(); } guard } #[test] fn mid_mut_works() { let mut storage = VecStorage::with_capacity(2); let mut channel1 = [11, 12, 13, 14]; let mut channel2 = [21, 22, 23, 24]; let chunk: &mut [&mut [_]] = &mut [&mut channel1, &mut channel2]; { let guard = mid_mut(&mut storage, chunk, 0, 0); assert_eq!(guard.len(), 2); assert!(guard[0].is_empty()); assert!(guard[1].is_empty()); } { let guard = mid_mut(&mut storage, chunk, 0, 1); assert_eq!(guard.len(), 2); assert_eq!(guard[0], &mut [11]); assert_eq!(guard[1], &mut [21]); } { let guard = mid_mut(&mut storage, chunk, 0, 2); assert_eq!(guard.len(), 2); assert_eq!(guard[0], &mut [11, 12]); assert_eq!(guard[1], &mut [21, 22]); } { let guard = mid_mut(&mut storage, chunk, 1, 2); assert_eq!(guard.len(), 2); assert_eq!(guard[0], &mut [12]); assert_eq!(guard[1], &mut [22]); } } #[test] fn mid_works() { let mut storage = VecStorage::with_capacity(2); let channel1 = [11, 12, 13, 14]; let channel2 = [21, 22, 23, 24]; let chunk: &[&[_]] = &[&channel1, &channel2]; { let guard = mid(&mut storage, chunk, 0, 0); assert_eq!(guard.len(), 2); assert!(guard[0].is_empty()); assert!(guard[1].is_empty()); } { let guard = mid(&mut storage, chunk, 0, 1); assert_eq!(guard.len(), 2); assert_eq!(guard[0], &[11]); assert_eq!(guard[1], &[21]); } { let guard = mid(&mut storage, chunk, 0, 2); assert_eq!(guard.len(), 2); assert_eq!(guard[0], &[11, 12]); assert_eq!(guard[1], &[21, 22]); } { let guard = mid(&mut storage, chunk, 1, 2); assert_eq!(guard.len(), 2); assert_eq!(guard[0], &[12]); assert_eq!(guard[1], &[22]); } } #[test] fn eventqueue_queue_event_new_event_ignored_when_already_full_and_new_event_comes_first() { let initial_buffer = vec![Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49)]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); // Check our assumption: assert_eq!(queue.queue.capacity(), queue.queue.len()); // Act queue.queue_event(Timed::new(3, 9), AlwaysIgnoreNew); // Assert: assert_eq!(queue.queue, initial_buffer); } #[test] fn event_queue_queue_event_first_event_removed_when_already_full_and_new_event_after_first() { let initial_buffer = vec![Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49)]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); // Check our assumption: assert_eq!(queue.queue.capacity(), queue.queue.len()); // Act queue.queue_event(Timed::new(5, 25), AlwaysInsertNewAfterOld); // Assert: assert_eq!( queue.queue, vec![Timed::new(5, 25), Timed::new(6, 36), Timed::new(7, 49),] ); } #[test] fn eventqueue_queue_event_new_event_inserted_at_correct_location() { let initial_buffer = vec![Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49)]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); queue.queue.reserve(1); // Act queue.queue_event(Timed::new(5, 25), AlwaysInsertNewAfterOld); // Assert: assert_eq!( queue.queue, vec![ Timed::new(4, 16), Timed::new(5, 25), Timed::new(6, 36), Timed::new(7, 49), ] ); } #[test] fn eventqueue_queue_event_with_always_ignore_new_new_event_ignored_when_already_event_at_that_location( ) { let initial_buffer = vec![Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49)]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); queue.queue.reserve(1); // Act queue.queue_event(Timed::new(6, 25), AlwaysIgnoreNew); // Assert: assert_eq!(queue.queue, initial_buffer); } #[test] fn eventqueue_queue_event_with_always_ignore_old_old_event_ignored_when_already_event_at_that_location( ) { let initial_buffer = vec![Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49)]; let expected_buffer = vec![Timed::new(4, 16), Timed::new(6, 25), Timed::new(7, 49)]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); queue.queue.reserve(1); // Act let result = queue.queue_event(Timed::new(6, 25), AlwaysRemoveOld); assert_eq!(result, Some(Timed::new(6, 36))); // Assert: assert_eq!(queue.queue, expected_buffer); } #[test] fn eventqueue_queue_event_with_always_insert_new_after_old() { let initial_buffer = vec![Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49)]; let expected_buffer = vec![ Timed::new(4, 16), Timed::new(6, 36), Timed::new(6, 25), Timed::new(7, 49), ]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); queue.queue.reserve(1); // Act let result = queue.queue_event(Timed::new(6, 25), AlwaysInsertNewAfterOld); assert_eq!(result, None); // Assert: assert_eq!(queue.queue, expected_buffer); } #[test] fn eventqueue_queue_event_with_always_insert_new_after_old_with_doubles() { let initial_buffer = vec![Timed::new(6, 16), Timed::new(6, 36), Timed::new(7, 49)]; let expected_buffer = vec![ Timed::new(6, 16), Timed::new(6, 36), Timed::new(6, 25), Timed::new(7, 49), ]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); queue.queue.reserve(1); // Act let result = queue.queue_event(Timed::new(6, 25), AlwaysInsertNewAfterOld); assert_eq!(result, None); // Assert: assert_eq!(queue.queue, expected_buffer); } #[test] fn eventqueue_queue_event_with_always_insert_new_before_old() { let initial_buffer = vec![Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49)]; let expected_buffer = vec![ Timed::new(4, 16), Timed::new(6, 25), Timed::new(6, 36), Timed::new(7, 49), ]; let mut queue = EventQueue::from_vec(initial_buffer.clone()); queue.queue.reserve(1); // Act let result = queue.queue_event(Timed::new(6, 25), AlwaysInsertNewBeforeOld); assert_eq!(result, None); // Assert: assert_eq!(queue.queue, expected_buffer); } #[test] fn eventqueue_forget_before() { let mut queue = EventQueue::from_vec({ vec![ Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49), Timed::new(8, 64), ] }); queue.forget_before(7); assert_eq!(queue.queue, vec![Timed::new(7, 49), Timed::new(8, 64),]); } #[test] fn eventqueue_forget_everything() { let mut queue = EventQueue::from_vec({ vec![ Timed::new(4, 16), Timed::new(6, 36), Timed::new(7, 49), Timed::new(8, 64), ] }); queue.forget_before(9); assert_eq!(queue.queue, Vec::new()); }
JavaScript
UTF-8
1,598
2.625
3
[]
no_license
const express = require('express') const mongoose = require('mongoose') const app = express() app.use(express.json()) mongoose.connect('mongodb://localhost:27018/empDB', { useNewUrlParser: true }) .then(() => { console.log('Connected to DB...') }) .catch(err => { console.error(`Error: ${err}`) }) const Employees = mongoose.model('Employees', new mongoose.Schema({ empNumber: { type: Number, required: true }, empName: { type: String, required: true }, dept: { type: String, required: true } })) // @get route: all employees app.get('/api/employee', async (req, res) => { const empList = await Employees.find().sort({'empName': 1}) res.send(empList) }) // @get route: requested employee app.get('/api/employee/:empNumber', async(req, res) => { const emp = await Employees.find({"empNumber": req.params.empNumber}) res.send(emp) }) // @post route: add new employee app.post('/api/employee/:empNumber', async (req, res) => { const employee = new Employees({ empNumber: req.body.empNumber, empName: req.body.empName, dept: req.body.dept }) await employee.save() res.send('Successfully added employee in DB!') }) // @delete route: delete specified employee app.delete('/api/employee/:empNumber', async (req, res) => { await Employees.deleteOne({'empNumber': req.params.empNumber}) res.send('Successfully removed employee from DB!') }) const port = process.env.PORT || 5000 app.listen(port, () => { console.log(`Server running on port ${port}...`) })
Python
UTF-8
1,211
4.40625
4
[]
no_license
''' leetcode 225 Implement a last in first out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal queue (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. You must use only standard operations of a queue, which means only push to back, peek/pop from front, size, and is empty operations are valid. ''' from collections import deque class MyStack: def __init__(self): self.data = deque() def push(self, x): self.data.appendleft(x) for i in range(len(self.data)-1): self.data.appendleft(self.data.pop()) def pop(self): return self.data.pop() def top(self): return self.data[-1] def empty(self): return len(self.data) == 0 if __name__ == "__main__": stack = MyStack() stack.push(1); stack.push(2); print(stack.top()) # 2 print(stack.pop()) # 2 print(stack.empty()) # False
C++
UTF-8
2,737
2.515625
3
[]
no_license
#include "buffer.h" #include <glt/zplane.h> #include <glt/error.h> //////////////////////////////////////////////// CsgDepthBufferHelper::CsgDepthBufferHelper(const bool useCopy) : _useCopy(useCopy), _viewport(true), _buffer(NULL) { if (_useCopy) glViewport(0,0,_viewport.width()>>1,_viewport.height()); } CsgDepthBufferHelper::~CsgDepthBufferHelper() { if (_buffer) delete _buffer; _buffer = NULL; } bool CsgDepthBufferHelper::empty() const { return _buffer==NULL; } void CsgDepthBufferHelper::read() { GLERROR if (_useCopy) { glPushAttrib(GL_VIEWPORT_BIT | GL_ENABLE_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); _viewport.set(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0,_viewport.width(),0,_viewport.height(),0.0,1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glRasterPos2f(_viewport.width()>>1,0.0F); glDisable(GL_STENCIL_TEST); glEnable(GL_DEPTH_TEST); glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE); glDepthMask(GL_TRUE); glDepthFunc(GL_ALWAYS); glDisable(GL_CULL_FACE); glCopyPixels(0,0,_viewport.width()>>1,_viewport.height(),GL_DEPTH); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopAttrib(); } else { if (!_buffer) _buffer = new depthBuffer(); else _buffer->read(); } GLERROR } void CsgDepthBufferHelper::write(const bool merge) { GLERROR glDisable(GL_STENCIL_TEST); glDisable(GL_CULL_FACE); glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); if (merge) glDepthFunc(GL_LESS); else glDepthFunc(GL_ALWAYS); if (_useCopy) { glPushAttrib(GL_VIEWPORT_BIT); _viewport.set(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0,_viewport.width(),0,_viewport.height(),0.0,1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glRasterPos2f(0.0f,0.0f); glCopyPixels(_viewport.width()>>1,0,_viewport.width()>>1,_viewport.height(),GL_DEPTH); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopAttrib(); } else if (_buffer) _buffer->write(); GLERROR }
C#
UTF-8
1,878
2.5625
3
[]
no_license
using DataBaseConnector; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace win_database { public partial class frmUpdat : Form { private string _TBNName { set; get; } private string _TBNCell { set; get; } private string _TBNColval { set; get; } private string _TBNWhere { set; get; } private bool _TBLIsInt { set; get; } public frmUpdat(string TBNName ,string TBNCell ,string TBNColval, string TBNWhere,bool TBLIsInt) { _TBNName = TBNName; _TBNCell = TBNCell; _TBNColval = TBNColval; _TBNWhere = TBNWhere; _TBLIsInt = TBLIsInt; InitializeComponent(); } private void FrmUpdat_Load(object sender, EventArgs e) { lbl_2.Text = "مقدار قبلی در" + _TBNName + ":" + _TBNColval; } /* UPDATE [{_TBNName}] SET [{_TBNCell}] = {flog} WHERE {_TBNWhere} */ private void Btn_save_Click(object sender, EventArgs e) { PDBC db = new PDBC(); db.Connect(); string result = "عدم توانایی"; if(_TBLIsInt) { int flog = 0; if(Int32.TryParse(lbl_1.Text,out flog)) { result = db.Script($" UPDATE [{_TBNName}] SET [{_TBNCell}] = {flog} WHERE {_TBNWhere}"); } } else { result = db.Script($" UPDATE [{_TBNName}] SET [{_TBNCell}] = '{lbl_1.Text}' WHERE {_TBNWhere}"); } db.DC(); MessageBox.Show(result); this.Hide(); } } }
C++
UTF-8
1,466
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Node { int conn[10003]; uint32_t weight; }; int N_EDGE; int N_NODE; Node NODES[10003]; bool CHECKED[10003]; uint32_t min_weight = -1; uint32_t min_weight_node = -1; int dfs(int i, int prev = -1) { CHECKED[i] = 1; int cc = 1; uint32_t weight = 0; for (int j=0; j<N_NODE; j++) { if (NODES[i].conn[j] < 0 && !CHECKED[j]) { int x = dfs(j , i); NODES[i].conn[j] = x; cc += x; weight += x * (x-1); } } if (prev >= 0) { int x = N_NODE-cc; NODES[i].conn[prev] = x; weight += x * (x-1); } weight >>= 1; NODES[i].weight = weight; if (weight < min_weight) { min_weight = weight; min_weight_node = i; } return cc; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.precision(10); cin >> N_EDGE; N_NODE = N_EDGE+1; for (int i = 0; i < N_EDGE; i++) { int a,b; cin>>a>>b; NODES[a].conn[b]=-1; NODES[b].conn[a]=-1; } dfs(0); uint32_t n1 = N_EDGE * (N_EDGE-1) / 2 - min_weight; int x1 = -1, x2 = -1; for (int j=0; j<N_NODE; j++) { int cc = NODES[min_weight_node].conn[j]; if (cc > x1) { x2 = x1; x1 = cc; } else if (cc > x2) { x2 = cc; } } cout << n1 << ' ' << n1 - x1 * x2 << endl; }
Java
UTF-8
882
2
2
[]
no_license
package com.checkpoint.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.checkpoint.service.LogService; @Controller @RequestMapping("/ejercicio") public class Checkpoint1Controller { @Autowired @Qualifier("LogService1") LogService logService; @GetMapping("/method1") public String method1() { return "redirect:method2"; } @GetMapping("/method2") public String method2(Model model) { this.logService.showLog(); model.addAttribute("mensaje", "Hola desde el servicio Checkpoint1"); return "vista"; } }
Markdown
UTF-8
475
2.59375
3
[ "CC0-1.0" ]
permissive
# Contribution Guidelines Ensure your pull request adheres to the following guidelines: - Search included books before adding a new one, as yours may be a duplicate. - Every workflow addition should follow the same format. 1. The book should be put into its appropriate category (Pick the one you think is closest if you are not sure). - Check your spelling and grammar. Thank you for your [suggestions](https://github.com/learn-anything/books/edit/master/readme.md)! 💜
Java
UTF-8
5,214
3.671875
4
[]
no_license
import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.BasicStroke; import java.awt.Dimension; import java.awt.Point; import java.awt.Color; import javax.swing.JFrame; import java.util.Collection; import java.util.ArrayList; // Aplicação do padrão Decorator. // Interface comum a todos os Shapes interface Shape { public void draw(Graphics g); public Point getCenter(); public int getRadius(); } // Superclasse abstrata que serve debase para as formas geométricas concretas abstract class BasicShape implements Shape{ protected Point center; } // Superclasse abastrata que serve de base para os decoradores abstract class ShapeDecorator implements Shape { // decoradores mantem uma referência ao objeto a ser decorado // que será do tipo Shape. Dessa forma o objeto decorado pode // ser tanto uma forma geometrica concreta, quanto um outro // decorador. Isso possibilita a aplicação de múltiplos decoradores // a uma forma geométrica concreta. protected Shape shape; public Point getCenter(){ // o centro do decorador será o mesmo da forma // geometrica decorada. Por isso simplesmente // chamamos getCenter() no objeto decorado e // devolvemos o resultado. return shape.getCenter(); } public int getRadius(){ // o raio do decorador será o mesmo da forma // geometrica decorada. Por isso simplesmente // chamamos getRadius() no objeto decorado e // devolvemos o resultado. return shape.getRadius(); } } // Formas geometricas concretas class Rectangle extends BasicShape { private Dimension size; public Rectangle(Point center, Dimension size){ this.center = center; this.size = size; } public void draw(Graphics g){ int x, y, w, h; x = center.x - size.width/2; y = center.y - size.height/2; w = size.width; h = size.height; g.setColor(Color.BLUE); g.fillRect(x, y, w, h); } public Point getCenter(){ return center; } public int getRadius(){ return (int) Math.sqrt(Math.pow(size.width, 2) + Math.pow(size.height, 2)) / 2; } } class Triangle extends BasicShape { int radius; public Triangle(Point center, int radius){ this.center = center; this.radius = radius; } public void draw(Graphics g){ int aux_x = (int) ((Math.sqrt(3) * radius) / 2.0); int [] x = {center.x, center.x - aux_x, center.x + aux_x}; int [] y = {center.y -radius, center.y + radius/2, center.y + radius/2 }; g.setColor(Color.GREEN); g.fillPolygon(x, y, 3); } public int getRadius(){ return radius; } public Point getCenter(){ return center; } } // Implementações dos decoradores class CenterDecorator extends ShapeDecorator { // O construtor do decorador recebe uma // referencia do objeto a ser decorado. public CenterDecorator(Shape s){ shape = s; } // o método "draw" de um decorador invoca o metodo "draw" // do objeto decorado e acrescenta algum comportamento extra // como, no caso desta classe, fazer o desenho do centro. public void draw(Graphics g){ shape.draw(g); Point center = getCenter(); g.setColor(Color.BLACK); g.drawLine(center.x - 5, center.y, center.x + 5, center.y); g.drawLine(center.x, center.y - 5, center.x, center.y + 5); g.drawString("(" + center.x + ", " + center.y + ")", center.x + 10, center.y + g.getFontMetrics().getHeight()); } } class CircleDecorator extends ShapeDecorator { // O construtor do decorador recebe uma // referencia do objeto a ser decorado. public CircleDecorator(Shape s){ shape = s; } // o método "draw" de um decorador invoca o metodo "draw" // do objeto decorado e acrescenta algum comportamento extra // como, no caso desta classe, fazer o desenho do circulo // circunscrito. public void draw(Graphics g){ int x, y, w, h; shape.draw(g); Point center = getCenter(); x = center.x - getRadius(); y = center.y - getRadius(); w = getRadius() * 2; h = getRadius() * 2; g.setColor(Color.BLACK); g.drawOval(x, y, w, h); } } class ShapeFrame extends JFrame { Collection<Shape> shapes = null; public ShapeFrame(int width, int height){ shapes = new ArrayList<Shape>(); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(width, height); } public void add(Shape s){ shapes.add(s); } public void paint(Graphics g){ System.out.println("paint"); g.setColor(Color.LIGHT_GRAY); g.fillRect(0, 0, getWidth() - 1, getHeight() - 1); for(Shape s : shapes){ s.draw(g); } } public void exibir(){ setVisible(true); } } public class ShapeTest4 { public static void main(String [] args){ ShapeFrame frame = new ShapeFrame(600, 600); Shape s; int [] x = {50, 200, 450}; for(int i = 0; i < 3; i++){ s = new Rectangle(new Point(x[i], 180), new Dimension((i + 1) * 70, (i + 1) * 50)); if(i == 0) s = new CenterDecorator(s); if(i == 1) s = new CircleDecorator(s); if(i == 2) s = new CircleDecorator(new CenterDecorator(s)); frame.add(s); s = new Triangle(new Point(x[i], 440), (i + 1) * 35); if(i == 0) s = new CenterDecorator(s); if(i == 1) s = new CircleDecorator(s); if(i == 2) s = new CircleDecorator(new CenterDecorator(s)); frame.add(s); } frame.exibir(); } }
Java
UTF-8
1,534
2.546875
3
[]
no_license
package com.eclipsekingdom.warpmagic.sys.config; import com.eclipsekingdom.warpmagic.WarpMagic; import com.google.common.collect.ImmutableList; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; public class ConfigLoader { private static final String pluginFolder = "WarpMagic"; private static ImmutableList<String> configs = new ImmutableList.Builder<String>() .add("config") .build(); private static ImmutableList<String> languages = new ImmutableList.Builder<String>() .add("en") .build(); public static void load() { try { for (String config : configs) { File target = new File("plugins/" + pluginFolder, config + ".yml"); if (!target.exists()) { load("Config/" + config + ".yml", target); } } for (String lang : languages) { File target = new File("plugins/" + pluginFolder + "/Locale", lang + ".yml"); if (!target.exists()) { load("Locale/" + lang + ".yml", target); } } } catch (IOException e) { e.printStackTrace(); } } private static void load(String resource, File file) throws IOException { file.getParentFile().mkdirs(); InputStream in = WarpMagic.getPlugin().getResource(resource); Files.copy(in, file.toPath()); in.close(); } }
Java
UTF-8
2,078
2.421875
2
[]
no_license
package com.example.recorder; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class RecordingsAdapter extends RecyclerView.Adapter<RecordingsAdapter.ViewHolder> { private Context context; ArrayList<RecordInfo> recordings = new ArrayList<>(); public RecordingsAdapter(Context context) { this.context = context; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.recording_item,parent,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { holder.duration.setText(recordings.get(position).size); holder.name.setText(recordings.get(position).name); holder.name.setSelected(true); holder.layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PlayerMedia media = new PlayerMedia(context); media.setpath(recordings.get(position).path); media.create().show(); } }); } @Override public int getItemCount() { return recordings.size(); } class ViewHolder extends RecyclerView.ViewHolder{ TextView name,duration; LinearLayout layout; public ViewHolder(@NonNull View itemView) { super(itemView); layout = itemView.findViewById(R.id.layout); name = itemView.findViewById(R.id.recording_name); duration = itemView.findViewById(R.id.duration); } } public void setRecordings(ArrayList<RecordInfo> recordings) { this.recordings = recordings; notifyDataSetChanged(); } }
Java
UTF-8
1,449
2.203125
2
[]
no_license
package com.example.colombo_life.model; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @Entity @Table(name = "flight") @EntityListeners(AuditingEntityListener.class) @JsonIgnoreProperties(value = { "createdAt", "updatedAt" }, allowGetters = true) public class Flight implements Serializable { @Id private String flightId; private int noOfPassengers; @OneToOne(mappedBy = "flight") private Reservation reservation; public Reservation getReservation() { return reservation; } public void setReservation(Reservation reservation) { this.reservation = reservation; } public String getFlightId() { return flightId; } public void setFlightId(String flightId) { this.flightId = flightId; } public int getNoOfPassengers() { return noOfPassengers; } public void setNoOfPassengers(int noOfPassengers) { this.noOfPassengers = noOfPassengers; } } //https://stackoverflow.com/questions/36565422/getting-referenced-property-not-a-onemanytoone-hibernate-exception?rq=1
Markdown
UTF-8
851
3.296875
3
[ "MIT" ]
permissive
## AWS Secrets Manager This Python example shows you how to retrieve the decrypted secret value from an AWS Secrets Manager secret. The secret could be created using either the Secrets Manager console or the CLI/SDK. The code uses the AWS SDK for Python to retrieve a decrypted secret value. # Prerequisite tasks To set up and run this example, you must first set up the following: 1. Configure your AWS credentials, as described in [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html). 2. Create a secret with the AWS Secrets Manager, as described in the [AWS Secrets Manager Developer Guide](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html) # Retrieve the secret value The following example shows how to: 1. Retrieve a secret value using `get_secret_value`.
Shell
UTF-8
322
2.5625
3
[ "MIT" ]
permissive
#!/usr/bin/env bash set -eo pipefail SELFDIR=$(dirname "$0") SELFDIR=$(cd "$SELFDIR" && pwd) PASSENGER_ROOT=$(cd "$SELFDIR/../../.." && pwd) # shellcheck source=../lib/functions.sh source "$SELFDIR/../lib/functions.sh" # shellcheck source=../lib/setup-container.sh source "$PASSENGER_ROOT/dev/ci/lib/setup-container.sh"
Ruby
UTF-8
65
2.5625
3
[]
no_license
class Dice def self.roll(side) rand(side) + 1 end end
Java
UTF-8
2,543
2.21875
2
[ "MIT" ]
permissive
package com.godcheese.nimrod.user.mapper; import com.godcheese.nimrod.user.entity.UserEntity; import com.godcheese.tile.mybatis.CrudMapper; import com.github.pagehelper.Page; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; /** * @author godcheese [godcheese@outlook.com] * @date 2018-02-22 */ @Component("userMapper") @Mapper public interface UserMapper extends CrudMapper<UserEntity, Long> { /** * 指定 username 获取用户 * * @param username 用户名 * @return UserEntity */ UserEntity getOneByUsername(@Param("username") String username); /** * 指定电子邮箱,获取用户 * * @param email 电子邮箱 * @return UserEntity */ UserEntity getOneByEmail(@Param("email") String email); /** * 指定手机号码,获取用户 * * @param cellphone 手机号码 * @return UserEntity */ UserEntity getOneByCellphone(@Param("cellphone") String cellphone); /** * 伪删除用户,标记 gmtDeleted 字段 * * @param idList id list * @param gmtDeleted 删除时间 * @return int */ int fakeDeleteAll(@Param("idList") List<Long> idList, @Param("gmtDeleted") Date gmtDeleted); /** * 撤销伪删除用户,不标记 gmtDeleted 字段 * * @param idList id list * @return int */ int revokeFakeDeleteAll(@Param("idList") List<Long> idList); /** * 指定部门 id,分页获取所有用户 * * @param departmentId 部门 id * @return */ Page<UserEntity> pageAllByDepartmentId(@Param("departmentId") Long departmentId); /** * 指定部门 id,获取用户 * * @param departmentId 部门 id * @return UserEntity */ UserEntity getOneByDepartmentId(@Param("departmentId") Long departmentId); /** * 分页获取所有用户 * * @param userEntity UserEntity * @param gmtCreatedStart gmtCreatedStart * @param gmtCreatedEnd gmtCreatedEnd * @param gmtDeletedStart gmtDeletedStart * @param gmtDeletedEnd gmtDeletedEnd * @return Page<UserEntity> */ Page<UserEntity> pageAll(@Param("userEntity") UserEntity userEntity, @Param("gmtCreatedStart") String gmtCreatedStart, @Param("gmtCreatedEnd") String gmtCreatedEnd, @Param("gmtDeletedStart") String gmtDeletedStart, @Param("gmtDeletedEnd") String gmtDeletedEnd); }
Python
UTF-8
4,930
2.609375
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env python # Copyright 2014 The 'mumble-releng' Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that # can be found in the LICENSE file in the source tree or at # <http://mumble.info/mumble-releng/LICENSE>. # This script returns the Mumble version string for a Mumble Git # repository. The script must be run from within a Mumble Git # repository. # This is a replacement for `git describe` to make snapshots # use the future, untagged version number rather than the previous. # # The version is of form 1.3.0~154~g4f336a2~snapshot. # It includes the target release version rather than the previous # release (as git describe does). # # Detailed description: # # Once upon a time, Mumble used the output of `git describe` as # its version string. # # If a commit was tagged, it was a "release", and got a simple # string which was the name of the tag. # # If a commit wasn't tagged, it got '1.2.6-234-gf552ag1', which # consists of the number of commits since the latest tag, and # the commit hash of the latest commit. # # However, the output of `git describe` was found to be confusing # in practice. This is because the base version of the `git describe` # output is the latest tag, which is to say: the *previous* # version of Mumble. # # So, a user running a snapshot that would become 1.3.0 would be # running a version like 1.2.6-234-gf552ag1. This is confusing # simply by looking at the version numbers, but the way versioning # works inside the Mumble client made it worse: the client's version # was refered to as "1.3.0" in several places, but the actual version # number said 1.2.6-234-gf552ag1. # # This script is the replacement for `git describe`. It outputs the # *actual* base version of the Mumble tree, rather than the latest tag. # This means that snapshots for Mumble 1.3.0 now have the base version # '1.3.0'. # # It also changes the version string slightly. Instead of using dashes # as a separator in the version string, it now uses tildes. This allows # Debian's dpkg version comparer to correctly sort snapshot versions # before release versions. The new string also includes 'snapshot' in the # version string to denote to users that the given version is a pre-release # snapshot. A full new-style version string looks like this: # 1.3.0~154~g4f336a2~snapshot. from __future__ import (unicode_literals, print_function, division) import os import platform import subprocess import sys def strip(s): s = s.replace('\r', '') s = s.replace('\n', '') return s def cmd(args): shell = platform.system() == 'Windows' p = subprocess.Popen(args, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = p.communicate() if p.returncode != 0: raise Exception('cmd: {0} failed with status {1}: {2}'.format(args, p.returncode, stderr)) return stdout.decode('utf-8') # Reads the version from src/mumble.pri def readMumblePriVersion(): sourceTreeRoot = strip(cmd(['git', 'rev-parse', '--show-toplevel'])) version = None with open(os.path.join(sourceTreeRoot, 'src', 'mumble.pri'), 'r') as f: for line in f: if 'VERSION' in line: line = line.replace('VERSION', '') line = line.replace('=', '') line = line.replace('\t', '') line = line.replace(' ', '') line = strip(line) version = line break if version is None: raise Exception('unable to read version from mumble.pri') return version def main(): latestTag = cmd(['git', 'describe', '--abbrev=0', '--tags']) latestTag = strip(latestTag) if len(latestTag) == 0: raise Exception('empty latestTag, unable to continue') latestCommit = cmd(['git', 'rev-parse', 'HEAD']) if len(latestCommit) < 7: raise Exception('bad commit string: {0}'.format(latestCommit)) latestCommit = strip(latestCommit) revListStr = cmd(['git', 'rev-list', '{0}..HEAD'.format(latestTag)]) revList = revListStr.split('\n') nrevs = len(revList)-1 # Consider the newline at the end. version = '' if nrevs == 0: # The most recent tag is the latest commit. That means this must # be a tagged release version. # We verify that the tag commit is the current HEAD to make sure it is. revListStr = cmd(['git', 'rev-list', latestTag]) revList = revListStr.split('\n') if len(revList) == 0: raise Exception('unable to get rev-list for potential release tag') latestCommitForLatestTag = revList[0] if latestCommitForLatestTag != latestCommit: raise Exception('commit-hash mismatch; aborting potential relase version string') version = latestTag else: mumblePriVersion = readMumblePriVersion() if len(mumblePriVersion) == 0 or not '.' in mumblePriVersion: raise Exception('bad mumblePriVersion: "{0}"'.format(mumblePriVersion)) version = '{0}~{1}~g{2}~snapshot'.format(mumblePriVersion, nrevs, latestCommit[0:7]) end = '' if '--newline' in sys.argv: end = None print(version, end=end) if __name__ == '__main__': main()
Python
UTF-8
939
3.078125
3
[]
no_license
import sys from PyQt5.QtWidgets import * class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("PyQt_01") self.setGeometry(50,50,350,350) self.UI() def UI(self): # all your code is here : self.lbl = QLabel("My Text",self) btn_enter = QPushButton("Enter",self) btn_exit = QPushButton("Exit",self) self.lbl.move(160,50) btn_enter.move(100,100) btn_exit.move(200,100) btn_enter.clicked.connect(self.enterFunc) btn_exit.clicked.connect(self.exitFunc) self.show() def enterFunc(self): self.lbl.setText("Enter") self.lbl.resize(150,30) def exitFunc(self): self.lbl.setText("Exit") self.lbl.resize(150,30) def main(): App = QApplication(sys.argv) W = Window() sys.exit(App.exec_()) if __name__ == '__main__': main()
Java
UTF-8
1,473
1.875
2
[]
no_license
package com.petro.span.client.application.header; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.gwtplatform.mvp.client.ViewImpl; import com.gwtplatform.mvp.client.proxy.PlaceManager; import com.petro.span.shared.CurrentUser; import com.petro.span.shared.UserInfo; public class HeaderView extends ViewImpl implements HeaderPresenter.MyView { interface Binder extends UiBinder<Widget, HeaderView> { } // private static Binder uiBinder = GWT.create(Binder.class); @UiField Label userNameLabel; @UiField Label logoutLabel; @Inject PlaceManager placeManager; private final CurrentUser currentUser; @Inject HeaderView(Binder uiBinder,UserInfo user,CurrentUser currentUser) { initWidget(uiBinder.createAndBindUi(this)); this.currentUser = currentUser; } @UiHandler("logoutLabel") void onLogoutLabelClick(ClickEvent event) { currentUser.setLoggedIn(false); currentUser.setUsername(""); Window.Location.assign(Window.Location.getHref().replace(Window.Location.getHash(), "#login")); Window.Location.reload(); } @Override public void initialize() { userNameLabel.setText(currentUser.getUsername()); } }
JavaScript
UTF-8
237
3.828125
4
[ "MIT" ]
permissive
/* Smallest difference pair of values between two unsorted Arrays */ function smallest_difference(arrayOne, arrayTwo) { } console.log(`Smallest Difference Pair: ${smallest_difference([-1, 5, 10, 20, 28, 3], [26, 134, 135, 15, 17])}`);
C#
UTF-8
9,666
3
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; /* * This code handles the spawning of new rooms from room points. Room points exist on the outside of * doorways. The code is also a source of dynamic programming, as there exist certain rooms for which * it does not make sense to spawn random rooms. The most prominent example of this is the points that * spawn off of the sides of their rooms, where we don't want to spawn additional rooms that split off * to the sides or we would circle back on ourselves. */ public class RoomScript : MonoBehaviour { // These are the rooms that can be spawned, listed for access by the script. The code will randomly // choose one, and instantiate the prebuilt prefab at the location of the room point public GameObject Collapse1, Collapse2, Collapse3, Fish, Gem, SmallRm, Tunnel1, Tunnel2, Tunnel3, Tunnel4, Multi, Arena, Split1, Split2, Split3, Cathedral, Switchback, Stlth, Tri, Spade; // There must be an offset to allow for the rooms to spawn correctly adjacent regarless of orientation, // thought the variable names is not accurate as "angle" float angleX, angleY; // This variable allows for choosing of rooms only fit for certain sides int side; // Start is called before the first frame update // We need to set a variable, then spawn the room void Start() { //This seed is the room randomly chosen of the first 16 available int seed = Random.Range(0, 16); // Call the spawning function with the seed generated Spawn(seed); } // The spawning function determines the offsets, rotation, and room to be spawned, yet we // allow it to be overridden in the event different spawning rules would be better or // necessary public virtual void Spawn(int seed) { // If the room goes upward from the cavern if(transform.rotation.eulerAngles.z == 90f) { // Shift the x and y exactly as far as the rooms are from the origin in their prefab angleX = -0.5f; angleY = 9.5f; // Set an additional offset for the allowance of different rooms than the others side = 3; } // If the room goes downward from the cavern else if(transform.rotation.eulerAngles.z == 270f) { // Shift the x and y as far from the origin as they are in the prefab to match up to a bottom point angleX = 0.5f; angleY = -9.5f; // Allow for different rooms to spawn on the bottom than from the top or sides side = 2; } // If the room goes to the right from the cavern else { // Shift the x and y as necessary, but it must be swapped in order for it to work this direction angleX = 9.5f; angleY = 0.5f; // Less rooms are allowed for the right paths, since they are two that are too close for bigger rooms side = 0; } // A switch case based on the random seed and the additional potentials factored in switch (seed+side) { case 0: // Not available for rooms due upward or downward Instantiate(Collapse1, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 1: // Not available for rooms due upward or downward Instantiate(Collapse2, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 2: // Not available for rooms due upward Instantiate(Collapse3, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 3: Instantiate(Fish, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 4: Instantiate(Gem, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 5: Instantiate(SmallRm, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 6: Instantiate(Tunnel1, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 7: Instantiate(Tunnel2, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 8: Instantiate(Tunnel3, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 9: Instantiate(Tunnel4, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 10: Instantiate(Multi, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 11: Instantiate(Arena, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 12: Instantiate(Split1, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 13: Instantiate(Split2, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 14: Instantiate(Split3, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 15: Instantiate(Cathedral, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 16: Instantiate(Switchback, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 17: // Only available for room points due upward or downward, as the spade is a large room that splits to the sides Instantiate(Spade, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 18: // Only available for room points due upward or downward, as the Tri room is large and splits to the sides Instantiate(Tri, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; case 19: // Only available for room points due upward, as the "stealth" room is too large to be on the right sides Instantiate(Stlth, new Vector3(transform.position.x + angleX, transform.position.y + angleY, 0), Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, transform.rotation.eulerAngles.z)); break; default: // If the numbers should somehow be outside our options, don't spawn a room // SHOULD HAVE SOME DEFAULT, maybe SmallRm? break; } //Once the room is spawned, the room point is unneeded and can be removed to despawn the object (invisible though it may be, it still has this script attached, and all the room objects associated) Object.Destroy(this.gameObject); } }
C++
UTF-8
2,208
2.671875
3
[]
no_license
/************************************************************************* File Name: SPOJ_ORDERSET.cpp ID: obsoles1 PROG: LANG: C++ Mail: 384099319@qq.com Created Time: 2015年08月07日 星期五 09时33分02秒 ************************************************************************/ #include<cstdio> #include<ctime> #include<cstdlib> using namespace std; struct treap{ treap *l,*r; int v,fix,size; treap(int _v):v(_v){ l=r=0,size=1,fix=rand(); } int l_size(){return l? l->size:0;} int r_size(){return r? r->size:0;} void merger(){size=1+l_size()+r_size();} }*root; void l_rotate(treap *&x){ treap *t=x->r; x->r=t->l,t->l=x; x->merger(),t->merger(); x=t; } void r_rotate(treap *&x){ treap *t=x->l; x->l=t->r,t->r=x; x->merger(),t->merger(); x=t; } void insert(treap *&p,int v){ if(!p)p=new treap(v); else{ if(p->v > v){ insert(p->l,v); if(p->l->fix < p->fix)r_rotate(p); }else if(p->v < v){ insert(p->r,v); if(p->r->fix < p->fix)l_rotate(p); } } p->merger(); } void del(treap *&p,int v){ if(!p)return; if(p->v == v){ if(!p->r || !p->l){ if(!p->r)p=p->l; else p=p->r; }else{ if(p->l->fix < p->r->fix){ r_rotate(p); del(p->r,v); }else{ l_rotate(p); del(p->l,v); } } }else if(p->v > v) del(p->l,v); else del(p->r,v); if(p)p->merger(); } treap *find_kth(treap *&p,int k){ if(k < p->l_size()+1)return find_kth(p->l,k); else if(k > p->l_size()+1) return find_kth(p->r,k-(p->l_size()+1)); else return p; } int q_count(treap *&p,int v,int cnt){ if(!p)return cnt; if(p->v > v)return q_count(p->l,v,cnt); else return q_count(p->r,v,cnt+p->l_size()+1); } int main(){ int q,x; char op[2]; srand(time(0)); while(~scanf("%d",&q)){ puts("Case"); root=0; while(q--){ scanf("%s%d",op,&x); if(op[0]=='I')insert(root,x); else if(op[0]=='D')del(root,x); else if(op[0]=='C'){ printf("%d\n",q_count(root,x-1,0)); }else if(op[0]=='K'){ if(root && root->size >= x)printf("%d\n",find_kth(root,x)->v); else puts("invalid"); } } } }
Markdown
UTF-8
2,262
3.15625
3
[ "MIT" ]
permissive
# Cypress testing vs selenium ### Cypress Testing : Cypress is a purely a javascript based frontend testing tool used for morden web.it can be useful for both developers and QAs, but it is more developer friendly tool because for web development mainly javascript is used and cypress is also a javascript based tool using cypress you can: - set up test - write a test - execute test - debug a test. ### Selenium : Selenium is open source tool used for testing, it supports multiple browsers and multiple languages, you can use a language of your interest and with which your are comfortable and you can create a test scription. Selenium has a suite of software that contains: -Selenium Integrated Development Environment -Selenium Remote Control -Selenium webdriver -Selenium Grid Now let's start the comparison of both tools, as we know both the tools are used for functional testing using web browser, but both have it's own diffirent features. Selenium is widely used for testing and cypress is recently introduced tool. ### 1. Language Supported : Selenium supports multiple languages like Java,Python,C# ,Ruby,Php etc, but cypress supports only one language that is a javascript, it can be a banifit for developer and disadvantage for some QAs who does not know the javascript. ### 2. Browser Support : Selenium supports the multiiple browsers like Chrome, Firefox,Safari,Edge,IE and Opera.While cypress suports only Chrome,Firefox ,Edge and Electron,most peapole used chrome of Firefox so both the tools supports these two browsers but for more browser supports selenium will be a benificiary ### 3 Framework support : Cypress supports React,Vue,Angular,Elm etc javascript based frameworks,when selenium suppports Maven,JUnit,TestNG also Jenkins for CI/CD for automating the deployment process. ###4 Performance : Performance wise selenium is slower then cypress because it creates so many layers for runnig the code between the test and browser.while cypress does not have many layred architectured. ###5 Network Traffic Control : selenium does not control network traffic flow while cypress no network lag as tests are executed within the browser, you csn control,stub and test edge test cases without any involvement of the server
Java
UTF-8
341
3.078125
3
[]
no_license
class Solution { public int removeElement(int[] nums, int val) { int read = 0; int write = 0; while (read < nums.length) { if (nums[read] == val) { read++; } else { nums[write++] = nums[read++]; } } return write; } }
C++
UTF-8
804
3.421875
3
[]
no_license
#include "order.h" Order::Order(std::string email) : _email{email} { } std::string Order::email() {return _email;} double Order::cost() { double sum; for (auto& po : _products) sum += po.cost(); return sum; } void Order::add_product_order(Product_order po) { _products.push_back(po); } int Order::num_product_orders() {return _products.size();} Product_order Order::product_order(int index) { if (0 > index || index > (_products.size()-1)) throw std::out_of_range{"Order: Product index " + std::to_string(index) + " with only " + std::to_string(_products.size()-1) + " products"}; return _products[index]; } std::ostream& operator<<(std::ostream& ost, const Order& order) { for (auto& po : order._products) ost << " " << po << '\n'; return ost; }
Java
UTF-8
311
2.84375
3
[]
no_license
/** * Player class * @author Johnathan Poeschel * @version 1.0, 25 Nov 2019 */ public abstract class Player { /** * makeMove method, must be defined for each player * @param board game board to vaildate move * @return int for spot to move in */ public int makeMove(Board board){return 0;} }
Java
UTF-8
10,460
2.203125
2
[]
no_license
package com.eparking.informationPush.entity.system; public class RouteInfo { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.id * * @mbg.generated */ private Integer id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.name * * @mbg.generated */ private String name; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.username * * @mbg.generated */ private String username; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.password * * @mbg.generated */ private String password; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.ver_num * * @mbg.generated */ private String verNum; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.server_ip * * @mbg.generated */ private String serverIp; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.server_port * * @mbg.generated */ private String serverPort; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.in_path * * @mbg.generated */ private String inPath; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.out_path * * @mbg.generated */ private String outPath; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.heart_path * * @mbg.generated */ private String heartPath; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.static_path * * @mbg.generated */ private String staticPath; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column route_info.dynamic_path * * @mbg.generated */ private String dynamicPath; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.id * * @return the value of route_info.id * * @mbg.generated */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.id * * @param id the value for route_info.id * * @mbg.generated */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.name * * @return the value of route_info.name * * @mbg.generated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.name * * @param name the value for route_info.name * * @mbg.generated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.username * * @return the value of route_info.username * * @mbg.generated */ public String getUsername() { return username; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.username * * @param username the value for route_info.username * * @mbg.generated */ public void setUsername(String username) { this.username = username == null ? null : username.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.password * * @return the value of route_info.password * * @mbg.generated */ public String getPassword() { return password; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.password * * @param password the value for route_info.password * * @mbg.generated */ public void setPassword(String password) { this.password = password == null ? null : password.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.ver_num * * @return the value of route_info.ver_num * * @mbg.generated */ public String getVerNum() { return verNum; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.ver_num * * @param verNum the value for route_info.ver_num * * @mbg.generated */ public void setVerNum(String verNum) { this.verNum = verNum == null ? null : verNum.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.server_ip * * @return the value of route_info.server_ip * * @mbg.generated */ public String getServerIp() { return serverIp; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.server_ip * * @param serverIp the value for route_info.server_ip * * @mbg.generated */ public void setServerIp(String serverIp) { this.serverIp = serverIp == null ? null : serverIp.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.server_port * * @return the value of route_info.server_port * * @mbg.generated */ public String getServerPort() { return serverPort; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.server_port * * @param serverPort the value for route_info.server_port * * @mbg.generated */ public void setServerPort(String serverPort) { this.serverPort = serverPort == null ? null : serverPort.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.in_path * * @return the value of route_info.in_path * * @mbg.generated */ public String getInPath() { return inPath; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.in_path * * @param inPath the value for route_info.in_path * * @mbg.generated */ public void setInPath(String inPath) { this.inPath = inPath == null ? null : inPath.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.out_path * * @return the value of route_info.out_path * * @mbg.generated */ public String getOutPath() { return outPath; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.out_path * * @param outPath the value for route_info.out_path * * @mbg.generated */ public void setOutPath(String outPath) { this.outPath = outPath == null ? null : outPath.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.heart_path * * @return the value of route_info.heart_path * * @mbg.generated */ public String getHeartPath() { return heartPath; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.heart_path * * @param heartPath the value for route_info.heart_path * * @mbg.generated */ public void setHeartPath(String heartPath) { this.heartPath = heartPath == null ? null : heartPath.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.static_path * * @return the value of route_info.static_path * * @mbg.generated */ public String getStaticPath() { return staticPath; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.static_path * * @param staticPath the value for route_info.static_path * * @mbg.generated */ public void setStaticPath(String staticPath) { this.staticPath = staticPath == null ? null : staticPath.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column route_info.dynamic_path * * @return the value of route_info.dynamic_path * * @mbg.generated */ public String getDynamicPath() { return dynamicPath; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column route_info.dynamic_path * * @param dynamicPath the value for route_info.dynamic_path * * @mbg.generated */ public void setDynamicPath(String dynamicPath) { this.dynamicPath = dynamicPath == null ? null : dynamicPath.trim(); } }
Java
UTF-8
448
1.851563
2
[]
no_license
package com.octopus.Practice.dao.dto; import lombok.Data; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import java.util.Date; @Data @Accessors(chain = true) public class PostDto { @Getter @Setter private int id; private String title; private String text; private String photoURL; private int likes; private Date createdAt; private Date modifiedAt; }
C++
UTF-8
251
2.515625
3
[ "MIT" ]
permissive
#include "model/ChessPiece.h" ChessPiece::ChessPiece(const common::ChessPieceColor& color, const common::ChessPieceType& type) : m_color(color) , m_type(type) {} ChessPiece::~ChessPiece() { printf("Destructor called for Chess Piece\n"); }
C++
UTF-8
2,192
3
3
[]
no_license
#include "Dollar.h" #include "../../Renderer/Image.h" #include "../../Utilities/Rect.h" #include "../Sprite.h" #include "../../Utilities/Time.h" #include <iostream> const float Dollar::ANIM_RATE = 0.4f; const int Dollar::NUM_SPRITES = 6; Sprite** Dollar::dollarSprites = nullptr; Dollar::Dollar(int x, int y) : Entity(x, y) { sprites = dollarSprites; endAnimTime = 0.0f; _visible = false; _moneyReceived = false; winingMoney = false; } void Dollar::Reset() { Entity::Reset(); endAnimTime = 0.0f; _visible = false; _moneyReceived = false; winingMoney = false; } void Dollar::Init(Image* dollarImage) { //Fondo dolar Rect sRect; sRect.Width = dollarImage->GetWidth() / NUM_SPRITES; sRect.Height = dollarImage->GetHeight(); sRect.X = 0; sRect.Y = 0; dollarSprites = new Sprite * [NUM_SPRITES]; for (int i = 0; i < NUM_SPRITES; i++) { sRect.X = i * sRect.Width; dollarSprites[i] = new Sprite(dollarImage, sRect); } } void Dollar::Release() { for (int i = 0; i < NUM_SPRITES; ++i) delete dollarSprites[i]; delete[] dollarSprites; dollarSprites = nullptr; } void Dollar::Update(float delta) { int newDollarState; //Recibiendo ahora la moneda if (winingMoney) { switch (currentState) { case DollarState::DOLLAR_ANIM_0: if (Time::time >= endAnimTime - ANIM_RATE / 2) newDollarState = DollarState::DOLLAR_ANIM_1; else newDollarState = DollarState::DOLLAR_ANIM_0; break; case DollarState::DOLLAR_ANIM_1: //Fin de la animaci�n if (Time::time >= endAnimTime) { winingMoney = false; newDollarState = DollarState::DOLLAR_VISIBLE_MONEY; } else newDollarState = DollarState::DOLLAR_ANIM_1; break; default: //Se inicia la animaci�n _moneyReceived = true; endAnimTime = Time::time + ANIM_RATE; newDollarState = DollarState::DOLLAR_ANIM_0; break; } } else if (_visible && _moneyReceived) newDollarState = DollarState::DOLLAR_VISIBLE_MONEY; else if (_visible) newDollarState = DollarState::DOLLAR_VISIBLE; else if (_moneyReceived) newDollarState = DollarState::DOLLAR_MONEY; else newDollarState = DollarState::DOLLAR_EMPTY; CheckState(delta, newDollarState); }
C++
UTF-8
325
2.578125
3
[]
no_license
Node *func(int pre[],char arr[],int &id,int n) { if(id >=n) return NULL; Node *root=new Node(pre[id]); id++; if(arr[id-1]=='L') return root; root->left=func(pre,arr,id,n); root->right=func(pre,arr,id,n); } struct Node *constructTree(int n, int pre[], char arr[]) { // Code here int id=0; return func(pre,arr,id,n); }
Ruby
UTF-8
542
3.6875
4
[]
no_license
def bubble_sort(v) n = 1 while n < v.length i = 0 until i == v.length-n if v[i] > v[i+1] v[i], v[i+1] = v[i+1], v[i] end i += 1 end n += 1 end puts v.join(', ') end bubble_sort([4,3,78,2,0,2]) def bubble_sort_by(v) n = 1 while n < v.length i = 0 until i == v.length-n if (yield v[i], v[i+1]) > 0 v[i], v[i+1] = v[i+1], v[i] end i += 1 end n += 1 end puts v.join(', ') end bubble_sort_by(["hi", "how is it going", "hello", "hey"]) do |left,right| left.length - right.length end
Python
UTF-8
11,398
2.90625
3
[]
no_license
from docx import Document from docx.styles.style import _ParagraphStyle from docx.styles.style import _TableStyle import logging import os from collections import OrderedDict class WordWriter: """Microsoft Word specification writer for prpl HL-API. It generates a new word file document for the prpl HL-API based on the specified template. Example: # Setup an API. from prpl.apis.hl.com import API as HLAPI # Create list of objects. api_objects = [] # Create list of response codes. api_response_codes = [] # Create list of version. api_versions = [] # Create API. api = HLAPI(api_objects, api_response_codes, api_versions) # Import module. from prpl.apis.hl.spec.builder import WordWriter as HLAPISpecWriter # Load API. writer = HLAPIWordWriter(api, 'specs/prpl HL-API ({}).docx'.format(self.api.get_version())) # Generate report. writer.build() """ def __init__(self, api, file, template='specs/templates/prpl.docx'): """Initializes the specification writer. Args: api (prpl.apis.hl.com.api): API to be parsed. file (str): Target filename for the specification. template (str): Word template to be used. """ self.api = api self.file = file self.document = Document(template) # Init logger. self.logger = logging.getLogger('WordWriter') # Load template styles. self.logger.debug('Styles - Started looking up template styles.') styles = self.document.styles # Find styles. self.prpl_cover_version_number_style = list( filter(lambda x: type(x) is _ParagraphStyle and x.name == 'prplCoverVersionNumber', styles))[0] self.prpl_table_text_style = list( filter(lambda x: type(x) is _ParagraphStyle and x.name == 'prplTableText', styles))[0] self.paragraph_style = list(filter(lambda x: type(x) is _ParagraphStyle and x.name == 'Normal', styles))[0] self.table_style = list(filter(lambda x: type(x) is _TableStyle and x.name == 'Table Grid', styles))[0] self.logger.debug('Styles - Finished looking up template styles.') # Remove old file. self.logger.debug('File - Removing previous report "{}".'.format(self.file)) try: os.remove(self.file) except FileNotFoundError: pass self.logger.debug('File - Finished removing previous report "{}".'.format(self.file)) def _append_table(self, headers, entries): """Creates a new table with the specified entries. It includes a header row and populates the remaining rows with the contents of entries based on the attributes specified on the headers. Args: headers (OrderedDict): Table headers used to create the first row and fetch the contents of each entry. The keys depict the attributes of the entries, and the values correspond to the header names. entries (list<object>): List of entries to be appended to the table. """ # Create new table. t = self.document.add_table(rows=len(entries) + 1, cols=len(headers)) # Assign a style. t.style = self.table_style # Writer header. for idx, header in enumerate(headers.values()): row_cells = t.rows[0].cells row_cells[idx].text = header # Append entries. for idx_entry, entry in enumerate(entries): row_cells = t.rows[idx_entry + 1].cells for idx_header, header in enumerate(headers.keys()): row_cells[idx_header].text = str(getattr(entry, header)) def _update_cover(self): """Updates cover with API version number.""" for paragraph in self.document.paragraphs: # Lookup version variable. if '$(VERSION)' in paragraph.text: # Replace text with version number. paragraph.text = 'Version {}'.format(self.api.get_version()) paragraph.style = self.prpl_cover_version_number_style self.logger.debug('Cover - Updated with version {}.'.format(paragraph.text)) break def _append_change_log(self): """Updates the release notes table.""" cl_table = self.document.tables[0] for v in self.api.versions: cl_table.add_row() cl_table.rows[-1].cells[0].text = v.number cl_table.rows[-1].cells[1].text = v.date cl_table.rows[-1].cells[2].text = v.get_changes() self.logger.debug('ChangeLog - Appended version {}.'.format(v.number)) def _append_return_codes(self): """Adds return codes section.""" # Add chapter header. self.document.add_heading('Return Codes', level=1) # Write a chapter description. p = self.document.add_paragraph( 'The following list of return codes is applicable to all objects and procedures.', style=self.paragraph_style) # Append response codes table. self._append_table( OrderedDict([('name', 'Name'), ('sample', 'Sample'), ('description', 'Description')]), self.api.response_codes) def _append_procedures(self): """Adds procedures section.""" # Add heading. self.document.add_heading('Procedures', level=1) # Iterate through each object. for idx, obj in enumerate(self.api.objects): # Include page break between objects unless first and last. if 0 < idx < len(self.api.objects): self.document.add_page_break() # Object Header. self.document.add_heading(obj.name, 2) self.logger.debug('Procedures - Appended object "{}".'.format(obj.name)) # Iterate through each procedure. for idx_proc, procedure in enumerate(obj.procedures): # Include page break between procedures unless first and last. if 0 < idx_proc < len(obj.procedures): self.document.add_page_break() # Procedure Header. self.document.add_heading(procedure.name, 3) # Description. self.document.add_paragraph(procedure.description, style=self.paragraph_style) # Usage. self.document.add_heading('Usage', 4) request_body = '' if procedure.sample_request != '-': request_body = ' "{}RequestBody{}"'.format('{', '}') self.document.add_paragraph( 'ubus call {} {}{}'.format(obj.name, procedure.name, request_body), style=self.paragraph_style) # Sample. self.document.add_heading('Sample', 4) self._append_table(OrderedDict([('sample_request', 'Request Body'), ('sample_response', 'Response Body')]), [procedure]) # Input. self.document.add_heading('Input', 4) args = list(filter(lambda x: x.is_input is True, procedure.fields)) if len(args) == 0: self.document.add_paragraph('N/A.', style=self.paragraph_style) else: self._append_table(OrderedDict([('name', 'Name'), ('description', 'Description'), ('type', 'Type'), ('is_required', 'Required'), ('notes', 'Notes')]), args) # Output. self.document.add_heading('Output', 4) fields = list(filter(lambda x: x.is_output is True, procedure.fields)) if len(fields) == 0: self.document.add_paragraph('N/A.', style=self.paragraph_style) else: self._append_table(OrderedDict([('name', 'Name'), ('description', 'Description'), ('type', 'Type'), ('notes', 'Notes')]), fields) self.logger.debug('Procedures - Appended procedure "{}".'.format(procedure.name)) def _append_events(self): """Adds events section. Generates one table for each object and skips objects with no events. """ # Add page break. self.document.add_page_break() # Include chapter header. self.document.add_heading('Events', level=1) # Filter out objects with no events. objects_with_events = list(filter(lambda x: len(x.events) > 0, self.api.objects)) # Iterate through each object. for idx, obj in enumerate(objects_with_events): # Include page break between objects unless first and last. if 0 < idx < len(objects_with_events): self.document.add_page_break() # Create object header. self.document.add_heading('{}'.format(obj.name), level=2) # Append events table. self._append_table(OrderedDict([('code', 'Code'), ('name', 'Name'), ('description', 'Description'), ('sample', 'Sample')]), obj.events) self.logger.debug('Events - Added events for object "{}" with {} entries.'.format(obj.name, len(obj.events))) def build(self): """Generates a Word file specification for the HL-API.""" # Cover. self.logger.debug('Cover - Started writing.') self._update_cover() self.logger.debug('Cover - Finished.\n') # Add Change-Log. self.logger.debug('ChangeLog - Started writing.') self._append_change_log() self.logger.debug('ChangeLog - Finished.\n') # Add Return Codes. self.logger.debug('Response Codes - Started writing.') self._append_return_codes() self.logger.debug('Response - Finished.\n') # Add Objects. self.logger.debug('Procedures - Started writing.') self._append_procedures() self.logger.debug('Procedures - Finished.\n') # Add Events. self.logger.debug('Events - Started writing.') self._append_events() self.logger.debug('Events - Finished.\n') # Save file. self.logger.debug('File - Saving.') self.document.save(self.file) self.logger.debug('File - Finished.\n')