code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/*! Copyright 2011, Ben Lin (http://dreamerslab.com/) * Licensed under the MIT License (LICENSE.txt). * * Version: 1.0.0 * * Requires: jQuery 1.2.3+ */ $.preload = function(){ var tmp = [], i = arguments.length; // reverse loop run faster for( ; i-- ; ) tmp.push( $( '<img />' ).attr( 'src', arguments[ i ] )); };
dreamerslab/ci.view
example_site/assets/js/lib/jquery.preload.js
JavaScript
mit
320
/*jshint indent: 4, browser:true*/ /*global L*/ /* * L.TimeDimension.Player */ //'use strict'; L.TimeDimension.Player = (L.Layer || L.Class).extend({ includes: (L.Evented || L.Mixin.Events), initialize: function(options, timeDimension) { L.setOptions(this, options); this._timeDimension = timeDimension; this._paused = false; this._buffer = this.options.buffer || 5; this._minBufferReady = this.options.minBufferReady || 1; this._waitingForBuffer = false; this._loop = this.options.loop || false; this._steps = 1; this._timeDimension.on('timeload', (function(data) { this.release(); // free clock this._waitingForBuffer = false; // reset buffer }).bind(this)); this.setTransitionTime(this.options.transitionTime || 1000); this._timeDimension.on('limitschanged availabletimeschanged timeload', (function(data) { this._timeDimension.prepareNextTimes(this._steps, this._minBufferReady, this._loop); }).bind(this)); }, _tick: function() { var maxIndex = this._getMaxIndex(); var maxForward = (this._timeDimension.getCurrentTimeIndex() >= maxIndex) && (this._steps > 0); var maxBackward = (this._timeDimension.getCurrentTimeIndex() == 0) && (this._steps < 0); if (maxForward || maxBackward) { // we reached the last step if (!this._loop) { this.pause(); this.stop(); this.fire('animationfinished'); return; } } if (this._paused) { return; } var numberNextTimesReady = 0, buffer = this._bufferSize; if (this._minBufferReady > 0) { numberNextTimesReady = this._timeDimension.getNumberNextTimesReady(this._steps, buffer, this._loop); // If the player was waiting, check if all times are loaded if (this._waitingForBuffer) { if (numberNextTimesReady < buffer) { console.log('Waiting until buffer is loaded. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } else { // all times loaded console.log('Buffer is fully loaded!'); this.fire('running'); this._waitingForBuffer = false; } } else { // check if player has to stop to wait and force to full all the buffer if (numberNextTimesReady < this._minBufferReady) { console.log('Force wait for load buffer. ' + numberNextTimesReady + ' of ' + buffer + ' loaded'); this._waitingForBuffer = true; this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); this.fire('waiting', { buffer: buffer, available: numberNextTimesReady }); return; } } } this.pause(); this._timeDimension.nextTime(this._steps, this._loop); if (buffer > 0) { this._timeDimension.prepareNextTimes(this._steps, buffer, this._loop); } }, _getMaxIndex: function(){ return Math.min(this._timeDimension.getAvailableTimes().length - 1, this._timeDimension.getUpperLimitIndex() || Infinity); }, start: function(numSteps) { if (this._intervalID) return; this._steps = numSteps || 1; this._waitingForBuffer = false; var startedOver = false; if (this.options.startOver){ if (this._timeDimension.getCurrentTimeIndex() === this._getMaxIndex()){ this._timeDimension.setCurrentTimeIndex(this._timeDimension.getLowerLimitIndex() || 0); startedOver = true; } } this.release(); this._intervalID = window.setInterval( L.bind(this._tick, this), this._transitionTime); if (!startedOver) this._tick(); this.fire('play'); this.fire('running'); }, stop: function() { if (!this._intervalID) return; clearInterval(this._intervalID); this._intervalID = null; this._waitingForBuffer = false; this.fire('stop'); }, pause: function() { this._paused = true; }, release: function () { this._paused = false; }, getTransitionTime: function() { return this._transitionTime; }, isPlaying: function() { return this._intervalID ? true : false; }, isWaiting: function() { return this._waitingForBuffer; }, isLooped: function() { return this._loop; }, setLooped: function(looped) { this._loop = looped; this.fire('loopchange', { loop: looped }); }, setTransitionTime: function(transitionTime) { this._transitionTime = transitionTime; if (typeof this._buffer === 'function') { this._bufferSize = this._buffer.call(this, this._transitionTime, this._minBufferReady, this._loop); console.log('Buffer size changed to ' + this._bufferSize); } else { this._bufferSize = this._buffer; } if (this._intervalID) { this.stop(); this.start(this._steps); } this.fire('speedchange', { transitionTime: transitionTime, buffer: this._bufferSize }); }, getSteps: function() { return this._steps; } });
geofbaum/geofbaum.github.io
src/leaflet.timedimension.player.js
JavaScript
mit
5,914
<?php namespace pagosBundle\Entity; use Doctrine\ORM\EntityRepository; use Doctrine\DBAL\DriverManager; class pagoRepository extends EntityRepository { public function facturar($lineas,$entidad,$cuenta) { $datos=array('serie'=>'', 'folio'=>'', 'empresa_id'=>'', 'observaciones'=>'', 'fecha'=>'', 'cliente_id'=>$entidad->getClienteId(), 'receptor_nombre'=>$entidad->getRazonSocial(), 'receptor_rfc'=>$entidad->getRfc(), 'calle'=>$entidad->getCalle(), 'no_exterior'=>$entidad->getNoExterior(), 'no_interior'=>$entidad->getNoInterior(), 'referencia'=>$entidad->getReferencia(), 'colonia'=>$entidad->getColonia(), 'municipio'=>$entidad->getMunicipio(), 'codigo_postal'=>$entidad->getCodigoPostal(), 'localidad'=>$entidad->getLocalidad(), 'estado'=>$entidad->getEstado(), 'pais'=>$entidad->getPais(), 'forma_de_pago'=>'Pago en una sola exhibición', 'condiciones_de_pago'=>'', 'moneda_id'=>'MXN', 'tipo_cambio'=>'1', 'metodo_de_pago'=>'targeta', 'num_cuenta_pago'=>$cuenta, 'fecha_vencimiento'=>date('d/m/Y'), 'vendedor_id'=>'', 'vendedor_nombre'=>'', 'opReq1'=>'ventas:facturas_venta:facturas_venta:Add','operaciones'=>'2'); $x=0; foreach ($lineas as $linea ) { $masDatos[]=array( 'conceptos['.$x.'][sku]'=>'SERVICIO', 'conceptos['.$x.'][cantidad]'=>$linea->getCantidad(), 'conceptos['.$x.'][no_identificacion]'=>'', 'conceptos['.$x.'][cuenta_predial_numero]'=>'', 'conceptos['.$x.'][precio_unitario]'=>$linea->getTotal(), 'conceptos['.$x.'][precio_lista]'=>$linea->getTotal(), 'conceptos['.$x.'][descuento]'=>'0', 'conceptos['.$x.'][tipo_descuento]'=>'F', 'conceptos['.$x.'][factor_descuento]'=>'0', 'conceptos['.$x.'][importe_precio_lista]'=>$linea->getTotal(), 'conceptos['.$x.'][importe]'=>$linea->getTotal(), 'conceptos['.$x.'][importe_ieps]'=>'0', 'conceptos['.$x.'][observaciones]'=>'', 'conceptos['.$x.'][unidad_id]'=>'PZ', 'conceptos['.$x.'][usa_lotes]'=>'N', 'conceptos['.$x.'][usa_series]'=>'N', 'conceptos['.$x.'][es_paquete]'=>'N', 'conceptos['.$x.'][almacenable]'=>'N', 'conceptos['.$x.'][costo]'=>'0', 'conceptos['.$x.'][impuestos_traslados][0][esquema_impuestos_id]'=>'IVA_GENERAL', 'conceptos['.$x.'][impuestos_traslados][0][impuesto]'=>'IVA', 'conceptos['.$x.'][impuestos_traslados][0][aplicacion]'=>'T', 'conceptos['.$x.'][impuestos_traslados][0][tasa]'=>'16.0000', 'conceptos['.$x.'][impuestos_traslados][0][num_impuesto]'=>'1', 'conceptos['.$x.'][impuestos_traslados][0][importe]'=>'0.16', 'conceptos['.$x.'][pedido_serie]'=>'', 'conceptos['.$x.'][pedido_folio]'=>'', 'conceptos['.$x.'][pedido_item]'=>'', 'conceptos['.$x.'][impuestos_retenciones]'=>'', 'conceptos['.$x.'][lista_precios_id]'=>'', 'conceptos['.$x.'][descripcion]'=>'SERVICIO' ); $x++; } $req=''; $req1=''; foreach ($datos as $key => $value) { $fullipnA[$key] = $value; $encodedvalue = urlencode(stripslashes($value)); $req .= "&$key=$encodedvalue"; } for($i=0;$i<count($masDatos); $i++){ foreach ($masDatos[$i] as $key => $value) { $fullipnA[$key] = $value; $encodedvalue = urlencode(stripslashes($value)); $req1 .= "&$key=$encodedvalue"; } } // echo $req; $url='https://e.sisnet.mx:7443/SisnetV3/php/responseweb.php'; $curl_result=$curl_err=''; $varPost="&workspace=default&usuario=demo&contrasena=demo&sucursal=aps_01|MATRIZ|43&resultType=xml"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_CERTINFO,true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS,$varPost.$req.$req1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $datos= curl_exec ($ch); curl_close ($ch); //echo $datos; $resultado=explode('||', $datos); $max_int_length = strlen((string) PHP_INT_MAX) - 1; $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $resultado[1]); // echo $json_without_bigints; $elarrid = json_decode($json_without_bigints,true, 512); return $elarrid['record']; } public function sellar($datos,$usuario){ $valores=array('opReq1'=>'ventas:facturas_venta:facturas_venta:OpenCFD', 'empresa_id'=>$datos['empresa_id'], 'serie'=>$datos['serie'], 'folio'=>$datos['folio'], 'preview'=>'true', 'opReq2'=>'ventas:facturas_venta:facturas_venta:SendMail', 'nombre'=>$usuario->getNombre(), 'correo'=>$usuario->getEmail(),'operaciones'=>'3'); $req=''; foreach ($valores as $key => $value) { $fullipnA[$key] = $value; $encodedvalue = urlencode(stripslashes($value)); $req .= "&$key=$encodedvalue"; } $url='https://e.sisnet.mx:7443/SisnetV3/php/responseweb.php'; $curl_result=$curl_err=''; $varPost="&workspace=default&usuario=demo&contrasena=demo&sucursal=aps_01|MATRIZ|43&resultType=xml"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_CERTINFO,true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS,$varPost.$req); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //$datos= curl_exec ($ch); curl_close ($ch); echo $datos; $resultado=explode('||', $datos); /*$max_int_length = strlen((string) PHP_INT_MAX) - 1; $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $resultado[1]); // echo $json_without_bigints; $elarrid = json_decode($json_without_bigints,true, 512);*/ } public function addMonth($dates,$num = 1,$format='d/m/Y') { $date = $dates->format('Y-n-j'); list($y, $m, $d) = explode('-', $date); $m += $num; while ($m > 12) { $m -= 12; $y++; } $last_day = date('t', strtotime("$y-$m-1")); if ($d > $last_day) { $d = $last_day; } $dates->setDate($y, $m, $d); return $dates->format($format); } }
elmaspicudo/algo
src/pagosBundle/Entity/pagoRepository.php
PHP
mit
8,184
package com.bitdubai.fermat_bnk_api.layer.bnk_wallet.bank_money.exceptions; import com.bitdubai.fermat_api.FermatException; /** * Created by Yordin Alayn on 18.09.15. */ public class CantTransactionBankMoneyException extends FermatException { public static final String DEFAULT_MESSAGE = "Falled To Get Bank Transaction Wallet Bank Money."; public CantTransactionBankMoneyException(String message, Exception cause, String context, String possibleReason) { super(message, cause, context, possibleReason); } }
fvasquezjatar/fermat-unused
fermat-bnk-api/src/main/java/com/bitdubai/fermat_bnk_api/layer/bnk_wallet/bank_money/exceptions/CantTransactionBankMoneyException.java
Java
mit
533
<?php namespace SMARTASK\HomeBundle\Entity; use Doctrine\ORM\Mapping as ORM; use SMARTASK\UserBundle\Entity\User ; use FOS\ElasticaBundle\Configuration\Search; use Symfony\Component\Validator\Constraints as Assert; /** * Task * * @ORM\Table(name="task") * @Search(repositoryClass="SMARTASK\HomeBundle\Repository\TaskRepository") * @ORM\Entity(repositoryClass="SMARTASK\HomeBundle\Repository\TaskRepository") */ class Task { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * Many Tasks have Many Users. * @ORM\ManyToMany(targetEntity="SMARTASK\UserBundle\Entity\User", mappedBy="tasks") */ private $users; /** * @var string * * @ORM\Column(name="titre", type="string", length=255, unique=true) * @Assert\Length(min=5) * @Assert\NotBlank() */ private $titre; /** * @var string * * @ORM\Column(name="localisation", type="string", length=255, nullable=true) */ private $localisation; /** * One Task has One Groupe. * @ORM\ManyToOne(targetEntity="SMARTASK\HomeBundle\Entity\Groupe") * @ORM\JoinColumn(name="group_id", referencedColumnName="id") * @Assert\NotBlank() */ private $group; /** * One Task has One resp. * @ORM\ManyToOne(targetEntity="SMARTASK\UserBundle\Entity\User") * @ORM\JoinColumn(name="resp_id", referencedColumnName="id") * @Assert\NotBlank() */ private $resp; /** * One Task has One Manager. * @ORM\ManyToOne(targetEntity="SMARTASK\UserBundle\Entity\User") * @ORM\JoinColumn(name="manager_id", referencedColumnName="id") * @Assert\NotBlank() */ private $manager; /** * @var datetime * * @ORM\Column(name="date", type="date", nullable=true) */ private $date; /** * @var time * * @ORM\Column(name="time", type="time", nullable=true) * @Assert\DateTime() */ private $time; /** * @var string * * @ORM\Column(name="description", type="string", length=255, nullable=true) */ private $description; /** * @var int * * @ORM\Column(name="isalarmeon", type="integer", nullable=true) */ private $isalarmeon; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set titre * * @param string $titre * * @return Task */ public function setTitre($titre) { $this->titre = $titre; return $this; } /** * Get titre * * @return string */ public function getTitre() { return $this->titre; } /** * Set localisation * * @param string $localisation * * @return Task */ public function setLocalisation($localisation) { $this->localisation = $localisation; return $this; } /** * Get localisation * * @return string */ public function getLocalisation() { return $this->localisation; } /** * Set group * * @param Group $group * * @return Task */ public function setGroup($group) { $this->group = $group; return $this; } /** * Get group * * @return Group */ public function getGroup() { return $this->group; } /** * Set resp * * @param Contact $resp * * @return Task */ public function setResp($resp) { $this->resp = $resp; return $this; } /** * Get manager * * @return User */ public function getManager() { return $this->manager; } /** * Set manager * * @param Contact $manager * * @return Task */ public function setManager($manager) { $this->manager = $manager; return $this; } /** * Get resp * * @return Contact */ public function getResp() { return $this->resp; } /** * Set date * * @param date $datetime * * @return Task */ public function setDate($date) { $this->date = $date; return $this; } /** * Get datetime * * @return datetime */ public function getDate() { return $this->date; } /** * Set description * * @param time $time * * @return Task */ public function setTime($time) { $this->time = $time; return $this; } /** * Get time * * @return time */ public function getTime() { return $this->time; } /** * Set description * * @param string $description * * @return Task */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set isalarmeon * * @param integer $isalarmeon * * @return Task */ public function setIsalarmeon($isalarmeon) { $this->isalarmeon = $isalarmeon; return $this; } /** * Get isalarmeon * * @return int */ public function getIsalarmeon() { return $this->isalarmeon; } public function getUsers() { return $this->users; } public function setUsers($users) { $this->users = $users; return $this; } }
tonymayflower/smartask
src/SMARTASK/HomeBundle/Entity/Task.php
PHP
mit
5,793
/* * 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 modelo; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * * @author Deivis */ public class Cotacao { private int id; private Date data; private Double valor; private TipoMoeda tipoMoeda; public TipoMoeda getTipoMoeda() { return tipoMoeda; } public void setTipoMoeda(TipoMoeda tipoMoeda) { this.tipoMoeda = tipoMoeda; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Date getData() { return data; } public String getDataString() { if (this.data != null) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(this.data); } else { return null; } } public String getDataStringBr() { if (this.data != null) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); return df.format(this.data); } else { return null; } } public void setData(String data) throws ParseException { if (!"".equals(data)) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); this.data = df.parse(data); } else { this.data = null; } } public void setDataBr(String data) throws ParseException { if (!"".equals(data)) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); this.data = df.parse(data); } else { this.data = null; } } public void setDataString(String data) throws ParseException { if (!"".equals(data)) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); this.data = df.parse(data); } else { this.data = null; } } public Double getValor() { return valor; } public String getValorString() { return valor.toString(); } public void setValor(String valor) { if (!"".equals(valor)) { this.valor = Double.parseDouble(valor.replace(",", ".")); } else { this.valor = null; } } }
deivisvieira/PosJava
src/java/modelo/Cotacao.java
Java
mit
2,527
<?php namespace MM\Util\Dummy; trigger_error("simulating php error/warining"); class Dummy2 { }
marianmeres/mm-php
mm-util/tests/MM/Util/Dummy/Dummy2.php
PHP
mit
98
require 'test_helper' class SecurityErrorTest < Minitest::Test end
bgreg/humanist-errors
test/backlog/security_error_test.rb
Ruby
mit
69
<?php /* Safe sample input : Uses popen to read the file /tmp/tainted.txt using cat command sanitize : settype (float) construction : use of sprintf via a %d */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $handle = popen('/bin/cat /tmp/tainted.txt', 'r'); $tainted = fread($handle, 4096); pclose($handle); if(settype($tainted, "float")) $tainted = $tainted ; else $tainted = 0.0 ; $query = sprintf("SELECT Trim(a.FirstName) & ' ' & Trim(a.LastName) AS employee_name, a.city, a.street & (' ' +a.housenum) AS address FROM Employees AS a WHERE a.supervisor=%d", $tainted); $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_89/safe/CWE_89__popen__CAST-func_settype_float__multiple_AS-sprintf_%d.php
PHP
mit
1,780
// // EFDataSource.h // Pods // // Created by Ilya Sedov on 30/04/16. // // #import <Foundation/Foundation.h> @class EFCellModel; @protocol EFDataSource <NSObject> @required - (NSInteger)count; - (EFCellModel *)objectAtIndex:(NSInteger)index; - (void)add:(EFCellModel *)object; - (void)removeAtIndex:(NSInteger)index; - (void)updateAtIndex:(NSInteger)index model:(EFCellModel *)model; - (id)objectAtIndexedSubscript:(NSUInteger)idx; - (NSArray *)allObjects; @end
setoff/EasyForm
EasyForm/Core/EFDataSource.h
C
mit
478
'use strict'; angular.module('mean.settings').config(['$stateProvider', function($stateProvider) { var checkLoggedin = function($q, $timeout, $http, $location) { // Initialize a new promise var deferred = $q.defer(); // Make an AJAX call to check if the user is logged in $http.get('/loggedin').success(function(user) { // Authenticated if (user !== '0') $timeout(deferred.resolve); // Not Authenticated else { $timeout(deferred.reject); $location.url('/'); } }); return deferred.promise; }; $stateProvider.state('settings', { url: '/settings', templateUrl: 'settings/views/index.html', resolve: { loggedin: checkLoggedin } }); } ]);
indie-hackathon/dchat
packages/custom/settings/public/routes/settings.js
JavaScript
mit
787
import Express = require("express"); import Geohash = require("latlon-geohash"); import Nconf = require("nconf"); import Path = require("path"); import * as multer from "multer"; import { Picnic } from "../../models/Picnic"; import { User } from "../../models/User"; import { Module } from "../Module"; import { UserModule } from "../user/UserModule"; // Load Configuration Nconf.file(Path.join(__dirname, "../../../config.json")); const picknicConfig = Nconf.get("picknic"); export class DataModule extends Module { public addRoutes(app: Express.Application) { // Tables app.post("/data/tables/find/near", (req: Express.Request, res: Express.Response) => { const bounds = req.body; const query = Picnic.find({}).limit(picknicConfig.data.near.default).where("geometry").near(bounds).lean(); query.exec().then((tables: any) => { res.send(tables); }); }); app.post("/data/tables/find/within", (req: Express.Request, res: Express.Response) => { const bounds = req.body; Picnic.find({}).where("geometry").within(bounds).lean().exec().then((tables) => { res.send(tables); }); }); app.get("/data/tables/get", (req: Express.Request, res: Express.Response) => { const id = req.query.id; if (id) { Picnic.findById(id).lean().exec().then((table) => { res.send(table); }); } else { res.send("Error: No ID supplied."); } }); app.get("/data/tables/heatmap", (req: Express.Request, res: Express.Response) => { // TODO: Add admin permissions, because this is quite computational. Picnic.find().lean().exec().then((tables: any) => { // Geohash the locations, and calculate the number of tables in each hashed area. // TODO: Change this to a set? const weightedSet: any = {}; const newWeightedSet: Set<string> = new Set<string>(); for (const table of tables) { const lng: number = table.geometry.coordinates[0]; const lat: number = table.geometry.coordinates[1]; // TODO: This 4 was created by trial and error. If there are more than 10,000 results returned // then decrease the number by one (i.e. change 4 to 3) const geohash = Geohash.encode(lat, lng, 4); newWeightedSet.add(geohash); if (weightedSet.hasOwnProperty(geohash)) { weightedSet[geohash] += 1; } else { weightedSet[geohash] = 1; } } // Decode the geohashes and return a weighted heatmap const returnSet = new Array(); newWeightedSet.forEach((table) => { const point = Geohash.decode(table); const numTables = weightedSet[table]; returnSet.push([point.lat, point.lon, numTables]); }); res.send(JSON.stringify(returnSet)); }); }); app.post("/data/tables/add", multer().single(), (req: Express.Request, res: Express.Response) => { // Authenticate const user = UserModule.getLoggedInUser(req); if (!user) { res.send("Error: No user authentication."); return; } const fields = req.body; const table = new Picnic({ geometry: { coordinates: [Number(fields.longitude), Number(fields.latitude)], type: "Point", }, properties: { comment: fields.comment, license: { name: fields.license_name, url: fields.license_url, }, source: { name: fields.source_name, retrieved: Date.now(), url: fields.source_url, }, type: "table", user, }, type: "Feature", }); // Switch form text (yes/no) to boolean switch (fields.sheltered.toLowerCase()) { case "yes": table.properties.sheltered = true; break; case "no": table.properties.sheltered = false; break; } switch (fields.accessible.toLowerCase()) { case "yes": table.properties.accessible = true; break; case "no": table.properties.accessible = false; break; } // Add picnic table to database Picnic.create(table, (error: any) => { if (error) { res.send("Error: " + error); // console.log(error); } else { res.redirect(req.header("Referer")); } }); }); app.post("/data/tables/edit", multer().single(), (req: Express.Request, res: Express.Response) => { // Authenticate const user = UserModule.getLoggedInUser(req); if (!user) { res.send("Error: No user authentication."); return; } // TODO: Authenticate the permission on the actual table. User.findOne({ email: user }, async (userFindError) => { if (userFindError) { res.send("Error: There was an error checking permissions."); } const fields = req.body; const table = await Picnic.findOne({ id: fields.id }).exec(); table.properties.comment = fields.comment; table.properties.license.url = fields.license_url; table.properties.license.name = fields.license_name; // Switch form text (yes/no) to boolean switch (fields.sheltered.toLowerCase()) { case "yes": table.properties.sheltered = true; break; case "no": table.properties.sheltered = false; break; } switch (fields.accessible.toLowerCase()) { case "yes": table.properties.accessible = true; break; case "no": table.properties.accessible = false; break; } table.save((err) => { if (err) { res.send("Error: Failed saving updated table."); } else { res.redirect(req.header("Referer")); } }); }); }); } }
earthiverse/picknic
source/modules/data/DataModule.ts
TypeScript
mit
6,060
<!-- Modal ADD --> <div class="modal fade" id="modal-form" role="dialog"> <div class="modal-dialog modal-lg"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title"><small></small></h4> </div> <div class="modal-body"> <?php echo form_open('', 'id="form" class="form-horizontal"'); ?> <!-- form login --> <div style="width: auto" align="center"> <h3>RSIA. LOMBOK DUA DUA</h3> <h5>RINCIAN BIAYA</h5> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label class="col-sm-3 control-label">Nama Pasien</label> <div class="col-sm-9"> <input type="text" class="form-control" name="nama_pasien" placeholder="Nama pasien" required> </div> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label class="col-sm-4 control-label">Kode Transaksi</label> <div class="col-sm-8"> <input type="text" class="form-control" name="kode_transaksi" value="<?= date('ymdhis') ?>" disabled=""> </div> </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label class="col-sm-3 control-label">Nama Suami</label> <div class="col-sm-9"> <input type="text" class="form-control" name="nama_suami" placeholder="Nama suami" required> </div> </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label class="col-sm-3 control-label">Alamat</label> <div class="col-sm-9"> <input type="text" class="form-control" name="alamat" placeholder="Alamat" required> </div> </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label class="col-sm-3 control-label">No Telp</label> <div class="col-sm-9"> <input type="text" class="form-control" name="telp" placeholder="No Telp" required> </div> </div> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label class="col-sm-3 control-label">Tgl Masuk</label> <div class="col-sm-9"> <input type="text" class="form-control" name="tgl_masuk" value="<?= date('Y/m/d') ?>" disabled=""> </div> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label class="col-sm-4 control-label">Tgl Keluar</label> <div class="col-sm-8"> <input type="text" class="form-control" name="tgl_keluar" data-inputmask="'alias': 'yyyy/mm/dd'" data-mask required placeholder="Tanggal Keluar"> </div> </div> </div> </div> <hr> <div class="form-group"> <label class="col-sm-2 control-label">Dokter Utama</label> <div class="col-sm-4"> <input type="text" class="form-control" name="dokter_utama" placeholder="Dokter utama" required> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Perincian Biaya</label> <div class="col-sm-8"> <input type="text" class="form-control" name="title" placeholder="Keterangan" required> </div> </div> <hr> <div style="margin: 40px"> <table class="table"> <tr> <td><b><i>Keterangan</b></i></td> <td width="20%"><b><i>Jumlah</b></i></td> </tr> <tr> <td>Kartu Pasien</td> <td><input type="number" class="form-control" name="kartu_pasien" placeholder="" required></td> </tr> <tr> <td>Administrasi</td> <td><input type="number" class="form-control" name="administrasi" placeholder="" required></td> </tr> <tr> <td>Komponen OK Alat Anastesi</td> <td><input type="number" class="form-control" name="komponen_ok" placeholder="" required></td> </tr> </table> <hr><strong>Pemakaian Kamar</strong> <table class="table"> <td>Jasa Pelayanan</td> <td style="width: 20%"><input type="number" class="form-control" name="jasa_pelayanan" placeholder="" ></td> </tr> <tr> <td>Kamar Inap</td> <td><input type="number" class="form-control" name="kamar_inap" placeholder="" ></td> </tr> <tr> <td>Kamar Operasi</td> <td><input type="number" class="form-control" name="kamar_operasi" placeholder="" ></td> </tr> <tr> <td>Kamar Bersalin</td> <td><input type="number" class="form-control" name="kamar_bersali" placeholder="" ></td> </tr> </table> <hr><strong>Penunjang Medis</strong> <table class="table"> <td>Laboratorium</td> <td style="width: 20%"><input type="number" class="form-control" name="laboratorium" placeholder="" ></td> </tr> </table> <hr><strong>Pemakaian Obat dan Alkes</strong> <table class="table"> <td>Luar Paket (Obat Dengan Resep)</td> <td style="width: 20%"><input type="number" class="form-control" name="luar_paket" placeholder="" ></td> </tr> <tr> <td>di Kamar Rawat Inap</td> <td><input type="number" class="form-control" name="di_kamar_rawat_inap" placeholder="" ></td> </tr> <tr> <td>di Kamar Operasi</td> <td><input type="number" class="form-control" name="di_kamar_operasi" placeholder="" ></td> </tr> <tr> <td>di Kamar Bersalin</td> <td><input type="number" class="form-control" name="di_kamar_bersali" placeholder="" ></td> </tr> </table> <hr><strong>Rincian Biaya Tindakan</strong> <table class="table"> <td>NST</td> <td style="width: 20%"><input type="number" class="form-control" name="nst" placeholder="" ></td> </tr> </table> <hr><strong>Tindakan dan HR Dokter</strong> <hr><strong>Lain - Lain</strong> <table class="table"> <td>Lain - Lain</td> <td style="width: 20%"><input type="number" class="form-control" name="lain_lain" placeholder="" ></td> </tr> </table> </div> <div class="box-footer"> <div class="pull-right"> <button type="reset" class="btn btn-default" data-dismiss="modal">Cancel</button> &nbsp;&nbsp; <button type="submit" class="btn btn-success">Simpan</button> </div> </div><!-- /.box-footer --> <?php echo form_close(); ?> <!-- form close --> </div><!-- /.form-box --> </div><!-- /.register-box --> </div> </div>
nizamiftahul/ci_p1
application/views/rawat_jalan/_edit.php
PHP
mit
7,969
#Attribute set in both superclass and subclass class C(object): def __init__(self): self.var = 0 class D(C): def __init__(self): self.var = 1 # self.var will be overwritten C.__init__(self) #Attribute set in both superclass and subclass class E(object): def __init__(self): self.var = 0 # self.var will be overwritten class F(E): def __init__(self): E.__init__(self) self.var = 1
github/codeql
python/ql/test/query-tests/Classes/overwriting-attribute/overwriting_attribute.py
Python
mit
451
#include <iostream> #include <fftw3.h> #include <omp.h> #include <cstdlib> #include <sweet/SimulationVariables.hpp> class TestFFTPlans { public: bool importWisdom(int i_reuse_spectral_transformation_plans) { static const char *wisdom_file = "sweet_fftw"; std::cout << "fftw_import_wisdom_from_filename(" << wisdom_file << ")" << std::endl; int wisdom_plan_loaded = fftw_import_wisdom_from_filename(wisdom_file); if (wisdom_plan_loaded == 0) { std::cerr << "Failed to load FFTW wisdom from file '" << wisdom_file << "'" << std::endl; if (i_reuse_spectral_transformation_plans == 2) exit(1); } std::cout << "WISDOM: " << fftw_export_wisdom_to_string() << std::endl; return true; } bool exportWisdom() { static const char *wisdom_file = "sweet_fftw"; std::cout << "fftw_export_wisdom_to_filename(" << wisdom_file << ")" << std::endl; int wisdom_plan_stored = fftw_export_wisdom_to_filename(wisdom_file); if (wisdom_plan_stored == 0) { std::cerr << "Failed to store FFTW wisdom to file " << wisdom_file << std::endl; exit(1); } std::cout << "WISDOM: " << fftw_export_wisdom_to_string() << std::endl; return true; } bool printWisdom() { std::cout << "WISDOM: " << fftw_export_wisdom_to_string() << std::endl; return true; } int run( int i_reuse_spectral_transformation_plans, int i_res[2], int i_nthreads ) { #if SWEET_THREADING std::cout << "fftw_init_threads()" << std::endl; int retval = fftw_init_threads(); if (retval == 0) { std::cerr << "ERROR: fftw_init_threads()" << std::endl; exit(1); } std::cout << "fftw_plan_with_nthreads(" << i_nthreads << ")" << std::endl; fftw_plan_with_nthreads(i_nthreads); #endif importWisdom(i_reuse_spectral_transformation_plans); unsigned int num_cells = i_res[0]*i_res[1]; unsigned flags = 0; if (i_reuse_spectral_transformation_plans == -1) { flags |= FFTW_ESTIMATE; } else { // estimation base don workload if (num_cells < 32*32) //flags |= FFTW_EXHAUSTIVE; num_cells |= FFTW_MEASURE; else if (num_cells < 128*128) num_cells |= FFTW_MEASURE; else num_cells |= FFTW_PATIENT; if (i_reuse_spectral_transformation_plans == 2) { std::cout << "Enforcing to use Wisdom" << std::endl; flags |= FFTW_WISDOM_ONLY; } } // allocate more data than necessary for spectral space fftw_complex *data_spectral = (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * i_res[0]*i_res[1]); // physical space data double *data_physical = (double*)fftw_malloc(sizeof(double)*2 * i_res[0]*i_res[1]); std::cout << "fftw_plan_dft_r2c_2d(...)" << std::endl; fftw_plan fftw_plan_forward; fftw_plan_forward = fftw_plan_dft_r2c_2d( i_res[1], i_res[0], data_physical, (fftw_complex*)data_spectral, flags ); printWisdom(); if (fftw_plan_forward == nullptr) { std::cout << "Wisdom: " << fftw_export_wisdom_to_string() << std::endl; std::cerr << "Failed to get forward plan dft_r2c fftw" << std::endl; exit(-1); } exportWisdom(); #if SWEET_THREADING fftw_cleanup_threads(); #endif fftw_cleanup(); return 0; } }; int main(int i_argc, char **i_argv) { SimulationVariables simVars; simVars.setupFromMainParameters(i_argc, i_argv, nullptr, true); simVars.outputConfig(); #if SWEET_THREADING int nthreads = omp_get_max_threads(); std::cout << " + nthreads: " << nthreads << std::endl; #else int nthreads = 0; #endif TestFFTPlans t; t.run(simVars.misc.reuse_spectral_transformation_plans, simVars.disc.space_res_physical, nthreads); std::cout << "FIN" << std::endl; return 0; }
schreiberx/sweet
src/unit_tests/test_plane_fftw_wisdom_import_export.cpp
C++
mit
3,655
<form id="formCopyMove"> <fieldset> <div class="modal-body"> <label>{{i18n.select_destination}}:</label> <div id="copyMoveTree"><div class="text-center"><span class="icon icon-spin5 animate-spin"></span></div></div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" id="copyButton">{{i18n.copy}}</button> <button type="button" class="btn btn-default" id="moveButton">{{i18n.move}}</button> <button type="button" class="btn btn-default" id="cancelButton">{{i18n.cancel}}</button> </div> </fieldset> </form>
digitalmobil/ifm
src/templates/modal.copymove.html
HTML
mit
550
class Comment < Sequel::Model many_to_one :post include Splam splammable :body do |splam| splam.threshold = 40 splam.rules = [:bad_words, :html, :bbcode, :href, :chinese, :line_length, :russian] end def before_save return false if super == false self.published = !self.splam? true end end
whoisjake/thoughts
models/comment.rb
Ruby
mit
329
#pragma once #define FILE_NAME_MAX 512 #define FILE_PATH_MAX 512 typedef struct linked_list_s linked_list; typedef struct list_item_s list_item; typedef struct meta_info_s { char name[0x100]; char compatible[0x10]; char description[0x200]; char developer[0x100]; char devsite[0x100]; char added[0x100]; u32 texture; char version[0xA]; char pic[0x100]; u32 pictexture; u32 id; } meta_info; typedef struct ntrdb_info_s { char titleId[0xAA]; meta_info meta; char downloadURL[0x100]; } ntrdb_info; typedef enum data_op_e { DATAOP_COPY, DATAOP_DELETE } data_op; typedef struct data_op_data_s { void* data; data_op op; // Copy u32 copyBufferSize; bool copyEmpty; u32 copyBytesPerSecond; u32 processed; u32 total; u64 currProcessed; u64 currTotal; Result (*isSrcDirectory)(void* data, u32 index, bool* isDirectory); Result (*makeDstDirectory)(void* data, u32 index); Result (*openSrc)(void* data, u32 index, u32* handle); Result (*closeSrc)(void* data, u32 index, bool succeeded, u32 handle); Result (*getSrcSize)(void* data, u32 handle, u64* size); Result (*readSrc)(void* data, u32 handle, u32* bytesRead, void* buffer, u64 offset, u32 size); Result (*openFile)(void* data, u32 index, void* initialReadBlock, u64 size, u32* handle); Result (*closeFile)(void* data, u32 index, bool succeeded, u32 handle); Result (*writeFile)(void* data, u32 handle, u32* bytesWritten, void* buffer, u64 offset, u32 size); Result (*suspendCopy)(void* data, u32 index, u32* srcHandle, u32* dstHandle); Result (*restoreCopy)(void* data, u32 index, u32* srcHandle, u32* dstHandle); // Delete Result (*delete)(void* data, u32 index); // Suspend Result (*suspend)(void* data, u32 index); Result (*restore)(void* data, u32 index); // Errors bool (*error)(void* data, u32 index, Result res); // General volatile bool finished; Result result; Handle cancelEvent; } data_op_data; typedef struct populate_ntrdb_data_s { linked_list* items; volatile bool finished; Result result; Handle cancelEvent; } populate_ntrdb_data; typedef struct populate_titles_data_s { linked_list* items; void* userData; bool (*filter)(void* data, u64 titleId, FS_MediaType mediaType); int (*compare)(void* data, const void* p1, const void* p2); volatile bool finished; Result result; Handle cancelEvent; } populate_titles_data; typedef struct title_info_s { FS_MediaType mediaType; u64 titleId; char productCode[0x10]; u16 version; u64 installedSize; bool twl; bool hasMeta; meta_info meta; } title_info; void task_init(); void task_exit(); bool task_is_quit_all(); Handle task_get_pause_event(); Handle task_get_suspend_event(); Result task_data_op(data_op_data* data); void task_free_ntrdb(list_item* item); void task_clear_ntrdb(linked_list* items); Result task_populate_ntrdb(populate_ntrdb_data* data);
adrifcastr/NTRDBI
source/ui/section/task/task.h
C
mit
3,028
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_hobbit-hackconf-2015_session'
dimitardanailov/hobbit-hackconf-2015
config/initializers/session_store.rb
Ruby
mit
152
namespace EVTC_Log_Parser.Model { public class Interval { public int Start { get; set; } public int End { get; set; } } }
M4xZ3r0/GW2RaidTool
GW2RaidTool/EVTC-Log-Parser/Model/Data/Skill/Interval.cs
C#
mit
153
package br.com.dbsoft.rest.dados; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import br.com.dbsoft.rest.interfaces.IStatus; @JsonInclude(value=Include.NON_NULL) @JsonTypeInfo(use = JsonTypeInfo.Id.NONE) @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public class DadosStatus implements IStatus { private static final long serialVersionUID = -6552296817145232368L; @JsonProperty("status") private Boolean wStatus; @Override public Boolean getStatus() { return wStatus; } @Override public void setStatus(Boolean pStatus) { wStatus = pStatus; } }
dbsoftcombr/dbssdk
src/main/java/br/com/dbsoft/rest/dados/DadosStatus.java
Java
mit
1,014
import PropTypes from 'prop-types' import React from 'react' import block from 'bem-cn-lite' import { Field, reduxForm } from 'redux-form' import { compose } from 'underscore' import { connect } from 'react-redux' import { renderTextInput } from '../text_input' import { renderCheckboxInput } from '../checkbox_input' import { signUp, updateAuthFormStateAndClearError } from '../../client/actions' import { GDPRMessage } from 'desktop/components/react/gdpr/GDPRCheckbox' function validate(values) { const { accepted_terms_of_service, email, name, password } = values const errors = {} if (!name) errors.name = 'Required' if (!email) errors.email = 'Required' if (!password) errors.password = 'Required' if (!accepted_terms_of_service) errors.accepted_terms_of_service = 'Please agree to our terms to continue' return errors } function SignUp(props) { const { error, handleSubmit, isLoading, signUpAction, updateAuthFormStateAndClearErrorAction, } = props const b = block('consignments-submission-sign-up') return ( <div className={b()}> <div className={b('title')}>Create an Account</div> <div className={b('subtitle')}> Already have an account?{' '} <span className={b('clickable')} onClick={() => updateAuthFormStateAndClearErrorAction('logIn')} > Log in </span>. </div> <form className={b('form')} onSubmit={handleSubmit(signUpAction)}> <div className={b('row')}> <div className={b('row-item')}> <Field name="name" component={renderTextInput} item={'name'} label={'Full Name'} autofocus /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="email" component={renderTextInput} item={'email'} label={'Email'} type={'email'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="password" component={renderTextInput} item={'password'} label={'Password'} type={'password'} /> </div> </div> <div className={b('row')}> <div className={b('row-item')}> <Field name="accepted_terms_of_service" component={renderCheckboxInput} item={'accepted_terms_of_service'} label={<GDPRMessage />} value={false} /> </div> </div> <button className={b .builder()('sign-up-button') .mix('avant-garde-button-black')()} type="submit" > {isLoading ? <div className="loading-spinner-white" /> : 'Submit'} </button> {error && <div className={b('error')}>{error}</div>} </form> </div> ) } const mapStateToProps = state => { return { error: state.submissionFlow.error, isLoading: state.submissionFlow.isLoading, } } const mapDispatchToProps = { signUpAction: signUp, updateAuthFormStateAndClearErrorAction: updateAuthFormStateAndClearError, } SignUp.propTypes = { error: PropTypes.string, handleSubmit: PropTypes.func.isRequired, isLoading: PropTypes.bool.isRequired, signUpAction: PropTypes.func.isRequired, updateAuthFormStateAndClearErrorAction: PropTypes.func.isRequired, } export default compose( reduxForm({ form: 'signUp', // a unique identifier for this form validate, }), connect(mapStateToProps, mapDispatchToProps) )(SignUp)
kanaabe/force
src/desktop/apps/consign/components/sign_up/index.js
JavaScript
mit
3,781
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System.Collections.Generic; using DotSpatial.Data; namespace DotSpatial.Symbology { /// <summary> /// Interface for LayerProvider. /// </summary> public interface ILayerProvider { #region Properties /// <summary> /// Gets a basic description of what your provider does. /// </summary> string Description { get; } /// <summary> /// Gets a dialog read filter that lists each of the file type descriptions and file extensions, delimeted /// by the | symbol. Each will appear in DotSpatial's open file dialog filter, preceeded by the name provided /// on this object. /// </summary> string DialogReadFilter { get; } /// <summary> /// Gets a dialog filter that lists each of the file type descriptions and extensions for a Save File Dialog. /// Each will appear in DotSpatial's open file dialog filter, preceeded by the name provided on this object. /// </summary> string DialogWriteFilter { get; } /// <summary> /// Gets a prefereably short name that identifies this data provider. Example might be GDAL. /// This will be prepended to each of the DialogReadFilter members from this plugin. /// </summary> string Name { get; } #endregion #region Methods /// <summary> /// This open method is only called if this plugin has been given priority for one /// of the file extensions supported in the DialogReadFilter property supplied by /// this control. Failing to provide a DialogReadFilter will result in this plugin /// being added to the list of DataProviders being supplied under the Add Other Data /// option in the file menu. /// </summary> /// <param name="fileName">A string specifying the complete path and extension of the file to open.</param> /// <param name="inRam">A boolean that, if ture, will request that the data be loaded into memory</param> /// <param name="container">Any valid IContainer that should have the new layer automatically added to it</param> /// <param name="progressHandler">An IProgressHandler interface for status messages</param> /// <returns>A List of IDataSets to be added to the Map. These can also be groups of datasets.</returns> ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler); #endregion } }
CGX-GROUP/DotSpatial
Source/DotSpatial.Symbology/ILayerProvider.cs
C#
mit
2,747
using System.Runtime.Serialization; namespace PushbulletSharp.Models.Responses.Ephemerals { [DataContract] public class DismissalEphemeral : IEphemeral { /// <summary> /// Gets or sets the type. /// </summary> /// <value> /// The type. /// </value> [DataMember(Name = "type")] public string Type { get; set; } /// <summary> /// Gets or sets the name of the package. /// </summary> /// <value> /// The name of the package. /// </value> [DataMember(Name = "package_name")] public string PackageName { get; set; } /// <summary> /// Gets or sets the source user iden. /// </summary> /// <value> /// The source user iden. /// </value> [DataMember(Name = "source_user_iden")] public string SourceUserIden { get; set; } /// <summary> /// Gets or sets the notification identifier. /// </summary> /// <value> /// The notification identifier. /// </value> [DataMember(Name = "notification_id")] public string NotificationId { get; set; } /// <summary> /// Gets or sets the notification tag. /// </summary> /// <value> /// The notification tag. /// </value> [DataMember(Name = "notification_tag")] public string NotificationTag { get; set; } /// <summary> /// Gets or sets the source device iden. /// </summary> /// <value> /// The source device iden. /// </value> [DataMember(Name = "source_device_iden")] public string SourceDeviceIden { get; set; } } }
adamyeager/PushbulletSharp
PushbulletSharp/Models/Responses/Ephemerals/DismissalEphemeral.cs
C#
mit
1,753
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_02) on Mon Apr 25 06:16:42 CEST 2016 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>org.gradle.api.plugins.jetty (Gradle API 2.13)</title> <meta name="date" content="2016-04-25"> <link rel="stylesheet" type="text/css" href="../../../../../javadoc.css" title="Style"> </head> <body> <h1 class="bar"><a href="../../../../../org/gradle/api/plugins/jetty/package-summary.html" target="classFrame">org.gradle.api.plugins.jetty</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="AbstractJettyRunTask.html" title="class in org.gradle.api.plugins.jetty" target="classFrame">AbstractJettyRunTask</a></li> <li><a href="JettyPlugin.html" title="class in org.gradle.api.plugins.jetty" target="classFrame">JettyPlugin</a></li> <li><a href="JettyPluginConvention.html" title="class in org.gradle.api.plugins.jetty" target="classFrame">JettyPluginConvention</a></li> <li><a href="JettyRun.html" title="class in org.gradle.api.plugins.jetty" target="classFrame">JettyRun</a></li> <li><a href="JettyRunWar.html" title="class in org.gradle.api.plugins.jetty" target="classFrame">JettyRunWar</a></li> <li><a href="JettyStop.html" title="class in org.gradle.api.plugins.jetty" target="classFrame">JettyStop</a></li> <li><a href="ScanTargetPattern.html" title="class in org.gradle.api.plugins.jetty" target="classFrame">ScanTargetPattern</a></li> </ul> </div> </body> </html>
HenryHarper/Acquire-Reboot
gradle/docs/javadoc/org/gradle/api/plugins/jetty/package-frame.html
HTML
mit
1,627
* { margin: 0; padding: 0; } h2 { font-family: verdana, sans-serif; font-size: 18px; margin: 10px 5px; } .box h2 { background:#ddd; color:black; padding:5px; font-size: 14px; margin: 0; } .box p { color:#333; padding:5px; font-size: 14px} .box, .box-v { border:1px solid #ddd; background: lightyellow; width: 250px; margin: 5px; float:left; border-radius:5px; font-family: Helvetica, sans-serif; } .box-v { float: None; } .box p { text-align: center; } .box img { margin: 5px 35px; } .column { margin-right: 20px; float: left; } p.timestamp { font: 12px "Helvetica Neue",Helvetica,Arial,sans-serif; font-style: italic; }
wrecker/vmw-chargepoint
wsgi/static/cp_style.css
CSS
mit
716
package com.landenlabs.all_flipanimation; /** * Copyright (c) 2015 Dennis Lang (LanDen Labs) landenlabs@gmail.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @author Dennis Lang (3/21/2015) * @see http://landenlabs.com * */ import android.animation.ObjectAnimator; import android.app.Activity; import android.graphics.Camera; import android.graphics.Matrix; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LinearInterpolator; import android.view.animation.Transformation; import android.widget.CheckBox; import android.widget.TextView; /** * Demonstrate rotating View animation using two rotating animations. * * @author Dennis Lang (LanDen Labs) * @see <a href="http://landenlabs.com/android/index-m.html"> author's web-site </a> * // http://www.inter-fuser.com/2009/08/android-animations-3d-flip.html */ public class ActivityRotAnimation extends Activity { // ---- Layout ---- View mView1; View mView2; View mClickView; DrawView mDrawView; TextView mAngle1; TextView mAngle2; // ---- Data ---- float mCameraZ = -25; Flip3dAnimation mRotation1; Flip3dAnimation mRotation2; boolean mRotateYaxis = true; boolean mIsForward = true; boolean mAutoMode = false; MediaPlayer mSoundClick; MediaPlayer mSoundShut; // ---- Timer ---- private Handler m_handler = new Handler(); private int mDurationMsec = 3000; private Runnable m_updateElapsedTimeTask = new Runnable() { public void run() { animateIt(); m_handler.postDelayed(this, mDurationMsec); // Re-execute after msec } }; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.rot_animation); mView1 = Ui.viewById(this, R.id.view1); mView2 = Ui.viewById(this, R.id.view2); // Create a new 3D rotation with the supplied parameter mRotation1 = new Flip3dAnimation(); mRotation2 = new Flip3dAnimation(); Ui.<TextView>viewById(this, R.id.side_title).setText("Rotating Animation"); setupUI(); } /** * Start animation. */ public void animateIt() { ObjectAnimator.ofFloat(mClickView, View.ALPHA, mClickView.getAlpha(), 0).start(); final float end = 90.0f; if (mIsForward) { mRotation1.mFromDegrees = 0.0f; mRotation1.mToDegrees = end; mRotation2.mFromDegrees = -end; mRotation2.mToDegrees = 0.0f; } else { mRotation1.mFromDegrees = end; mRotation1.mToDegrees = 0.0f; mRotation2.mFromDegrees = 0.0f; mRotation2.mToDegrees = -end; } mIsForward = !mIsForward; if (mRotateYaxis) { mRotation1.mCenterX = mView1.getWidth(); mRotation1.mCenterY = mView1.getHeight() / 2.0f; mRotation2.mCenterX = 0.0f; mRotation2.mCenterY = mView2.getHeight() / 2.0f; } else { mRotation1.mCenterY = 0.0f; // mView1.getHeight(); mRotation1.mCenterX = mView1.getWidth() / 2.0f; mRotation2.mCenterY = mView1.getHeight(); // 0.0f; mRotation2.mCenterX = mView2.getWidth() / 2.0f; } mRotation1.reset(mView1, mDurationMsec, mCameraZ); mRotation2.reset(mView2, mDurationMsec, mCameraZ); mRotation2.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { mSoundShut.start(); } @Override public void onAnimationRepeat(Animation animation) { } }); // Run both animations in parallel. AnimationSet animationSet = new AnimationSet(true); animationSet.setInterpolator(new LinearInterpolator()); animationSet.addAnimation(mRotation1); animationSet.addAnimation(mRotation2); animationSet.start(); } public class Flip3dAnimation extends Animation { float mFromDegrees; float mToDegrees; float mCenterX = 0; float mCenterY = 0; float mCameraZ = -8; Camera mCamera; View mView; public Flip3dAnimation() { setFillEnabled(true); setFillAfter(true); setFillBefore(true); } public void reset(View view, int durationMsec, float cameraZ) { mCameraZ = cameraZ; setDuration(durationMsec); view.clearAnimation(); // This is very important to get 2nd..nth run to work. view.setAnimation(this); mView = view; } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); mCamera = new Camera(); } @Override protected void applyTransformation(float interpolatedTime, Transformation trans) { final float fromDegrees = mFromDegrees; float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime); final Camera camera = mCamera; final Matrix matrix = trans.getMatrix(); camera.save(); camera.setLocation(0, 0, mCameraZ); if (mRotateYaxis) camera.rotateY(degrees); else camera.rotateX(degrees); camera.getMatrix(matrix); camera.restore(); matrix.preTranslate(-mCenterX, -mCenterY); matrix.postTranslate(mCenterX, mCenterY); final float degree3 = degrees; if (mView == mView1) { mDrawView.setAngle1(degree3); mAngle1.setText(String.format("%.0f°", degree3)); } else { mDrawView.setAngle2(degree3); mAngle2.setText(String.format("%.0f°", degree3)); } } } /** * Build User Interface - setup callbacks. */ private void setupUI() { mSoundClick = MediaPlayer.create(this, R.raw.click); // mSoundClick.setVolume(0.5f, 0.5f); mSoundShut = MediaPlayer.create(this, R.raw.shut); // mSoundShut.setVolume(0.3f, 0.3f); final TextView title = (TextView) this.findViewById(R.id.title); mClickView = this.findViewById(R.id.click_view); mClickView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mSoundClick.start(); animateIt(); } }); final SlideBar seekspeedSB = new SlideBar(this.findViewById(R.id.seekSpeed), "Delay:"); seekspeedSB.setValueChanged(new SlideBar.ValueChanged() { @Override public float onValueChanged(View v, float value) { mDurationMsec = (int) (value = 100 + value * 100); title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ)); return value; } }); final SlideBar cameraZpos = new SlideBar(this.findViewById(R.id.cameraZpos), "CamZ:"); cameraZpos.setProgress((int) (mCameraZ / -2 + 50)); cameraZpos.setValueChanged(new SlideBar.ValueChanged() { @Override public float onValueChanged(View v, float value) { mCameraZ = value = (50 - value) * 2.0f; title.setText(String.format("Delay:%d CameraZ:%.0f", mDurationMsec, mCameraZ)); return value; } }); final CheckBox autoFlipCb = Ui.viewById(this, R.id.autoflip); autoFlipCb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mAutoMode = ((CheckBox) v).isChecked(); if (mAutoMode) { m_handler.postDelayed(m_updateElapsedTimeTask, 0); } else { m_handler.removeCallbacks(m_updateElapsedTimeTask); } } }); final CheckBox yaxisCb = Ui.viewById(this, R.id.yaxis); mRotateYaxis = yaxisCb.isChecked(); yaxisCb.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { boolean autoMode = mAutoMode; if (autoMode) autoFlipCb.performClick(); // Stop automatic animation. mRotateYaxis = ((CheckBox) v).isChecked(); if (autoMode) autoFlipCb.performClick(); // Restart automatic animation. } }); mDrawView = Ui.viewById(this, R.id.drawView); mAngle1 = Ui.viewById(this, R.id.angle1); mAngle2 = Ui.viewById(this, R.id.angle2); } }
landenlabs2/all_FlipAnimation
app/src/main/java/com/landenlabs/all_flipanimation/ActivityRotAnimation.java
Java
mit
10,273
I am an unordered list. I am typically used for unnumbered lists
JupiterSmalltalk/Pillar
repository/Pillar-Model.package/PRUnorderedList.class/README.md
Markdown
mit
64
<?xml version="1.0" ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <!-- saved from url=(0017)http://localhost/ --> <script language="JavaScript" src="../../displayToc.js"></script> <script language="JavaScript" src="../../tocParas.js"></script> <script language="JavaScript" src="../../tocTab.js"></script> <link rel="stylesheet" type="text/css" href="../../scineplex.css"> <title></title> <link rel="stylesheet" href="../../Active.css" type="text/css" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rev="made" href="mailto:" /> </head> <body> <ul id="index"> <li><a href="#NAME">NAME</a></li> <li><a href="#SYNOPSIS">SYNOPSIS</a></li> <li><a href="#DESCRIPTION">DESCRIPTION</a></li> <li><a href="#SUPPORTED-CODE-SETS">SUPPORTED CODE SETS</a></li> <li><a href="#ROUTINES">ROUTINES</a></li> <li><a href="#SEE-ALSO">SEE ALSO</a></li> <li><a href="#AUTHOR">AUTHOR</a></li> <li><a href="#COPYRIGHT">COPYRIGHT</a></li> </ul> <h1 id="NAME">NAME</h1> <p>Locale::Currency - standard codes for currency identification</p> <h1 id="SYNOPSIS">SYNOPSIS</h1> <pre><code><code> <span class="keyword">use</span> <span class="variable">Locale::Currency</span><span class="operator">;</span> <span class="variable">$curr</span> <span class="operator">=</span> <span class="variable">code2currency</span><span class="operator">(</span><span class="string">'usd'</span><span class="operator">);</span> <span class="comment"># $curr gets 'US Dollar'</span> <span class="variable">$code</span> <span class="operator">=</span> <span class="variable">currency2code</span><span class="operator">(</span><span class="string">'Euro'</span><span class="operator">);</span> <span class="comment"># $code gets 'eur'</span> <span class="variable">@codes</span> <span class="operator">=</span> <span class="variable">all_currency_codes</span><span class="operator">();</span> <span class="variable">@names</span> <span class="operator">=</span> <span class="variable">all_currency_names</span><span class="operator">();</span> </code></code></pre> <h1 id="DESCRIPTION">DESCRIPTION</h1> <p>The <code><code>Locale::Currency</code></code> module provides access to standard codes used for identifying currencies and funds, such as those defined in ISO 4217.</p> <p>Most of the routines take an optional additional argument which specifies the code set to use. If not specified, the default ISO 4217 three-letter codes will be used.</p> <h1 id="SUPPORTED-CODE-SETS">SUPPORTED CODE SETS</h1> <p>There are several different code sets you can use for identifying currencies. A code set may be specified using either a name, or a constant that is automatically exported by this module.</p> <p>For example, the two are equivalent:</p> <pre><code><code> <span class="variable">$curr</span> <span class="operator">=</span> <span class="variable">code2currency</span><span class="operator">(</span><span class="string">'usd'</span><span class="operator">,</span><span class="string">'alpha'</span><span class="operator">);</span> <span class="variable">$curr</span> <span class="operator">=</span> <span class="variable">code2currency</span><span class="operator">(</span><span class="string">'usd'</span><span class="operator">,</span><span class="variable">LOCALE_CURR_ALPHA</span><span class="operator">);</span> </code></code></pre> <p>The codesets currently supported are:</p> <dl> <dt id="alpha-LOCALE_CURR_ALPHA"><b>alpha, LOCALE_CURR_ALPHA</b></dt> <dd> <p>This is a set of three-letter (uppercase) codes from ISO 4217 such as EUR for Euro.</p> <p>Two of the codes specified by the standard (XTS which is reserved for testing purposes and XXX which is for transactions where no currency is involved) are omitted.</p> <p>This is the default code set.</p> </dd> <dt id="num-LOCALE_CURR_NUMERIC"><b>num, LOCALE_CURR_NUMERIC</b></dt> <dd> <p>This is the set of three-digit numeric codes from ISO 4217.</p> </dd> </dl> <h1 id="ROUTINES">ROUTINES</h1> <dl> <dt id="code2currency-CODE-CODESET-"><b>code2currency ( CODE [,CODESET] )</b></dt> <dd> </dd> <dt id="currency2code-NAME-CODESET-"><b>currency2code ( NAME [,CODESET] )</b></dt> <dd> </dd> <dt id="currency_code2code-CODE-CODESET-CODESET2-"><b>currency_code2code ( CODE ,CODESET ,CODESET2 )</b></dt> <dd> </dd> <dt id="all_currency_codes-CODESET-"><b>all_currency_codes ( [CODESET] )</b></dt> <dd> </dd> <dt id="all_currency_names-CODESET-"><b>all_currency_names ( [CODESET] )</b></dt> <dd> </dd> <dt id="Locale::Currency::rename_currency-CODE-NEW_NAME-CODESET-"><b>Locale::Currency::rename_currency ( CODE ,NEW_NAME [,CODESET] )</b></dt> <dd> </dd> <dt id="Locale::Currency::add_currency-CODE-NAME-CODESET-"><b>Locale::Currency::add_currency ( CODE ,NAME [,CODESET] )</b></dt> <dd> </dd> <dt id="Locale::Currency::delete_currency-CODE-CODESET-"><b>Locale::Currency::delete_currency ( CODE [,CODESET] )</b></dt> <dd> </dd> <dt id="Locale::Currency::add_currency_alias-NAME-NEW_NAME-"><b>Locale::Currency::add_currency_alias ( NAME ,NEW_NAME )</b></dt> <dd> </dd> <dt id="Locale::Currency::delete_currency_alias-NAME-"><b>Locale::Currency::delete_currency_alias ( NAME )</b></dt> <dd> </dd> <dt id="Locale::Currency::rename_currency_code-CODE-NEW_CODE-CODESET-"><b>Locale::Currency::rename_currency_code ( CODE ,NEW_CODE [,CODESET] )</b></dt> <dd> </dd> <dt id="Locale::Currency::add_currency_code_alias-CODE-NEW_CODE-CODESET-"><b>Locale::Currency::add_currency_code_alias ( CODE ,NEW_CODE [,CODESET] )</b></dt> <dd> </dd> <dt id="Locale::Currency::delete_currency_code_alias-CODE-CODESET-"><b>Locale::Currency::delete_currency_code_alias ( CODE [,CODESET] )</b></dt> <dd> <p>These routines are all documented in the Locale::Codes::API man page.</p> </dd> </dl> <h1 id="SEE-ALSO">SEE ALSO</h1> <dl> <dt id="Locale::Codes"><b>Locale::Codes</b></dt> <dd> <p>The Locale-Codes distribution.</p> </dd> <dt id="Locale::Codes::API"><b>Locale::Codes::API</b></dt> <dd> <p>The list of functions supported by this module.</p> </dd> <dt id="http:-www.iso.org-iso-support-currency_codes_list-1.htm"><b>http://www.iso.org/iso/support/currency_codes_list-1.htm</b></dt> <dd> <p>The ISO 4217 data.</p> </dd> </dl> <h1 id="AUTHOR">AUTHOR</h1> <p>See Locale::Codes for full author history.</p> <p>Currently maintained by Sullivan Beck (sbeck@cpan.org).</p> <h1 id="COPYRIGHT">COPYRIGHT</h1> <pre><code><code> Copyright (c) 1997-2001 Canon Research Centre Europe (CRE). Copyright (c) 2001 Michael Hennecke Copyright (c) 2001-2010 Neil Bowers Copyright (c) 2010-2012 Sullivan Beck</code></code></pre> <p>This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.</p> </body> </html>
amidoimidazol/bio_info
Beginning Perl for Bioinformatics/html/lib/Locale/Currency.html
HTML
mit
6,828
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DesktopCharacter.Model.Locator; using DesktopCharacter.ViewModel.SettingTab; namespace DesktopCharacter.ViewModel { class SettingViewModel : Livet.ViewModel { public LauncherSettingViewModel LauncherSetting { set; private get; } public CharacterSettingViewModel CharacterSetting { set; private get; } public TwitterSettingViewModel TwitterSetting { set; private get; } public CodicSettingTabViewModel CodicSettingTab { set; private get; } public SlackSettingViewModel SlackSetting { set; private get; } public SettingViewModel() { } public void ClosedEvent() { TwitterSetting.OnClose(); CodicSettingTab.OnClose(); CharacterSetting.OnClose(); SlackSetting.OnClose(); LauncherSetting.OnClose(); ServiceLocator.Instance.ClearConfigBaseContext(); } } }
Babumi/DesktopCharacter
DesktopCharacter/ViewModel/SettingViewModel.cs
C#
mit
1,063
.style-target { font-family: Arial, sans-serif; }
Pilatch/AssetLoader
tst/css/sans-serif.css
CSS
mit
50
TF.listen();
rivers/tabfusion
src/listener.js
JavaScript
mit
13
<?php /** * Close.io Api Wrapper - LLS Internet GmbH - Loopline Systems. * * @see https://github.com/loopline-systems/closeio-api-wrapper for the canonical source repository * * @copyright Copyright (c) 2014 LLS Internet GmbH - Loopline Systems (http://www.loopline-systems.com) * @license https://github.com/loopline-systems/closeio-api-wrapper/blob/master/LICENSE (MIT Licence) */ declare(strict_types=1); namespace LooplineSystems\CloseIoApiWrapper\Model; use LooplineSystems\CloseIoApiWrapper\Library\Exception\InvalidParamException; use LooplineSystems\CloseIoApiWrapper\Library\Exception\InvalidUrlException; use LooplineSystems\CloseIoApiWrapper\Library\JsonSerializableHelperTrait; use LooplineSystems\CloseIoApiWrapper\Library\ObjectHydrateHelperTrait; class Lead implements \JsonSerializable { const LEAD_STATUS_POTENTIAL = 'Potential'; const LEAD_STATUS_BAD_FIT = 'Bad Fit'; const LEAD_STATUS_QUALIFIED = 'Qualified'; const LEAD_STATUS_CUSTOMER = 'Customer'; use ObjectHydrateHelperTrait; use JsonSerializableHelperTrait; /** * @var string */ private $id; /* * @var string */ private $status_id; /** * @var string */ private $status; /* * @var string */ private $status_label; /** * @var string */ private $description; /** * @var string */ private $display_name; /** * @var Address[] */ private $addresses; /** * @var string */ private $organization; /** * @var string */ private $created_by; /** * @var string */ private $url; /** * @var Task[] */ private $tasks; /** * @var string */ private $name; /** * @var Contact[] */ private $contacts; /** * @var string */ private $date_created; /** * @var array */ private $custom; /** * @var string */ private $updated_by_name; /** * @var string */ private $created_by_name; /** * @var Opportunity[] */ private $opportunities; /** * @var string */ private $html_url; /** * @var string */ private $updated_by; /** * @var string */ private $date_updated; /** * @var string */ private $organization_id; /** * @param array $data * * @throws InvalidParamException */ public function __construct(array $data = null) { if ($data) { // custom is not a class and should be set separately if (isset($data['custom'])) { $this->setCustom($data['custom']); unset($data['custom']); } // child objects $nestedObjects = ['contacts', 'tasks', 'addresses', 'opportunities', 'custom']; $this->hydrate($data, $nestedObjects); } } /** * @return string */ public function getId() { return $this->id; } /** * @param string $id * * @return $this */ public function setId($id) { $this->id = $id; return $this; } /** * @return Address[] */ public function getAddresses() { return $this->addresses; } /** * @param Address $address * * @return $this */ public function addAddress(Address $address) { $this->addresses[] = $address; return $this; } /** * @param Address[] $addresses * * @return $this */ public function setAddresses(array $addresses) { $this->addresses = $addresses; return $this; } /** * @return Contact[] */ public function getContacts() { return $this->contacts; } /** * @param Contact $contact * * @return $this */ public function addContact(Contact $contact) { $this->contacts[] = $contact; return $this; } /** * @param Contact[] $contacts * * @return $this */ public function setContacts(array $contacts) { $this->contacts = $contacts; return $this; } /** * @return string */ public function getCreatedBy() { return $this->created_by; } /** * @param string $created_by * * @return $this */ public function setCreatedBy($created_by) { $this->created_by = $created_by; return $this; } /** * @return array */ public function getCustom() { return $this->custom; } /** * @param array $custom * * @return $this */ public function setCustom($custom) { $this->custom = $custom; return $this; } /** * Sets the value of a custom field. By passing a `null` value the field * will be unset from the lead. * * @param string $name The name or ID of the field * @param mixed $value The value * * @return $this */ public function setCustomField(string $name, $value) { $this->custom[$name] = $value; return $this; } /** * @return string */ public function getDateCreated() { return $this->date_created; } /** * @param string $date_created * * @return $this */ public function setDateCreated($date_created) { $this->date_created = $date_created; return $this; } /** * @return string */ public function getDescription() { return $this->description; } /** * @param string $description * * @return $this */ public function setDescription($description) { $this->description = $description; return $this; } /** * @return string */ public function getDisplayName() { return $this->display_name; } /** * @param string $display_name * * @return $this */ public function setDisplayName($display_name) { $this->display_name = $display_name; return $this; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name * * @return $this */ public function setName($name) { $this->name = $name; return $this; } /** * @return Opportunity[] */ public function getOpportunities() { return $this->opportunities; } /** * @param Opportunity[] $opportunities * * @return $this */ public function setOpportunities(array $opportunities) { $this->opportunities = $opportunities; return $this; } /** * @return string */ public function getOrganization() { return $this->organization; } /** * @param string $organization * * @return $this */ public function setOrganization($organization) { $this->organization = $organization; return $this; } /** * @return string */ public function getStatusId() { return $this->status_id; } /** * @param string $status * * @return $this */ public function setStatusId($status) { $this->status_id = $status; return $this; } /** * @return string */ public function getStatus() { return $this->status; } /** * @param string $status */ public function setStatus($status) { $this->status = $status; return $this; } /** * @return string */ public function getStatusLabel() { return $this->status_label; } /** * @param string $status_label * * @return $this */ public function setStatusLabel($status_label) { $this->status_label = $status_label; return $this; } /** * @return Task[] */ public function getTasks() { return $this->tasks; } /** * @param Task[] $tasks * * @return $this */ public function setTasks($tasks) { $this->tasks = $tasks; return $this; } /** * @return string */ public function getUrl() { return $this->url; } /** * @param string $url * * @return $this * * @throws InvalidUrlException */ public function setUrl($url) { // validate url if (filter_var($url, FILTER_VALIDATE_URL)) { $this->url = $url; } else { throw new InvalidUrlException('"' . $url . '" is not a valid URL'); } return $this; } /** * @return string */ public function getCreatedByName() { return $this->created_by_name; } /** * @param string $created_by_name * * @return $this */ public function setCreatedByName($created_by_name) { $this->created_by_name = $created_by_name; return $this; } /** * @return string */ public function getDateUpdated() { return $this->date_updated; } /** * @param string $date_updated * * @return $this */ public function setDateUpdated($date_updated) { $this->date_updated = $date_updated; return $this; } /** * @return string */ public function getHtmlUrl() { return $this->html_url; } /** * @param string $html_url * * @return $this */ public function setHtmlUrl($html_url) { $this->html_url = $html_url; return $this; } /** * @return string */ public function getOrganizationId() { return $this->organization_id; } /** * @param string $organization_id * * @return $this */ public function setOrganizationId($organization_id) { $this->organization_id = $organization_id; return $this; } /** * @return string */ public function getUpdatedBy() { return $this->updated_by; } /** * @param string $updated_by * * @return $this */ public function setUpdatedBy($updated_by) { $this->updated_by = $updated_by; return $this; } /** * @return string */ public function getUpdatedByName() { return $this->updated_by_name; } /** * @param string $updated_by_name * * @return $this */ public function setUpdatedByName($updated_by_name) { $this->updated_by_name = $updated_by_name; return $this; } public function __set(string $name, $value) { if (strpos($name, 'custom.') === 0) { @trigger_error('Setting a custom field using the $object->$fieldName syntax is deprecated since version 0.8. Use the setCustomField() method instead.', E_USER_DEPRECATED); $this->custom[substr($name, 7)] = $value; } else { $this->$name = $value; } } }
loopline-systems/closeio-api-wrapper
src/Model/Lead.php
PHP
mit
11,400
package com.example.apahlavan1.top10downloader; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
AriaPahlavan/Android-Apps
Top10Downloader/app/src/androidTest/java/com/example/apahlavan1/top10downloader/ApplicationTest.java
Java
mit
369
#ifndef BLOWFISH_H #define BLOWFISH_H ///////////////////////////////////////////////////////////////////////// // ** NOTICE ** ///////////////////////////////////////////////////////////////////////// // The following resources are required by this module (or submodules): // #define BLOWFISHDATA 21000 // Since this is a reusable class, we don't have access to a resource file. // // 1) Make sure that the above defines are "rolled into" your project's // resource file. Select "Resource Set Includes" on the View menu and add // this header file to the "Read-only symbol directives" listbox. // 2) Make sure your project includes the associated resources in its // resource file. // // Also... // // BLOWFISHDATA BINARY MOVEABLE PURE "<path>Blowfish\\BLOWFISH.DAT" // // This line should be added to the project's resource file, in a // custom section called "BINARY" (or you can cut and paste the item // using the resource viewer, and then edit the path in its properties.) // Or just import a resource, use BINARY type, and browse for the file, then // rename the resource from IDR_... to BLOWFISHDATA. // We want to exclude the remainder of the include file when dealing with App Studio. #ifndef RC_INVOKED ///////////////////////////////////////////////////////////////////////// #include "..\..\StandardTypes.h" // For uHuge type // Max key size for algorithms is 56 bytes/448 bits. const short MAXKEYBYTES = 56; // N represents the number of iterations through F() // for each encrypted block. 16 is extremely secure. const short N = 16; typedef struct { unsigned long P[N + 2]; unsigned long S[4][256]; } BLOWFISH_SUBKEYS; class BlowFish { protected: BLOWFISH_SUBKEYS SubKeys; inline unsigned long F(unsigned long x); inline void Encipher( unsigned long *xl, unsigned long *xr ); inline void Decipher( unsigned long *xl, unsigned long *xr ); public: BlowFish() : // Init vars. bInitialized( false ) {} ~BlowFish() {} // Make sure that key is UNSIGNED! bool InitializeSubKeys( unsigned char* pszKey, unsigned int nKeyLen ); bool bInitialized; bool Encrypt( void* pBuffer, int nBufferLength ); bool Decrypt( void* pBuffer, int nBufferLength ); bool StreamEncrypt( void* pBuffer, int nBufferLength ); bool StreamDecrypt( void* pBuffer, int nBufferLength ); }; #endif // RC_INVOKED #endif // BLOWFISH
moodboom/Reusable
c++/Win32/MFC/Crypto/Blowfish/Blowfish.h
C
mit
2,461
# Agenda _A monthly event manager_ Check out the [DEMO](http://danielemeli.com/agenda) ## Setup The project is already compiled in the /dist folder. By the way, it you want to compile it by yourself, here is the 3 steps. - Install [Node.js](https://nodejs.org) and [npm](https://www.npmjs.com/) - In the root folder run `npm i` then `gulp build` - Run a php server and go into the dist folder with your browser ## Dependencies Agenda is based on [Vue.js](https://vuejs.org/) for the management of the UI, on [flickity](http://flickity.metafizzy.co/) to controll the months sliding and [lodash](https://lodash.com/) because we always need lodash :) ## Notes - Written in HTML5, SASS, ES6 and compiled using gulp. Use `gulp watch` to development purpose. Use `gulp build` to compile for prod. - The calendar moves automatically to the current month and the single day view automatically move to the current hour
dnlml/agenda
README.md
Markdown
mit
923
import pymongo def connect (): ''' Create the connection to the MongoDB and create 3 collections needed ''' try: # Create the connection to the local host conn = pymongo.MongoClient() print 'MongoDB Connection Successful' except pymongo.errors.ConnectionFailure, err: print 'MongoDB Connection Unsuccessful' return False # This is the name of the database -'GtownTwitter' db = conn['GtownTwitter_PROD'] return db
Macemann/Georgetown-Capstone
app/db/connect.py
Python
mit
493
/* Customized CSS for jQuery UI: simple info button and box. */ .ui-widget-content { font-family: Verdana,Arial,sans-serif; font-size:11px; } /* trim space around info button */ .ui-button-text-only .ui-button-text { padding: 0px; } .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 0px solid #000000; } /* changing dialog close button */ .ui-dialog-titlebar-close { outline-width: 0px !important; background-color: transparent !important; background-image: url('images/icon-close-16.png') !important; background-repeat:no-repeat !important; } /* changing dialog close button */ .ui-dialog-titlebar-close:hover, .ui-dialog-titlebar-close:focus { background-color: transparent !important; background-image: url('images/icon-close-16.png') !important; background-repeat:no-repeat !important; } /* hide the default "x" close image */ .ui-dialog-titlebar-close span { display:none !important; } /* translucent background */ .ui-dialog { opacity: .90; width:600px; }
playsign/fidemo
css/info.css
CSS
mit
1,062
<div class="commune_descr limited"> <p> Bettainvillers est un village situé dans le département de Meurthe-et-Moselle en Lorraine. Elle totalisait 194 habitants en 2008.</p> <p>Si vous pensez venir habiter à Bettainvillers, vous pourrez aisément trouver une maison à acheter. </p> <p>Le nombre de logements, à Bettainvillers, était réparti en 2011 en dix appartements et 101 maisons soit un marché plutôt équilibré.</p> <p>À coté de Bettainvillers sont localisées les villes de <a href="{{VLROOT}}/immobilier/mont-bonvillers_54084/">Mont-Bonvillers</a> située à 5&nbsp;km, 960 habitants, <a href="{{VLROOT}}/immobilier/anderny_54015/">Anderny</a> localisée à 2&nbsp;km, 303 habitants, <a href="{{VLROOT}}/immobilier/avril_54036/">Avril</a> à 4&nbsp;km, 764 habitants, <a href="{{VLROOT}}/immobilier/sancy_54491/">Sancy</a> située à 5&nbsp;km, 345 habitants, <a href="{{VLROOT}}/immobilier/mancieulles_54342/">Mancieulles</a> localisée à 2&nbsp;km, 1&nbsp;546 habitants, <a href="{{VLROOT}}/immobilier/tucquegnieux_54536/">Tucquegnieux</a> localisée à 1&nbsp;km, 2&nbsp;649 habitants, entre autres. De plus, Bettainvillers est située à seulement 28&nbsp;km de <a href="{{VLROOT}}/immobilier/metz_57463/">Metz</a>.</p> </div>
donaldinou/frontend
src/Viteloge/CoreBundle/Resources/descriptions/54066.html
HTML
mit
1,270
require 'compiler_helper' module Alf class Compiler describe Default, "join" do subject{ compiler.call(expr) } let(:right){ compact(an_operand) } let(:expr){ join(an_operand(leaf), right) } it_should_behave_like "a traceable compiled" it 'is a Join::Hash cog' do subject.should be_a(Engine::Join::Hash) end it 'has the correct left sub-cog' do subject.left.should be(leaf) end it 'has the correct right sub-cog' do subject.right.should be_a(Engine::Compact) end end end end
alf-tool/alf-core
spec/unit/alf-compiler/default/test_join.rb
Ruby
mit
620
@ru <p>На сервисе <a class="link" href="https://www.airbnb.ru/{{ config('cfg.airbnb_link') }}">Airbnb</a> по купону <span class="font-bold">{{ $coupon }}</span> можно получить скидку в 10 евро при бронировании жилья в {{ $city }}.</p> @en <p>You can get &euro;10 discount on <a class="link" href="https://www.airbnb.com/{{ config('cfg.airbnb_link') }}">Airbnb</a> with <span class="font-bold">{{ $coupon }}</span> coupon code.</p> @endru
ivacuum/hosting
resources/views/tpl/airbnb_coupon.blade.php
PHP
mit
504
<?php // This file assumes that you have included the nav walker from https://github.com/twittem/wp-bootstrap-navwalker // somewhere in your theme. ?> <?php if (!get_theme_mod('hide-header')) { ?> <header class="container-fluid"> <div class="row"> <div class="banner navbar navbar-default navbar-static-top affix" role="banner"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only"><?= __('Toggle navigation', 'sage'); ?></span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?= esc_url(home_url('/')); ?>"> <?php /** * Display logo from Appearance > Customize or blog name if logo not set */ has_custom_logo() ? Roots\Sage\Extras\sage_the_custom_logo() : bloginfo('name'); ?> </a> </div> <nav class="collapse navbar-collapse" role="navigation"> <?php if (has_nav_menu('primary_navigation')) : wp_nav_menu([ 'theme_location' => 'primary_navigation' , 'walker' => new wp_bootstrap_navwalker() , 'menu_class' => 'nav navbar-nav pull-right' ]); endif; ?> </nav> </div><!-- /.container --> </div><!-- /.navbar --> </div><!-- /.row --> <?php /** * Pull in header content defined by ACF plugin */ if (class_exists('acf')) { get_template_part('templates/components/header-content'); } ?> </header><!-- /.container-fluid --> <?php } ?>
allurewebsolutions/sage-starter
templates/header.php
PHP
mit
1,868
<?php /** * This file is part of the "litgroup/enumerable" package. * * (c) Roman Shamritskiy <roman@litgroup.ru> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Test\LitGroup\Enumerable; use LitGroup\Enumerable\Test\EnumerableTestCase; use Test\LitGroup\Enumerable\Fixtures\AnotherColorEnum; use Test\LitGroup\Enumerable\Fixtures\ColorEnum; use Test\LitGroup\Enumerable\Fixtures\DuplicateIndexEnum; use Test\LitGroup\Enumerable\Fixtures\FloatIndexedEnum; use Test\LitGroup\Enumerable\Fixtures\InvalidReturnTypeEnum; use Test\LitGroup\Enumerable\Fixtures\InvalidScalarReturnTypeEnum; use Test\LitGroup\Enumerable\Fixtures\SerializableEnum; use Test\LitGroup\Enumerable\Fixtures\NonFinalEnum; class EnumerableTest extends EnumerableTestCase { public function testIndex() { $this->assertEnumHasRawValues([ ColorEnum::RED => ColorEnum::red(), ColorEnum::GREEN => ColorEnum::green(), ColorEnum::BLUE => ColorEnum::blue(), ]); } public function testEquality() { $this->assertEquals(ColorEnum::red(), ColorEnum::red()); $this->assertNotEquals(ColorEnum::red(), ColorEnum::green()); $this->assertTrue(ColorEnum::red()->equals(ColorEnum::red())); $this->assertFalse(ColorEnum::red()->equals(ColorEnum::blue())); } public function testExceptionOnEqualityCheckOfDifferentTypes() { $this->expectException(\InvalidArgumentException::class); ColorEnum::red()->equals(AnotherColorEnum::red()); } public function testIdentity() { $this->assertSame(ColorEnum::red(), ColorEnum::red()); $this->assertNotSame(ColorEnum::red(), ColorEnum::green()); } public function testSwitchStatement() { switch (ColorEnum::green()) { case ColorEnum::green(): break; default: $this->fail('GREEN case had to be called.'); } } public function testGetValueOf() { $this->assertSame(ColorEnum::red(), ColorEnum::getValueOf(ColorEnum::RED)); $this->assertSame(ColorEnum::green(), ColorEnum::getValueOf(ColorEnum::GREEN)); $this->assertSame(ColorEnum::blue(), ColorEnum::getValueOf(ColorEnum::BLUE)); } public function testGetValueForNonExistentIndex() { $this->expectException(\OutOfBoundsException::class); ColorEnum::getValueOf('incorrect_index'); } public function testGetValues() { $this->assertSame( [ ColorEnum::RED => ColorEnum::red(), ColorEnum::GREEN => ColorEnum::green(), ColorEnum::BLUE => ColorEnum::blue(), ], ColorEnum::getValues() ); } public function testValuesForNonFinalEnum() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Enumerable class must be final, but "Test\LitGroup\Enumerable\Fixtures\NonFinalEnum" is not final'); NonFinalEnum::getValues(); } public function testEnumCannotBeSerializable() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Enumerable cannot be serializable, but enum class "Test\LitGroup\Enumerable\Fixtures\SerializableEnum" implements "Serializable" interface'); SerializableEnum::getValues(); } public function testInitializationExceptionOnDuplicateIndex() { $this->expectException(\LogicException::class); DuplicateIndexEnum::some(); } public function testOnlyStringOrIntCanBeUsedForIndex() { $this->expectException(\InvalidArgumentException::class); FloatIndexedEnum::one(); } public function testShouldThrowAnExceptionIfEnumMethodReturnsInstanceOfDifferentClass() { $this->expectException(\LogicException::class); InvalidReturnTypeEnum::getValues(); } public function testExceptionWhenEnumFactoryMethodReturnsScalarValue() { $this->expectException(\LogicException::class); InvalidScalarReturnTypeEnum::getValues(); } public function testClone(): void { $red = ColorEnum::red(); $this->expectException(\BadMethodCallException::class); $otherRed = clone $red; } public function testSerialize(): void { $red = ColorEnum::red(); $this->expectException(\BadMethodCallException::class); serialize($red); } }
LitGroup/enumerable.php
test/EnumerableTest.php
PHP
mit
4,578
require_relative "../lib/stressfactor" require "pry" file = GPX::GPXFile.new(:gpx_file => "examples/data/sample.gpx") pc = Stressfactor::PaceCalculator.new(file) pace = pc.calculate puts pace binding.pry
andrewhao/stressfactor
scripts/analyze_sample_gpx.rb
Ruby
mit
204
--- layout: ci_navbar_sidebar title: Coding Standards permalink: /practice/ci/coding_standards/ --- <div class="jumbotron"> <h1><small>Continuous Integration</small></h1> <h1>Coding Standards Check</h1> <p>Apply code analysis and styling checks and if unsatisfactory mark the build as a failure</p> </div> <div class="row"> <div id="start" class="col-md-10 col-md-offset-1" style="font-size:140%"> <h2>About</h2> <p>Code can be written that appears to perform the required task; however, is it coded with consistency, will it crash if the data input is not 100% correct, have any TODO tags been forgotten?</p> <p>We can run automated tests for these, and more, and then set our build result to fail if we do not get a satisfactory compliance result.</p> <h2>Options</h2> <p>Many packages are available; a search on the internet will return many results. Most will only perform part of the requirement. When selecting packages, try to include: code analysis, styling, open tasks and metrics. Other packages might also be required when handling the results.</p> <h3>Python Projects</h3> <p>The Python example below uses the following:</p> <ul> <li><h4>PYLINT</h4> <p>PyLint is a static code analyser of coding standards and quality.</p> <p>PyLint's tests include checking for docstrings, duplication, open tasks, PEP8 styling and bugs.</p> <p>It highlights problems and gives the code a score out of 10.</p> </li> <li> <h4>VIOLATIONS PLUGIN</h4> <p>This Jenkins plugin will display the PyLint results on the Jenkins view of the project.</p> </li> <li> <h4>TEXTFINDER PLUGIN</h4> <p>This Jenkins plugin will search text files against a regular expression. The result of which can be used to set a build to pass, fail, unstable.</p> </li> </ul> <h3>Java Projects</h3> <p>TODO</p> <h2>PyLint</h2> <h3>Prerequisites</h3> <h4>PYTHON PACKAGES</h4> <p><code>pip install pylint</code></p> <h3>Add to your Project</h3> <p>Select <button>Add build step</button> and choose "Execute Windows batch command".</p> <p>Enter in the Command box:</p> <pre>pylint project_name.py --output-format=parseable | tee pylint.out</pre> <p>You might need to drag this step to follow existing actions.</p> <h3>Explanation of Commands</h3> <p><code>Pylint project_name.py</code>: this starts the pylint application and tells it to analyse the specified python module.</p> <p>For multiple files names, just add them to the list. There is no current means of specifying <i>all files</i>. Writing a python file discovery function might be worthwhile.</p> <p>Is there a way of doing this programmatically? - <i>Under investigation.</i></p> <p><code>--output-format=parseable</code>: the output can be in many formats, including text and html. Parseable is a format that the Violations plugin can read.</p> <p><code>| tee pylint.out</code>: The pipe (|) is a means of redirecting the output, tee sends the output to both the screen and to a file, in this case a file named pylint.out.</p> <p><img src="../../../images/ci/coding_standards_pylint_command.png" alt="Screenshot of PyLint configuration in Jenkins" class = "img-thumbnail"/></p> <h3>Example</h3> <p>Click <a href="/practice/ci_pylint_text_output">here</a> for a simple example of PyLint's text output for the calculator.</p> <p>Lint report graph</p> <h3>Customization</h3> <p>PyLint tests can be tailored to your requires by using the a config file (rcfile). Enter <code>pylint --help</code> in the command line for info. <code>--generate-rcfile, --rcfile=&lt;file&gt;</code></p> <h2>Violations Plugin</h2> <h3>Prerequisites</h3> <p>"Violations plugin"</p> <h3>Add to your Project</h3> <p>Select <button>Add post-build action</button> and choose <samp>Report Violations</samp>.</p> <p>A long list of options will appear; we only need to complete the line for <samp>pylint</samp>. Place the file name in the box provided, e.g. <code>**/pylint.out</code></p> <h3>Example</h3> <p><img src="../../../images/ci/coding_standards_violations_report.png" alt="Screenshot of Violations report" class = "img-thumbnail"></p> <p>Running the project a few times will provide a graph that can be drilled down to the detail.</p> <p><img src="../../../images/ci/coding_standards_pylint_report_graph.png" alt="Screenshot of PyLint report" class = "img-thumbnail"></p> <p><img src="../../../images/ci/coding_standards_pylint_report_drill_down_1.png" alt="Screenshot of PyLint report drill down level 1" class = "img-thumbnail"></p> <p><img src="../../../images/ci/coding_standards_pylint_report_drill_down_2.png" alt="Screenshot of PyLint report drill down level 2" class = "img-thumbnail"></p> <h2>TextFinder</h2> <h3>Prerequisites</h3> <p>"TextFinder plugin"</p> <h3>Add to your Project</h3> <p>In this example, we scan the output of PyLint for the rating. If the rating is lower than eight the build is marked as unstable.</p> <p>Select <button>Add post-build action</button> and choose "Jenkins Text Finder".</p> <p>Enter the file name of the PyLint output file, for example, pylint.out.</p> <p>For the "Regular expression" enter: <code>"Your code has been rated at ([0-7]).\d*\/10"</code></p> <p>Then tick the "Unstable if found" option.</p> <p>Note that using "Succeed if found" will override previously obtained Fail results.</p> <p><img src="../../../images/ci/coding_standards_text_finder.png" class="img-thumbnail" alt="Screenshot of TextFinder"></p> <h3>Explanation of Regular Expression</h3> <p>This expression checks for the string "Your code has been rated at".</p> <p>Then it checks for 0 to 7, a decimal point, and any number of digits.</p> <p>Then it checks for "/10" to check that the value has been scored out of ten.</p> <p>If a rating less than 8 out of ten is present, the expression is true.</p> <p>If a rating 8 or more out of ten is present, the expression is false.</p> <h3>Example</h3> <p>In the screenshot below you can see build #82 and #83 set to unstable due to a low score obtained in PyLint.</p> <p><img src="../../../images/ci/coding_standards_pylint_affect_in_build_history.png" class="img-thumbnail" alt="Screenshot showing unstable build in Build History"></p> <h2>Open Tasks</h2> <p>The PyLint report includes Open Tasks; nevertheless, if you want the Open Tasks count on the project view screen, you need the Open Tasks Plugin.</p> <p>If required, add the plugin and configure it with the open task keywords, such as, TODO and FIXME.</p> <p><img src="../../../images/ci/coding_standards_open_task_config.png" class="img-thumbnail" alt="Screenshot showing Open Tasks configuration"></p> <p>After a build, the count will show on the project view that one can select and drill down.</p> <p><img src="../../../images/ci/coding_standards_open_task_result.png" class="img-thumbnail" alt="Screenshot showing Open Tasks count"></p> <p><img src="../../../images/ci/coding_standards_open_task_result_drill_down.png" class="img-thumbnail" alt="Screenshot showing Open Tasks drill down"></p> </div> </div>
LandRegistry/landregistry.github.io
practice/ci/coding_standards.html
HTML
mit
7,617
$(document).ready(function() { $(document).on('submit', '.status-button', function(e) { e.preventDefault(); var joinButton = e.target $.ajax(joinButton.action, { method: 'PATCH', data: $(this).serialize() }) .done(function(data) { gameDiv = $(joinButton).parent(); gameDiv.replaceWith(data); }) .fail(function() { alert("Failure!"); }); }); });
nyc-dragonflies-2015/whos_got_next
app/assets/javascripts/players.js
JavaScript
mit
412
# consul-template-install Installs [Hashicorp's Consul Template] (https://github.com/hashicorp/consul-template) ## Role Variables ```yml --- --- consul_template_app: name: consul_template version: 0.11.0 arch: linux_amd64 file_owner: consul file_group: consul consul_template_install: dir : /usr/local/bin download_location: https://github.com/hashicorp/consul-template/releases/download file_list: - consul-template ``` Example Playbook ---------------- ```yml - hosts: local sudo: true gather_facts: true roles: - { role: marcelocorreia.consul_template-install } - vars: consul_template_app: name: consul_template version: 0.11.0 arch: linux_amd64 file_owner: consul file_group: consul consul_template_install: dir : /usr/local/bin download_location: https://github.com/hashicorp/consul-template/releases/download file_list: - consul-template ``` License ------- MIT Author Information ------------------ Some useful stuff at: - [https://github.com/marcelocorreia](https://github.com/marcelocorreia) - [https://galaxy.ansible.com/list#/users/15516](https://galaxy.ansible.com/list#/users/15516) - [https://hub.docker.com/u/marcelocorreia/](https://hub.docker.com/u/marcelocorreia/) - Any issues, pull-request are welcome
marcelocorreia/consul-template-install
README.md
Markdown
mit
1,369
require_relative 'spec_helper.rb' feature "can deal cards" do before do create_and_join_room("jnmandal", "bsheridan12") end scenario "allows you to choose amount of cards dealt" do in_browser(:one) do expect(page).to have_field "initial-deal-count" end end scenario "deal cards button deals cards" do in_browser(:one) do deal_cards(4) within "div.player-hand" do expect(page).to have_selector ".card" end end end scenario "dealt cards viewable by other user" do in_browser(:one) do deal_cards(4) end in_browser(:two) do within "div.player-hand" do expect(page).to have_selector ".card" end end end scenario "does not deal cards when user enters 0" do in_browser(:one) do deal_cards(0) end in_browser(:two) do within "div.player-hand" do page.assert_no_selector(".card") end end end scenario "deals correct number of cards" do in_browser(:one) do deal_cards(5) within "div.player-hand" do page.assert_selector(".card", count: 5) end end end end
KYoon/Stacks-on-Deck
spec/capybara/deal_cards_spec.rb
Ruby
mit
1,146
function OrganizationController() { // injetando dependência 'ngInject'; // ViewModel const vm = this; console.log('OrganizationController'); } export default { name: 'OrganizationController', fn: OrganizationController };
dnaloco/digitala
app/erp/js/controllers/human-resource/organiz.js
JavaScript
mit
242
--- layout: home5 excerpt: "A minimal Jekyll theme for your blog by designer Michael Rose." tags: [Jekyll, theme, responsive, blog, template] ---
harshnisar/insights_gamma
home3/index.md
Markdown
mit
151
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2016, Jianfeng Chen <jchen37@ncsu.edu> # vim: set ts=4 sts=4 sw=4 expandtab smartindent: # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from __future__ import division def dist(a, b): return sum((i-j)**2 for i, j in zip(a, b)) def GD(PF0, PFc): up = 0 for i in PFc: up += min([dist(i, j) for j in PF0]) return up**0.5 / (len(PFc))
Ginfung/FSSE
Metrics/gd.py
Python
mit
1,445
import React, { Component } from 'react'; import Header from './Header'; import MainSection from './MainSection'; export default class App extends Component { render() { return ( <div> <Header/> <MainSection/> </div> ); } }
loggur/react-redux-provide
examples/todomvc/components/App.js
JavaScript
mit
265
import unittest from unittest import skip from decimal import Decimal from cnab240 import errors from cnab240.bancos import itau from tests.data import get_itau_data_from_file class TestRegistro(unittest.TestCase): def setUp(self): itau_data = get_itau_data_from_file() self.header_arquivo = itau_data['header_arquivo'] self.seg_p = itau_data['seg_p1'] self.seg_p_str = itau_data['seg_p1_str'] self.seg_q = itau_data['seg_q1'] self.seg_q_str = itau_data['seg_q1_str'] def test_leitura_campo_num_decimal(self): self.assertEqual(self.seg_p.valor_titulo, Decimal('100.00')) def test_escrita_campo_num_decimal(self): # aceitar somente tipo Decimal with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = 10.0 with self.assertRaises(errors.TipoError): self.seg_p.valor_titulo = '' # Testa se as casas decimais estao sendo verificadas with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('100.2') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1001') with self.assertRaises(errors.NumDecimaisError): self.seg_p.valor_titulo = Decimal('1.000') # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.seg_p.valor_titulo = Decimal('10000000008100.21') # armazemamento correto de um decimal self.seg_p.valor_titulo = Decimal('2.13') self.assertEqual(self.seg_p.valor_titulo, Decimal('2.13')) def test_leitura_campo_num_int(self): self.assertEqual(self.header_arquivo.controle_banco, 341) def test_escrita_campo_num_int(self): # aceitar somente inteiros (int e long) with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = 10.0 with self.assertRaises(errors.TipoError): self.header_arquivo.controle_banco = '' # verifica se o numero de digitos esta sendo verificado with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 12345678234567890234567890 with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.controle_banco = 1234 # verifica valor armazenado self.header_arquivo.controle_banco = 5 self.assertEqual(self.header_arquivo.controle_banco, 5) def test_leitura_campo_alfa(self): self.assertEqual(self.header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') @skip def test_escrita_campo_alfa(self): # Testa que serao aceitos apenas unicode objects with self.assertRaises(errors.TipoError): self.header_arquivo.cedente_nome = 'tracy' # Testa que strings mais longas que obj.digitos nao serao aceitas with self.assertRaises(errors.NumDigitosExcedidoError): self.header_arquivo.cedente_convenio = '123456789012345678901' # Testa que o valor atribuido foi guardado no objeto self.header_arquivo.cedente_nome = 'tracy' self.assertEqual(self.header_arquivo.cedente_nome, 'tracy') def test_fromdict(self): header_dict = self.header_arquivo.todict() header_arquivo = itau.registros.HeaderArquivo(**header_dict) self.assertEqual(header_arquivo.cedente_nome, 'TRACY TECNOLOGIA LTDA ME') self.assertEqual(header_arquivo.nome_do_banco, 'BANCO ITAU SA') def test_necessario(self): self.assertTrue(self.seg_p) seg_p2 = itau.registros.SegmentoP() self.assertFalse(seg_p2.necessario()) seg_p2.controle_banco = 33 self.assertFalse(seg_p2.necessario()) seg_p2.vencimento_titulo = 10102012 self.assertTrue(seg_p2.necessario()) def test_unicode(self): def unicode_test(seg_instance, seg_str): seg_gen_str = str(seg_instance) self.assertEqual(len(seg_gen_str), 240) self.assertEqual(len(seg_str), 240) self.assertEqual(seg_gen_str, seg_str) unicode_test(self.seg_p, self.seg_p_str) unicode_test(self.seg_q, self.seg_q_str) if __name__ == '__main__': unittest.main()
Trust-Code/python-cnab
tests/test_registro.py
Python
mit
4,409
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: An extra interface implemented by the material system // implementation of vgui::ISurface // // $Revision: $ // $NoKeywords: $ //===========================================================================// #ifndef IMATSYSTEMSURFACE_H #define IMATSYSTEMSURFACE_H #ifdef _WIN32 #pragma once #endif #include <vgui/VGUI.h> #include "vgui/ISurface.h" //----------------------------------------------------------------------------- // Forward declarations //----------------------------------------------------------------------------- class VMatrix; class IMaterial; struct InputEvent_t; //----------------------------------------------------------------------------- // Callbacks for mouse getting + setting //----------------------------------------------------------------------------- typedef void (*GetMouseCallback_t)(int &x, int &y); typedef void (*SetMouseCallback_t)(int x, int y); //----------------------------------------------------------------------------- // Callbacks for sound playing //----------------------------------------------------------------------------- typedef void (*PlaySoundFunc_t)(const char *pFileName); //----------------------------------------------------------------------------- // // An extra interface implemented by the material system implementation of vgui::ISurface // //----------------------------------------------------------------------------- #define MAT_SYSTEM_SURFACE_INTERFACE_VERSION "MatSystemSurface008" class IMatSystemSurface : public vgui::ISurface { public: // Hook needed to get input to work. // If the app drives the input (like the engine needs to do for VCR mode), // it can set bLetAppDriveInput to true and call HandleInputEvent for the input events. virtual void AttachToWindow( void *hwnd, bool bLetAppDriveInput=false ) = 0; // Tells the surface to ignore windows messages virtual void EnableWindowsMessages( bool bEnable ) = 0; // Starts, ends 3D painting // NOTE: These methods should only be called from within the paint() // method of a panel. virtual void Begin3DPaint( int iLeft, int iTop, int iRight, int iBottom, bool bRenderToTexture = true ) = 0; virtual void End3DPaint() = 0; // NOTE: This also should only be called from within the paint() // method of a panel. Use it to disable clipping for the rendering // of this panel. virtual void DisableClipping( bool bDisable ) = 0; virtual void GetClippingRect( int &left, int &top, int &right, int &bottom, bool &bClippingDisabled ) = 0; // <<<<< NOTE: output flag is *disabled* state, not enabled, to match the rest of the interface virtual void SetClippingRect( int left, int top, int right, int bottom ) = 0; // Prevents vgui from changing the cursor virtual bool IsCursorLocked() const = 0; // Sets the mouse get + set callbacks virtual void SetMouseCallbacks( GetMouseCallback_t getFunc, SetMouseCallback_t setFunc ) = 0; // Installs a function to play sounds virtual void InstallPlaySoundFunc( PlaySoundFunc_t soundFunc ) = 0; // Some drawing methods that cannot be accomplished under Win32 virtual void DrawColoredCircle( int centerx, int centery, float radius, int r, int g, int b, int a ) = 0; virtual int DrawColoredText( vgui::HFont font, int x, int y, int r, int g, int b, int a, PRINTF_FORMAT_STRING const char *fmt, ... ) = 0; // Draws text with current font at position and wordwrapped to the rect using color values specified virtual void DrawColoredTextRect( vgui::HFont font, int x, int y, int w, int h, int r, int g, int b, int a, PRINTF_FORMAT_STRING const char *fmt, ... ) = 0; virtual void DrawTextHeight( vgui::HFont font, int w, int& h, PRINTF_FORMAT_STRING const char *fmt, ... ) = 0; // Returns the length of the text string in pixels virtual int DrawTextLen( vgui::HFont font, PRINTF_FORMAT_STRING const char *fmt, ... ) = 0; // Draws a panel in 3D space. Assumes view + projection are already set up // Also assumes the (x,y) coordinates of the panels are defined in 640xN coords // (N isn't necessary 480 because the panel may not be 4x3) // The width + height specified are the size of the panel in world coordinates virtual void DrawPanelIn3DSpace( vgui::VPANEL pRootPanel, const VMatrix &panelCenterToWorld, int nPixelWidth, int nPixelHeight, float flWorldWidth, float flWorldHeight ) = 0; // Binds a material to a surface texture ID virtual void DrawSetTextureMaterial( int id, IMaterial *pMaterial ) = 0; // Handles an input event, returns true if the event should be filtered from the rest of the game virtual bool HandleInputEvent( const InputEvent_t &event ) = 0; virtual void Set3DPaintTempRenderTarget( const char *pRenderTargetName ) = 0; virtual void Reset3DPaintTempRenderTarget( void ) = 0; // Gets a material bound to a surface texture ID virtual IMaterial *DrawGetTextureMaterial( int id ) = 0; virtual void GetFullscreenViewportAndRenderTarget( int & x, int & y, int & w, int & h, ITexture **ppRenderTarget ) = 0; virtual void SetFullscreenViewportAndRenderTarget( int x, int y, int w, int h, ITexture *pRenderTarget ) = 0; }; #endif // IMATSYSTEMSURFACE_H
BerntA/tfo-code
public/VGuiMatSurface/IMatSystemSurface.h
C
mit
5,197
#!/usr/bin/env python3 # # Copyright (c) 2017 Nick Douma # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from argparse import ArgumentParser, ArgumentTypeError import datetime import json import re import urllib.error import urllib.parse import urllib.request import sys ISO8601 = r"^(\d{4})-?(\d{2})-?(\d{2})?[T ]?(\d{2}):?(\d{2}):?(\d{2})" def iso8601_to_unix_timestamp(value): try: return int(value) except ValueError: pass matches = re.match(ISO8601, value) if not matches: raise ArgumentTypeError("Argument is not a valid UNIX or ISO8601 " "timestamp.") return int(datetime.datetime( *[int(m) for m in matches.groups()])).timestamp() def hex_value(value): value = value.replace("#", "") if not re.match(r"^[a-f0-9]{6}$", value): raise ArgumentTypeError("Argument is not a valid hex value.") return value parser = ArgumentParser(description="Send notifications using Slack") parser.add_argument("--webhook-url", help="Webhook URL.", required=True) parser.add_argument("--channel", help="Channel to post to (prefixed with #), " "or a specific user (prefixed with @).") parser.add_argument("--username", help="Username to post as") parser.add_argument("--title", help="Notification title.") parser.add_argument("--title_link", help="Notification title link.") parser.add_argument("--color", help="Sidebar color (as a hex value).", type=hex_value) parser.add_argument("--ts", help="Unix timestamp or ISO8601 timestamp " "(will be converted to Unix timestamp).", type=iso8601_to_unix_timestamp) parser.add_argument("message", help="Notification message.") args = parser.parse_args() message = {} for param in ["channel", "username"]: value = getattr(args, param) if value: message[param] = value attachment = {} for param in ["title", "title_link", "color", "ts", "message"]: value = getattr(args, param) if value: attachment[param] = value attachment['fallback'] = attachment['message'] attachment['text'] = attachment['message'] del attachment['message'] message['attachments'] = [attachment] payload = {"payload": json.dumps(message)} try: parameters = urllib.parse.urlencode(payload).encode('UTF-8') url = urllib.request.Request(args.webhook_url, parameters) responseData = urllib.request.urlopen(url).read() except urllib.error.HTTPError as he: print("Sending message to Slack failed: {}".format(he)) sys.exit(1)
LordGaav/notification-scripts
slack.py
Python
mit
3,578
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class MultilayerGeneratorServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { /* | |--------------------------------------------------------------------------------- | Please do not uncomment the commented lines, do not delete them, nor edit them. | any action will result in serious damage to the package functionality. |-------------------------------------------------------------------------------- | */ $this->app->booting(function(){ $loader = \Illuminate\Foundation\AliasLoader::getInstance(); /* | | Interfaces | */ //DummyAliasLoadingForInterfaces /* | | Repositories Classes | */ //DummyAliasLoadingForRepositories /* | | Object Classes | */ //DummyAliasLoadingForObjects /* | | Traits | */ $loader->alias('CRUDtrait', 'App\Http\Traits\CRUDtrait'); //DummyAliasLoadingForTraits /* | | Motors | */ $loader->alias('Motor', 'App\Http\Motors\Motor'); //DummyAliasLoadingForMotors }); } }
HOuaghad/multilayering
src/providers/MultilayerGeneratorServiceProvider.php
PHP
mit
1,662
class BlogPost < ActiveRecord::Base end
heedspin/transactional-factories
test/lib/blog_post.rb
Ruby
mit
39
#region License // The MIT License (MIT) // // Copyright (c) 2016 João Simões // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #endregion namespace EULex.SimpleSOAPClient.Helpers { using System.IO; using System.Xml.Linq; using System.Xml.Serialization; /// <summary> /// Helper class with extensions for XML manipulation /// </summary> internal static class XmlHelpers { private static readonly XmlSerializerNamespaces EmptyXmlSerializerNamespaces; static XmlHelpers () { EmptyXmlSerializerNamespaces = new XmlSerializerNamespaces (); EmptyXmlSerializerNamespaces.Add ("", ""); } /// <summary> /// Serializes the given object to a XML string /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="item">The item to serialize</param> /// <returns>The XML string</returns> public static string ToXmlString<T> (this T item) { if (item == null) return null; using (var textWriter = new StringWriter ()) { new XmlSerializer (item.GetType ()).Serialize (textWriter, item, EmptyXmlSerializerNamespaces); var result = textWriter.ToString (); return result; } } /// <summary> /// Serializes a given object to XML and returns the <see cref="XElement"/> representation. /// </summary> /// <typeparam name="T">The object type</typeparam> /// <param name="item">The item to convert</param> /// <returns>The object as a <see cref="XElement"/></returns> public static XElement ToXElement<T> (this T item) { return item == null ? null : XElement.Parse (item.ToXmlString ()); } /// <summary> /// Deserializes a given XML string to a new object of the expected type. /// If null or white spaces the default(T) will be returned; /// </summary> /// <typeparam name="T">The type to be deserializable</typeparam> /// <param name="xml">The XML string to deserialize</param> /// <returns>The deserialized object</returns> public static T ToObject<T> (this string xml) { if (string.IsNullOrWhiteSpace (xml)) return default (T); using (var textWriter = new StringReader (xml)) { var result = (T)new XmlSerializer (typeof (T)).Deserialize (textWriter); return result; } } /// <summary> /// Deserializes a given <see cref="XElement"/> to a new object of the expected type. /// If null the default(T) will be returned. /// </summary> /// <typeparam name="T">The type to be deserializable</typeparam> /// <param name="xml">The <see cref="XElement"/> to deserialize</param> /// <returns>The deserialized object</returns> public static T ToObject<T> (this XElement xml) { return xml == null ? default (T) : xml.ToString ().ToObject<T> (); } } }
EULexNET/EULex.NET
src/EULex/SimpleSOAPClient/Helpers/XmlHelpers.cs
C#
mit
4,158
perl C:\DATA\Projects\SetWindows7LockScreen\setLockScreenToBing.pl
ChrisYounger/Bing-Lockscreen-Background
run.bat
Batchfile
mit
68
#region Copyright (c) 2014 Orcomp development team. // ------------------------------------------------------------------------------------------------------------------- // <copyright file="ParseException.cs" company="Orcomp development team"> // Copyright (c) 2014 Orcomp development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace SolutionValidator.FolderStructure { #region using... using System; #endregion public class ParseException : ApplicationException { public ParseException(string message, int lineNumber, int column) : base(message) { LineNumber = lineNumber; Column = column; } public int LineNumber { get; set; } public int Column { get; set; } } }
Orcomp/SolutionValidator
src/SolutionValidator.Core/Validator/FolderStructure/Exceptions/ParseException.cs
C#
mit
834
package com.kkk.retrofitdemo; import com.kkk.retrofitdemo.bean.Repo; import com.kkk.retrofitdemo.bean.SearchRepoResult; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; import rx.Observable; public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); @GET("search/repositories") Observable<SearchRepoResult> searchRepos(@Query("q") String keyword, @Query("sort") String sort, @Query("order") String order); }
kylm53/learn-android
RetrofitDemo/src/main/java/com/kkk/retrofitdemo/GitHubService.java
Java
mit
655
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class ArticleProlongImageUrl extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('articles', function (Blueprint $table) { $table->string('image_url', 768)->change(); $table->string('url', 768)->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('articles', function (Blueprint $table) { $table->string('image_url')->change(); $table->string('url')->change(); }); } }
remp2020/remp
Beam/database/migrations/2018_12_07_145030_article_prolong_image_url.php
PHP
mit
761
version https://git-lfs.github.com/spec/v1 oid sha256:641860132ccb9772e708b19feb3d59bb6291f6c40eebbfcfa0982a4e8eeda219 size 69639
yogeshsaroya/new-cdnjs
ajax/libs/holder/2.5.0/holder.js
JavaScript
mit
130
<div class="cms-control-panel" ng-show="ctrl.isAuthenticated()"> <div class="panel-button pull-right"><i class="fa fa-2x fa-cog" ng-click="ctrl.showPanel()"></i></div> <div class="panel-widget" ng-show="ctrl.panel"> <i class="fa fa-2x fa-save" ng-click="ctrl.save()" ng-hide="saved"></i> <i class="fa fa-2x fa-ellipsis-h" ng-show="saved"></i> <i class="fa fa-2x fa-undo" ng-click="ctrl.undo()"></i> </div> </div>
brugsel/angular-cms-blox
src/cms/cms-control-panel.template.html
HTML
mit
452
(function(global) { var vwl = {}; var receivePoster; var receiveEntry; var receiveLoadedList; // vwl.init - advertise VWL info and register for VWL messages // // Parameters: // left - (optional) url of this world's initial left entry image // right - (optional) url of this world's initial right entry image // receivePosterFunc - (optional) function to handle poster images from other // worlds // receiveEntryFunc - (optional) function to handle entry images from other // worlds // recevieLoadedListFunc - (optional) function to handle list of loaded worlds vwl.init = function(left, right, receivePosterFunc, receiveEntryFunc, receiveLoadedListFunc) { receivePoster = receivePosterFunc; receiveEntry = receiveEntryFunc; receiveLoadedList = receiveLoadedListFunc; receiveEntry && window.addEventListener('message', function(message) { if (message.source != window || message.origin != window.location.origin) return; if (message.data.tabInfo) { var left = null; var right = null; if (message.data.tabInfo.info && message.data.tabInfo.info.entry_image) { left = message.data.tabInfo.info.entry_image.left_src; right = message.data.tabInfo.info.entry_image.right_src; } receiveEntry(message.data.tabInfo.url, message.data.tabInfo.loaded, left, right); } if (message.data.loadedList !== undefined) { receiveLoadedList(message.data.loadedList); } }, false); window.postMessage({info:{entry_image:{ left_src:left, right_src:right}}}, '*'); } // vwl.getInfo - get info (entry image and poster image) on a specific world // // Parameters: // url - url of worlds to get info on // getPoster - (optional) if true get the poster image vwl.getInfo = function(url, getPoster) { if (receivePoster && getPoster) { var request = new XMLHttpRequest(); var dir = url.substr(0, url.lastIndexOf('/') + 1); request.open('GET', dir + 'vwl_info.json'); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { var poster = JSON.parse(request.responseText).poster_image; receivePoster(url, poster.left_src ? dir + poster.left_src : null, poster.right_src ? dir + poster.right_src : null, poster._2d_src ? dir + poster._2d_src : null); } else { receivePoster(url); } } request.send(null); } receiveEntry && window.postMessage({getInfo:url}, '*'); } // vwl.getLoadedList - get the list of loaded worlds vwl.getLoadedList = function() { window.postMessage({getLoadedList:true}, '*'); } // vwl.open - load world // // Parameters: // url - url of world to open vwl.open = function(url) { window.postMessage({open:url}, '*'); } // vwl.navigate - navigate to a world // // Parameters: // left - (optional) new left entry image for current world // right - (optional) new right entry image for current world // url - url of world to navigate to vwl.navigate = function(left, right, url) { var message = {navigate:url}; if (left && right) { message.info = {entry_image:{left_src:left, right_src:right}}; } window.postMessage(message, '*'); } global.vwl = vwl; }) (window);
BigRobCoder/VirtualWorldLink
lib/vwl.js
JavaScript
mit
3,364
# -*- coding: utf-8 -*- """The initialization file for the Pywikibot framework.""" # # (C) Pywikibot team, 2008-2015 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, unicode_literals __release__ = '2.0b3' __version__ = '$Id$' __url__ = 'https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Pywikibot' import datetime import math import re import sys import threading import json if sys.version_info[0] > 2: from queue import Queue long = int else: from Queue import Queue from warnings import warn # Use pywikibot. prefix for all in-package imports; this is to prevent # confusion with similarly-named modules in version 1 framework, for users # who want to continue using both from pywikibot import config2 as config from pywikibot.bot import ( output, warning, error, critical, debug, stdout, exception, input, input_choice, input_yn, inputChoice, handle_args, showHelp, ui, log, calledModuleName, Bot, CurrentPageBot, WikidataBot, # the following are flagged as deprecated on usage handleArgs, ) from pywikibot.exceptions import ( Error, InvalidTitle, BadTitle, NoPage, NoMoveTarget, SectionError, SiteDefinitionError, NoSuchSite, UnknownSite, UnknownFamily, UnknownExtension, NoUsername, UserBlocked, PageRelatedError, IsRedirectPage, IsNotRedirectPage, PageSaveRelatedError, PageNotSaved, OtherPageSaveError, LockedPage, CascadeLockedPage, LockedNoPage, NoCreateError, EditConflict, PageDeletedConflict, PageCreatedConflict, ServerError, FatalServerError, Server504Error, CaptchaError, SpamfilterError, CircularRedirect, InterwikiRedirectPage, WikiBaseError, CoordinateGlobeUnknownException, ) from pywikibot.tools import PY2, UnicodeMixin, redirect_func from pywikibot.i18n import translate from pywikibot.data.api import UploadWarning from pywikibot.diff import PatchManager import pywikibot.textlib as textlib import pywikibot.tools textlib_methods = ( 'unescape', 'replaceExcept', 'removeDisabledParts', 'removeHTMLParts', 'isDisabled', 'interwikiFormat', 'interwikiSort', 'getLanguageLinks', 'replaceLanguageLinks', 'removeLanguageLinks', 'removeLanguageLinksAndSeparator', 'getCategoryLinks', 'categoryFormat', 'replaceCategoryLinks', 'removeCategoryLinks', 'removeCategoryLinksAndSeparator', 'replaceCategoryInPlace', 'compileLinkR', 'extract_templates_and_params', 'TimeStripper', ) __all__ = ( 'config', 'ui', 'UnicodeMixin', 'translate', 'Page', 'FilePage', 'Category', 'Link', 'User', 'ItemPage', 'PropertyPage', 'Claim', 'html2unicode', 'url2unicode', 'unicode2html', 'stdout', 'output', 'warning', 'error', 'critical', 'debug', 'exception', 'input_choice', 'input', 'input_yn', 'inputChoice', 'handle_args', 'handleArgs', 'showHelp', 'ui', 'log', 'calledModuleName', 'Bot', 'CurrentPageBot', 'WikidataBot', 'Error', 'InvalidTitle', 'BadTitle', 'NoPage', 'NoMoveTarget', 'SectionError', 'SiteDefinitionError', 'NoSuchSite', 'UnknownSite', 'UnknownFamily', 'UnknownExtension', 'NoUsername', 'UserBlocked', 'UserActionRefuse', 'PageRelatedError', 'IsRedirectPage', 'IsNotRedirectPage', 'PageSaveRelatedError', 'PageNotSaved', 'OtherPageSaveError', 'LockedPage', 'CascadeLockedPage', 'LockedNoPage', 'NoCreateError', 'EditConflict', 'PageDeletedConflict', 'PageCreatedConflict', 'UploadWarning', 'ServerError', 'FatalServerError', 'Server504Error', 'CaptchaError', 'SpamfilterError', 'CircularRedirect', 'InterwikiRedirectPage', 'WikiBaseError', 'CoordinateGlobeUnknownException', 'QuitKeyboardInterrupt', ) __all__ += textlib_methods if PY2: # T111615: Python 2 requires __all__ is bytes globals()['__all__'] = tuple(bytes(item) for item in __all__) for _name in textlib_methods: target = getattr(textlib, _name) wrapped_func = redirect_func(target) globals()[_name] = wrapped_func deprecated = redirect_func(pywikibot.tools.deprecated) deprecate_arg = redirect_func(pywikibot.tools.deprecate_arg) class Timestamp(datetime.datetime): """Class for handling MediaWiki timestamps. This inherits from datetime.datetime, so it can use all of the methods and operations of a datetime object. To ensure that the results of any operation are also a Timestamp object, be sure to use only Timestamp objects (and datetime.timedeltas) in any operation. Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to create Timestamp objects from MediaWiki string formats. As these constructors are typically used to create objects using data passed provided by site and page methods, some of which return a Timestamp when previously they returned a MediaWiki string representation, these methods also accept a Timestamp object, in which case they return a clone. Use Site.getcurrenttime() for the current time; this is more reliable than using Timestamp.utcnow(). """ mediawikiTSFormat = "%Y%m%d%H%M%S" ISO8601Format = "%Y-%m-%dT%H:%M:%SZ" def clone(self): """Clone this instance.""" return self.replace(microsecond=self.microsecond) @classmethod def fromISOformat(cls, ts): """Convert an ISO 8601 timestamp to a Timestamp object.""" # If inadvertantly passed a Timestamp object, use replace() # to create a clone. if isinstance(ts, cls): return ts.clone() return cls.strptime(ts, cls.ISO8601Format) @classmethod def fromtimestampformat(cls, ts): """Convert a MediaWiki internal timestamp to a Timestamp object.""" # If inadvertantly passed a Timestamp object, use replace() # to create a clone. if isinstance(ts, cls): return ts.clone() return cls.strptime(ts, cls.mediawikiTSFormat) def isoformat(self): """ Convert object to an ISO 8601 timestamp accepted by MediaWiki. datetime.datetime.isoformat does not postfix the ISO formatted date with a 'Z' unless a timezone is included, which causes MediaWiki ~1.19 and earlier to fail. """ return self.strftime(self.ISO8601Format) toISOformat = redirect_func(isoformat, old_name='toISOformat', class_name='Timestamp') def totimestampformat(self): """Convert object to a MediaWiki internal timestamp.""" return self.strftime(self.mediawikiTSFormat) def __str__(self): """Return a string format recognized by the API.""" return self.isoformat() def __add__(self, other): """Perform addition, returning a Timestamp instead of datetime.""" newdt = super(Timestamp, self).__add__(other) if isinstance(newdt, datetime.datetime): return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour, newdt.minute, newdt.second, newdt.microsecond, newdt.tzinfo) else: return newdt def __sub__(self, other): """Perform substraction, returning a Timestamp instead of datetime.""" newdt = super(Timestamp, self).__sub__(other) if isinstance(newdt, datetime.datetime): return Timestamp(newdt.year, newdt.month, newdt.day, newdt.hour, newdt.minute, newdt.second, newdt.microsecond, newdt.tzinfo) else: return newdt class Coordinate(object): """ Class for handling and storing Coordinates. For now its just being used for DataSite, but in the future we can use it for the GeoData extension. """ def __init__(self, lat, lon, alt=None, precision=None, globe='earth', typ="", name="", dim=None, site=None, entity=''): """ Represent a geo coordinate. @param lat: Latitude @type lat: float @param lon: Longitude @type lon: float @param alt: Altitute? TODO FIXME @param precision: precision @type precision: float @param globe: Which globe the point is on @type globe: str @param typ: The type of coordinate point @type typ: str @param name: The name @type name: str @param dim: Dimension (in meters) @type dim: int @param entity: The URL entity of a Wikibase item @type entity: str """ self.lat = lat self.lon = lon self.alt = alt self._precision = precision if globe: globe = globe.lower() self.globe = globe self._entity = entity self.type = typ self.name = name self._dim = dim if not site: self.site = Site().data_repository() else: self.site = site def __repr__(self): string = 'Coordinate(%s, %s' % (self.lat, self.lon) if self.globe != 'earth': string += ', globe="%s"' % self.globe string += ')' return string @property def entity(self): if self._entity: return self._entity return self.site.globes()[self.globe] def toWikibase(self): """ Export the data to a JSON object for the Wikibase API. FIXME: Should this be in the DataSite object? """ if self.globe not in self.site.globes(): raise CoordinateGlobeUnknownException( u"%s is not supported in Wikibase yet." % self.globe) return {'latitude': self.lat, 'longitude': self.lon, 'altitude': self.alt, 'globe': self.entity, 'precision': self.precision, } @classmethod def fromWikibase(cls, data, site): """Constructor to create an object from Wikibase's JSON output.""" globes = {} for k in site.globes(): globes[site.globes()[k]] = k globekey = data['globe'] if globekey: globe = globes.get(data['globe']) else: # Default to earth or should we use None here? globe = 'earth' return cls(data['latitude'], data['longitude'], data['altitude'], data['precision'], globe, site=site, entity=data['globe']) @property def precision(self): u""" Return the precision of the geo coordinate. The biggest error (in degrees) will be given by the longitudinal error; the same error in meters becomes larger (in degrees) further up north. We can thus ignore the latitudinal error. The longitudinal can be derived as follows: In small angle approximation (and thus in radians): M{Δλ ≈ Δpos / r_φ}, where r_φ is the radius of earth at the given latitude. Δλ is the error in longitude. M{r_φ = r cos φ}, where r is the radius of earth, φ the latitude Therefore:: precision = math.degrees(self._dim/(radius*math.cos(math.radians(self.lat)))) """ if not self._precision: radius = 6378137 # TODO: Support other globes self._precision = math.degrees( self._dim / (radius * math.cos(math.radians(self.lat)))) return self._precision def precisionToDim(self): """Convert precision from Wikibase to GeoData's dim.""" raise NotImplementedError class WbTime(object): """A Wikibase time representation.""" PRECISION = {'1000000000': 0, '100000000': 1, '10000000': 2, '1000000': 3, '100000': 4, '10000': 5, 'millenia': 6, 'century': 7, 'decade': 8, 'year': 9, 'month': 10, 'day': 11, 'hour': 12, 'minute': 13, 'second': 14 } FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z' def __init__(self, year=None, month=None, day=None, hour=None, minute=None, second=None, precision=None, before=0, after=0, timezone=0, calendarmodel=None, site=None): """ Create a new WbTime object. The precision can be set by the Wikibase int value (0-14) or by a human readable string, e.g., 'hour'. If no precision is given, it is set according to the given time units. """ if year is None: raise ValueError('no year given') self.precision = self.PRECISION['second'] if second is None: self.precision = self.PRECISION['minute'] second = 0 if minute is None: self.precision = self.PRECISION['hour'] minute = 0 if hour is None: self.precision = self.PRECISION['day'] hour = 0 if day is None: self.precision = self.PRECISION['month'] day = 1 if month is None: self.precision = self.PRECISION['year'] month = 1 self.year = long(year) self.month = month self.day = day self.hour = hour self.minute = minute self.second = second self.after = after self.before = before self.timezone = timezone if calendarmodel is None: if site is None: site = Site().data_repository() calendarmodel = site.calendarmodel() self.calendarmodel = calendarmodel # if precision is given it overwrites the autodetection above if precision is not None: if (isinstance(precision, int) and precision in self.PRECISION.values()): self.precision = precision elif precision in self.PRECISION: self.precision = self.PRECISION[precision] else: raise ValueError('Invalid precision: "%s"' % precision) @classmethod def fromTimestr(cls, datetimestr, precision=14, before=0, after=0, timezone=0, calendarmodel=None, site=None): match = re.match(r'([-+]?\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z', datetimestr) if not match: raise ValueError(u"Invalid format: '%s'" % datetimestr) t = match.groups() return cls(long(t[0]), int(t[1]), int(t[2]), int(t[3]), int(t[4]), int(t[5]), precision, before, after, timezone, calendarmodel, site) def toTimestr(self): """ Convert the data to a UTC date/time string. @return: str """ return self.FORMATSTR.format(self.year, self.month, self.day, self.hour, self.minute, self.second) def toWikibase(self): """ Convert the data to a JSON object for the Wikibase API. @return: dict """ json = {'time': self.toTimestr(), 'precision': self.precision, 'after': self.after, 'before': self.before, 'timezone': self.timezone, 'calendarmodel': self.calendarmodel } return json @classmethod def fromWikibase(cls, ts): return cls.fromTimestr(ts[u'time'], ts[u'precision'], ts[u'before'], ts[u'after'], ts[u'timezone'], ts[u'calendarmodel']) def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return u"WbTime(year=%(year)d, month=%(month)d, day=%(day)d, " \ u"hour=%(hour)d, minute=%(minute)d, second=%(second)d, " \ u"precision=%(precision)d, before=%(before)d, after=%(after)d, " \ u"timezone=%(timezone)d, calendarmodel='%(calendarmodel)s')" \ % self.__dict__ class WbQuantity(object): """A Wikibase quantity representation.""" def __init__(self, amount, unit=None, error=None): u""" Create a new WbQuantity object. @param amount: number representing this quantity @type amount: float @param unit: not used (only unit-less quantities are supported) @param error: the uncertainty of the amount (e.g. ±1) @type error: float, or tuple of two floats, where the first value is the upper error and the second is the lower error value. """ if amount is None: raise ValueError('no amount given') if unit is None: unit = '1' self.amount = amount self.unit = unit upperError = lowerError = 0 if isinstance(error, tuple): upperError, lowerError = error elif error is not None: upperError = lowerError = error self.upperBound = self.amount + upperError self.lowerBound = self.amount - lowerError def toWikibase(self): """Convert the data to a JSON object for the Wikibase API.""" json = {'amount': self.amount, 'upperBound': self.upperBound, 'lowerBound': self.lowerBound, 'unit': self.unit } return json @classmethod def fromWikibase(cls, wb): """ Create a WbQuanity from the JSON data given by the Wikibase API. @param wb: Wikibase JSON """ amount = eval(wb['amount']) upperBound = eval(wb['upperBound']) lowerBound = eval(wb['lowerBound']) error = (upperBound - amount, amount - lowerBound) return cls(amount, wb['unit'], error) def __str__(self): return json.dumps(self.toWikibase(), indent=4, sort_keys=True, separators=(',', ': ')) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return (u"WbQuantity(amount=%(amount)s, upperBound=%(upperBound)s, " u"lowerBound=%(lowerBound)s, unit=%(unit)s)" % self.__dict__) _sites = {} _url_cache = {} # The code/fam pair for each URL def Site(code=None, fam=None, user=None, sysop=None, interface=None, url=None): """A factory method to obtain a Site object. Site objects are cached and reused by this method. By default rely on config settings. These defaults may all be overridden using the method parameters. @param code: language code (override config.mylang) @type code: string @param fam: family name or object (override config.family) @type fam: string or Family @param user: bot user name to use on this site (override config.usernames) @type user: unicode @param sysop: sysop user to use on this site (override config.sysopnames) @type sysop: unicode @param interface: site class or name of class in pywikibot.site (override config.site_interface) @type interface: subclass of L{pywikibot.site.BaseSite} or string @param url: Instead of code and fam, does try to get a Site based on the URL. Still requires that the family supporting that URL exists. @type url: string """ # Either code and fam or only url if url and (code or fam): raise ValueError('URL to the wiki OR a pair of code and family name ' 'should be provided') _logger = "wiki" if url: if url not in _url_cache: matched_sites = [] # Iterate through all families and look, which does apply to # the given URL for fam in config.family_files: family = pywikibot.family.Family.load(fam) code = family.from_url(url) if code is not None: matched_sites += [(code, fam)] if matched_sites: if len(matched_sites) > 1: pywikibot.warning( 'Found multiple matches for URL "{0}": {1} (use first)' .format(url, ', '.join(str(s) for s in matched_sites))) _url_cache[url] = matched_sites[0] else: # TODO: As soon as AutoFamily is ready, try and use an # AutoFamily _url_cache[url] = None cached = _url_cache[url] if cached: code = cached[0] fam = cached[1] else: raise SiteDefinitionError("Unknown URL '{0}'.".format(url)) else: # Fallback to config defaults code = code or config.mylang fam = fam or config.family interface = interface or config.site_interface # config.usernames is initialised with a dict for each family name family_name = str(fam) if family_name in config.usernames: user = user or config.usernames[family_name].get(code) \ or config.usernames[family_name].get('*') sysop = sysop or config.sysopnames[family_name].get(code) \ or config.sysopnames[family_name].get('*') if not isinstance(interface, type): # If it isnt a class, assume it is a string try: tmp = __import__('pywikibot.site', fromlist=[interface]) interface = getattr(tmp, interface) except ImportError: raise ValueError("Invalid interface name '%(interface)s'" % locals()) if not issubclass(interface, pywikibot.site.BaseSite): warning('Site called with interface=%s' % interface.__name__) user = pywikibot.tools.normalize_username(user) key = '%s:%s:%s:%s' % (interface.__name__, fam, code, user) if key not in _sites or not isinstance(_sites[key], interface): _sites[key] = interface(code=code, fam=fam, user=user, sysop=sysop) debug(u"Instantiated %s object '%s'" % (interface.__name__, _sites[key]), _logger) if _sites[key].code != code: warn('Site %s instantiated using different code "%s"' % (_sites[key], code), UserWarning, 2) return _sites[key] # alias for backwards-compability getSite = pywikibot.tools.redirect_func(Site, old_name='getSite') from pywikibot.page import ( Page, FilePage, Category, Link, User, ItemPage, PropertyPage, Claim, ) from pywikibot.page import html2unicode, url2unicode, unicode2html link_regex = re.compile(r'\[\[(?P<title>[^\]|[<>{}]*)(\|.*?)?\]\]') @pywikibot.tools.deprecated("comment parameter for page saving method") def setAction(s): """Set a summary to use for changed page submissions.""" config.default_edit_summary = s def showDiff(oldtext, newtext, context=0): """ Output a string showing the differences between oldtext and newtext. The differences are highlighted (only on compatible systems) to show which changes were made. """ PatchManager(oldtext, newtext, context=context).print_hunks() # Throttle and thread handling stopped = False def stopme(): """Drop this process from the throttle log, after pending threads finish. Can be called manually if desired, but if not, will be called automatically at Python exit. """ global stopped _logger = "wiki" if not stopped: debug(u"stopme() called", _logger) def remaining(): remainingPages = page_put_queue.qsize() - 1 # -1 because we added a None element to stop the queue remainingSeconds = datetime.timedelta( seconds=(remainingPages * config.put_throttle)) return (remainingPages, remainingSeconds) page_put_queue.put((None, [], {})) stopped = True if page_put_queue.qsize() > 1: num, sec = remaining() format_values = dict(num=num, sec=sec) output(u'\03{lightblue}' u'Waiting for %(num)i pages to be put. ' u'Estimated time remaining: %(sec)s' u'\03{default}' % format_values) while(_putthread.isAlive()): try: _putthread.join(1) except KeyboardInterrupt: if input_yn('There are %i pages remaining in the queue. ' 'Estimated time remaining: %s\nReally exit?' % remaining(), default=False, automatic_quit=False): return # only need one drop() call because all throttles use the same global pid try: list(_sites.values())[0].throttle.drop() log(u"Dropped throttle(s).") except IndexError: pass import atexit atexit.register(stopme) # Create a separate thread for asynchronous page saves (and other requests) def async_manager(): """Daemon; take requests from the queue and execute them in background.""" while True: (request, args, kwargs) = page_put_queue.get() if request is None: break request(*args, **kwargs) page_put_queue.task_done() def async_request(request, *args, **kwargs): """Put a request on the queue, and start the daemon if necessary.""" if not _putthread.isAlive(): try: page_put_queue.mutex.acquire() try: _putthread.start() except (AssertionError, RuntimeError): pass finally: page_put_queue.mutex.release() page_put_queue.put((request, args, kwargs)) # queue to hold pending requests page_put_queue = Queue(config.max_queue_size) # set up the background thread _putthread = threading.Thread(target=async_manager) # identification for debugging purposes _putthread.setName('Put-Thread') _putthread.setDaemon(True) wrapper = pywikibot.tools.ModuleDeprecationWrapper(__name__) wrapper._add_deprecated_attr('ImagePage', FilePage) wrapper._add_deprecated_attr( 'PageNotFound', pywikibot.exceptions.DeprecatedPageNotFoundError, warning_message=('{0}.{1} is deprecated, and no longer ' 'used by pywikibot; use http.fetch() instead.')) wrapper._add_deprecated_attr( 'UserActionRefuse', pywikibot.exceptions._EmailUserError, warning_message='UserActionRefuse is deprecated; ' 'use UserRightsError and/or NotEmailableError') wrapper._add_deprecated_attr( 'QuitKeyboardInterrupt', pywikibot.bot.QuitKeyboardInterrupt, warning_message='pywikibot.QuitKeyboardInterrupt is deprecated; ' 'use pywikibot.bot.QuitKeyboardInterrupt instead')
icyflame/batman
pywikibot/__init__.py
Python
mit
26,823
package gui; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.awt.Toolkit; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.SwingConstants; import javax.swing.JTextField; import javax.swing.JButton; import javax.swing.JSpinner; import javax.swing.SpinnerNumberModel; import javax.swing.JComboBox; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; import javax.swing.DefaultComboBoxModel; import javax.swing.UIManager; import app.Applikation; import javax.swing.DropMode; import parsers.*; import java.io.IOException; import java.util.Random; public class GUI { private JFrame frmImageDownloader; private JTextField txtInsertTagHere; private JTextArea textArea; private JSpinner PageSpinner; private JComboBox<Object> comboBox; private ImageParser parser; private JButton Parsebtn; private JTextField DelayField; private BufferedImage bgImage; private JLabel lblNewLabel; private JLabel lblNewLabel_1; private JLabel lblTag; private final String FOURCHAN_THREAD = "4chan-Thread - http://boards.4chan.org/x/res/123123"; private final String FOURCHAN_BOARD = "4chan-Board - http://boards.4chan.org/x/catalog"; private final String INFINITYCHAN_THREAD = "Infinity Chan Thread - https://8chan.co/BOARD/res/THREADNR.html"; private final String INFINITYCHAN_BOARD = "Infinity Chan Board - https://8chan.co/BOARDNR/"; private final String PAHEAL = "http://rule34.paheal.net/"; private final String XXX = "http://rule34.xxx/"; private final String GELBOORU = "http://gelbooru.com/"; private final String R34HENTAI = "http://rule34hentai.net/"; private final String TUMBLR = "Tumblr Artist - http://XxXxXxX.tumblr.com"; private final String IMGUR = "Imgur-Album - http://imgur.com/a/xXxXx"; private final String GE_HENTAI_SINGLE = "http://g.e-hentai.org/ - Single Album Page"; private final String GE_HENTAI_MORE = "http://g.e-hentai.org/ - >=1 Pages"; private final String ARCHIVE_MOE_THREAD = "archive.moe/fgts.jp (Thread) - https://archive.moe/BOARD/thread/THREADNR/"; private final String ARCHIVE_MOE_BOARD = "archive-moe (Board) - https://archive.moe/BOARD/"; private final String FGTS_JP_BOARD = "fgts.jp (Board) - http://fgts.jp/BOARD/"; private boolean parsing; public GUI() { System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } frmImageDownloader = new JFrame(); frmImageDownloader.setIconImage(Toolkit.getDefaultToolkit() .getImage(this.getClass().getResource("/images/icon.png"))); frmImageDownloader.getContentPane().setBackground( UIManager.getColor("Button.background")); frmImageDownloader.setResizable(false); frmImageDownloader.setTitle("Image Downloader v1.5.1"); frmImageDownloader.setBounds(100, 100, 761, 558); frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmImageDownloader.getContentPane().setLayout(null); JLabel lblMadeByLars = new JLabel("@ berserkingyadis"); lblMadeByLars.setFont(new Font("Dialog", Font.PLAIN, 12)); lblMadeByLars.setBounds(14, 468, 157, 40); frmImageDownloader.getContentPane().add(lblMadeByLars); JScrollPane scrollPane = new JScrollPane(); scrollPane .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setBounds(205, 185, 542, 331); scrollPane.setAutoscrolls(true); frmImageDownloader.getContentPane().add(scrollPane); try { bgImage = ImageIO.read(Applikation.class.getResource("/images/bg" + (new Random().nextInt(4) + 1) + ".png")); } catch (IOException e) { appendLog("Could not get Background Image", true); } textArea = new BackgroundArea(bgImage); textArea.setEditable(false); textArea.setDropMode(DropMode.INSERT); textArea.setColumns(2); textArea.setFont(new Font("Monospaced", Font.PLAIN, 11)); scrollPane.setViewportView(textArea); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); txtInsertTagHere = new JTextField(); txtInsertTagHere.setText("insert tag here"); txtInsertTagHere.setFont(new Font("Dialog", Font.PLAIN, 14)); txtInsertTagHere.setBounds(14, 208, 181, 30); frmImageDownloader.getContentPane().add(txtInsertTagHere); txtInsertTagHere.setColumns(10); lblTag = new JLabel("Tag:"); lblTag.setFont(new Font("Dialog", Font.BOLD, 12)); lblTag.setBounds(12, 183, 175, 24); frmImageDownloader.getContentPane().add(lblTag); Parsebtn = new JButton("start parsing"); Parsebtn.setBounds(12, 372, 181, 85); frmImageDownloader.getContentPane().add(Parsebtn); PageSpinner = new JSpinner(); PageSpinner.setModel(new SpinnerNumberModel(new Integer(1), new Integer(1), null, new Integer(1))); PageSpinner.setBounds(155, 249, 40, 30); frmImageDownloader.getContentPane().add(PageSpinner); lblNewLabel = new JLabel("Pages to parse:"); lblNewLabel.setFont(new Font("Dialog", Font.BOLD, 11)); lblNewLabel.setBounds(12, 249, 123, 30); frmImageDownloader.getContentPane().add(lblNewLabel); lblNewLabel_1 = new JLabel("1 Page = 50-60 Pictures"); lblNewLabel_1.setFont(new Font("Dialog", Font.PLAIN, 12)); lblNewLabel_1.setBounds(12, 290, 175, 30); frmImageDownloader.getContentPane().add(lblNewLabel_1); comboBox = new JComboBox<Object>(); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { switch (comboBox.getSelectedItem().toString()) { case GE_HENTAI_SINGLE: Parsebtn.setEnabled(true); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setText("start parsing"); DelayField.setText("100"); lblNewLabel_1.setEnabled(true); PageSpinner.setEnabled(false); lblTag.setText("Page URL:"); txtInsertTagHere.setText("insert page URL here"); lblNewLabel.setEnabled(false); break; case GE_HENTAI_MORE: Parsebtn.setEnabled(true); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setText("start parsing"); DelayField.setText("100"); lblNewLabel.setEnabled(true); lblNewLabel_1.setEnabled(true); PageSpinner.setEnabled(true); lblTag.setText("Album URL:"); txtInsertTagHere.setText("insert album URL here"); break; case PAHEAL: case GELBOORU: case R34HENTAI: case XXX: Parsebtn.setEnabled(true); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setText("start parsing"); DelayField.setText("100"); lblNewLabel.setEnabled(true); lblNewLabel_1.setEnabled(true); PageSpinner.setEnabled(true); lblTag.setText("Tag:"); txtInsertTagHere.setText("insert tag here"); lblNewLabel.setText("Pages to parse:"); break; case FOURCHAN_THREAD: case INFINITYCHAN_THREAD: case ARCHIVE_MOE_THREAD: Parsebtn.setEnabled(true); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setText("start parsing"); DelayField.setText("10"); lblNewLabel.setText("Pages to parse:"); lblNewLabel.setEnabled(false); lblNewLabel_1.setEnabled(false); PageSpinner.setEnabled(false); lblTag.setText("Thread URL:"); txtInsertTagHere.setText("insert link here"); break; case FOURCHAN_BOARD: case INFINITYCHAN_BOARD: Parsebtn.setEnabled(true); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setText("start parsing"); DelayField.setText("10"); lblNewLabel.setEnabled(true); lblNewLabel.setText("Threads to parse:"); lblNewLabel_1.setEnabled(false); PageSpinner.setEnabled(true); lblTag.setText("Board(eg: v or e):"); txtInsertTagHere.setText("insert Board Letter here"); break; case ARCHIVE_MOE_BOARD: case FGTS_JP_BOARD: Parsebtn.setEnabled(true); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setText("start parsing"); DelayField.setText("10"); lblNewLabel.setEnabled(true); lblNewLabel.setText("Sites to parse(1 Site = 100 Threads):"); lblNewLabel_1.setEnabled(false); PageSpinner.setEnabled(true); lblTag.setText("Board(eg: v or e):"); txtInsertTagHere.setText("insert Board Letter here"); break; case TUMBLR: Parsebtn.setEnabled(true); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setText("start parsing"); DelayField.setText("100"); lblNewLabel.setEnabled(true); lblNewLabel_1.setEnabled(true); PageSpinner.setEnabled(true); lblTag.setText("Artist name:"); txtInsertTagHere.setText("insert artist name here"); lblNewLabel.setText("Pages to parse:"); break; case IMGUR: lblNewLabel.setEnabled(false); lblNewLabel_1.setEnabled(false); PageSpinner.setEnabled(false); DelayField.setText("100"); lblTag.setText("Album Letters: (eg: \"Bl1QP\")"); txtInsertTagHere.setText("insert the letters here"); Parsebtn.setText("start parsing"); Parsebtn.setFont(new Font("Dialog", Font.BOLD, 12)); Parsebtn.setEnabled(true); break; } } }); comboBox.setModel(new DefaultComboBoxModel<Object>( new String[]{ PAHEAL, XXX, R34HENTAI, GELBOORU, GE_HENTAI_SINGLE, GE_HENTAI_MORE, FOURCHAN_THREAD, FOURCHAN_BOARD, //ARCHIVE_MOE_THREAD, //ARCHIVE_MOE_BOARD, //FGTS_JP_BOARD, INFINITYCHAN_THREAD, INFINITYCHAN_BOARD, TUMBLR, IMGUR })); comboBox.setBounds(434, 35, 313, 24); comboBox.setFont(new Font("Dialog", Font.PLAIN, 11)); frmImageDownloader.getContentPane().add(comboBox); JLabel lblNewLabel_2 = new JLabel("choose the Site to parse:"); lblNewLabel_2.setFont(new Font("Dialog", Font.BOLD, 12)); lblNewLabel_2.setBounds(434, 5, 268, 30); frmImageDownloader.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_3 = new JLabel( "<html>\nWelcome to the Image Downloader. <br>\nYour can enter the Tag of the images you are looking for below. <br>\nImgur is not supported yet. <br>\nWhen you click parse a folder with the name of the tag will be <br>\ncreated and the images will be downloaded into it. <br><br>\nI strongly advise you to not set the delay under 100 ms, <br>\nif you abuse this you will get banned from the site <br><br>\n\nhave fun :)\n\n\n</html>"); lblNewLabel_3.setVerticalAlignment(SwingConstants.TOP); lblNewLabel_3.setFont(new Font("Dialog", Font.PLAIN, 12)); lblNewLabel_3.setBounds(12, 12, 404, 195); frmImageDownloader.getContentPane().add(lblNewLabel_3); JLabel lblDelay = new JLabel("Delay(ms):"); lblDelay.setFont(new Font("Dialog", Font.BOLD, 12)); lblDelay.setBounds(12, 331, 85, 30); frmImageDownloader.getContentPane().add(lblDelay); DelayField = new JTextField(); DelayField.setText("100"); DelayField.setBounds(140, 331, 55, 30); frmImageDownloader.getContentPane().add(DelayField); DelayField.setColumns(10); JLabel lblPahealSearchFor = new JLabel( "<html>\r\npaheal: Search for Characters or Artists\r\n\t\t eg: Tifa Lockhart, Fugtrup<br>\r\nrule34.xxx: Search for things\r\n\t\teg: long hair, hand on hip<br>\r\ngelbooru: Search for what you want<br>\r\n4chan/8chan: paste the Thread URL/Boardletter in the\r\n\t\tTextfield <br>\r\ntumblr: enter the artist's name<br>imgur: enter the album id</html>"); lblPahealSearchFor.setVerticalAlignment(SwingConstants.TOP); lblPahealSearchFor.setFont(new Font("Dialog", Font.PLAIN, 11)); lblPahealSearchFor.setBounds(434, 71, 313, 109); frmImageDownloader.getContentPane().add(lblPahealSearchFor); Parsebtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (parsing) { parser.diePlease(); parser = null; } else { GUI g = getGUI(); textArea.setText(""); frmImageDownloader .setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); String tag = txtInsertTagHere.getText().replace(' ', '_'); int pages = (int) PageSpinner.getValue(); String site = comboBox.getSelectedItem().toString(); int delay = Integer.parseInt(DelayField.getText()); switch (site) { case PAHEAL: parser = new PahealParser(); parser.setup(tag, pages, g, delay); break; case XXX: parser = new XXXParser(); parser.setup(tag, pages, g, delay); break; case R34HENTAI: parser = new R34HentaiParser(); parser.setup(tag, pages, g, delay); break; case GELBOORU: parser = new GelBooruParser(); parser.setup(tag, pages, g, delay); break; case FOURCHAN_THREAD: parser = new FourChanParser(tag, delay, g, 0); break; case FOURCHAN_BOARD: parser = new FourChanParser(tag, delay, g, 1, pages); break; case INFINITYCHAN_THREAD: parser = new InfinityChanParser(tag, delay, g, 0); break; case INFINITYCHAN_BOARD: parser = new InfinityChanParser(tag, delay, g, 1, pages); break; case ARCHIVE_MOE_THREAD: parser = new ArchiveMoeParser(tag, delay, g, 0); break; case ARCHIVE_MOE_BOARD: parser = new ArchiveMoeParser(tag, delay, g, 1, pages); break; case FGTS_JP_BOARD: parser = new ArchiveMoeParser(tag, delay, g, 2, pages); break; case TUMBLR: parser = new TumblrParser(); parser.setup(tag, pages, g, delay); break; case IMGUR: parser = new ImgurParser(tag, delay, g); break; case GE_HENTAI_SINGLE: parser = new GEHentaiParser(tag, delay, g, false, pages); break; case GE_HENTAI_MORE: parser = new GEHentaiParser(tag, delay, g, true, pages); } parser.start(); parsing = true; Parsebtn.setText("stop parsing"); } } }); frmImageDownloader.setVisible(true); parsing = false; } public void appendLog(String txt, boolean brk) { textArea.append(txt); if (brk) textArea.append("\n"); } private GUI getGUI() { return this; } public void reportback() { Parsebtn.setEnabled(true); frmImageDownloader.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Parsebtn.setText("start parsing"); parsing = false; } }
berserkingyadis/ImageDownloader
src/main/java/gui/GUI.java
Java
mit
18,735
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Slate Sample</title> <script src="https://use.fontawesome.com/3d815f531c.js"></script> </head> <body> <div id="root"></div> <script src="bin/app.bundle.js"></script> </body> </html>
marschi/slate-sample
client/index.html
HTML
mit
270
<table width="90%" border="0"><tr><td><script>function openfile(url) {fullwin = window.open(url, "fulltext", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");}</script><div class="flayoutclass"><div class="flayoutclass_first"><table class="tableoutfmt2"><tr><th class="std1"><b>條目&nbsp;</b></th><td class="std2">負固不悛</td></tr> <tr><th class="std1"><b>注音&nbsp;</b></th><td class="std2">ㄈㄨ<sup class="subfont">ˋ</sup> ㄍㄨ<sup class="subfont">ˋ</sup> ㄅㄨ<sup class="subfont">ˋ</sup> ㄑㄩㄢ</td></tr> <tr><th class="std1"><b>漢語拼音&nbsp;</b></th><td class="std2"><font class="english_word">fù gù bù quān</font></td></tr> <tr><th class="std1"><b>釋義&nbsp;</b></th><td class="std2">憑恃險阻,不肯服罪。秦併六國平話˙卷下:<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>若負固不悛,執迷不返,則命將遺師剿平諸國。<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>亦作<img src=/cydic/dicword/fa40.gif border=0 alt=* class=fontimg valign=center>負固不服<img src=/cydic/dicword/fa41.gif border=0 alt=* class=fontimg valign=center>。</td></tr> <tr><th class="std1"><b><font class="fltypefont">附錄</font>&nbsp;</b></th><td class="std2">修訂本參考資料</td></tr> </td></tr></table></div> <!-- flayoutclass_first --><div class="flayoutclass_second"></div> <!-- flayoutclass_second --></div> <!-- flayoutclass --></td></tr></table>
BuzzAcademy/idioms-moe-unformatted-data
all-data/21000-21999/21469-22.html
HTML
mit
1,520
/* * 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 curveavg; /** * Small helper class for computing the circular arc between two points. * @author Sebastian Weiss */ public class CircularArc { private static final float EPSILON = 1e-5f; private final Vector3f P; private final Vector3f A; private final Vector3f B; private Vector3f C; private float r; private Vector3f N; private Vector3f CA; private float angle; /** * Computes the circular arc between the points A and B, with the point P on the * medial axis (i.e. |A-N|==|B-N|). * @param P the point on the medial axis, A and B are at the same distance from P * @param A the closest point from P on the first control curve * @param B the closest point from P on the second control curve */ public CircularArc(Vector3f P, Vector3f A, Vector3f B) { this.P = P; this.A = A; this.B = B; computeCenter(); } private void computeCenter() { Vector3f PA = A.subtract(P); Vector3f PB = B.subtract(P); N = PA.cross(PB); //check for degenerated case if (N.lengthSquared() <= EPSILON*EPSILON) { // System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line"); r = 0; return; //Degenerated to a line } //compute directions of A,B to the center C N.normalizeLocal(); PA.normalizeLocal(); PB.normalizeLocal(); Vector3f U = N.cross(PA); Vector3f V = N.cross(PB); //C is now the intersection of A+aU and B+bV Vector3f UxV = U.cross(V); Vector3f rhs = (B.subtract(A)).cross(V); float a1 = rhs.x / UxV.x; float a2 = rhs.y / UxV.y; float a3 = rhs.z / UxV.z; //all a1,a2,a3 have to be equal C = A.addScaled(a1, U); //compute radius and angle r = C.distance(A); CA = A.subtract(C); angle = (CA.normalize()).angleBetween((B.subtract(C).normalizeLocal())); } private float computeCenter_old() { //check for degenerated case Vector3f PA = A.subtract(P); Vector3f PB = B.subtract(P); N = PA.cross(PB); if (N.lengthSquared() <= EPSILON*EPSILON) { // System.out.println("A="+A+", B="+B+" P="+P+" -> it is a line"); return 0; //Degenerated to a line } //define orthonormal basis I,J,K N.normalizeLocal(); Vector3f I = PA.normalize(); Vector3f J = N.cross(I); Vector3f K = N; Vector3f IxK = I.cross(K); Vector3f JxK = J.cross(K); //project points in the plane PAB Vector3f PAxN = PA.cross(N); Vector3f PBxN = PB.cross(N); Vector2f P2 = new Vector2f(0, 0); Vector2f A2 = new Vector2f(PA.dot(JxK)/I.dot(JxK), PA.dot(IxK)/J.dot(IxK)); Vector2f B2 = new Vector2f(PB.dot(JxK)/I.dot(JxK), PB.dot(IxK)/J.dot(IxK)); //compute time t of C=P+tPA° float t; if (B2.x == A2.x) { t = (B2.y - A2.y) / (A2.x - B2.x); } else { t = (B2.x - A2.x) / (A2.y - B2.y); } //compute C Vector2f PArot = new Vector2f(A.y-P.y, P.x-A.x); Vector2f C2 = P2.addLocal(PArot.multLocal(t)); //project back C = new Vector3f(P); C.addScaledLocal(C2.x, I); C.addScaledLocal(C2.y, J); //Debug // System.out.println("A="+A+", B="+B+" P="+P+" -> I="+I+", J="+J+", K="+K+", P'="+P2+", A'="+A2+", B'="+B2+", t="+t+", C'="+C2+", C="+C); //set radius return C.distance(A); } /** * Computes a point on the actual circular arc from A to B. * The vectors C and the float r are the result from * {@link #computeCenter(curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f, curveavg.Vector3f) }. * It interpolates from A (alpha=0) to B (alpha=1) in a circular arc. * @param alpha * @return */ public Vector3f getPointOnArc(float alpha) { if (isDegenerated()) { Vector3f V = new Vector3f(); return V.interpolateLocal(A, B, alpha); //degenerated case } //normal case, rotate Vector3f V = rotate(alpha*angle, CA, N); return V.addLocal(C); } private static Vector3f rotate(float angle, Vector3f X, Vector3f N) { Vector3f W = N.mult(N.dot(X)); Vector3f U = X.subtract(W); return W.add(U.mult((float) Math.cos(angle))) .subtract(N.cross(U).mult((float) Math.sin(angle))); } public boolean isDegenerated() { return r==0; } public Vector3f getCenter() { return C; } public float getRadius() { return r; } public Vector3f getNormal() { return N; } public float getAngle() { return angle; } @Override public String toString() { return "CircularArc{" + "P=" + P + ", A=" + A + ", B=" + B + " -> C=" + C + ", r=" + r + ", N=" + N + ", angle=" + angle + '}'; } }
shamanDevel/CurveAverage
src/curveavg/CircularArc.java
Java
mit
4,540
// These two object contain information about the state of Ebl var GlobalState = Base.extend({ constructor: function() { this.isAdmin = false; this.authToken = null; this.docTitle = null; this.container = null; // default config this.config = { template: 'default', language: 'en', postsPerPage: 5, pageTitleFormat: "{ebl_title} | {doc_title}", // callbacks onBlogLoaded: null, onPostOpened: null, onPageChanged: null }; } }); var LocalState = Base.extend({ constructor: function() { this.page = 0; this.post = null; this.editors = null; } }); var PostStatus = { NEW: 0, DRAFT: 1, PUBLISHED: 2, parse: function (s) { if (s.toLowerCase() == "new") return 0; if (s.toLowerCase() == "draft") return 1; if (s.toLowerCase() == "published") return 2; return null; } }; var gState = new GlobalState(); // state shared among the entire session var lState = new LocalState(); // state of the current view
alessandrofrancesconi/ebl
ebl/core/js_src/state/state.js
JavaScript
mit
1,178
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DiveConditions.ViewModels.Manage { public class FactorViewModel { public string Purpose { get; set; } } }
DiveConditions/DiveConditions
src/DiveConditions/ViewModels/Manage/FactorViewModel.cs
C#
mit
237
using System; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using Xunit; namespace ApplicationInsights.OwinExtensions.Tests { public class OperationIdContextTests : IDisposable { public OperationIdContextTests() { OperationIdContext.Clear(); } [Fact] public void Can_Create_Context() { OperationIdContext.Create(); OperationIdContext.Get().Should().NotBeNullOrEmpty(); } [Fact] public void Can_Clear_Context() { OperationIdContext.Create(); OperationIdContext.Clear(); OperationIdContext.Get().Should().BeNull(); } [Fact] public void Can_Set_Context() { OperationIdContext.Set("test"); OperationIdContext.Get().Should().Be("test"); } [Fact] public async Task Operation_Context_Flows_With_Async() { OperationIdContext.Create(); var expected = OperationIdContext.Get(); using (var client = new HttpClient()) await client.GetAsync("http://google.com"); var actual = OperationIdContext.Get(); actual.Should().NotBeNullOrEmpty(); actual.Should().Be(expected); } public void Dispose() { OperationIdContext.Clear(); } } }
marcinbudny/applicationinsights-owinextensions
src/ApplicationInsights.OwinExtensions.Tests/OperationIdContextTests.cs
C#
mit
1,442
sprayreadings ============= scala, spray app
rohshall/sprayreadings
README.md
Markdown
mit
46
// // CRToast // Copyright (c) 2014-2015 Collin Ruffenach. All rights reserved. // #import <Foundation/Foundation.h> #import "CRToastManager.h" @import UIKit; typedef void (^CRToastImageBlock)(UIImageView*); @interface CRToastImageBlockContainer : NSObject @property (nonatomic, copy) CRToastImageBlock block; - (instancetype)initWithBlock:(CRToastImageBlock)block; - (void)performWith:(UIImageView*)imageView; @end @class CRToastSwipeGestureRecognizer, CRToastTapGestureRecognizer; /** CRToastInteractionType defines the types of interactions that can be injected into a CRToastIneractionResponder. */ typedef NS_OPTIONS(NSInteger, CRToastInteractionType) { CRToastInteractionTypeSwipeUp = 1 << 0, CRToastInteractionTypeSwipeLeft = 1 << 1, CRToastInteractionTypeSwipeDown = 1 << 2, CRToastInteractionTypeSwipeRight = 1 << 3, CRToastInteractionTypeTapOnce = 1 << 4, CRToastInteractionTypeTapTwice = 1 << 5, CRToastInteractionTypeTwoFingerTapOnce = 1 << 6, CRToastInteractionTypeTwoFingerTapTwice = 1 << 7, //An interaction responder with a CRToastInteractionTypeSwipe interaction type will fire on all swipe interactions CRToastInteractionTypeSwipe = (CRToastInteractionTypeSwipeUp | CRToastInteractionTypeSwipeLeft | CRToastInteractionTypeSwipeDown | CRToastInteractionTypeSwipeRight), //An interaction responder with a CRToastInteractionTypeTap interaction type will fire on all tap interactions CRToastInteractionTypeTap = (CRToastInteractionTypeTapOnce | CRToastInteractionTypeTapTwice | CRToastInteractionTypeTwoFingerTapOnce | CRToastInteractionTypeTwoFingerTapTwice), //An interaction responder with a CRToastInteractionTypeAll interaction type will fire on all swipe and tap interactions CRToastInteractionTypeAll = (CRToastInteractionTypeSwipe, CRToastInteractionTypeTap) }; extern NSString *NSStringFromCRToastInteractionType(CRToastInteractionType interactionType); /** CRToastInteractionResponder is a container object to configure responses to user interactions with a notification. A collection of interaction responders can be included in the options for any given notification or in defaults. */ @interface CRToastInteractionResponder : NSObject /** Creates an interaction responder for a given interaction type. @param interactionType The kind of interaction that will trigger the responder @param automaticallyDismiss A BOOL indiciating if the notification should automatically be dismissed on the interaction being observed. If YES the configured notification dismisall animation will begin immidiately upon encountering the interaction. @param block A block of code to be called immidiately upon the interaction being encountered. The block will be provided the specific CRToastInteractionType that resulted in the block firing */ + (instancetype)interactionResponderWithInteractionType:(CRToastInteractionType)interactionType automaticallyDismiss:(BOOL)automaticallyDismiss block:(void (^)(CRToastInteractionType interactionType))block; @end ///-------------------- /// @name Notification Option Types ///-------------------- /** `CRToastType` defines the height of the notification. `CRToastTypeStatusBar` covers the status bar, `CRToastTypeNavigationBar` covers the status bar and navigation bar */ typedef NS_ENUM(NSInteger, CRToastType){ CRToastTypeStatusBar, CRToastTypeNavigationBar, CRToastTypeCustom }; /** `CRToastPresentationType` defines whether a notification will cover the contents of the status/navigation bar or whether the content will be pushed out by the notification. */ typedef NS_ENUM(NSInteger, CRToastPresentationType){ CRToastPresentationTypeCover, CRToastPresentationTypePush }; /** `CRToastAnimationDirection` defines the direction of the notification. A direction can be specified for both notification entrance and exit. */ typedef NS_ENUM(NSInteger, CRToastAnimationDirection) { CRToastAnimationDirectionTop, CRToastAnimationDirectionBottom, CRToastAnimationDirectionLeft, CRToastAnimationDirectionRight }; /** `CRToastAnimationType` defines the timing function used for the notification presentation. */ typedef NS_ENUM(NSInteger, CRToastAnimationType) { CRToastAnimationTypeLinear, CRToastAnimationTypeSpring, CRToastAnimationTypeGravity }; /** `CRToastState` defines the current state of the CRToast. Used for internal state management in the manager */ typedef NS_ENUM(NSInteger, CRToastState){ CRToastStateWaiting, CRToastStateEntering, CRToastStateDisplaying, CRToastStateExiting, CRToastStateCompleted }; /** `CRToastImageAlignment` defines the alignment of the image given to the CRToast. */ typedef NS_ENUM(NSInteger, CRToastAccessoryViewAlignment){ CRToastAccessoryViewAlignmentLeft, CRToastAccessoryViewAlignmentCenter, CRToastAccessoryViewAlignmentRight }; ///-------------------- /// @name Option Keys ///-------------------- /** These are the keys that define the options that can be set for a notifaction. All primitive types mentioned should be wrapped as `NSNumber`s or `NSValue`s */ /** The notification type for the notification. Expects type `CRToastType`. */ extern NSString *const kCRToastNotificationTypeKey; /** The preferred height for the notificaiton, this will only be used for notifications with CRToastTypeCustom set for kCRToastNotificationTypeKey */ extern NSString *const kCRToastNotificationPreferredHeightKey; /** The presentation type for the notification. Expects type `CRToastPresentationType`. */ extern NSString *const kCRToastNotificationPresentationTypeKey; /** Indicates whether the notification should slide under the staus bar, leaving it visible or not. Making this YES with `kCRToastNotificationTypeKey` set to `CRToastTypeStatusBar` isn't sensible and will look odd. Expects type `BOOL`. */ extern NSString *const kCRToastUnderStatusBarKey; /** Keep toast within navigation bar border. The standard navigation bar has a thin border on the bottom. Animations are improved when the toast is within the border. Customized bars without the border should have this set to NO. Expects type `BOOL`. Defaults to YES. */ extern NSString *const kCRToastKeepNavigationBarBorderKey; /** The animation in type for the notification. Expects type `CRToastAnimationType`. */ extern NSString *const kCRToastAnimationInTypeKey; /** The animation out type for the notification. Expects type `CRToastAnimationType`. */ extern NSString *const kCRToastAnimationOutTypeKey; /** The animation in direction for the notification. Expects type `CRToastAnimationDirection`. */ extern NSString *const kCRToastAnimationInDirectionKey; /** The animation out direction for the notification. Expects type `CRToastAnimationDirection`. */ extern NSString *const kCRToastAnimationOutDirectionKey; /** The animation in time interval for the notification. Expects type `NSTimeInterval`. */ extern NSString *const kCRToastAnimationInTimeIntervalKey; /** The notification presentation timeinterval of type for the notification. This is how long the notification will be on screen after its presentation but before its dismissal. Expects type `NSTimeInterval`. */ extern NSString *const kCRToastTimeIntervalKey; /** The animation out timeinterval for the notification. Expects type `NSTimeInterval`. */ extern NSString *const kCRToastAnimationOutTimeIntervalKey; /** The spring damping coefficient to be used when `kCRToastAnimationInTypeKey` or `kCRToastAnimationOutTypeKey` is set to `CRToastAnimationTypeSpring`. Currently you can't define separate damping for in and out. Expects type `CGFloat`. */ extern NSString *const kCRToastAnimationSpringDampingKey; /** The initial velocity coefficient to be used when `kCRToastAnimationInTypeKey` or `kCRToastAnimationOutTypeKey` is set to `CRToastAnimationTypeSpring`. Currently you can't define initial velocity for in and out. Expects type `CGFloat`. */ extern NSString *const kCRToastAnimationSpringInitialVelocityKey; /** The gravity magnitude coefficient to be used when `kCRToastAnimationInTypeKey` or `kCRToastAnimationOutTypeKey` is set to `CRToastAnimationTypeGravity`. Currently you can't define gravity magnitude for in and out. Expects type `CGFloat`. */ extern NSString *const kCRToastAnimationGravityMagnitudeKey; /** The main text to be shown in the notification. Expects type `NSString`. */ extern NSString *const kCRToastTextKey; /** The attributed main text to be shown in the notification. Expects type `NSAttributedString`. */ extern NSString *const kCRToastAttributedTextKey; /** The font to be used for the `kCRToastTextKey` value . Expects type `UIFont`. */ extern NSString *const kCRToastFontKey; /** The text color to be used for the `kCRToastTextKey` value . Expects type `UIColor`. */ extern NSString *const kCRToastTextColorKey; /** The text alignment to be used for the `kCRToastTextKey` value . Expects type `NSTextAlignment`. */ extern NSString *const kCRToastTextAlignmentKey; /** The shadow color to be used for the `kCRToastTextKey` value . Expects type `UIColor`. */ extern NSString *const kCRToastTextShadowColorKey; /** The shadow offset to be used for the `kCRToastTextKey` value . Expects type `CGSize`. */ extern NSString *const kCRToastTextShadowOffsetKey; /** The max number of lines to be used for the `kCRToastTextKey` value . Expects type `NSInteger`. */ extern NSString *const kCRToastTextMaxNumberOfLinesKey; /** The subtitle text to be shown in the notification. Expects type `NSString`. */ extern NSString *const kCRToastSubtitleTextKey; /** The attributed subtitle text to be shown in the notification. Expects type `NSAttributedString`. */ extern NSString *const kCRToastAttributedSubtitleTextKey; /** The font to be used for the `kCRToastSubtitleTextKey` value . Expects type `UIFont`. */ extern NSString *const kCRToastSubtitleFontKey; /** The text color to be used for the `kCRToastSubtitleTextKey` value . Expects type `UIColor`. */ extern NSString *const kCRToastSubtitleTextColorKey; /** The text alignment to be used for the `kCRToastSubtitleTextKey` value . Expects type `NSTextAlignment`. */ extern NSString *const kCRToastSubtitleTextAlignmentKey; /** The shadow color to be used for the `kCRToastSubtitleTextKey` value . Expects type `UIColor`. */ extern NSString *const kCRToastSubtitleTextShadowColorKey; /** The shadow offset to be used for the `kCRToastSubtitleTextKey` value . Expects type `NSInteger`. */ extern NSString *const kCRToastSubtitleTextShadowOffsetKey; /** The max number of lines to be used for the `kCRToastSubtitleTextKey` value . Expects type `NSInteger`. */ extern NSString *const kCRToastSubtitleTextMaxNumberOfLinesKey; /** The status bar style for the navigation bar. Expects type `UIStatusBarStyle`. */ extern NSString *const kCRToastStatusBarStyleKey; /** The background color for the notification. Expects type `UIColor`. */ extern NSString *const kCRToastBackgroundColorKey; /** Custom view used as the background of the notification */ extern NSString *const kCRToastBackgroundViewKey; /** The image to be shown on the left side of the notification. Expects type `UIImage`. */ extern NSString *const kCRToastImageKey; /** The left image view size to use. Expects type CGSize. */ extern NSString *const kCRToastImageSizeKey; /** The left image corner radius. Expects type CGFloat. */ extern NSString *const kCRToastImageCornerRadiusKey; /** The left image inset. Expects type UIEdgeInset. */ extern NSString *const kCRToastImageInsetKey; /** The image content mode to use for `kCRToastImageKey` image. Exptects type `UIViewContentMode` */ extern NSString *const kCRToastImageContentModeKey; /** The block that is used to set image for left toast image view. Exptects type `CRToastImageBlock` */ extern NSString *const kCRToastImageBlockKey; /** The image to be shown on the left side of the notification. Expects type `UIImage`. */ extern NSString *const kCRToastRightImageKey; /** The left image view size to use. Expects type CGSize. */ extern NSString *const kCRToastRightImageSizeKey; /** The left image corner radius. Expects type CGFloat. */ extern NSString *const kCRToastRightImageCornerRadiusKey; /** The left image inset. Expects type UIEdgeInset. */ extern NSString *const kCRToastRightImageInsetKey; /** The image content mode to use for `kCRToastImageKey` image. Exptects type `UIViewContentMode` */ extern NSString *const kCRToastRightImageContentModeKey; /** The image alignment to use. Expects type `CRToastAccessoryViewAlignment`. */ extern NSString *const kCRToastImageAlignmentKey; /** BOOL setting whether the CRToast should show a loading indicator in the left image location. */ extern NSString *const kCRToastShowActivityIndicatorKey; /** The activity indicator view style. Expects type `UIActivityIndicatorViewStyle` */ extern NSString *const kCRToastActivityIndicatorViewStyleKey; /** The activity indicator alignment to use. Expects type `CRToastAccessoryViewAlignment`. */ extern NSString *const kCRToastActivityIndicatorAlignmentKey; /** An Array of Interaction Responders for the Notification. Expects type `NSArray` full of `CRToastInteractionResponders` */ extern NSString *const kCRToastInteractionRespondersKey; /** BOOL setting whether the CRToast should force the user to interact with it, ignoring the `kCRToastTimeIntervalKey` key */ extern NSString *const kCRToastForceUserInteractionKey; /** An BOOL setting whether the CRToast's should autorotate. Expects type `BOOL` defaults to `YES` */ extern NSString *const kCRToastAutorotateKey; /** Key for the Identifier for a notification. */ extern NSString *const kCRToastIdentifierKey; /** A BOOL setting whether the CRToast's should capture the screen behind the default UIWindow. Expects type `BOOL` defaults to `YES` */ extern NSString *const kCRToastCaptureDefaultWindowKey; #pragma mark - CRToast Interface @interface CRToast : NSObject <UIGestureRecognizerDelegate> @property (nonatomic, strong) NSUUID *uuid; @property (nonatomic, assign) CRToastState state; //Top Level Properties @property (nonatomic, strong) NSDictionary *options; @property (nonatomic, copy) void(^completion)(void); @property (nonatomic, copy) void(^appearance)(void); //Interactions @property (nonatomic, strong) NSArray *gestureRecognizers; //Autorotate @property (nonatomic, assign) BOOL autorotate; //Views and Layout Data @property (nonatomic, readonly) UIView *notificationView; @property (nonatomic, readonly) CGRect notificationViewAnimationFrame1; @property (nonatomic, readonly) CGRect notificationViewAnimationFrame2; @property (nonatomic, readonly) UIView *statusBarView; @property (nonatomic, readonly) CGRect statusBarViewAnimationFrame1; @property (nonatomic, readonly) CGRect statusBarViewAnimationFrame2; @property (nonatomic, strong) UIDynamicAnimator *animator; //Read Only Convinence Properties Providing Default Values or Values from Options @property (nonatomic, readonly) CRToastType notificationType; @property (nonatomic, assign) CGFloat preferredHeight; @property (nonatomic, readonly) CRToastPresentationType presentationType; @property (nonatomic, readonly) BOOL displayUnderStatusBar; @property (nonatomic, readonly) BOOL shouldKeepNavigationBarBorder; @property (nonatomic, readonly) CRToastAnimationType inAnimationType; @property (nonatomic, readonly) CRToastAnimationType outAnimationType; @property (nonatomic, readonly) CRToastAnimationDirection inAnimationDirection; @property (nonatomic, readonly) CRToastAnimationDirection outAnimationDirection; @property (nonatomic, readonly) NSTimeInterval animateInTimeInterval; @property (nonatomic, readonly) NSTimeInterval timeInterval; @property (nonatomic, readonly) NSTimeInterval animateOutTimeInterval; @property (nonatomic, readonly) CGFloat animationSpringDamping; @property (nonatomic, readonly) CGFloat animationSpringInitialVelocity; @property (nonatomic, readonly) CGFloat animationGravityMagnitude; @property (nonatomic, readonly) NSString *text; @property (nonatomic, readonly) NSAttributedString *attributedText; @property (nonatomic, readonly) UIFont *font; @property (nonatomic, readonly) UIColor *textColor; @property (nonatomic, readonly) NSTextAlignment textAlignment; @property (nonatomic, readonly) UIColor *textShadowColor; @property (nonatomic, readonly) CGSize textShadowOffset; @property (nonatomic, readonly) NSInteger textMaxNumberOfLines; @property (nonatomic, readonly) NSString *subtitleText; @property (nonatomic, readonly) NSAttributedString *attributedSubtitleText; @property (nonatomic, readonly) UIFont *subtitleFont; @property (nonatomic, readonly) UIColor *subtitleTextColor; @property (nonatomic, readonly) NSTextAlignment subtitleTextAlignment; @property (nonatomic, readonly) UIColor *subtitleTextShadowColor; @property (nonatomic, readonly) CGSize subtitleTextShadowOffset; @property (nonatomic, readonly) NSInteger subtitleTextMaxNumberOfLines; @property (nonatomic, readonly) UIStatusBarStyle statusBarStyle; @property (nonatomic, readonly) UIColor *backgroundColor; @property (nonatomic, readonly) UIView *backgroundView; @property (nonatomic, readonly) UIImage *image; @property (nonatomic, readonly) UIViewContentMode imageContentMode; @property (nonatomic, readonly) CGSize leftImageSize; @property (nonatomic, readonly) CGFloat leftImageCornerRadius; @property (nonatomic, readonly) UIEdgeInsets leftImageInsets; @property (nonatomic, readonly) CRToastImageBlock imageBlock; @property (nonatomic, readonly) UIImage *rightImage; @property (nonatomic, readonly) UIViewContentMode rightImageContentMode; @property (nonatomic, readonly) CGSize rightImageSize; @property (nonatomic, readonly) CGFloat rightImageCornerRadius; @property (nonatomic, readonly) UIEdgeInsets rightImageInsets; @property (nonatomic, readonly) CRToastAccessoryViewAlignment imageAlignment; @property (nonatomic, readonly) UIActivityIndicatorViewStyle activityIndicatorViewStyle; @property (nonatomic, readonly) CRToastAccessoryViewAlignment activityViewAlignment; @property (nonatomic, readonly) BOOL showActivityIndicator; @property (nonatomic, readonly) BOOL forceUserInteraction; @property (nonatomic, readonly) CGVector inGravityDirection; @property (nonatomic, readonly) CGVector outGravityDirection; @property (nonatomic, readonly) CGPoint inCollisionPoint1; @property (nonatomic, readonly) CGPoint inCollisionPoint2; @property (nonatomic, readonly) CGPoint outCollisionPoint1; @property (nonatomic, readonly) CGPoint outCollisionPoint2; - (void)swipeGestureRecognizerSwiped:(CRToastSwipeGestureRecognizer*)swipeGestureRecognizer; - (void)tapGestureRecognizerTapped:(CRToastTapGestureRecognizer*)tapGestureRecognizer; - (void)initiateAnimator:(UIView *)view; @end
Naithar/CRToast
CRToast/CRToast.h
C
mit
19,415
// // This file genenerated by the Buckle tool on 2/13/2015 at 8:27 AM. // // Contains strongly typed wrappers for resources in VacuumResources.resx // namespace Vacuum { using System; using System.Reflection; using System.Resources; using System.Diagnostics; using System.Globalization; /// <summary> /// Strongly typed resource wrappers generated from VacuumResources.resx. /// </summary> public class VacuumResources { internal static readonly ResourceManager ResourceManager = new ResourceManager(typeof(VacuumResources)); /// <summary> /// File '{0}' does not exist /// </summary> public static string FileNotFound(object param0) { string format = ResourceManager.GetString("FileNotFound", CultureInfo.CurrentUICulture); return string.Format(CultureInfo.CurrentCulture, format, param0); } } }
jlyonsmith/Vacuum
VacuumLibrary/Resources/VacuumResources.cs
C#
mit
847
# test_eng.py # Copyright (c) 2013-2016 Pablo Acosta-Serafini # See LICENSE for details # pylint: disable=C0103,C0111,C0302,E0611,R0913,R0915,W0108,W0212 # Standard library imports import functools import sys import pytest from numpy import array, ndarray # Putil imports import putil.eng from putil.test import AE, AI, CS ### # Global variables ### DFLT = 'def' PY2 = bool(sys.hexversion < 0x03000000) ### # Helper functions ### isdflt = lambda obj: bool(obj == DFLT) h = lambda num: '100.'+('0'*num) o = lambda num: '1.'+('0'*num) pv = lambda py2arg, py3arg: py2arg if PY2 else py3arg sarg = lambda msg: 'Argument `{0}` is not valid'.format(msg) t = lambda num: '10.'+('0'*num) def to_sci_string(number): """ Returns a string with the number formatted in scientific notation. This function does not have all the configurability of the public function to_scientific_string, it is a convenience function to test _to_eng_tuple """ mant, exp = putil.eng._to_eng_tuple(number) return '{mant}E{exp_sign}{exp}'.format( mant=mant, exp_sign='-' if exp < 0 else '+', exp=abs(exp) ) ### # Test functions ### @pytest.mark.parametrize( 'text, sep, num, lstrip, rstrip, ref', [ ('a, b, c, d', ',', 1, DFLT, DFLT, ('a', ' b', ' c', ' d')), ('a , b , c , d ', ',', 1, DFLT, DFLT, ('a ', ' b ', ' c ', ' d ')), ('a , b , c , d ', ',', 1, True, DFLT, ('a ', 'b ', 'c ', 'd ')), ('a , b , c , d ', ',', 1, DFLT, True, ('a', ' b', ' c', ' d')), ('a , b , c , d ', ',', 1, True, True, ('a', 'b', 'c', 'd')), ('a, b, c, d', ',', 2, DFLT, DFLT, ('a, b', ' c, d')), ('a, b, c, d', ',', 3, DFLT, DFLT, ('a, b, c', ' d')), ('a, b, c, d', ',', 4, DFLT, DFLT, ('a, b, c, d',)), ('a, b, c, d', ',', 5, DFLT, DFLT, ('a, b, c, d',)), ] ) def test_split_every(text, sep, num, lstrip, rstrip, ref): """ Test _split_every function behavior """ # DFLT in lstrip or rstrip means default argument values should be used obj = putil.eng._split_every obj = obj if isdflt(lstrip) else functools.partial(obj, lstrip=lstrip) obj = obj if isdflt(rstrip) else functools.partial(obj, rstrip=rstrip) assert obj(text, sep, num) == ref @pytest.mark.parametrize( 'num, ref', [ (0.000000000000000000000001001234567890, '1.00123456789E-24'), (0.000000000000000000000001, '1E-24'), (0.00000000000000000000001001234567890, '10.0123456789E-24'), (0.00000000000000000000001, '10E-24'), (0.0000000000000000000001001234567890, '100.123456789E-24'), (0.0000000000000000000001, '100E-24'), (0.000000000000000000001001234567890, '1.00123456789E-21'), (0.000000000000000000001, '1E-21'), (0.00000000000000000001001234567890, '10.0123456789E-21'), (0.00000000000000000001, '10E-21'), (0.0000000000000000001001234567890, '100.123456789E-21'), (0.0000000000000000001, '100E-21'), (0.000000000000000001001234567890, '1.00123456789E-18'), (0.000000000000000001, '1E-18'), (0.00000000000000001001234567890, '10.0123456789E-18'), (0.00000000000000001, '10E-18'), (0.0000000000000001001234567890, '100.123456789E-18'), (0.0000000000000001, '100E-18'), (0.000000000000001001234567890, '1.00123456789E-15'), (0.000000000000001, '1E-15'), (0.00000000000001001234567890, '10.0123456789E-15'), (0.00000000000001, '10E-15'), (0.0000000000001001234567890, '100.123456789E-15'), (0.0000000000001, '100E-15'), (0.000000000001001234567890, '1.00123456789E-12'), (0.000000000001, '1E-12'), (0.00000000001001234567890, '10.0123456789E-12'), (0.00000000001, '10E-12'), (0.0000000001001234567890, '100.123456789E-12'), (0.0000000001, '100E-12'), (0.000000001001234567890, '1.00123456789E-9'), (0.000000001, '1E-9'), (0.00000001001234567890, '10.0123456789E-9'), (0.00000001, '10E-9'), (0.0000001001234567890, '100.123456789E-9'), (0.0000001, '100E-9'), (0.000001001234567890, '1.00123456789E-6'), (0.000001, '1E-6'), (0.00001001234567890, '10.0123456789E-6'), (0.00001, '10E-6'), (0.0001001234567890, '100.123456789E-6'), (0.0001, '100E-6'), (0.001001234567890, '1.00123456789E-3'), (0.001, '1E-3'), (0.01001234567890, '10.0123456789E-3'), (0.01, '10E-3'), (0.1001234567890, '100.123456789E-3'), (0.1, '100E-3'), (0, '0E+0'), (1, '1E+0'), (1.1234567890, '1.123456789E+0'), (10, '10E+0'), (10.1234567890, '10.123456789E+0'), (100, '100E+0'), (100.1234567890, '100.123456789E+0'), (1000, '1E+3'), (1000.1234567890, pv('1.00012345679E+3', '1.000123456789E+3')), (10000, '10E+3'), (10000.1234567890, pv('10.0001234568E+3', '10.000123456789E+3')), (100000, '100E+3'), (100000.1234567890, pv('100.000123457E+3', '100.000123456789E+3')), (1000000, '1E+6'), (1000000.1234567890, pv('1.00000012346E+6', '1.000000123456789E+6')), (10000000, '10E+6'), (10000000.1234567890, pv('10.0000001235E+6', '10.00000012345679E+6')), (100000000, '100E+6'), (100000000.1234567890, pv('100.000000123E+6', '100.00000012345679E+6')), (1000000000, '1E+9'), (1000000000.1234567890, pv('1.00000000012E+9', '1.0000000001234568E+9')), (10000000000, '10E+9'), (10000000000.1234567890, pv(t(9)+'1E+9', '10.000000000123457E+9')), (100000000000, '100E+9'), (100000000000.1234567890, pv('100E+9', '100.00000000012346E+9')), (1000000000000, '1E+12'), (1000000000000.1234567890, pv('1E+12', '1.0000000000001234E+12')), (10000000000000, '10E+12'), (10000000000000.1234567890, pv('10E+12', '10.000000000000123E+12')), (100000000000000, '100E+12'), (100000000000000.1234567890, pv('100E+12', '100.00000000000012E+12')), (1000000000000000, '1E+15'), (1000000000000000.1234567890, pv('1E+15', '1.0000000000000001E+15')), (10000000000000000, '10E+15'), (10000000000000000.1234567890, '10E+15'), (100000000000000000, '100E+15'), (100000000000000000.1234567890, '100E+15'), (1000000000000000000, '1E+18'), (1000000000000000000.1234567890, '1E+18'), (10000000000000000000, '10E+18'), (10000000000000000000.1234567890, '10E+18'), (100000000000000000000, '100E+18'), (100000000000000000000.1234567890, '100E+18'), (1000000000000000000000, '1E+21'), (1000000000000000000000.1234567890, '1E+21'), (10000000000000000000000, '10E+21'), (10000000000000000000000.1234567890, '10E+21'), (100000000000000000000000, '100E+21'), (100000000000000000000000.1234567890, pv('100E+21', h(13)+'1E+21')), (1000000000000000000000000, '1E+24'), (1000000000000000000000000.1234567890, '1E+24'), (10000000000000000000000000, '10E+24'), (10000000000000000000000000.1234567890, '10E+24'), (100000000000000000000000000, '100E+24'), (100000000000000000000000000.1234567890, '100E+24'), (-0.000000000000000000000001001234567890, '-1.00123456789E-24'), (-0.000000000000000000000001, '-1E-24'), (-0.00000000000000000000001001234567890, '-10.0123456789E-24'), (-0.00000000000000000000001, '-10E-24'), (-0.0000000000000000000001001234567890, '-100.123456789E-24'), (-0.0000000000000000000001, '-100E-24'), (-0.000000000000000000001001234567890, '-1.00123456789E-21'), (-0.000000000000000000001, '-1E-21'), (-0.00000000000000000001001234567890, '-10.0123456789E-21'), (-0.00000000000000000001, '-10E-21'), (-0.0000000000000000001001234567890, '-100.123456789E-21'), (-0.0000000000000000001, '-100E-21'), (-0.000000000000000001001234567890, '-1.00123456789E-18'), (-0.000000000000000001, '-1E-18'), (-0.00000000000000001001234567890, '-10.0123456789E-18'), (-0.00000000000000001, '-10E-18'), (-0.0000000000000001001234567890, '-100.123456789E-18'), (-0.0000000000000001, '-100E-18'), (-0.000000000000001001234567890, '-1.00123456789E-15'), (-0.000000000000001, '-1E-15'), (-0.00000000000001001234567890, '-10.0123456789E-15'), (-0.00000000000001, '-10E-15'), (-0.0000000000001001234567890, '-100.123456789E-15'), (-0.0000000000001, '-100E-15'), (-0.000000000001001234567890, '-1.00123456789E-12'), (-0.000000000001, '-1E-12'), (-0.00000000001001234567890, '-10.0123456789E-12'), (-0.00000000001, '-10E-12'), (-0.0000000001001234567890, '-100.123456789E-12'), (-0.0000000001, '-100E-12'), (-0.000000001001234567890, '-1.00123456789E-9'), (-0.000000001, '-1E-9'), (-0.00000001001234567890, '-10.0123456789E-9'), (-0.00000001, '-10E-9'), (-0.0000001001234567890, '-100.123456789E-9'), (-0.0000001, '-100E-9'), (-0.000001001234567890, '-1.00123456789E-6'), (-0.000001, '-1E-6'), (-0.00001001234567890, '-10.0123456789E-6'), (-0.00001, '-10E-6'), (-0.0001001234567890, '-100.123456789E-6'), (-0.0001, '-100E-6'), (-0.001001234567890, '-1.00123456789E-3'), (-0.001, '-1E-3'), (-0.01001234567890, '-10.0123456789E-3'), (-0.01, '-10E-3'), (-0.1001234567890, '-100.123456789E-3'), (-0.1, '-100E-3'), (-1, '-1E+0'), (-1.1234567890, '-1.123456789E+0'), (-10, '-10E+0'), (-10.1234567890, '-10.123456789E+0'), (-100, '-100E+0'), (-100.1234567890, '-100.123456789E+0'), (-1000, '-1E+3'), (-1000.1234567890, pv('-1.00012345679E+3', '-1.000123456789E+3')), (-10000, '-10E+3'), (-10000.1234567890, pv('-10.0001234568E+3', '-10.000123456789E+3')), (-100000, '-100E+3'), (-100000.1234567890, pv('-100.000123457E+3', '-100.000123456789E+3')), (-1000000, '-1E+6'), (-1000000.1234567890, pv('-1.00000012346E+6', '-1.000000123456789E+6')), (-10000000, '-10E+6'), (-10000000.1234567890, pv('-10.0000001235E+6', '-10.00000012345679E+6')), (-100000000, '-100E+6'), (-100000000.1234567890, pv('-'+h(6)+'123E+6', '-100.00000012345679E+6')), (-1000000000, '-1E+9'), (-1000000000.1234567890, pv('-'+o(9)+'12E+9', '-1.0000000001234568E+9')), (-10000000000, '-10E+9'), (-10000000000.1234567890, pv('-'+t(9)+'1E+9', '-'+t(9)+'123457E+9')), (-100000000000, '-100E+9'), (-100000000000.1234567890, pv('-100E+9', '-100.00000000012346E+9')), (-1000000000000, '-1E+12'), (-1000000000000.1234567890, pv('-1E+12', '-1.0000000000001234E+12')), (-10000000000000, '-10E+12'), (-10000000000000.1234567890, pv('-10E+12', '-10.000000000000123E+12')), (-100000000000000, '-100E+12'), (-100000000000000.1234567890, pv('-100E+12', '-100.00000000000012E+12')), (-1000000000000000, '-1E+15'), (-1000000000000000.1234567890, pv('-1E+15', '-1.0000000000000001E+15')), (-10000000000000000, '-10E+15'), (-10000000000000000.1234567890, '-10E+15'), (-100000000000000000, '-100E+15'), (-100000000000000000.1234567890, '-100E+15'), (-1000000000000000000, '-1E+18'), (-1000000000000000000.1234567890, '-1E+18'), (-10000000000000000000, '-10E+18'), (-10000000000000000000.1234567890, '-10E+18'), (-100000000000000000000, '-100E+18'), (-100000000000000000000.1234567890, '-100E+18'), (-1000000000000000000000, '-1E+21'), (-1000000000000000000000.1234567890, '-1E+21'), (-10000000000000000000000, '-10E+21'), (-10000000000000000000000.1234567890, '-10E+21'), (-100000000000000000000000, '-100E+21'), (-100000000000000000000000.1234567890, pv('-100E+21', '-'+h(13)+'1E+21')), (-1000000000000000000000000, '-1E+24'), (-1000000000000000000000000.1234567890, '-1E+24'), (-10000000000000000000000000, '-10E+24'), (-10000000000000000000000000.1234567890, '-10E+24'), (-100000000000000000000000000, '-100E+24'), (-100000000000000000000000000.1234567890, '-100E+24'), ('100000.1234567890', '100.000123456789E+3'), ('-100000.1234567890', '-100.000123456789E+3'), ] ) def test_to_sci_string(num, ref): """ Test _to_eng_string function behavior """ assert to_sci_string(num) == ref @pytest.mark.parametrize( 'num, ref', [ (0, '0'), (0.0, '0.0'), (4, '4'), (4.0, '4.0'), (45, '45'), (450, '450'), (1234567, '1234567'), (4.5, '4.5'), (4.1234, '4.1234'), (4123.4E4, '41234000'), (0.1, '0.1'), (1.43E-2, '0.0143'), (100000000.0, '100000000.0'), (1000000, '1000000'), (1e3, '1000.0'), ] ) def test_no_exp(num, ref): """ Test no_exp function behavior """ assert putil.eng.no_exp(num) == ref @pytest.mark.eng def test_no_ex_exceptions(): """ Test no_exp function exceptions """ AI(putil.eng.no_exp, 'number', number='a') @pytest.mark.eng @pytest.mark.parametrize( 'args, name', [ (dict(number=['5'], frac_length=3, rjust=True), 'number'), (dict(number=5, frac_length=3.5, rjust=True), 'frac_length'), (dict(number=5, frac_length=-2, rjust=True), 'frac_length'), (dict(number=5, frac_length=3, rjust='a'), 'rjust') ] ) def test_peng_exceptions(args, name): """ Test peng function exceptions """ AI(putil.eng.peng, name, **args) @pytest.mark.parametrize( 'num, mant, rjust, ref', [ (3.0333333333, 1, False, '3.0'), (0, 3, True, ' 0.000 '), (0, 3, False, '0.000'), (125.5, 0, False, '126'), (1e-25, 3, True, ' 1.000y'), (1e-24, 3, True, ' 1.000y'), (1e-23, 3, True, ' 10.000y'), (1e-22, 3, True, ' 100.000y'), (1e-21, 3, True, ' 1.000z'), (1e-20, 3, True, ' 10.000z'), (1e-19, 3, True, ' 100.000z'), (1e-18, 3, True, ' 1.000a'), (1e-17, 3, True, ' 10.000a'), (1e-16, 3, True, ' 100.000a'), (1e-15, 3, True, ' 1.000f'), (1e-14, 3, True, ' 10.000f'), (1e-13, 3, True, ' 100.000f'), (1e-12, 3, True, ' 1.000p'), (1e-11, 3, True, ' 10.000p'), (1e-10, 3, True, ' 100.000p'), (1e-9, 3, True, ' 1.000n'), (1e-8, 3, True, ' 10.000n'), (1e-7, 3, True, ' 100.000n'), (1e-6, 3, True, ' 1.000u'), (1e-5, 3, True, ' 10.000u'), (1e-4, 3, True, ' 100.000u'), (1e-3, 3, True, ' 1.000m'), (1e-2, 3, True, ' 10.000m'), (1e-1, 3, True, ' 100.000m'), (1e-0, 3, True, ' 1.000 '), (1e+1, 3, True, ' 10.000 '), (1e+2, 3, True, ' 100.000 '), (1e+3, 3, True, ' 1.000k'), (1e+4, 3, True, ' 10.000k'), (1e+5, 3, True, ' 100.000k'), (1e+6, 3, True, ' 1.000M'), (1e+7, 3, True, ' 10.000M'), (1e+8, 3, True, ' 100.000M'), (1e+9, 3, True, ' 1.000G'), (1e+10, 3, True, ' 10.000G'), (1e+11, 3, True, ' 100.000G'), (1e+12, 3, True, ' 1.000T'), (1e+13, 3, True, ' 10.000T'), (1e+14, 3, True, ' 100.000T'), (1e+15, 3, True, ' 1.000P'), (1e+16, 3, True, ' 10.000P'), (1e+17, 3, True, ' 100.000P'), (1e+18, 3, True, ' 1.000E'), (1e+19, 3, True, ' 10.000E'), (1e+20, 3, True, ' 100.000E'), (1e+21, 3, True, ' 1.000Z'), (1e+22, 3, True, ' 10.000Z'), (1e+23, 3, True, ' 100.000Z'), (1e+24, 3, True, ' 1.000Y'), (1e+25, 3, True, ' 10.000Y'), (1e+26, 3, True, ' 100.000Y'), (1e+27, 3, True, ' 999.999Y'), (12.45, 1, True, ' 12.5 '), (998.999e3, 1, True, ' 999.0k'), (998.999e3, 1, False, '999.0k'), (999.999e3, 1, True, ' 1.0M'), (999.999e3, 1, DFLT, ' 1.0M'), (999.999e3, 1, False, '1.0M'), (0.995, 0, False, '995m'), (0.9999, 0, False, '1'), (1.9999, 0, False, '2'), (999.99, 0, False, '1k'), (9.99, 1, False, '10.0'), (5.25e3, 1, True, ' 5.3k'), (1.05e3, 0, True, ' 1k'), (-1e-25, 3, True, ' -1.000y'), (-1e-24, 3, True, ' -1.000y'), (-1e-23, 3, True, ' -10.000y'), (-1e-22, 3, True, '-100.000y'), (-1e-21, 3, True, ' -1.000z'), (-1e-20, 3, True, ' -10.000z'), (-1e-19, 3, True, '-100.000z'), (-1e-18, 3, True, ' -1.000a'), (-1e-17, 3, True, ' -10.000a'), (-1e-16, 3, True, '-100.000a'), (-1e-15, 3, True, ' -1.000f'), (-1e-14, 3, True, ' -10.000f'), (-1e-13, 3, True, '-100.000f'), (-1e-12, 3, True, ' -1.000p'), (-1e-11, 3, True, ' -10.000p'), (-1e-10, 3, True, '-100.000p'), (-1e-9, 3, True, ' -1.000n'), (-1e-8, 3, True, ' -10.000n'), (-1e-7, 3, True, '-100.000n'), (-1e-6, 3, True, ' -1.000u'), (-1e-5, 3, True, ' -10.000u'), (-1e-4, 3, True, '-100.000u'), (-1e-3, 3, True, ' -1.000m'), (-1e-2, 3, True, ' -10.000m'), (-1e-1, 3, True, '-100.000m'), (-1e-0, 3, True, ' -1.000 '), (-1e+1, 3, True, ' -10.000 '), (-1e+2, 3, True, '-100.000 '), (-1e+3, 3, True, ' -1.000k'), (-1e+4, 3, True, ' -10.000k'), (-1e+5, 3, True, '-100.000k'), (-1e+6, 3, True, ' -1.000M'), (-1e+7, 3, True, ' -10.000M'), (-1e+8, 3, True, '-100.000M'), (-1e+9, 3, True, ' -1.000G'), (-1e+10, 3, True, ' -10.000G'), (-1e+11, 3, True, '-100.000G'), (-1e+12, 3, True, ' -1.000T'), (-1e+13, 3, True, ' -10.000T'), (-1e+14, 3, True, '-100.000T'), (-1e+15, 3, True, ' -1.000P'), (-1e+16, 3, True, ' -10.000P'), (-1e+17, 3, True, '-100.000P'), (-1e+18, 3, True, ' -1.000E'), (-1e+19, 3, True, ' -10.000E'), (-1e+20, 3, True, '-100.000E'), (-1e+21, 3, True, ' -1.000Z'), (-1e+22, 3, True, ' -10.000Z'), (-1e+23, 3, True, '-100.000Z'), (-1e+24, 3, True, ' -1.000Y'), (-1e+25, 3, True, ' -10.000Y'), (-1e+26, 3, True, '-100.000Y'), (-1e+27, 3, True, '-999.999Y'), (-12.45, 1, True, ' -12.5 '), (-998.999e3, 1, True, '-999.0k'), (-998.999e3, 1, False, '-999.0k'), (-999.999e3, 1, True, ' -1.0M'), (-999.999e3, 1, DFLT, ' -1.0M'), (-999.999e3, 1, False, '-1.0M'), (-0.995, 0, False, '-995m'), (-0.9999, 0, False, '-1'), (-1.9999, 0, False, '-2'), (-999.99, 0, False, '-1k'), (-9.99, 1, False, '-10.0'), (-5.25e3, 1, True, ' -5.3k'), (-1.05e3, 0, True, ' -1k') ] ) def test_peng(num, mant, rjust, ref): """ Test peng function behavior """ obj = putil.eng.peng obj = obj if isdflt(rjust) else functools.partial(obj, rjust=rjust) assert obj(num, mant) == ref @pytest.mark.eng @pytest.mark.parametrize('arg', [None, 5, '', ' 5x', 'a5M', '- - a5M']) @pytest.mark.parametrize( 'func', [ putil.eng.peng_float, putil.eng.peng_frac, putil.eng.peng_int, putil.eng.peng_mant, putil.eng.peng_power, putil.eng.peng_suffix, ] ) def test_peng_snum_exceptions(func, arg): """ Test exceptions of functions that receive a string representing a number in engineering notation """ AI(func, 'snum', **dict(snum=arg)) @pytest.mark.parametrize( 'arg, ref', [ (putil.eng.peng(5234.567, 3, True), 5.235e3), (' 5.235k ', 5.235e3), (' -5.235k ', -5.235e3), ] ) def test_peng_float(arg, ref): """ Test peng_float function behavior """ assert putil.eng.peng_float(arg) == ref @pytest.mark.parametrize( 'arg, ref', [ (putil.eng.peng(5234.567, 6, True), 234567), (putil.eng.peng(5234, 0, True), 0) ] ) def test_peng_frac(arg, ref): """ Test peng_frac function behavior """ assert putil.eng.peng_frac(arg) == ref def test_peng_int(): """ Test peng_int function behavior """ assert putil.eng.peng_int(putil.eng.peng(5234.567, 6, True)) == 5 def test_peng_mant(): """ Test peng_mant function behavior """ assert putil.eng.peng_mant(putil.eng.peng(5234.567, 3, True)) == 5.235 def test_peng_power(): """ Test peng_power function behavior """ tup = putil.eng.peng_power(putil.eng.peng(1234.567, 3, True)) assert tup == ('k', 1000.0) assert isinstance(tup[1], float) @pytest.mark.parametrize( 'arg, ref', [ (putil.eng.peng(1, 3, True), ' '), (putil.eng.peng(-10.5e-6, 3, False), 'u') ] ) def test_peng_suffix(arg, ref): """ Test peng_suffix function behavior """ assert putil.eng.peng_suffix(arg) == ref @pytest.mark.eng @pytest.mark.parametrize( 'args, extype, name', [ (dict(suffix='X', offset=-1), RuntimeError, 'suffix'), (dict(suffix='M', offset='a'), RuntimeError, 'offset'), (dict(suffix='M', offset=20), ValueError, 'offset'), ] ) @pytest.mark.eng def test_peng_suffix_math_exceptions(args, extype, name): """ Test peng_suffix_math function exceptions """ AE(putil.eng.peng_suffix_math, extype, sarg(name), **args) @pytest.mark.parametrize('args, ref', [((' ', 3), 'G'), (('u', -2), 'p')]) def test_peng_suffix_math(args, ref): """ Test peng_suffix_math function behavior """ assert putil.eng.peng_suffix_math(*args) == ref @pytest.mark.parametrize( 'num, frac_length, exp_length, sign_always, ref', [ ('5.35E+3', DFLT, DFLT, DFLT, '5.35E+3'), (0, DFLT, DFLT, DFLT, '0E+0'), (0.1, DFLT, DFLT, DFLT, '1E-1'), (0.01, DFLT, DFLT, DFLT, '1E-2'), (0.001, DFLT, DFLT, DFLT, '1E-3'), (0.00101, DFLT, DFLT, DFLT, '1.01E-3'), (0.123456789012, DFLT, DFLT, DFLT, '1.23456789012E-1'), (1234567.89012, DFLT, DFLT, DFLT, '1.23456789012E+6'), (1, DFLT, DFLT, DFLT, '1E+0'), (20, DFLT, DFLT, DFLT, '2E+1'), (100, DFLT, DFLT, DFLT, '1E+2'), (200, DFLT, DFLT, DFLT, '2E+2'), (333, DFLT, DFLT, DFLT, '3.33E+2'), (4567, DFLT, DFLT, DFLT, '4.567E+3'), (4567.890, DFLT, DFLT, DFLT, '4.56789E+3'), (500, 3, DFLT, DFLT, '5.000E+2'), (4567.890, 8, DFLT, DFLT, '4.56789000E+3'), (99.999, 1, DFLT, DFLT, '1.0E+2'), (4567.890, DFLT, DFLT, True, '+4.56789E+3'), (500, 3, DFLT, True, '+5.000E+2'), (4567.890, 8, DFLT, True, '+4.56789000E+3'), (99.999, 1, DFLT, True, '+1.0E+2'), (500, 3, 2, True, '+5.000E+02'), (4567.890, 8, 3, True, '+4.56789000E+003'), (9999999999.999, 1, 1, True, '+1.0E+10'), (-0.1, DFLT, DFLT, DFLT, '-1E-1'), (-0.01, DFLT, DFLT, DFLT, '-1E-2'), (-0.001, DFLT, DFLT, DFLT, '-1E-3'), (-0.00101, DFLT, DFLT, DFLT, '-1.01E-3'), (-0.123456789012, DFLT, DFLT, DFLT, '-1.23456789012E-1'), (-1234567.89012, DFLT, DFLT, DFLT, '-1.23456789012E+6'), (-1, DFLT, DFLT, DFLT, '-1E+0'), (-20, DFLT, DFLT, DFLT, '-2E+1'), (-100, DFLT, DFLT, DFLT, '-1E+2'), (-200, DFLT, DFLT, DFLT, '-2E+2'), (-333, DFLT, DFLT, DFLT, '-3.33E+2'), (-4567, DFLT, DFLT, DFLT, '-4.567E+3'), (-4567.890, DFLT, DFLT, DFLT, '-4.56789E+3'), (-500, 3, DFLT, DFLT, '-5.000E+2'), (-4567.890, 8, DFLT, DFLT, '-4.56789000E+3'), (-99.999, 1, DFLT, DFLT, '-1.0E+2'), (-4567.890, DFLT, DFLT, True, '-4.56789E+3'), (-500, 3, DFLT, True, '-5.000E+2'), (-4567.890, 8, DFLT, True, '-4.56789000E+3'), (-99.999, 1, DFLT, True, '-1.0E+2'), (-500, 3, 2, True, '-5.000E+02'), (-4567.890, 8, 3, True, '-4.56789000E+003'), (-9999999999.999, 1, 1, True, '-1.0E+10'), ] ) def test_to_scientific_string(num, frac_length, exp_length, sign_always, ref): """ Test _to_scientific function behavior """ fp = functools.partial obj = putil.eng.to_scientific_string obj = obj if isdflt(frac_length) else fp(obj, frac_length=frac_length) obj = obj if isdflt(exp_length) else fp(obj, exp_length=exp_length) obj = obj if isdflt(sign_always) else fp(obj, sign_always=sign_always) assert obj(num) == ref CVECTOR = [-1+2j, 3+4j, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j] @pytest.mark.parametrize( 'vector, args, ref, header', [ ( None, DFLT, 'None', '' ), ( [1, 2, 3, 4, 5, 6, 7, 8], DFLT, '[ 1, 2, 3, 4, 5, 6, 7, 8 ]', '' ), ( [1, 2, 3, 4, 5, 6, 7, 8], dict(indent=20), '[ 1, 2, 3, 4, 5, 6, 7, 8 ]', '' ), ( [1, 2, 3, 4, 5, 6, 7, 8], dict(indent=20), '[ 1, 2, 3, 4, 5, 6, 7, 8 ]', '' ), ( [1, 2, 3, 4, 5, 6, 7, 8], dict(limit=True), '[ 1, 2, 3, ..., 6, 7, 8 ]', '' ), ( [1, 2, 3, 4, 5, 6, 7, 8], dict(limit=True, indent=20), '[ 1, 2, 3, ..., 6, 7, 8 ]', '' ), # Float and integer item #ref = ( ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(eng=True), '[ 1.000m, 20.000u, 300.000M, 4.000p,' ' 5.250k, -6.000n, 700.000 , 800.000m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(eng=True, indent=20), '[ 1.000m, 20.000u, 300.000M, 4.000p,' ' 5.250k, -6.000n, 700.000 , 800.000m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(limit=True, eng=True), '[ 1.000m, 20.000u, 300.000M,' ' ...,' ' -6.000n, 700.000 , 800.000m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(limit=True, eng=True, indent=20), '[ 1.000m, 20.000u, 300.000M,' ' ...,' ' -6.000n, 700.000 , 800.000m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(eng=True, frac_length=1), '[ 1.0m, 20.0u, 300.0M, 4.0p,' ' 5.3k, -6.0n, 700.0 , 800.0m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(eng=True, frac_length=1, indent=20), '[ 1.0m, 20.0u, 300.0M, 4.0p,' ' 5.3k, -6.0n, 700.0 , 800.0m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(limit=True, eng=True, frac_length=1), '[ 1.0m, 20.0u, 300.0M, ..., -6.0n, 700.0 , 800.0m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(limit=True, indent=20, eng=True, frac_length=1), '[ 1.0m, 20.0u, 300.0M, ..., -6.0n, 700.0 , 800.0m ]', '' ), ( [1, 2, 3, 4, 5, 6, 7, 8], dict(width=8), #12345678 '[ 1, 2,\n' ' 3, 4,\n' ' 5, 6,\n' ' 7, 8 ]', '' ), ( [1, 2, 3, 4, 5, 6, 7, 8], dict(width=10), '[ 1, 2, 3,\n' ' 4, 5, 6,\n' ' 7, 8 ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9], dict(width=20, eng=True, frac_length=0), '[ 1m, 20u,\n' ' 300M, 4p,\n' ' 5k, -6n,\n' ' 700 , 8 ,\n' ' 9 ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(width=30, eng=True, frac_length=1), '[ 1.0m, 20.0u, 300.0M,\n' ' 4.0p, 5.3k, -6.0n,\n' ' 700.0 , 800.0m ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9], dict(width=20, eng=True, frac_length=0, limit=True), '[ 1m,\n' ' 20u,\n' ' 300M,\n' ' ...\n' ' 700 ,\n' ' 8 ,\n' ' 9 ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9], dict(width=30, eng=True, frac_length=1, limit=True), '[ 1.0m, 20.0u, 300.0M,\n' ' ...\n' ' 700.0 , 8.0 , 9.0 ]', '' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9], dict(width=30, eng=True, frac_length=1, limit=True, indent=8), 'Vector: [ 1.0m, 20.0u, 300.0M,\n' ' ...\n' ' 700.0 , 8.0 , 9.0 ]', 'Vector: ' ), ( [1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 0.8], dict(width=30, eng=True, frac_length=1, indent=8), 'Vector: [ 1.0m, 20.0u, 300.0M,\n' ' 4.0p, 5.3k, -6.0n,\n' ' 700.0 , 800.0m ]', 'Vector: ' ), ( [ 1.23456789, 2.45678901, 3.45678901, 4.56789012, 5.67890123, 6.78901234, 7.89012345 ], dict(limit=True, width=80-22, indent=22), 'Independent variable: [ 1.23456789, 2.45678901, 3.45678901,\n' ' ...\n' ' 5.67890123, 6.78901234, 7.89012345 ]', 'Independent variable: ' ), ( [ 1.23456789, 2.45678901, 3.45678901, 4.56789012, 5.67890123, 6.78901234, 7.89012345 ], dict(width=49, indent=17), 'Independent var: [ 1.23456789, 2.45678901, 3.45678901, ' '4.56789012,\n' ' 5.67890123, 6.78901234, 7.89012345 ]', 'Independent var: ' ), # Complex items ( CVECTOR, DFLT, '[ -1+2j, 3+4j, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j ]', '' ), ( CVECTOR, dict(indent=20), '[ -1+2j, 3+4j, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j ]', '' ), ( CVECTOR, dict(limit=True), '[ -1+2j, 3+4j, 5+6j, ..., 11+12j, -13+14j, 15678-16j ]', '' ), ( CVECTOR, dict(limit=True, indent=20), '[ -1+2j, 3+4j, 5+6j, ..., 11+12j, -13+14j, 15678-16j ]', '' ), ( CVECTOR, dict(eng=True), '[ -1.000 + 2.000 j, 3.000 + 4.000 j,' ' 5.000 + 6.000 j,' ' 7.000 + 8.000 j, 9.000 - 10.000 j,' ' 11.000 + 12.000 j,' ' -13.000 + 14.000 j, 15.678k- 16.000 j ]', '' ), ( CVECTOR, dict(eng=True, indent=20), '[ -1.000 + 2.000 j, 3.000 + 4.000 j,' ' 5.000 + 6.000 j,' ' 7.000 + 8.000 j, 9.000 - 10.000 j,' ' 11.000 + 12.000 j,' ' -13.000 + 14.000 j, 15.678k- 16.000 j ]', '' ), ( CVECTOR, dict(limit=True, eng=True), '[ -1.000 + 2.000 j, 3.000 + 4.000 j,' ' 5.000 + 6.000 j,' ' ..., 11.000 + 12.000 j, -13.000 + 14.000 j,' ' 15.678k- 16.000 j ]', '' ), ( CVECTOR, dict(limit=True, eng=True, indent=20), '[ -1.000 + 2.000 j, 3.000 + 4.000 j,' ' 5.000 + 6.000 j,' ' ..., 11.000 + 12.000 j, -13.000 + 14.000 j,' ' 15.678k- 16.000 j ]', '' ), ( CVECTOR, dict(eng=True, frac_length=1), '[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,' ' 7.0 + 8.0 j, 9.0 - 10.0 j, 11.0 + 12.0 j,' ' -13.0 + 14.0 j, 15.7k- 16.0 j ]', '' ), ( CVECTOR, dict(eng=True, frac_length=1, indent=20), '[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,' ' 7.0 + 8.0 j, 9.0 - 10.0 j, 11.0 + 12.0 j,' ' -13.0 + 14.0 j, 15.7k- 16.0 j ]', '' ), ( CVECTOR, dict(limit=True, eng=True, frac_length=1), '[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,' ' ..., 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]', '' ), ( CVECTOR, dict(limit=True, eng=True, frac_length=1, indent=20), '[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,' ' ..., 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]', '' ), ( CVECTOR, dict(width=22), '[ -1+2j, 3+4j, 5+6j,\n' ' 7+8j, 9-10j, 11+12j,\n' ' -13+14j, 15678-16j ]', '' ), ( CVECTOR, dict(width=20), '[ -1+2j, 3+4j, 5+6j,\n' ' 7+8j, 9-10j,\n' ' 11+12j, -13+14j,\n' ' 15678-16j ]', '' ), ( CVECTOR, dict(width=29, eng=True, frac_length=0), '[ -1 + 2 j, 3 + 4 j,\n' ' 5 + 6 j, 7 + 8 j,\n' ' 9 - 10 j, 11 + 12 j,\n' ' -13 + 14 j, 16k- 16 j ]', '' ), ( CVECTOR, dict(width=37, eng=True, frac_length=1), '[ -1.0 + 2.0 j, 3.0 + 4.0 j,\n' ' 5.0 + 6.0 j, 7.0 + 8.0 j,\n' ' 9.0 - 10.0 j, 11.0 + 12.0 j,\n' ' -13.0 + 14.0 j, 15.7k- 16.0 j ]', '' ), ( CVECTOR, dict(width=16, eng=True, frac_length=0), '[ -1 + 2 j,\n' ' 3 + 4 j,\n' ' 5 + 6 j,\n' ' 7 + 8 j,\n' ' 9 - 10 j,\n' ' 11 + 12 j,\n' ' -13 + 14 j,\n' ' 16k- 16 j ]', '' ), ( CVECTOR, dict(width=16, eng=True, frac_length=0, limit=True), '[ -1 + 2 j,\n' ' 3 + 4 j,\n' ' 5 + 6 j,\n' ' ...\n' ' 11 + 12 j,\n' ' -13 + 14 j,\n' ' 16k- 16 j ]', '' ), ( CVECTOR, dict(width=56, eng=True, frac_length=1, limit=True), '[ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,\n' ' ...\n' ' 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]', '' ), ( CVECTOR, dict(width=64, eng=True, frac_length=1, limit=True, indent=8), 'Vector: [ -1.0 + 2.0 j, 3.0 + 4.0 j, 5.0 + 6.0 j,\n' ' ...\n' ' 11.0 + 12.0 j, -13.0 + 14.0 j, 15.7k- 16.0 j ]', 'Vector: ' ), ( CVECTOR, dict(width=20, indent=8), 'Vector: [ -1+2j, 3+4j, 5+6j,\n' ' 7+8j, 9-10j,\n' ' 11+12j, -13+14j,\n' ' 15678-16j ]', 'Vector: ' ), ( CVECTOR, dict(width=30, indent=8, limit=True), 'Vector: [ -1+2j, 3+4j, 5+6j,\n' ' ...\n' ' 11+12j, -13+14j, 15678-16j ]', 'Vector: ' ), ( CVECTOR, dict(width=20, indent=8, limit=True), 'Vector: [ -1+2j,\n' ' 3+4j,\n' ' 5+6j,\n' ' ...\n' ' 11+12j,\n' ' -13+14j,\n' ' 15678-16j ]', 'Vector: ' ), ( array( [ -0.10081675027325637-0.06910517142735251j, 0.018754229185649937+0.017142783560861786j, 0+18j ] ), DFLT, '[ -0.100816750273-0.0691051714274j, ' '0.0187542291856+0.0171427835609j, 18j ]', '' ), ( array( [ -0.10081675027325637-0.06910517142735251j, 0.018754229185649937+0.017142783560861786j, 0+18j ] ), dict(width=60, limit=True, indent=20), 'Dependent variable: [ -0.100816750273-0.0691051714274j,\n' ' 0.0187542291856+0.0171427835609j, 18j ]', 'Dependent variable: ' ), ( array( [ -0.10081675027325637-0.06910517142735251j, 0.018754229185649937+0.017142783560861786j, 0+18j, 0.118754229185649937+0.117142783560861786j, 0.218754229185649937+0.217142783560861786j, 0+28j, 10+2j, ] ), dict(width=60), '[ -0.100816750273-0.0691051714274j,\n' ' 0.0187542291856+0.0171427835609j, 18j,\n' ' 0.118754229186+0.117142783561j,\n' ' 0.218754229186+0.217142783561j, 28j, 10+2j ]', '' ), ( array( [ -0.10081675027325637-0.06910517142735251j, 0.018754229185649937+0.017142783560861786j, 0+18j, 0.118754229185649937+0.117142783560861786j, 0.218754229185649937+0.217142783560861786j, 0+28j, 10+2j, ] ), dict(width=60, limit=True), '[ -0.100816750273-0.0691051714274j,\n' ' 0.0187542291856+0.0171427835609j,\n' ' 18j,\n' ' ...\n' ' 0.218754229186+0.217142783561j,\n' ' 28j,\n' ' 10+2j ]', '' ), ] ) def test_pprint_vector(vector, args, ref, header): """ Test pprint_vector function behavior """ obj = putil.eng.pprint_vector obj = obj if isdflt(args) else functools.partial(obj, **args) CS(header+obj(vector), ref) @pytest.mark.parametrize( 'args', [ dict( vector=[1e-3, 20e-6, 300e+6, 4e-12, 5.25e3, -6e-9, 700, 8, 9], width=5, eng=True, frac_length=1, limit=True ), dict( vector=[-1+2j, 3, 5+6j, 7+8j, 9-10j, 11+12j, -13+14j, 15678-16j], width=8, limit=True ) ] ) @pytest.mark.eng def test_pprint_vector_exceptions(args): """ Test pprint_vector function exceptions """ msg = 'Argument `width` is too small' AE(putil.eng.pprint_vector, ValueError, msg, **args) @pytest.mark.parametrize( 'num, dec, ref', [ (None, DFLT, None), (1.3333, 2, 1.33), (1.5555E-12, 2, 1.56E-12), (3, 2, 3), (array([1.3333, 2.666666]), 2, array([1.33, 2.67])), (array([1.3333E-12, 2.666666E-12]), 2, array([1.33E-12, 2.67E-12])), (array([1, 3]), 2, array([1, 3])), ] ) def test_round_mantissa(num, dec, ref): """ Test round_mantissa function behavior """ obj = putil.eng.round_mantissa obj = obj if isdflt(dec) else functools.partial(obj, decimals=dec) test = obj(num) == ref assert test.all() if isinstance(num, ndarray) else test
pmacosta/putil
tests/test_eng.py
Python
mit
40,156
<div class="commune_descr limited"> <p> Le&nbsp;Caire est un village géographiquement positionné dans le département de l'Alpes-de-Haute-Provence en Provence-Alpes-Côte d'Azur. Elle comptait 70 habitants en 2008.</p> <p>Le parc de logements, à Le&nbsp;Caire, se décomposait en 2011 en sept appartements et 61 maisons soit un marché relativement équilibré.</p> <p>À coté de Le&nbsp;Caire sont situées les villes de <a href="{{VLROOT}}/immobilier/bayons_04023/">Bayons</a> située à 8&nbsp;km, 257 habitants, <a href="{{VLROOT}}/immobilier/brunet_04035/">Brunet</a> à 6&nbsp;km, 249 habitants, <a href="{{VLROOT}}/immobilier/saulce_05162/">La&nbsp;Saulce</a> à 7&nbsp;km, 1&nbsp;190 habitants, <a href="{{VLROOT}}/immobilier/melve_04118/">Melve</a> localisée à 5&nbsp;km, 109 habitants, <a href="{{VLROOT}}/immobilier/curbans_04066/">Curbans</a> localisée à 6&nbsp;km, 333 habitants, <a href="{{VLROOT}}/immobilier/claret_04058/">Claret</a> à 8&nbsp;km, 227 habitants, entre autres. De plus, Le&nbsp;Caire est située à seulement 21&nbsp;km de <a href="{{VLROOT}}/immobilier/gap_05061/">Gap</a>.</p> <p>Si vous envisagez de venir habiter à Le&nbsp;Caire, vous pourrez facilement trouver une maison à vendre. </p> </div>
donaldinou/frontend
src/Viteloge/CoreBundle/Resources/descriptions/04037.html
HTML
mit
1,259
--- layout: page title: Foster Networks Trade Fair date: 2016-05-24 author: Austin Morris tags: weekly links, java status: published summary: In vitae nisl et lectus consequat tincidunt sit amet. banner: images/banner/leisure-05.jpg booking: startDate: 11/11/2016 endDate: 11/12/2016 ctyhocn: SATSGHX groupCode: FNTF published: true --- Suspendisse tincidunt, purus eu mattis pretium, lacus erat pulvinar velit, ut iaculis turpis lorem et sem. Phasellus in lacinia ex. Suspendisse eget elit at ante elementum suscipit. Nam nisl erat, ultrices vitae urna vitae, pharetra sollicitudin sapien. Praesent ac purus eget ligula eleifend molestie. Praesent tempus, justo non facilisis pretium, ligula lectus pretium nisi, nec molestie metus ligula non ex. Sed egestas orci dolor, eu venenatis nisl sagittis eu. Nullam at turpis commodo, facilisis ligula ac, placerat augue. * Donec a odio vitae lorem gravida bibendum eget at tortor * Vestibulum fringilla augue in sapien vehicula hendrerit * Phasellus malesuada dolor quis lacus gravida fermentum * Aenean molestie felis rhoncus vestibulum consequat. Donec in arcu risus. Vestibulum bibendum pulvinar ullamcorper. Praesent ut porttitor neque. Fusce leo turpis, bibendum quis eros eu, tempus pulvinar elit. Morbi non urna sodales, facilisis arcu vitae, convallis orci. Vestibulum nisi felis, tempus ac mauris quis, rutrum placerat tellus. In ac arcu urna. Vestibulum non neque sed libero auctor interdum. Duis id purus odio. Curabitur id tempor ligula. Nullam posuere facilisis sagittis. Donec quis leo hendrerit, feugiat purus id, ornare massa. Phasellus consequat pretium erat, sed gravida turpis placerat ut. Mauris sodales nisi eu risus interdum congue. Proin orci nunc, rhoncus in fringilla ac, faucibus eget nisl. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
KlishGroup/prose-pogs
pogs/S/SATSGHX/FNTF/index.md
Markdown
mit
1,866
<?php include "config.php"; session_start(); if(!isset($_SESSION['username'])){ //header("location:login.php"); } ?> <!DOCTYPE html> <!-- This is a starter template page. Use this page to start your new project from scratch. This page gets rid of all links and provides the needed markup only. --> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>HOSPITAL MANAGMENT SYSTEM</title> <!-- Tell the browser to be responsive to screen width --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="bower_components/Ionicons/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="dist/css/AdminLTE.min.css"> <link rel="stylesheet" href="dist/css/skins/skin-blue.min.css"> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <!-- Main Header --> <header class="main-header"> <!-- Logo --> <a href="" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>H</b>MS</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>HMS</b></span> </a> <!-- Header Navbar --> <nav class="navbar navbar-static-top" role="navigation"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-user"></i> <b class="caret hidden-sm hidden-xs"></b> <span class="notification hidden-sm hidden-xs">2</span> <p class="hidden-lg hidden-md"> 5 Notifications <b class="caret"></b> </p> </a> <ul class="dropdown-menu"> <li><a href="login.php">Logout</a></li> <li><a href="#">change password</a></li> </ul> </li> <li class="separator hidden-lg hidden-md"></li> </ul> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="push-menu" role="button"> <span class="sr-only">Toggle navigation</span> </a> <!-- Navbar Right Menu --> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <li class="dropdown messages-menu"> <!-- Menu toggle button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success"></span> </a> <ul class="dropdown-menu"> <!-- inner menu: contains the messages --> <ul class="menu"> <li><!-- start message --> <a href="#"> <div class="pull-left"> <!-- User Image --> <i class=""></i> </div> </a> </li> <!-- end message --> </ul> <!-- /.menu --> </li> <li class="footer"><a href="#"></a></li> </ul> </li> <!-- /.messages-menu --> <!-- Notifications Menu --> <li class="dropdown notifications-menu"> <!-- Menu toggle button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class=""></i> <span class="label label-warning"></span> </a> <ul class="dropdown-menu"> <!-- Tasks Menu --> <li class="dropdown tasks-menu"> <!-- Menu Toggle Button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class=""></i> <span class=""></span> </a> <ul class="dropdown-menu"> <li class="header"></li> <li> </li> <!-- User Account Menu --> <!-- Menu Body --> <li class="user-body"> <!-- /.row --> </li> <!-- Menu Footer--> </ul> </li> <!-- Control Sidebar Toggle Button --> <li> <a href="#" data-toggle="control-sidebar"><i class=""></i></a> </li> </ul> </div> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar"> <!-- sidebar: style can be found in sidebar.less --> <section class="sidebar"> <!-- Sidebar Menu --> <?php include "sidebar.php"; ?> <!-- /.sidebar-menu --> </section> <!-- /.sidebar --> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> </section> <!-- Main content --> <section class="content container-fluid"> <?php include("xray_registration.php"); ?> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <!-- Main Footer --> <footer class="main-footer"> <!-- To the right --> <div class="pull-right hidden-xs"> </div> <!-- Default to the left --> <strong>Copyright &copy; 2017 <a href="#">Group</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Create the tabs --> <ul class="nav nav-tabs nav-justified control-sidebar-tabs"> <li class="active"><a href="#control-sidebar-home-tab" data-toggle="tab"><i class="fa fa-home"></i></a></li> <li><a href="#control-sidebar-settings-tab" data-toggle="tab"><i class="fa fa-gears"></i></a></li> </ul> <!-- Tab panes --> <div class="tab-content"> <!-- Home tab content --> <div class="tab-pane active" id="control-sidebar-home-tab"> <h3 class="control-sidebar-heading">Recent Activity</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:;"> <i class="menu-icon fa fa-birthday-cake bg-red"></i> <div class="menu-info"> <h4 class="control-sidebar-subheading">Langdon's Birthday</h4> <p>Will be 23 on April 24th</p> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> <h3 class="control-sidebar-heading">Tasks Progress</h3> <ul class="control-sidebar-menu"> <li> <a href="javascript:;"> <h4 class="control-sidebar-subheading"> Custom Template Design <span class="pull-right-container"> <span class="label label-danger pull-right">70%</span> </span> </h4> <div class="progress progress-xxs"> <div class="progress-bar progress-bar-danger" style="width: 70%"></div> </div> </a> </li> </ul> <!-- /.control-sidebar-menu --> </div> <!-- /.tab-pane --> <!-- Stats tab content --> <div class="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div> <!-- /.tab-pane --> <!-- Settings tab content --> <div class="tab-pane" id="control-sidebar-settings-tab"> <form method="post"> <h3 class="control-sidebar-heading">General Settings</h3> <div class="form-group"> <label class="control-sidebar-subheading"> Report panel usage <input type="checkbox" class="pull-right" checked> </label> <p> Some information about this general settings option </p> </div> <!-- /.form-group --> </form> </div> <!-- /.tab-pane --> </div> </aside> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- REQUIRED JS SCRIPTS --> <!-- jQuery 3 --> <script src="bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap 3.3.7 --> <script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- AdminLTE App --> <script src="dist/js/adminlte.min.js"></script> <!-- Optionally, you can add Slimscroll and FastClick plugins. Both of these plugins are recommended to enhance the user experience. --> </body> </html>
abdiwahab-omar/team
xray_display.php
PHP
mit
9,171
require "pact_broker/api/resources/can_i_deploy_pacticipant_version_by_tag_to_tag" require "pact_broker/matrix/service" module PactBroker module Api module Resources describe CanIDeployPacticipantVersionByBranchToEnvironment do include_context "stubbed services" before do allow(PactBroker::Deployments::EnvironmentService).to receive(:find_by_name).and_return(environment) allow(PactBroker::Matrix::Service).to receive(:can_i_deploy).and_return([]) allow(pacticipant_service).to receive(:find_pacticipant_by_name).and_return(pacticipant) allow(PactBroker::Api::Decorators::MatrixDecorator).to receive(:new).and_return(decorator) allow(version_service).to receive(:find_latest_by_pacticipant_name_and_branch_name).and_return(version) end let(:pacticipant) { double("pacticipant") } let(:version) { double("version") } let(:json_response_body) { JSON.parse(subject.body, symbolize_names: true) } let(:decorator) { double("decorator", to_json: "response_body") } let(:selectors) { double("selectors") } let(:options) { double("options") } let(:environment) { double("environment") } let(:path) { "/pacticipants/Foo/branches/main/latest-version/can-i-deploy/to-environment/dev" } subject { get(path, nil, "Content-Type" => "application/hal+json") } it "looks up the by branch" do expect(version_service).to receive(:find_latest_by_pacticipant_name_and_branch_name).with("Foo", "main") subject end it "checks if the version can be deployed to the environment" do expect(PactBroker::Matrix::Service).to receive(:can_i_deploy).with(anything, hash_including(environment_name: "dev")) subject end it { is_expected.to be_a_hal_json_success_response } context "when the environment does not exist" do let(:environment) { nil } its(:status) { is_expected.to eq 404 } end end end end end
pact-foundation/pact_broker
spec/lib/pact_broker/api/resources/can_i_deploy_pacticipant_version_by_branch_to_environment_spec.rb
Ruby
mit
2,071
import React from 'react' import { Container, Group, TabBar, Icon, Badge, amStyles, } from 'amazeui-touch' import {Link} from 'react-router' class App extends React.Component{ propsType ={ children:React.PropTypes.node } render(){ let { location, params, children, ...props } = this.props; let transition = children.props.transition || 'sfr' return ( <Container direction="column"> <Container transition={transition} > {children} </Container> <TabBar > <TabBar.Item component={Link} eventKey = 'home' active = {location.pathname === '/'} icon = 'home' title = '首页' to='/' /> <TabBar.Item component={Link} active={location.pathname === '/class'} eventKey="class" icon="list" title="课程" to='/class' /> <TabBar.Item active={location.pathname === '/search'} eventKey="search" icon="search" title="发现" /> <TabBar.Item component={Link} active={location.pathname === '/me'} eventKey="person" icon="person" title="我" to='/me' /> </TabBar> </Container> ) } } export default App
yiweimatou/yiweimatou-mobile
src/components/pages/app.js
JavaScript
mit
1,961
<?php $article_excerpt_categories = get_the_category(); $article_excerpt_categories_output = ""; if ( ! empty( $article_excerpt_categories ) ) { $article_excerpt_categories_output = esc_html( $article_excerpt_categories[0]->name ); } ?> <article class="su-article su-article--divider su-article--<?php echo strtolower($article_excerpt_categories_output); ?>" id="post-<?php the_ID(); ?>"> <header class="su-header su-article__header"> <h2 class="su-heading su-heading--two su-article__title"> <a href="<?php the_permalink() ?>" rel="bookmark" class="su-heading__link"> <?php the_title() ?> </a> </h2> <div class="su-article__date"><?php the_date() ?></div> </header> <div class="su-article__content"> <?php the_excerpt(); ?> <a href="<?php the_permalink()?>" class="su-article__more">Continue reading <span class="su-article__more-sr-only"><?php the_title() ?></span></a> </div> <footer class="su-article__footer"> <div class="su-article-meta su-article-meta--short"> <?php sheru_entry_meta(); ?> </div> </footer> </article>
shellbryson/sheru
template-parts/excerpt.php
PHP
mit
1,104
<?php namespace jeremykenedy\laravelusers; use Illuminate\Support\ServiceProvider; class LaravelUsersServiceProvider extends ServiceProvider { private $_packageTag = 'laravelusers'; /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application services. * * @return void */ public function boot() { $this->loadTranslationsFrom(__DIR__.'/resources/lang/', $this->_packageTag); } /** * Register the application services. * * @return void */ public function register() { $this->loadRoutesFrom(__DIR__.'/routes/web.php'); $this->loadViewsFrom(__DIR__.'/resources/views/', $this->_packageTag); $this->mergeConfigFrom(__DIR__.'/config/'.$this->_packageTag.'.php', $this->_packageTag); $this->publishFiles(); $this->app->make('jeremykenedy\laravelusers\App\Http\Controllers\UsersManagementController'); $this->app->singleton(jeremykenedy\laravelusers\App\Http\Controllers\UsersManagementController\UsersManagementController::class, function () { return new App\Http\Controllers\UsersManagementController(); }); $this->app->alias(UsersManagementController::class, 'laravelusers'); } /** * Publish files for the package. * * @return void */ private function publishFiles() { $publishTag = $this->_packageTag; $this->publishes([ __DIR__.'/config/'.$this->_packageTag.'.php' => base_path('config/'.$this->_packageTag.'.php'), ], $publishTag); $this->publishes([ __DIR__.'/resources/views' => resource_path('views/vendor/'.$this->_packageTag), ], $publishTag); $this->publishes([ __DIR__.'/resources/lang' => resource_path('lang/vendor/'.$this->_packageTag), ], $publishTag); } }
jeremykenedy/laravel-users
src/LaravelUsersServiceProvider.php
PHP
mit
1,963
<?php namespace framework\ext; //xml解析成数组 class Xml { public static function decode($xml) { $values = array(); $index = array(); $array = array(); $parser = xml_parser_create('utf-8'); xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); xml_parse_into_struct($parser, $xml, $values, $index); xml_parser_free($parser); $i = 0; $name = $values[$i]['tag']; $array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : ''; $array[$name] = self::_struct_to_array($values, $i); return $array; } private static function _struct_to_array($values, &$i) { $child = array(); if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']); while ($i++ < count($values)) { switch ($values[$i]['type']) { case 'cdata': array_push($child, $values[$i]['value']); break; case 'complete': $name = $values[$i]['tag']; if(!empty($name)) { $child[$name]= ($values[$i]['value'])?($values[$i]['value']):''; if(isset($values[$i]['attributes'])) { $child[$name] = $values[$i]['attributes']; } } break; case 'open': $name = $values[$i]['tag']; $size = isset($child[$name]) ? sizeof($child[$name]) : 0; $child[$name][$size] = self::_struct_to_array($values, $i); break; case 'close': return $child; break; } } return $child; } }
cyrilzhao/zqzirui
framework/ext/Xml.php
PHP
mit
1,581
import com.sendgrid.Method; import com.sendgrid.Request; import com.sendgrid.Response; import com.sendgrid.SendGrid; import com.sendgrid.helpers.mail.Mail; import com.sendgrid.helpers.mail.objects.Content; import com.sendgrid.helpers.mail.objects.Email; import com.sendgrid.helpers.mail.objects.Personalization; import java.io.IOException; public class SingleEmailMultipleRecipients { public static void main(String[] args) throws IOException { final Mail mail = new Mail(); mail.setFrom(new Email("test@example.com", "Example User")); mail.setSubject("Sending with Twilio SendGrid is Fun"); final Personalization personalization = new Personalization(); personalization.addTo(new Email("test1@example.com", "Example User1")); personalization.addTo(new Email("test2@example.com", "Example User2")); personalization.addTo(new Email("test3@example.com", "Example User3")); mail.addPersonalization(personalization); mail.addContent(new Content("text/plain", "and easy to do anywhere, even with Java")); mail.addContent(new Content("text/html", "<strong>and easy to do anywhere, even with Java</strong>")); send(mail); } private static void send(final Mail mail) throws IOException { final SendGrid client = new SendGrid(System.getenv("SENDGRID_API_KEY")); final Request request = new Request(); request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); final Response response = client.api(request); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); System.out.println(response.getHeaders()); } }
sendgrid/sendgrid-java
examples/helpers/mail/SingleEmailMultipleRecipients.java
Java
mit
1,666
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.5"/> <title>Bombás játék: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">Bombás játék </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.5 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">uivector Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="structuivector.html">uivector</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>allocsize</b> (defined in <a class="el" href="structuivector.html">uivector</a>)</td><td class="entry"><a class="el" href="structuivector.html">uivector</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>data</b> (defined in <a class="el" href="structuivector.html">uivector</a>)</td><td class="entry"><a class="el" href="structuivector.html">uivector</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>size</b> (defined in <a class="el" href="structuivector.html">uivector</a>)</td><td class="entry"><a class="el" href="structuivector.html">uivector</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Oct 29 2013 00:50:15 for Bombás játék by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.5 </small></address> </body> </html>
bmateusz-inc/bombas-jatek
doxygen/html/structuivector-members.html
HTML
mit
5,067
<?php namespace BlogBundle\Document; use Doctrine\ODM\MongoDB\DocumentRepository; class TagRepository extends DocumentRepository { public function getTagByName($name = '') { $query = $this->createQueryBuilder() ->field('name')->equals($name); return $query->getQuery()->getSingleResult(); } public function getAllTags() { return $this->createQueryBuilder() ->hydrate(false) ->getQuery() ->toArray(); } }
haltaction/blog
src/BlogBundle/Document/TagRepository.php
PHP
mit
505
require "faraday" require "faraday_middleware" require "sqoot/version" require "sqoot/client" directory = File.expand_path(File.dirname(__FILE__)) module Sqoot class << self attr_accessor :affiliate_token, :authentication_token, :api_url, :api_version # Configure default credentials easily # # @yield [Sqoot] def configure load_defaults yield self true end def load_defaults self.api_url ||= "https://api.sqoot.com" self.api_version ||= 2 end end end
causemetric/sqoot
lib/sqoot.rb
Ruby
mit
525
<?php /** * Phinx * * (The MIT license) * Copyright (c) 2014 Rob Morgan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated * documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * * @package Phinx * @subpackage Phinx\Db */ namespace Phinx\Db; use Phinx\Db\Table\Column; use Phinx\Db\Table\Index; use Phinx\Db\Table\ForeignKey; use Phinx\Db\Adapter\AdapterInterface; /** * * This object is based loosely on: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html. */ class Table { /** * @var string */ protected $name; /** * @var array */ protected $options = array(); /** * @var AdapterInterface */ protected $adapter; /** * @var array */ protected $columns = array(); /** * @var array */ protected $indexes = array(); /** * @var ForeignKey[] */ protected $foreignKeys = array(); /** * Class Constuctor. * * @param string $name Table Name * @param array $options Options * @param AdapterInterface $adapter Database Adapter * @return void */ public function __construct($name, $options = array(), AdapterInterface $adapter = null) { $this->setName($name); $this->setOptions($options); if (null !== $adapter) { $this->setAdapter($adapter); } } /** * Sets the table name. * * @param string $name Table Name * @return Table */ public function setName($name) { $this->name = $name; return $this; } /** * Gets the table name. * * @return string */ public function getName() { return $this->name; } /** * Sets the table options. * * @param array $options * @return Table */ public function setOptions($options) { $this->options = $options; return $this; } /** * Gets the table options. * * @return array */ public function getOptions() { return $this->options; } /** * Sets the database adapter. * * @param AdapterInterface $adapter Database Adapter * @return Table */ public function setAdapter(AdapterInterface $adapter) { $this->adapter = $adapter; return $this; } /** * Gets the database adapter. * * @return AdapterInterface */ public function getAdapter() { return $this->adapter; } /** * Does the table exist? * * @return boolean */ public function exists() { return $this->getAdapter()->hasTable($this->getName()); } /** * Drops the database table. * * @return void */ public function drop() { $this->getAdapter()->dropTable($this->getName()); } /** * Renames the database table. * * @param string $newTableName New Table Name * @return Table */ public function rename($newTableName) { $this->getAdapter()->renameTable($this->getName(), $newTableName); $this->setName($newTableName); return $this; } /** * Sets an array of columns waiting to be committed. * Use setPendingColumns * * @deprecated * @param array $columns Columns * @return Table */ public function setColumns($columns) { $this->setPendingColumns($columns); } /** * Gets an array of the table columns. * * @return Column[] */ public function getColumns() { return $this->getAdapter()->getColumns($this->getName()); } /** * Sets an array of columns waiting to be committed. * * @param array $columns Columns * @return Table */ public function setPendingColumns($columns) { $this->columns = $columns; return $this; } /** * Gets an array of columns waiting to be committed. * * @return array */ public function getPendingColumns() { return $this->columns; } /** * Sets an array of columns waiting to be indexed. * * @param array $indexes Indexes * @return Table */ public function setIndexes($indexes) { $this->indexes = $indexes; return $this; } /** * Gets an array of indexes waiting to be committed. * * @return array */ public function getIndexes() { return $this->indexes; } /** * Gets an array of foreign keys waiting to be commited. * * @param ForeignKey[] $foreignKeys foreign keys * @return Table */ public function setForeignKeys($foreignKeys) { $this->foreignKeys = $foreignKeys; return $this; } /** * Gets an array of foreign keys waiting to be commited. * * @return array|ForeignKey[] */ public function getForeignKeys() { return $this->foreignKeys; } /** * Resets all of the pending table changes. * * @return void */ public function reset() { $this->setPendingColumns(array()); $this->setIndexes(array()); $this->setForeignKeys(array()); } /** * Add a table column. * * Type can be: primary_key, string, text, integer, float, decimal, * datetime, timestamp, time, date, binary, boolean. * * Valid options can be: limit, default, null, precision or scale. * * @param string|Phinx\Db\Table\Column $columnName Column Name * @param string $type Column Type * @param array $options Column Options * @return Table */ public function addColumn($columnName, $type = null, $options = array()) { // we need an adapter set to add a column if (null === $this->getAdapter()) { throw new \RuntimeException('An adapter must be specified to add a column.'); } // create a new column object if only strings were supplied if (!$columnName instanceof Column) { $column = new Column(); $column->setName($columnName); $column->setType($type); $column->setOptions($options); // map options to column methods } else { $column = $columnName; } // check column type if (!in_array($column->getType(), $this->getAdapter()->getColumnTypes())) { throw new \InvalidArgumentException("An invalid column type was specified: {$column->getName()}"); } $this->columns[] = $column; return $this; } /** * Remove a table column. * * @param string $columnName Column Name * @return Table */ public function removeColumn($columnName) { $this->getAdapter()->dropColumn($this->getName(), $columnName); return $this; } /** * Rename a table column. * * @param string $oldName Old Column Name * @param string $newName New Column Name * @return Table */ public function renameColumn($oldName, $newName) { $this->getAdapter()->renameColumn($this->getName(), $oldName, $newName); return $this; } /** * Change a table column type. * * @param string $columnName Column Name * @param string|Column $newColumnType New Column Type * @param array $options Options * @return Table */ public function changeColumn($columnName, $newColumnType, $options = array()) { // create a column object if one wasn't supplied if (!$newColumnType instanceof Column) { $newColumn = new Column(); $newColumn->setType($newColumnType); $newColumn->setOptions($options); } else { $newColumn = $newColumnType; } // if the name was omitted use the existing column name if (null === $newColumn->getName() || strlen($newColumn->getName()) == 0) { $newColumn->setName($columnName); } $this->getAdapter()->changeColumn($this->getName(), $columnName, $newColumn); return $this; } /** * Checks to see if a column exists. * * @param string $columnName Column Name * @param array $options Options * @return boolean */ public function hasColumn($columnName, $options = array()) { return $this->getAdapter()->hasColumn($this->getName(), $columnName, $options); } /** * Add an index to a database table. * * In $options you can specific unique = true/false or name (index name). * * @param string|array|Index $columns Table Column(s) * @param array $options Index Options * @return Table */ public function addIndex($columns, $options = array()) { // create a new index object if strings or an array of strings were supplied if (!$columns instanceof Index) { $index = new Index(); if (is_string($columns)) { $columns = array($columns); // str to array } $index->setColumns($columns); $index->setOptions($options); } else { $index = $columns; } $this->indexes[] = $index; return $this; } /** * Removes the given index from a table. * * @param array $columns Columns * @param array $options Options * @return Table */ public function removeIndex($columns, $options = array()) { $this->getAdapter()->dropIndex($this->getName(), $columns, $options); return $this; } /** * Removes the given index identified by its name from a table. * * @param string $name Index name * @return Table */ public function removeIndexByName($name) { $this->getAdapter()->dropIndexByName($this->getName(), $name); return $this; } /** * Checks to see if an index exists. * * @param string|array $columns Columns * @param array $options Options * @return boolean */ public function hasIndex($columns, $options = array()) { return $this->getAdapter()->hasIndex($this->getName(), $columns, $options); } /** * Add a foreign key to a database table. * * In $options you can specify on_delete|on_delete = cascade|no_action .., * on_update, constraint = constraint name. * * @param string|array $columns Columns * @param string|Table $referencedTable Referenced Table * @param string|array $referencedColumns Referenced Columns * @param array $options Options * @return Table */ public function addForeignKey($columns, $referencedTable, $referencedColumns = array('id'), $options = array()) { if (is_string($referencedColumns)) { $referencedColumns = array($referencedColumns); // str to array } $fk = new ForeignKey(); if ($referencedTable instanceof Table) { $fk->setReferencedTable($referencedTable); } else { $fk->setReferencedTable(new Table($referencedTable, array(), $this->adapter)); } $fk->setColumns($columns) ->setReferencedColumns($referencedColumns) ->setOptions($options); $this->foreignKeys[] = $fk; return $this; } /** * Removes the given foreign key from the table. * * @param string|array $columns Column(s) * @param null|string $constraint Constraint names * @return Table */ public function dropForeignKey($columns, $constraint = null) { if (is_string($columns)) { $columns = array($columns); } if ($constraint) { $this->getAdapter()->dropForeignKey($this->getName(), array(), $constraint); } else { $this->getAdapter()->dropForeignKey($this->getName(), $columns); } return $this; } /** * Checks to see if a foreign key exists. * * @param string|array $columns Column(s) * @param null|string $constraint Constraint names * @return boolean */ public function hasForeignKey($columns, $constraint = null) { return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint); } /** * Add timestamp columns created_at and updated_at to the table. * * @return Table */ public function addTimestamps() { $this->addColumn('created_at', 'timestamp') ->addColumn('updated_at', 'timestamp', array( 'null' => true, 'default' => null )); return $this; } /** * Creates a table from the object instance. * * @return void */ public function create() { $this->getAdapter()->createTable($this); $this->reset(); // reset pending changes } /** * Updates a table from the object instance. * * @return void */ public function update() { if (!$this->exists()) { throw new \RuntimeException('Cannot update a table that doesn\'t exist!'); } // update table foreach ($this->getPendingColumns() as $column) { $this->getAdapter()->addColumn($this, $column); } foreach ($this->getIndexes() as $index) { $this->getAdapter()->addIndex($this, $index); } foreach ($this->getForeignKeys() as $foreignKey) { $this->getAdapter()->addForeignKey($this, $foreignKey); } $this->reset(); // reset pending changes } /** * Commits the table changes. * * If the table doesn't exist it is created otherwise it is updated. * * @return void */ public function save() { if ($this->exists()) { $this->update(); // update the table } else { $this->create(); // create the table } $this->reset(); // reset pending changes } }
rsdevigo/phinx
src/Phinx/Db/Table.php
PHP
mit
15,419
<?php namespace Forge\Log; /** * Log_File * File log writer. Writes out messages and stores them in a YYYY/MM directory. * * @package SuperFan * @category Log * @author Zach Jenkins <zach@superfanu.com> * @copyright (c) 2017 SuperFan, Inc. */ class File extends Writer { // Directory to place log files in protected $_directory; // Creates a new file logger. Checks that the directory exists and // is writable. public function __construct( $directory ) { if ( ! is_dir($directory) OR ! is_writable($directory)) { die('Directory ' . Debug::path( $directory ) . ' must be writable'); } // Determine the directory path $this->_directory = realpath($directory).DIRECTORY_SEPARATOR; } // Writes each of the messages into the log file. The log file will be // appended to the `YYYY/MM/DD.log.php` file, where YYYY is the current // year, MM is the current month, and DD is the current day. public function write(array $messages) { // Set the yearly directory name $directory = $this->_directory.date('Y'); if ( ! is_dir($directory)) { // Create the yearly directory mkdir($directory, 02777); // Set permissions (must be manually set to fix umask issues) chmod($directory, 02777); } // Add the month to the directory $directory .= DIRECTORY_SEPARATOR.date('m'); if ( ! is_dir($directory)) { // Create the monthly directory mkdir($directory, 02777); // Set permissions (must be manually set to fix umask issues) chmod($directory, 02777); } // Set the name of the log file $filename = $directory.DIRECTORY_SEPARATOR.date('d').EXT; if ( ! file_exists($filename)) { // Create the log file file_put_contents($filename, Aviana::FILE_SECURITY.' ?>'.PHP_EOL); // Allow anyone to write to log files chmod($filename, 0666); } foreach ($messages as $message) { // Write each message into the log file // Format: time --- level: body file_put_contents($filename, PHP_EOL.$message['time'].' --- '.$this->_log_levels[$message['level']].': '.$message['body'], FILE_APPEND); } } }
forgephp/core
classes/Log/File.php
PHP
mit
2,101
# The set of languages for which implicit dependencies are needed: set(CMAKE_DEPENDS_LANGUAGES "CXX" ) # The set of files for implicit dependencies of each language: set(CMAKE_DEPENDS_CHECK_CXX "/home/sriramana/argos3-examples/controllers/footbot_synchronization/footbot_synchronization.cpp" "/home/sriramana/argos3-examples/build/controllers/footbot_synchronization/CMakeFiles/footbot_synchronization.dir/footbot_synchronization.cpp.o" "/home/sriramana/argos3-examples/build/controllers/footbot_synchronization/footbot_synchronization_automoc.cpp" "/home/sriramana/argos3-examples/build/controllers/footbot_synchronization/CMakeFiles/footbot_synchronization.dir/footbot_synchronization_automoc.cpp.o" ) set(CMAKE_CXX_COMPILER_ID "GNU") # Preprocessor definitions for this target. set(CMAKE_TARGET_DEFINITIONS_CXX "QT_CORE_LIB" "QT_GUI_LIB" "QT_WIDGETS_LIB" ) # The include file search paths: set(CMAKE_CXX_TARGET_INCLUDE_PATH "controllers/footbot_synchronization" "../controllers/footbot_synchronization" "/home/sriramana/anaconda2/include/qt" "/home/sriramana/anaconda2/include/qt/QtWidgets" "/home/sriramana/anaconda2/include/qt/QtGui" "/home/sriramana/anaconda2/include/qt/QtCore" "/home/sriramana/anaconda2/./mkspecs/linux-g++" "../" "/usr/include/lua5.2" "../controllers" ) # Targets to which this target links. set(CMAKE_TARGET_LINKED_INFO_FILES ) # Fortran module output directory. set(CMAKE_Fortran_TARGET_MODULE_DIR "")
ssriramana93/EnvClassify
build/controllers/footbot_synchronization/CMakeFiles/footbot_synchronization.dir/DependInfo.cmake
CMake
mit
1,476
<!DOCTYPE html> <html lang="en"> <head> <!-- Basic Page Needs –––––––––––––––––––––––––––––––––––––––––––––––––– --> <meta charset="utf-8"> <title>Kemble Song - an index</title> <meta name="description" content="Index page for Kemble Song's corner of the internet."> <meta name="author" content="Kemble Song"> <!-- Mobile Specific Metas –––––––––––––––––––––––––––––––––––––––––––––––––– --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- FONT –––––––––––––––––––––––––––––––––––––––––––––––––– --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <!-- CSS –––––––––––––––––––––––––––––––––––––––––––––––––– --> <link rel="stylesheet" href="styles.min.css"> <!-- Favicon –––––––––––––––––––––––––––––––––––––––––––––––––– --> <link rel="icon" type="image/png" href="images/favicon.png"> </head> <body> <!-- Primary Page Layout –––––––––––––––––––––––––––––––––––––––––––––––––– --> <div class="container fade-in"> <div class="row"> <div class="one-half column" style="margin-top: 20%; margin-bottom: 6rem; font-size: 20px;"> <h4>🙇🏻 Hello,</h4> <p> My name is <strong>Kemble</strong>.<br>I write <strong>code</strong>, shoot <strong>film</strong> and make <strong>beats</strong>.<br> </p> </div> </div> <div class="row"> <div class="one-half column" style="margin-bottom: 1rem"> <h5>💾 Projects</h5> <ul> <li><a href="http://ksong.co/resume">resume</a> - a resume</li> <li><a href="http://kemblesong.com">who am i?</a> - a digital business card</li> <li><a href="http://soundcloud.com/latenightlaboratory">Late Night Laboratory</a> - instrumentals, beats</li> </ul> </div> </div> <div class="row"> <div class="one-half column"> <h5>👋🏻 Social</h5> <ul> <li><a href="http://github.com/kemblesong">github</a> - code lives here</li> <li><a href="http://kemblog.tumblr.com">tumblr</a> - some of my photography</li> <li><a href="http://instagram.com/kemblog">instagram</a> - selfies, fashion pics, other trash</li> <li><a href="mailto:yo@ksong.co">email</a> - still the go to method of contact in the 21st century</li> </ul> </div> </div> </div> <!-- End Document –––––––––––––––––––––––––––––––––––––––––––––––––– --> </body>
kemblesong/kemblesong.github.io
index.html
HTML
mit
3,190
require_relative "helper" class HooksTest < MiniTest::Unit::TestCase def setup @hooked_class = Class.new do class << self attr_accessor :existing_method_added_called def method_added(method) @existing_method_added_called = true end end include Harbor::Hooks attr_accessor :before_hook_calls, :after_hook_calls, :hooked_method_calls attr_accessor :before_hook_with_args_calls, :after_hook_with_args_calls, :hooked_method_with_args_calls attr_accessor :before_hook_with_block_calls, :after_hook_with_block_calls, :hooked_method_with_block_calls attr_accessor :before_hook_with_method_added_calls, :hooked_method_with_method_added_calls def initialize @before_hook_calls = 0 @after_hook_calls = 0 @hooked_method_calls = 0 @before_hook_with_args_calls = 0 @after_hook_with_args_calls = 0 @hooked_method_with_args_calls = 0 @before_hook_with_block_calls = 0 @after_hook_with_block_calls = 0 @hooked_method_with_block_calls = 0 @before_hook_with_method_added_calls = 0 @hooked_method_with_method_added_calls = 0 end def hooked_method @hooked_method_calls += 1 end before :hooked_method do |reciever| reciever.before_hook_calls += 1 end after :hooked_method do |reciever| reciever.after_hook_calls += 1 end def hooked_method_with_args(color, size) @hooked_method_with_args_calls += 1 end before :hooked_method_with_args do |reciever| reciever.before_hook_with_args_calls += 1 end after :hooked_method_with_args do |reciever| reciever.after_hook_with_args_calls += 1 end def hooked_method_with_block(color, size, &block) yield @hooked_method_with_block_calls += 1 end before :hooked_method_with_block do |reciever| reciever.before_hook_with_block_calls += 1 end after :hooked_method_with_block do |reciever| reciever.after_hook_with_block_calls += 1 end before :hooked_method_with_method_added do |reciever| reciever.before_hook_with_method_added_calls += 1 end def hooked_method_with_method_added @hooked_method_with_method_added_calls += 1 end before :hooked_method_with_throw_halt do |reciever| throw :halt, true end def hooked_method_with_throw_halt false end end end def test_before_hooks_register_class_method assert_respond_to(@hooked_class, :before) end def test_before_and_after_hook_firing hooked_instance = @hooked_class.new assert_equal(0, hooked_instance.before_hook_calls) assert_equal(0, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) hooked_instance.hooked_method assert_equal(1, hooked_instance.before_hook_calls) assert_equal(1, hooked_instance.hooked_method_calls) assert_equal(1, hooked_instance.after_hook_calls) end def test_after_hooks_register_class_method assert_respond_to(@hooked_class, :after) end def test_method_added_respects_existing_method_added assert(@hooked_class.existing_method_added_called) end def test_can_define_hooks_before_method_added hooked_instance = @hooked_class.new assert_equal(0, hooked_instance.before_hook_with_method_added_calls) assert_equal(0, hooked_instance.hooked_method_with_method_added_calls) hooked_instance.hooked_method_with_method_added assert_equal(1, hooked_instance.before_hook_with_method_added_calls) assert_equal(1, hooked_instance.hooked_method_with_method_added_calls) end def test_hooked_methods_should_preserve_arguments hooked_instance = @hooked_class.new assert_equal(0, hooked_instance.before_hook_with_args_calls) assert_equal(0, hooked_instance.hooked_method_with_args_calls) assert_equal(0, hooked_instance.after_hook_with_args_calls) hooked_instance.hooked_method_with_args("blue", 10) assert_equal(1, hooked_instance.before_hook_with_args_calls) assert_equal(1, hooked_instance.hooked_method_with_args_calls) assert_equal(1, hooked_instance.after_hook_with_args_calls) end def test_hooked_methods_should_preserve_block_arguments hooked_instance = @hooked_class.new assert_equal(0, hooked_instance.before_hook_with_block_calls) assert_equal(0, hooked_instance.hooked_method_with_block_calls) assert_equal(0, hooked_instance.after_hook_with_block_calls) @block_called = 0 hooked_instance.hooked_method_with_block("blue", 10) do @block_called += 1 end assert_equal(1, @block_called) assert_equal(1, hooked_instance.before_hook_with_block_calls) assert_equal(1, hooked_instance.hooked_method_with_block_calls) assert_equal(1, hooked_instance.after_hook_with_block_calls) end def test_hooks_are_run_when_hooked_method_is_redefined @hooked_class.class_eval do def hooked_method @hooked_method_calls = 2 end end hooked_instance = @hooked_class.new assert_equal(0, hooked_instance.before_hook_calls) assert_equal(0, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) hooked_instance.hooked_method assert_equal(1, hooked_instance.before_hook_calls) assert_equal(2, hooked_instance.hooked_method_calls) assert_equal(1, hooked_instance.after_hook_calls) end def test_hooks_are_run_when_class_is_subclassed subclass = Class.new(@hooked_class) hooked_instance = subclass.new assert_equal(0, hooked_instance.before_hook_calls) assert_equal(0, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) hooked_instance.hooked_method assert_equal(1, hooked_instance.before_hook_calls) assert_equal(1, hooked_instance.hooked_method_calls) assert_equal(1, hooked_instance.after_hook_calls) end def test_hooks_are_additive_in_subclass subclass = Class.new(@hooked_class) do before(:hooked_method) { |receiver| receiver.before_hook_calls += 1 } end hooked_instance = subclass.new assert_equal(0, hooked_instance.before_hook_calls) assert_equal(0, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) hooked_instance.hooked_method assert_equal(2, hooked_instance.before_hook_calls) assert_equal(1, hooked_instance.hooked_method_calls) assert_equal(1, hooked_instance.after_hook_calls) end def test_hooks_are_clearable @hooked_class.hooks[:hooked_method].clear! hooked_instance = @hooked_class.new assert_equal(0, hooked_instance.before_hook_calls) assert_equal(0, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) hooked_instance.hooked_method assert_equal(0, hooked_instance.before_hook_calls) assert_equal(1, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) end def test_hooks_are_clearble_from_subclass subclass = Class.new(@hooked_class) do hooks[:hooked_method].clear! before(:hooked_method) { |receiver| receiver.before_hook_calls += 1 } end hooked_instance = subclass.new assert_equal(0, hooked_instance.before_hook_calls) assert_equal(0, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) hooked_instance.hooked_method assert_equal(1, hooked_instance.before_hook_calls) assert_equal(1, hooked_instance.hooked_method_calls) assert_equal(0, hooked_instance.after_hook_calls) end def test_throw_halt_is_caught_and_returned hooked_instance = @hooked_class.new result = hooked_instance.hooked_method_with_throw_halt assert(result) end end
sam/harbor
test/hooks_test.rb
Ruby
mit
7,919
/* * @file sample.c * @author Akagi201 * @date 2014/12/06 */ #include <stdio.h> #include "bytes2str.h"" int main(void) { char in[] = {0xC8, 0x32, 0x9B, 0xFD, 0x0E, 0x01}; char out[32] = {0}; int olen = sizeof(out); bytes2str(in, 6, out, &olen); printf("out: %s, olen: %d\n", out, olen); return 0; }
Akagi201/bytes2str
sample.c
C
mit
332
/* * unstrap v1.1.3 * https://unstrap.org * 2015-2020 * MIT license */ const version = '1.1.3', collection = {}; function extendUnstrap (v) { var list; if (!collection[v].selectors) { collection[v].selectors = ['.' + collection[v].name]; } collection[v].selectors.forEach(function (sel) { list = document.querySelectorAll(sel); for (var i = 0; i < list.length; i++) { collection[v].extend && collection[v].extend(list.item(i)); } }) } function init () { var observer = new MutationObserver(function (mut) { mut.forEach(function (m) { var n = m.addedNodes, f; for (var i=0; i<n.length; i++) { var c = n.item(i).classList; if (c) { for (var j = 0; j < c.length; j++) { if (f = collection[c.item(j)]) { f.extend && f.extend(n.item(i)); } } } } }); }); Object.keys(collection).forEach(function (v) { extendUnstrap(v); }) observer.observe(document.body, {childList: true, subtree: true}); } function register (...components) { components.forEach((component) => { if (component.name) { collection[component.name] = component; } }) } function unregister (...components) { components.forEach((component) => { delete collection[component.name]; }) } function list () { return Object.keys(collection).sort(); } window.onload = init; export default { version, register, unregister, list }
unstrap/unstrap
unstrap.js
JavaScript
mit
1,620
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class NSArray; @protocol DVTLineGraphLayerDataSource <NSObject> - (NSArray *)lineDataForBounds:(struct _DVTGraphBounds)arg1; @end
wczekalski/Distraction-Free-Xcode-plugin
Archived/v1/WCDistractionFreeXcodePlugin/Headers/SharedFrameworks/DVTKit/DVTLineGraphLayerDataSource-Protocol.h
C
mit
294
<div class="modal-header"> <button type="button" class="close" ng-click="closeDialog()" aria-hidden="true">&times;</button> <h4 class="modal-title">Widget hinzufügen</h4> </div> <div class="modal-body" class="row"> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default" ng-repeat="(category, widgets) in categories" is-open="isopen"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> {{category}} </a> </h4> </div> <div id="#panel{{category}}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"> <ul class="list-group"> <li class="list-group-item" ng-repeat="(key, widget) in widgets"> <a href="" ng-click="addWidget(key)">{{widget.title}} <i class="fa fa-spinner fa-spin" ng-show="recentlyAdded.indexOf(key) > -1"></i></a> <p> <small ng-if="widget.description">{{widget.description}}</small> </p> </li> </ul> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" ng-click="closeDialog()"><i class="fa fa-times"></i> Schließen</button> </div>
Traperto/angular-dashboard-framework
src/templates/widget-add.html
HTML
mit
1,595
<?php /* PgGsbFraisBundle::accueilCompta.html.twig */ class __TwigTemplate_6194dcf338f5cd969f229bda597abec8b69c1f8371639ebcadc7c86b484b4c01 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = $this->env->loadTemplate("PgGsbFraisBundle::layout.html.twig"); $this->blocks = array( 'body' => array($this, 'block_body'), 'section' => array($this, 'block_section'), ); } protected function doGetParent(array $context) { return "PgGsbFraisBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 2 public function block_body($context, array $blocks = array()) { // line 3 echo "<nav> <div class=\"row\"> <div class=\"col-lg-10\"> <nav class=\"navbar navbar-default\" role=\"navigation\"> <div class=\"container-fluid\"> <div class=\"navbar-header\"> <a class=\"navbar-brand\" href=\""; // line 9 echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_home"); echo "\">Accueil</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class=\"collapse navbar-collapse\" id=\"bs-example-navbar-collapse-1\"> <ul class=\"nav navbar-nav\"> <li> <a href=\""; // line 15 echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_suivrefrais"); echo "\" title=\"Suivre fiche de frais \">Suivre fiche de frais</a> </li> <li> <a href= \""; // line 19 echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_validerfrais"); echo "\" title=\"Valider fiches de frais\">Valider fiches de frais</a> </li> </ul> </div> </nav> </div> <div class=\"col-lg-2\"> <nav class=\"navbar navbar-default\" role=\"deconnexion\"> <div class=\"container-fluid\"> "; // line 29 if ($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : null), "session", array(), "any", false, true), "get", array(0 => "nom"), "method", true, true)) { // line 30 echo " Bonjour "; echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "session"), "get", array(0 => "nom"), "method"), "html", null, true); echo " <br /> "; } // line 32 echo " <a href=\""; echo $this->env->getExtension('routing')->getPath("pg_gsb_frais_deconnexion"); echo "\" title=\"Se déconnecter\">Déconnexion</a> </div> </nav> </div> </div> </nav> <section> "; // line 39 $this->displayBlock('section', $context, $blocks); // line 41 echo "</section> "; } // line 39 public function block_section($context, array $blocks = array()) { // line 40 echo " "; } public function getTemplateName() { return "PgGsbFraisBundle::accueilCompta.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 98 => 40, 95 => 39, 90 => 41, 88 => 39, 77 => 32, 71 => 30, 69 => 29, 56 => 19, 49 => 15, 40 => 9, 32 => 3, 29 => 2, 31 => 3, 28 => 2,); } }
FCalligaris/GSB
app/cache/dev/twig/61/94/dcf338f5cd969f229bda597abec8b69c1f8371639ebcadc7c86b484b4c01.php
PHP
mit
4,000
'use strict'; const toBytes = s => [...s].map(c => c.charCodeAt(0)); const xpiZipFilename = toBytes('META-INF/mozilla.rsa'); const oxmlContentTypes = toBytes('[Content_Types].xml'); const oxmlRels = toBytes('_rels/.rels'); const fileType = input => { const buf = input instanceof Uint8Array ? input : new Uint8Array(input); if (!(buf && buf.length > 1)) { return null; } const check = (header, options) => { options = Object.assign({ offset: 0 }, options); for (let i = 0; i < header.length; i++) { // If a bitmask is set if (options.mask) { // If header doesn't equal `buf` with bits masked off if (header[i] !== (options.mask[i] & buf[i + options.offset])) { return false; } } else if (header[i] !== buf[i + options.offset]) { return false; } } return true; }; const checkString = (header, options) => check(toBytes(header), options); if (check([0xFF, 0xD8, 0xFF])) { return { ext: 'jpg', mime: 'image/jpeg' }; } if (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) { return { ext: 'png', mime: 'image/png' }; } if (check([0x47, 0x49, 0x46])) { return { ext: 'gif', mime: 'image/gif' }; } if (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) { return { ext: 'webp', mime: 'image/webp' }; } if (check([0x46, 0x4C, 0x49, 0x46])) { return { ext: 'flif', mime: 'image/flif' }; } // Needs to be before `tif` check if ( (check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) && check([0x43, 0x52], {offset: 8}) ) { return { ext: 'cr2', mime: 'image/x-canon-cr2' }; } if ( check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A]) ) { return { ext: 'tif', mime: 'image/tiff' }; } if (check([0x42, 0x4D])) { return { ext: 'bmp', mime: 'image/bmp' }; } if (check([0x49, 0x49, 0xBC])) { return { ext: 'jxr', mime: 'image/vnd.ms-photo' }; } if (check([0x38, 0x42, 0x50, 0x53])) { return { ext: 'psd', mime: 'image/vnd.adobe.photoshop' }; } // Zip-based file formats // Need to be before the `zip` check if (check([0x50, 0x4B, 0x3, 0x4])) { if ( check([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30}) ) { return { ext: 'epub', mime: 'application/epub+zip' }; } // Assumes signed `.xpi` from addons.mozilla.org if (check(xpiZipFilename, {offset: 30})) { return { ext: 'xpi', mime: 'application/x-xpinstall' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {offset: 30})) { return { ext: 'odt', mime: 'application/vnd.oasis.opendocument.text' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {offset: 30})) { return { ext: 'ods', mime: 'application/vnd.oasis.opendocument.spreadsheet' }; } if (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {offset: 30})) { return { ext: 'odp', mime: 'application/vnd.oasis.opendocument.presentation' }; } // https://github.com/file/file/blob/master/magic/Magdir/msooxml if (check(oxmlContentTypes, {offset: 30}) || check(oxmlRels, {offset: 30})) { const sliced = buf.subarray(4, 4 + 2000); const nextZipHeaderIndex = arr => arr.findIndex((el, i, arr) => arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4); const header2Pos = nextZipHeaderIndex(sliced); if (header2Pos !== -1) { const slicedAgain = buf.subarray(header2Pos + 8, header2Pos + 8 + 1000); const header3Pos = nextZipHeaderIndex(slicedAgain); if (header3Pos !== -1) { const offset = 8 + header2Pos + header3Pos + 30; if (checkString('word/', {offset})) { return { ext: 'docx', mime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }; } if (checkString('ppt/', {offset})) { return { ext: 'pptx', mime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }; } if (checkString('xl/', {offset})) { return { ext: 'xlsx', mime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }; } } } } } if ( check([0x50, 0x4B]) && (buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) && (buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8) ) { return { ext: 'zip', mime: 'application/zip' }; } if (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) { return { ext: 'tar', mime: 'application/x-tar' }; } if ( check([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) && (buf[6] === 0x0 || buf[6] === 0x1) ) { return { ext: 'rar', mime: 'application/x-rar-compressed' }; } if (check([0x1F, 0x8B, 0x8])) { return { ext: 'gz', mime: 'application/gzip' }; } if (check([0x42, 0x5A, 0x68])) { return { ext: 'bz2', mime: 'application/x-bzip2' }; } if (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) { return { ext: '7z', mime: 'application/x-7z-compressed' }; } if (check([0x78, 0x01])) { return { ext: 'dmg', mime: 'application/x-apple-diskimage' }; } if (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5 ( check([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {offset: 4}) && ( check([0x6D, 0x70, 0x34, 0x31], {offset: 8}) || // MP41 check([0x6D, 0x70, 0x34, 0x32], {offset: 8}) || // MP42 check([0x69, 0x73, 0x6F, 0x6D], {offset: 8}) || // ISOM check([0x69, 0x73, 0x6F, 0x32], {offset: 8}) || // ISO2 check([0x6D, 0x6D, 0x70, 0x34], {offset: 8}) || // MMP4 check([0x4D, 0x34, 0x56], {offset: 8}) || // M4V check([0x64, 0x61, 0x73, 0x68], {offset: 8}) // DASH ) )) { return { ext: 'mp4', mime: 'video/mp4' }; } if (check([0x4D, 0x54, 0x68, 0x64])) { return { ext: 'mid', mime: 'audio/midi' }; } // https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska if (check([0x1A, 0x45, 0xDF, 0xA3])) { const sliced = buf.subarray(4, 4 + 4096); const idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82); if (idPos !== -1) { const docTypePos = idPos + 3; const findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0)); if (findDocType('matroska')) { return { ext: 'mkv', mime: 'video/x-matroska' }; } if (findDocType('webm')) { return { ext: 'webm', mime: 'video/webm' }; } } } if (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) || check([0x66, 0x72, 0x65, 0x65], {offset: 4}) || check([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) || check([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG check([0x77, 0x69, 0x64, 0x65], {offset: 4})) { return { ext: 'mov', mime: 'video/quicktime' }; } // RIFF file format which might be AVI, WAV, QCP, etc if (check([0x52, 0x49, 0x46, 0x46])) { if (check([0x41, 0x56, 0x49], {offset: 8})) { return { ext: 'avi', mime: 'video/x-msvideo' }; } if (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) { return { ext: 'wav', mime: 'audio/x-wav' }; } // QLCM, QCP file if (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) { return { ext: 'qcp', mime: 'audio/qcelp' }; } } if (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) { return { ext: 'wmv', mime: 'video/x-ms-wmv' }; } if ( check([0x0, 0x0, 0x1, 0xBA]) || check([0x0, 0x0, 0x1, 0xB3]) ) { return { ext: 'mpg', mime: 'video/mpeg' }; } if (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {offset: 4})) { return { ext: '3gp', mime: 'video/3gpp' }; } // Check for MPEG header at different starting offsets for (let start = 0; start < 2 && start < (buf.length - 16); start++) { if ( check([0x49, 0x44, 0x33], {offset: start}) || // ID3 header check([0xFF, 0xE2], {offset: start, mask: [0xFF, 0xE2]}) // MPEG 1 or 2 Layer 3 header ) { return { ext: 'mp3', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xE4], {offset: start, mask: [0xFF, 0xE4]}) // MPEG 1 or 2 Layer 2 header ) { return { ext: 'mp2', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xF8], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 2 layer 0 using ADTS ) { return { ext: 'mp2', mime: 'audio/mpeg' }; } if ( check([0xFF, 0xF0], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 4 layer 0 using ADTS ) { return { ext: 'mp4', mime: 'audio/mpeg' }; } } if ( check([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4}) || check([0x4D, 0x34, 0x41, 0x20]) ) { return { ext: 'm4a', mime: 'audio/m4a' }; } // Needs to be before `ogg` check if (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) { return { ext: 'opus', mime: 'audio/opus' }; } // If 'OggS' in first bytes, then OGG container if (check([0x4F, 0x67, 0x67, 0x53])) { // This is a OGG container // If ' theora' in header. if (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 28})) { return { ext: 'ogv', mime: 'video/ogg' }; } // If '\x01video' in header. if (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {offset: 28})) { return { ext: 'ogm', mime: 'video/ogg' }; } // If ' FLAC' in header https://xiph.org/flac/faq.html if (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {offset: 28})) { return { ext: 'oga', mime: 'audio/ogg' }; } // 'Speex ' in header https://en.wikipedia.org/wiki/Speex if (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {offset: 28})) { return { ext: 'spx', mime: 'audio/ogg' }; } // If '\x01vorbis' in header if (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 28})) { return { ext: 'ogg', mime: 'audio/ogg' }; } // Default OGG container https://www.iana.org/assignments/media-types/application/ogg return { ext: 'ogx', mime: 'application/ogg' }; } if (check([0x66, 0x4C, 0x61, 0x43])) { return { ext: 'flac', mime: 'audio/x-flac' }; } if (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) { return { ext: 'amr', mime: 'audio/amr' }; } if (check([0x25, 0x50, 0x44, 0x46])) { return { ext: 'pdf', mime: 'application/pdf' }; } if (check([0x4D, 0x5A])) { return { ext: 'exe', mime: 'application/x-msdownload' }; } if ( (buf[0] === 0x43 || buf[0] === 0x46) && check([0x57, 0x53], {offset: 1}) ) { return { ext: 'swf', mime: 'application/x-shockwave-flash' }; } if (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) { return { ext: 'rtf', mime: 'application/rtf' }; } if (check([0x00, 0x61, 0x73, 0x6D])) { return { ext: 'wasm', mime: 'application/wasm' }; } if ( check([0x77, 0x4F, 0x46, 0x46]) && ( check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) ) ) { return { ext: 'woff', mime: 'font/woff' }; } if ( check([0x77, 0x4F, 0x46, 0x32]) && ( check([0x00, 0x01, 0x00, 0x00], {offset: 4}) || check([0x4F, 0x54, 0x54, 0x4F], {offset: 4}) ) ) { return { ext: 'woff2', mime: 'font/woff2' }; } if ( check([0x4C, 0x50], {offset: 34}) && ( check([0x00, 0x00, 0x01], {offset: 8}) || check([0x01, 0x00, 0x02], {offset: 8}) || check([0x02, 0x00, 0x02], {offset: 8}) ) ) { return { ext: 'eot', mime: 'application/octet-stream' }; } if (check([0x00, 0x01, 0x00, 0x00, 0x00])) { return { ext: 'ttf', mime: 'font/ttf' }; } if (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) { return { ext: 'otf', mime: 'font/otf' }; } if (check([0x00, 0x00, 0x01, 0x00])) { return { ext: 'ico', mime: 'image/x-icon' }; } if (check([0x00, 0x00, 0x02, 0x00])) { return { ext: 'cur', mime: 'image/x-icon' }; } if (check([0x46, 0x4C, 0x56, 0x01])) { return { ext: 'flv', mime: 'video/x-flv' }; } if (check([0x25, 0x21])) { return { ext: 'ps', mime: 'application/postscript' }; } if (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) { return { ext: 'xz', mime: 'application/x-xz' }; } if (check([0x53, 0x51, 0x4C, 0x69])) { return { ext: 'sqlite', mime: 'application/x-sqlite3' }; } if (check([0x4E, 0x45, 0x53, 0x1A])) { return { ext: 'nes', mime: 'application/x-nintendo-nes-rom' }; } if (check([0x43, 0x72, 0x32, 0x34])) { return { ext: 'crx', mime: 'application/x-google-chrome-extension' }; } if ( check([0x4D, 0x53, 0x43, 0x46]) || check([0x49, 0x53, 0x63, 0x28]) ) { return { ext: 'cab', mime: 'application/vnd.ms-cab-compressed' }; } // Needs to be before `ar` check if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) { return { ext: 'deb', mime: 'application/x-deb' }; } if (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) { return { ext: 'ar', mime: 'application/x-unix-archive' }; } if (check([0xED, 0xAB, 0xEE, 0xDB])) { return { ext: 'rpm', mime: 'application/x-rpm' }; } if ( check([0x1F, 0xA0]) || check([0x1F, 0x9D]) ) { return { ext: 'Z', mime: 'application/x-compress' }; } if (check([0x4C, 0x5A, 0x49, 0x50])) { return { ext: 'lz', mime: 'application/x-lzip' }; } if (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) { return { ext: 'msi', mime: 'application/x-msi' }; } if (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) { return { ext: 'mxf', mime: 'application/mxf' }; } if (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) { return { ext: 'mts', mime: 'video/mp2t' }; } if (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) { return { ext: 'blend', mime: 'application/x-blender' }; } if (check([0x42, 0x50, 0x47, 0xFB])) { return { ext: 'bpg', mime: 'image/bpg' }; } if (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) { // JPEG-2000 family if (check([0x6A, 0x70, 0x32, 0x20], {offset: 20})) { return { ext: 'jp2', mime: 'image/jp2' }; } if (check([0x6A, 0x70, 0x78, 0x20], {offset: 20})) { return { ext: 'jpx', mime: 'image/jpx' }; } if (check([0x6A, 0x70, 0x6D, 0x20], {offset: 20})) { return { ext: 'jpm', mime: 'image/jpm' }; } if (check([0x6D, 0x6A, 0x70, 0x32], {offset: 20})) { return { ext: 'mj2', mime: 'image/mj2' }; } } if (check([0x46, 0x4F, 0x52, 0x4D, 0x00])) { return { ext: 'aif', mime: 'audio/aiff' }; } if (checkString('<?xml ')) { return { ext: 'xml', mime: 'application/xml' }; } if (check([0x42, 0x4F, 0x4F, 0x4B, 0x4D, 0x4F, 0x42, 0x49], {offset: 60})) { return { ext: 'mobi', mime: 'application/x-mobipocket-ebook' }; } // File Type Box (https://en.wikipedia.org/wiki/ISO_base_media_file_format) if (check([0x66, 0x74, 0x79, 0x70], {offset: 4})) { if (check([0x6D, 0x69, 0x66, 0x31], {offset: 8})) { return { ext: 'heic', mime: 'image/heif' }; } if (check([0x6D, 0x73, 0x66, 0x31], {offset: 8})) { return { ext: 'heic', mime: 'image/heif-sequence' }; } if (check([0x68, 0x65, 0x69, 0x63], {offset: 8}) || check([0x68, 0x65, 0x69, 0x78], {offset: 8})) { return { ext: 'heic', mime: 'image/heic' }; } if (check([0x68, 0x65, 0x76, 0x63], {offset: 8}) || check([0x68, 0x65, 0x76, 0x78], {offset: 8})) { return { ext: 'heic', mime: 'image/heic-sequence' }; } } return null; };
jmhmd/dat-lambda
client/lib/file-type.js
JavaScript
mit
15,936