code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
line_mean
float64
0.5
100
line_max
int64
1
1k
alpha_frac
float64
0.25
1
autogenerated
bool
1 class
<?php namespace SCL\ZF2\Currency\Form\Fieldset; use Zend\Form\Fieldset; class TaxedPrice extends Fieldset { const AMOUNT_LABEL = 'Amount'; const TAX_LABEL = 'Tax'; public function init() { $this->add([ 'name' => 'amount', 'type' => 'text', 'options' => [ 'label' => self::AMOUNT_LABEL, ] ]); $this->add([ 'name' => 'tax', 'type' => 'text', 'options' => [ 'label' => self::TAX_LABEL, ] ]); } }
SCLInternet/SclZfCurrency
src/SCL/ZF2/Currency/Form/Fieldset/TaxedPrice.php
PHP
mit
581
18.366667
46
0.414802
false
var indexController = require('./controllers/cIndex'); var usuarioController = require('./controllers/cUsuario'); var clientesController = require('./controllers/cCliente'); var adminController = require('./controllers/cAdmin'); var umedController = require('./controllers/cUmed'); var matepController = require('./controllers/cMatep'); var empleController = require('./controllers/cEmple'); var accesosController = require('./controllers/cAccesos'); var cargoController = require('./controllers/cCargos'); var reactoController = require('./controllers/cReacto'); var lineasController = require('./controllers/cLineas'); var prodController = require('./controllers/cProd'); var envasesController = require('./controllers/cEnvases'); var tanquesController = require('./controllers/cTanques'); var ubicaController = require('./controllers/cUbica'); var recetaController = require('./controllers/cReceta'); var remitosController = require('./controllers/cRemitos'); var progController = require('./controllers/cProgramacion'); var FormEnReactorController = require('./controllers/cFormEnReactor'); var labController = require('./controllers/cLab'); var formController = require('./controllers/cFormulados'); var mEventos = require('./models/mEventos'); var consuController = require('./controllers/cConsumibles'); var produccionController = require('./controllers/cProduccion'); var fraccionadoController = require('./controllers/cFraccionado'); var aprobacionController = require('./controllers/cAprobacion'); var navesController = require('./controllers/cNaves'); var mapaController = require('./controllers/cMapa'); function logout (req, res) { fecha = new Date(); day = fecha.getDate(); month = fecha.getMonth(); if (day<10) day = "0" + day; if (month<10) month = "0" + month; fecha = fecha.getFullYear() + "/"+month+"/"+day+" "+fecha.getHours()+":"+fecha.getMinutes() mEventos.add(req.session.user.unica, fecha, "Logout", "", function(){ }); req.session = null; return res.redirect('/'); } // Verifica que este logueado function auth (req, res, next) { if (req.session.auth) { return next(); } else { console.log("dentro del else del auth ") return res.redirect('/') } } module.exports = function(app) { app.get('/', adminController.getLogin); app.get('/login', adminController.getLogin) app.post('/login', adminController.postLogin); app.get('/logout', logout); app.get('/inicio', auth, indexController.getInicio); app.get('/error', indexController.getError); //ayuda app.get('/ayuda', indexController.getAyuda); app.get('/ayudaver/:id', indexController.AyudaVer); //novedades app.get('/listanovedades', indexController.getNovedades); //usuarios app.get('/usuarioslista', auth, usuarioController.getUsuarios); app.get('/usuariosalta', auth, usuarioController.getUsuariosAlta); app.post('/usuariosalta', auth, usuarioController.putUsuario); app.get('/usuariosmodificar/:id', auth, usuarioController.getUsuarioModificar); app.post('/usuariosmodificar', auth, usuarioController.postUsuarioModificar); app.get('/usuariosborrar/:id', auth, usuarioController.getDelUsuario); //configurar accesos app.get('/accesoslista/:id', auth, accesosController.getAccesos); app.post('/accesoslista', auth, accesosController.postAccesos); //clientes app.get('/clienteslista', auth, clientesController.getClientes); app.get('/clientesalta', auth, clientesController.getClientesAlta); app.post('/clientesalta', auth, clientesController.putCliente); app.get('/clientesmodificar/:id', auth, clientesController.getClienteModificar); app.post('/clientesmodificar', auth, clientesController.postClienteModificar); app.get('/clientesborrar/:id', auth, clientesController.getDelCliente); app.get('/:cliente/materiasprimas', auth, clientesController.getMatep); //unidades de medida "umed" app.get('/umedlista', auth, umedController.getAllUmed); app.get('/umedalta', auth, umedController.getAlta); app.post('/umedalta', auth, umedController.postAlta); app.get('/umedmodificar/:id', auth, umedController.getModificar); app.post('/umedactualizar', auth, umedController.postModificar); app.get('/umedborrar/:id', auth, umedController.getDelUmed); //materias primas por cliente app.get('/mateplista/:cdcliente', auth, matepController.getAllMatepPorCliente); app.get('/matepalta/:cdcliente', auth, matepController.getAlta); app.post('/matepalta', auth, matepController.postAlta); app.get('/matepmodificar/:id', auth, matepController.getModificar); app.post('/matepmodificar', auth, matepController.postModificar); app.get('/matepborrar/:id', auth, matepController.getDelMatep); //cantidad maxima en tanque por matep app.get('/formenreactor/:id', auth, FormEnReactorController.getFormEnReactor); app.get('/formenreactoralta/:idform', auth, FormEnReactorController.getAlta); app.post('/formenreactoralta', auth, FormEnReactorController.postAlta); app.get('/formenreactormodificar/:id', auth, FormEnReactorController.getModificar); app.post('/formenreactormodificar', auth, FormEnReactorController.postModificar); app.get('/formenreactorborrar/:id', auth, FormEnReactorController.del); //producto por clientereactor app.get('/prodlista/:cdcliente', auth, prodController.getAllProdPorCliente); app.get('/prodalta/:cdcliente', auth, prodController.getAlta); app.post('/prodalta', auth, prodController.postAlta); app.get('/prodmodificar/:id', auth, prodController.getModificar); app.post('/prodmodificar', auth, prodController.postModificar); app.get('/prodborrar/:id', auth, prodController.getDelProd); app.get('/:idprod/ablote', auth, prodController.getAbLote); //empleados app.get('/emplelista', auth, empleController.getEmpleados); app.get('/emplealta', auth, empleController.getAlta); app.post('/emplealta', auth, empleController.postAlta); app.get('/emplemodificar/:codigo', auth, empleController.getModificar); app.post('/emplemodificar', auth, empleController.postModificar); app.get('/empleborrar/:codigo', auth, empleController.getDelEmple); //cargos de empleados app.get('/cargoslista', auth, cargoController.getAllCargos); app.get('/cargosalta', auth, cargoController.getAlta); app.post('/cargosalta', auth, cargoController.postAlta); app.get('/cargosmodificar/:id', auth, cargoController.getModificar); app.post('/cargosmodificar', auth, cargoController.postModificar); app.get('/cargosborrar/:id', auth, cargoController.getDelCargo); //reactores app.get('/reactolista', auth, reactoController.getAll); app.get('/reactoalta', auth, reactoController.getAlta); app.post('/reactoalta', auth, reactoController.postAlta); app.get('/reactomodificar/:id', auth, reactoController.getModificar); app.post('/reactomodificar', auth, reactoController.postModificar); app.get('/reactoborrar/:id', auth, reactoController.getDel); //lineas app.get('/lineaslista', auth, lineasController.getAll); app.get('/lineasalta', auth, lineasController.getAlta); app.post('/lineasalta', auth, lineasController.postAlta); app.get('/lineasmodificar/:id', auth, lineasController.getModificar); app.post('/lineasmodificar', auth, lineasController.postModificar); app.get('/lineasborrar/:id', auth, lineasController.getDel); //envases app.get('/envaseslista', auth, envasesController.getAll); app.get('/envasesalta', auth, envasesController.getAlta); app.post('/envasesalta', auth, envasesController.postAlta); app.get('/envasesmodificar/:id', auth, envasesController.getModificar); app.post('/envasesmodificar', auth, envasesController.postModificar); app.get('/envasesborrar/:id', auth, envasesController.getDel); app.get('/capacidadenvase/:id', auth, envasesController.getCapacidad); //tanques app.get('/tanqueslista', auth, tanquesController.getAll); app.get('/tanquesalta', auth, tanquesController.getAlta); app.post('/tanquesalta', auth, tanquesController.postAlta); app.get('/tanquesmodificar/:id', auth, tanquesController.getModificar); app.post('/tanquesmodificar', auth, tanquesController.postModificar); app.get('/tanquesborrar/:id', auth, tanquesController.getDel); //ubicaciones "ubica" app.get('/ubicalista', auth, ubicaController.getAll); app.get('/ubicaalta', auth, ubicaController.getAlta); app.post('/ubicaalta', auth, ubicaController.postAlta); app.get('/ubicamodificar/:id', auth, ubicaController.getModificar); app.post('/ubicamodificar', auth, ubicaController.postModificar); app.get('/ubicaborrar/:id', auth, ubicaController.getDel); //recetas app.get('/recetalista/:id', auth, recetaController.getRecetaPorFormulado); app.get('/recetaalta/:id', auth, recetaController.getAlta); app.post('/recetaalta', auth, recetaController.postAlta); app.get('/recetaborrar/:id', auth, recetaController.getDel); app.get('/recetamodificar/:id', auth, recetaController.getModificar); app.post('/recetamodificar', auth, recetaController.postModificar); //remitos app.get('/remitoslista', auth, remitosController.getAll); app.get('/remitosalta', auth, remitosController.getAlta); app.post('/remitosalta', auth, remitosController.postAlta); app.get('/remitosmodificar/:id', auth, remitosController.getModificar); app.post('/remitosmodificar', auth, remitosController.postModificar); app.get('/remitosborrar/:id', auth, remitosController.getDel); app.get('/buscarremito/:finicio/:ffin', auth, remitosController.getRemitos); //programacion app.get('/prog1lista', auth, progController.getAll); app.get('/prog1alta', auth, progController.getAlta); app.post('/prog1alta', auth, progController.postAlta); app.get('/prog2lista', auth, progController.getLista); app.get('/prog1alta2/:idprog', auth, progController.getAlta2); app.post('/prog1alta2', auth, progController.postAlta2); app.get('/prog1/:lote/:anio/:clienteid/:prodid', auth, progController.getCodigo); app.get('/prog1borrar/:id', auth, progController.getDel); app.get('/refrescaremito/:idcliente/:idmatep', auth, progController.getRemitos); app.get('/traerpa/:idform', auth, progController.getPA); app.get('/buscarprogramaciones/:fecha', auth, progController.getProgramaciones); app.get('/produccionborrarprogram/:id', auth, progController.getDelProgram); //laboratorio app.get('/lab/:idremito', auth, labController.getLab); app.post('/lab', auth, labController.postLab); //formulados app.get('/formuladoalta/:cdcliente', auth, formController.getAlta); app.post('/formuladoalta', auth, formController.postAlta); app.get('/formuladolista/:cdcliente', auth, formController.getAllFormuladoPorCliente); app.get('/formuladomodificar/:id', auth, formController.getModificar); app.post('/formuladomodificar', auth, formController.postModificar); app.get('/formuladoborrar/:id', auth, formController.getDelFormulado); app.get('/:id/formulados', auth, formController.getForms); app.get('/:idform/ablotee', auth, formController.getAbLote); //consumibles app.get('/consumibleslista/:idprod', auth, consuController.getAll); app.get('/consumiblesalta/:idprod', auth, consuController.getAlta); app.post('/consumiblesalta', auth, consuController.postAlta); app.get('/consumiblesborrar/:id', auth, consuController.getDel); //produccion app.get('/produccionlista', auth, produccionController.getLista); app.get('/buscarprogramaciones2/:fi/:ff', auth, produccionController.getProgramaciones); app.get('/produccionver/:id', auth, produccionController.getVerFormulado); app.post('/produccionver', auth, produccionController.postDatosFormulado); app.get('/produccionimprimir/:id', auth, produccionController.getImprimir); //borrar //fraccionado app.get('/fraccionadolista', auth, fraccionadoController.getLista); app.get('/fraccionadoalta/:id', auth, fraccionadoController.getAlta); app.post('/fraccionadoalta', auth, fraccionadoController.postAlta); app.get('/fraccionadomodificar/:id', auth, fraccionadoController.getModificar); app.post('/fraccionadomodificar', auth, fraccionadoController.postModificar); //borrar? //aprobacion app.get('/aprobacionlista', auth, aprobacionController.getLista); app.get('/aprobacionver/:id', auth, aprobacionController.getVer); app.post('/aprobacionver', auth, aprobacionController.postVer); app.get('/aprobacionimprimir/:id', auth, aprobacionController.getImprimir); //naves app.get('/naveslista', auth, navesController.getLista); //mapa app.get('/mapaver', auth, mapaController.getMapa); };
IsaacMiguel/ProchemBio
routes.js
JavaScript
mit
12,314
52.081897
92
0.762141
false
<?php /** * Created by PhpStorm. * User: tfg * Date: 25/08/15 * Time: 20:03 */ namespace AppBundle\Behat; use Sylius\Bundle\ResourceBundle\Behat\DefaultContext; class BrowserContext extends DefaultContext { /** * @Given estoy autenticado como :username con :password */ public function iAmAuthenticated($username, $password) { $this->getSession()->visit($this->generateUrl('fos_user_security_login', [], true)); $this->fillField('_username', $username); $this->fillField('_password', $password); $this->pressButton('_submit'); } /** * @Then /^presiono "([^"]*)" con clase "([^"]*)"$/ * * @param string $text * @param string $class */ public function iFollowLinkWithClass($text, $class) { $link = $this->getSession()->getPage()->find( 'xpath', sprintf("//*[@class='%s' and contains(., '%s')]", $class, $text) ); if (!$link) { throw new ExpectationException(sprintf('Unable to follow the link with class: %s and text: %s', $class, $text), $this->getSession()); } $link->click(); } }
sergiormb/ritsiga
src/AppBundle/Behat/BrowserContext.php
PHP
mit
1,153
25.837209
145
0.569818
false
## Close ### What is the value of the first triangle number to have over five hundred divisors? print max([len(m) for m in map(lambda k: [n for n in range(1,(k+1)) if k%n == 0], [sum(range(n)) for n in range(1,1000)])])
jacksarick/My-Code
Python/python challenges/euler/012_divisable_tri_nums.py
Python
mit
219
72.333333
123
0.6621
false
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Autos4Sale.Data.Models")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Autos4Sale.Data.Models")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("280798cb-7923-404f-90bb-e890b732d781")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
shopOFF/Autos4Sale
Autos4Sale/Data/Autos4Sale.Data.Models/Properties/AssemblyInfo.cs
C#
mit
1,415
38.222222
84
0.748584
false
from errors import * from manager import SchemaManager
Livefyre/pseudonym
pseudonym/__init__.py
Python
mit
55
26.5
33
0.836364
false
<?php namespace Syrma\WebContainer; /** * */ interface ServerInterface { /** * Start the server. * * @param ServerContextInterface $context * @param RequestHandlerInterface $requestHandler */ public function start(ServerContextInterface $context, RequestHandlerInterface $requestHandler); /** * Stop the server. */ public function stop(); /** * The server is avaiable. * * Here check requirements * * @return bool */ public static function isAvaiable(); }
syrma-php/web-container
src/Syrma/WebContainer/ServerInterface.php
PHP
mit
552
16.806452
100
0.61413
false
# Architecture When you are developing a new feature that requires architectural design, or if you are changing the fundamental design of an existing feature, make sure it is discussed with one of the Frontend Architecture Experts. A Frontend Architect is an expert who makes high-level Frontend design decisions and decides on technical standards, including coding standards and frameworks. Architectural decisions should be accessible to everyone, so please document them in the relevant Merge Request discussion or by updating our documentation when appropriate. You can find the Frontend Architecture experts on the [team page](https://about.gitlab.com/team). ## Examples You can find documentation about the desired architecture for a new feature built with Vue.js [here](vue.md).
iiet/iiet-git
doc/development/fe_guide/architecture.md
Markdown
mit
792
40.684211
97
0.814394
false
module Mailchimp class API include HTTParty format :plain default_timeout 30 attr_accessor :api_key, :timeout, :throws_exceptions def initialize(api_key = nil, extra_params = {}) @api_key = api_key || ENV['MAILCHIMP_API_KEY'] || self.class.api_key @default_params = {:apikey => @api_key}.merge(extra_params) @throws_exceptions = false end def api_key=(value) @api_key = value @default_params = @default_params.merge({:apikey => @api_key}) end def base_api_url "https://#{dc_from_api_key}api.mailchimp.com/1.3/?method=" end def valid_api_key?(*args) "Everything's Chimpy!" == call("ping") end protected def call(method, params = {}) api_url = base_api_url + method params = @default_params.merge(params) timeout = params.delete(:timeout) || @timeout response = self.class.post(api_url, :body => CGI::escape(params.to_json), :timeout => timeout) begin response = JSON.parse(response.body) rescue response = JSON.parse('['+response.body+']').first end if @throws_exceptions && response.is_a?(Hash) && response["error"] raise "Error from MailChimp API: #{response["error"]} (code #{response["code"]})" end response end def method_missing(method, *args) method = method.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } #Thanks for the gsub, Rails method = method[0].chr.downcase + method[1..-1].gsub(/aim$/i, 'AIM') call(method, *args) end class << self attr_accessor :api_key def method_missing(sym, *args, &block) new(self.api_key).send(sym, *args, &block) end end def dc_from_api_key (@api_key.nil? || @api_key.length == 0 || @api_key !~ /-/) ? '' : "#{@api_key.split("-").last}." end end end
herimedia/mailchimp-gem
lib/mailchimp/api.rb
Ruby
mit
1,894
27.268657
123
0.577614
false
Ti=Ownership sec=All {_Confidential_Information} furnished to {_the_Consultant} by {_the_Client} is the sole and exclusive property of {_the_Client} or its suppliers or customers. =[G/Z/ol/0]
CommonAccord/Cmacc-Org
Doc/Wx/com/cooleygo/US/Consult/Sec/Confidentiality_Ownership_v01.md
Markdown
mit
194
37.8
166
0.747423
false
/* Print.cpp - Base class that provides print() and println() Copyright (c) 2008 David A. Mellis. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Modified 23 November 2006 by David A. Mellis Modified 20 Aug 2014 by MediaTek Inc. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "Arduino.h" #include "Print.h" // Public Methods ////////////////////////////////////////////////////////////// /* default implementation: may be overridden */ size_t Print::write(const uint8_t *buffer, size_t size) { size_t n = 0; while (size--) { n += write(*buffer++); } return n; } size_t Print::print(const __FlashStringHelper *ifsh) { return print(reinterpret_cast<const char *>(ifsh)); } size_t Print::print(const String &s) { return write(s.c_str(), s.length()); } size_t Print::print(const char str[]) { return write(str); } size_t Print::print(char c) { return write(c); } size_t Print::print(unsigned char b, int base) { return print((unsigned long) b, base); } size_t Print::print(int n, int base) { return print((long) n, base); } size_t Print::print(unsigned int n, int base) { return print((unsigned long) n, base); } size_t Print::print(long n, int base) { if (base == 0) { return write(n); } else if (base == 10) { if (n < 0) { int t = print('-'); n = -n; return printNumber(n, 10) + t; } return printNumber(n, 10); } else { return printNumber(n, base); } } size_t Print::print(unsigned long n, int base) { if (base == 0) return write(n); else return printNumber(n, base); } size_t Print::print(double n, int digits) { return printFloat(n, digits); } size_t Print::println(const __FlashStringHelper *ifsh) { size_t n = print(ifsh); n += println(); return n; } size_t Print::print(const Printable& x) { return x.printTo(*this); } size_t Print::println(void) { size_t n = print('\r'); n += print('\n'); return n; } size_t Print::println(const String &s) { size_t n = print(s); n += println(); return n; } size_t Print::println(const char c[]) { size_t n = print(c); n += println(); return n; } size_t Print::println(char c) { size_t n = print(c); n += println(); return n; } size_t Print::println(unsigned char b, int base) { size_t n = print(b, base); n += println(); return n; } size_t Print::println(int num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(unsigned int num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(long num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(unsigned long num, int base) { size_t n = print(num, base); n += println(); return n; } size_t Print::println(double num, int digits) { size_t n = print(num, digits); n += println(); return n; } size_t Print::println(const Printable& x) { size_t n = print(x); n += println(); return n; } #include <stdarg.h> size_t Print::printf(const char *fmt, ...) { va_list args; char buf[256] = {0}; va_start(args, fmt); vsprintf(buf, fmt, args); va_end(args); return write(buf, strlen(buf)); } // Private Methods ///////////////////////////////////////////////////////////// size_t Print::printNumber(unsigned long n, uint8_t base) { char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte. char *str = &buf[sizeof(buf) - 1]; *str = '\0'; // prevent crash if called with base == 1 if (base < 2) base = 10; do { unsigned long m = n; n /= base; char c = m - base * n; *--str = c < 10 ? c + '0' : c + 'A' - 10; } while(n); return write(str); } size_t Print::printFloat(double number, uint8_t digits) { size_t n = 0; if (isnan(number)) return print("nan"); if (isinf(number)) return print("inf"); if (number > 4294967040.0) return print ("ovf"); // constant determined empirically if (number <-4294967040.0) return print ("ovf"); // constant determined empirically // Handle negative numbers if (number < 0.0) { n += print('-'); number = -number; } // Round correctly so that print(1.999, 2) prints as "2.00" double rounding = 0.5; for (uint8_t i=0; i<digits; ++i) rounding /= 10.0; number += rounding; // Extract the integer part of the number and print it unsigned long int_part = (unsigned long)number; double remainder = number - (double)int_part; n += print(int_part); // Print the decimal point, but only if there are digits beyond if (digits > 0) { n += print("."); } // Extract digits from the remainder one at a time while (digits-- > 0) { remainder *= 10.0; int toPrint = int(remainder); n += print(toPrint); remainder -= toPrint; } return n; }
gokr/ardunimo
wrapper/src/cores/arduino/Print.cpp
C++
mit
5,552
19.336996
86
0.614193
false
import { Injectable } from '@angular/core'; /** * Created by AAAA on 3/21/2017. */ //http://stackoverflow.com/questions/9671995/javascript-custom-event-listener //http://www.typescriptlang.org/play/ class MyEvent{ private context:Object; private cbs: Function[] = []; constructor(context: Object){ this.context = context; } public addListener(cb: Function){ this.cbs.push(cb); } public removeListener(cb: Function){ let i = this.cbs.indexOf(cb); if (i >-1) { this.cbs.splice(i, 1); } } public removeAllListeners(){ this.cbs=[]; } public trigger(...args){ this.cbs.forEach(cb => cb.apply(this.context, args)) }; } class EventContainer{ private events: MyEvent[]= []; public createEvent(context:Object):MyEvent{ let myEvent = new MyEvent(context); this.events.push(myEvent); return myEvent; } public removeEvent(myEvent:MyEvent):void{ let i = this.events.indexOf(myEvent); if (i >-1) { this.events.splice(i, 1); } }; public trigger(...args):void{ this.events.forEach(event => event.trigger(args)); }; } class LoginEvent extends EventContainer{} class LogoutEvent extends EventContainer{} @Injectable() export class EventsService { private _loginEvent:LoginEvent; private _logoutEvent:LogoutEvent; constructor() {} get loginEvent():LoginEvent{ if(!this._loginEvent) { this._loginEvent = new LoginEvent(); } return this._loginEvent; } get logoutEvent():LogoutEvent{ if(!this._logoutEvent) { this._logoutEvent = new LogoutEvent(); } return this._logoutEvent; } }
caohonghiep/lkth
src/app/services/events.service.ts
TypeScript
mit
1,639
18.987805
77
0.650397
false
import random from datetime import datetime from multiprocessing import Pool import numpy as np from scipy.optimize import minimize def worker_func(args): self = args[0] m = args[1] k = args[2] r = args[3] return (self.eval_func(m, k, r) - self.eval_func(m, k, self.rt) - self.temporal_diff_sum(m, k)) ** 2 def optimized_func_i_der(args): """ The derivative of the optimized function with respect to the ith component of the vector r """ self = args[0] r = args[1] i = args[2] result = 0 M = len(self.data) for m in range(M): Nm = self.data[m].shape[0] - 1 for k in range(Nm + 1): result += ((self.eval_func(m, k, r) - self.eval_func(m, k, self.rt) - self.temporal_diff_sum(m, k)) * 2 * self.eval_func_der(m, k, r, i)) return result def worker_func_der(args): self = args[0] m = args[1] k = args[2] r = args[3] i = args[4] return ((self.eval_func(m, k, r) - self.eval_func(m, k, self.rt) - self.temporal_diff_sum(m, k)) * 2 * self.eval_func_der(m, k, r, i)) class Agent: num_features = 22 def __init__(self): self.lf = 0.2 # Learning factor lambda self.data = [] # The features' values for all the games self.rewards = [] # Reward values for moving from 1 state to the next self.rt = np.array([]) self.max_iter = 50 def set_learning_factor(self, learning_factor): assert(learning_factor >= 0 and learning_factor <= 1) self.lf = learning_factor def set_rt(self, rt): assert(len(rt) == self.num_features) self.rt = rt def set_iter(self, max_iter): self.max_iter = max_iter def set_data(self, data): self.data = [] self.rewards = [] for game in data: game = np.vstack((game, np.zeros(self.num_features + 1))) self.data.append(game[:, :-1]) self.rewards.append(game[:, -1:]) def eval_func(self, m, k, r): """ The evaluation function value for the set of weights (vector) r at the mth game and kth board state """ return np.dot(r, self.data[m][k]) def eval_func_der(self, m, k, r, i): """ Find the derivative of the evaluation function with respect to the ith component of the vector r """ return self.data[m][k][i] def get_reward(self, m, s): """ Get reward for moving from state s to state (s + 1) """ return self.rewards[m][s + 1][0] def temporal_diff(self, m, s): """ The temporal diffence value for state s to state (s+1) in the mth game """ return (self.get_reward(m, s) + self.eval_func(m, s + 1, self.rt) - self.eval_func(m, s, self.rt)) def temporal_diff_sum(self, m, k): Nm = self.data[m].shape[0] - 1 result = 0 for s in range(k, Nm): result += self.lf**(s - k) * self.temporal_diff(m, s) return result def optimized_func(self, r): result = 0 M = len(self.data) pool = Pool(processes=4) for m in range(M): Nm = self.data[m].shape[0] - 1 k_args = range(Nm + 1) self_args = [self] * len(k_args) m_args = [m] * len(k_args) r_args = [r] * len(k_args) result += sum(pool.map(worker_func, zip(self_args, m_args, k_args, r_args))) return result def optimized_func_i_der(self, r, i): """ The derivative of the optimized function with respect to the ith component of the vector r """ result = 0 M = len(self.data) for m in range(M): Nm = self.data[m].shape[0] - 1 for k in range(Nm + 1): result += ((self.eval_func(m, k, r) - self.eval_func(m, k, self.rt) - self.temporal_diff_sum(m, k)) * 2 * self.eval_func_der(m, k, r, i)) return result def optimized_func_der(self, r): p = Pool(processes=4) self_args = [self] * len(r) i_args = range(len(r)) r_args = [r] * len(r) return np.array(p.map(optimized_func_i_der, zip(self_args, r_args, i_args))) def callback(self, r): print("Iteration %d completed at %s" % (self.cur_iter, datetime.now().strftime("%d/%m/%Y %H:%M:%S"))) self.cur_iter += 1 def compute_next_rt(self): print("Start computing at %s" % (datetime.now().strftime("%d/%m/%Y %H:%M:%S"))) self.cur_iter = 1 r0 = np.array([random.randint(-10, 10) for i in range(self.num_features)]) res = minimize(self.optimized_func, r0, method='BFGS', jac=self.optimized_func_der, options={'maxiter': self.max_iter, 'disp': True}, callback=self.callback) return res.x
ndt93/tetris
scripts/agent3.py
Python
mit
5,234
26.989305
78
0.503439
false
RSpec.describe Porch::ProcStepDecorator do describe ".decorates?" do it "returns true if the step is a proc" do expect(described_class).to be_decorates Proc.new {} end it "returns true if the step is a lambda" do expect(described_class).to be_decorates lambda {} end it "returns false if the step is a class" do expect(described_class).to_not be_decorates Object end end describe "#execute" do let(:context) { Hash.new } let(:organizer) { double(:organizer) } let(:step) { Proc.new {} } subject { described_class.new step, organizer } it "calls the proc with the context" do expect(step).to receive(:call).with(context) subject.execute context end end end
jwright/porch
spec/porch/step_decorators/proc_step_decorator_spec.rb
Ruby
mit
747
25.678571
57
0.658635
false
<?php declare(strict_types=1); namespace Symplify\MultiCodingStandard\Tests\PhpCsFixer\Factory; use PhpCsFixer\Fixer\FixerInterface; use PHPUnit\Framework\TestCase; use Symplify\MultiCodingStandard\PhpCsFixer\Factory\FixerFactory; final class FixerFactoryTest extends TestCase { /** * @var FixerFactory */ private $fixerFactory; protected function setUp() { $this->fixerFactory = new FixerFactory(); } /** * @dataProvider provideCreateData */ public function testResolveFixerLevels( array $fixerLevels, array $fixers, array $excludedFixers, int $expectedFixerCount ) { $fixers = $this->fixerFactory->createFromLevelsFixersAndExcludedFixers($fixerLevels, $fixers, $excludedFixers); $this->assertCount($expectedFixerCount, $fixers); if (count($fixers)) { $fixer = $fixers[0]; $this->assertInstanceOf(FixerInterface::class, $fixer); } } public function provideCreateData() : array { return [ [[], [], [], 0], [[], ['no_whitespace_before_comma_in_array'], [], 1], [['psr1'], [], [], 2], [['psr2'], [], [], 24], [['psr2'], [], ['visibility'], 24], [['psr1', 'psr2'], [], [], 26], [['psr1', 'psr2'], [], ['visibility'], 26], ]; } }
Symplify/MultiCodingStandard
tests/PhpCsFixer/Factory/FixerFactoryTest.php
PHP
mit
1,399
25.396226
119
0.563974
false
# -*- coding: utf-8 -*- """" ProjectName: pydemi Repo: https://github.com/chrisenytc/pydemi Copyright (c) 2014 Christopher EnyTC Licensed under the MIT license. """ # Dependencies import uuid from api import app from hashlib import sha1 from flask import request from flask import jsonify as JSON from api.models.user import User from cors import cors @app.route('/signup', methods=['POST']) @cors(origin='*', methods=['POST']) def signup(): # Create new user new_user = User() new_user.name = request.form['name'] new_user.email = request.form['email'] new_user.password = sha1(request.form['password']).hexdigest() new_user.token = str(uuid.uuid4()) new_user.save() return JSON(message='User created successfully') @app.route('/signin', methods=['POST']) @cors(origin='*', methods=['POST']) def signin(): # Retorna a user data user_info = User.objects(email=request.form['email'], password=sha1( request.form['password']).hexdigest()) if user_info.count(): return JSON(token=user_info.get().token, roles=user_info.get().roles) else: return JSON(message='User not found')
chrisenytc/pydemi
api/controllers/users.py
Python
mit
1,151
26.404762
77
0.675065
false
'use strict'; const buildType = process.config.target_defaults.default_configuration; const assert = require('assert'); if (process.argv[2] === 'fatal') { const binding = require(process.argv[3]); binding.error.throwFatalError(); return; } test(`./build/${buildType}/binding.node`); test(`./build/${buildType}/binding_noexcept.node`); function test(bindingPath) { const binding = require(bindingPath); assert.throws(() => binding.error.throwApiError('test'), function(err) { return err instanceof Error && err.message.includes('Invalid'); }); assert.throws(() => binding.error.throwJSError('test'), function(err) { return err instanceof Error && err.message === 'test'; }); assert.throws(() => binding.error.throwTypeError('test'), function(err) { return err instanceof TypeError && err.message === 'test'; }); assert.throws(() => binding.error.throwRangeError('test'), function(err) { return err instanceof RangeError && err.message === 'test'; }); assert.throws( () => binding.error.doNotCatch( () => { throw new TypeError('test'); }), function(err) { return err instanceof TypeError && err.message === 'test' && !err.caught; }); assert.throws( () => binding.error.catchAndRethrowError( () => { throw new TypeError('test'); }), function(err) { return err instanceof TypeError && err.message === 'test' && err.caught; }); const err = binding.error.catchError( () => { throw new TypeError('test'); }); assert(err instanceof TypeError); assert.strictEqual(err.message, 'test'); const msg = binding.error.catchErrorMessage( () => { throw new TypeError('test'); }); assert.strictEqual(msg, 'test'); assert.throws(() => binding.error.throwErrorThatEscapesScope('test'), function(err) { return err instanceof Error && err.message === 'test'; }); assert.throws(() => binding.error.catchAndRethrowErrorThatEscapesScope('test'), function(err) { return err instanceof Error && err.message === 'test' && err.caught; }); const p = require('./napi_child').spawnSync( process.execPath, [ __filename, 'fatal', bindingPath ]); assert.ifError(p.error); assert.ok(p.stderr.toString().includes( 'FATAL ERROR: Error::ThrowFatalError This is a fatal error')); }
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/node-addon-api/test/error.js
JavaScript
mit
2,328
30.890411
97
0.646907
false
using System.Web; using System.Web.Optimization; namespace WebAPI.Boilerplate.Api { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
Manoj-Bisht/WebAPI-Boilerplate
WebAPI.Boilerplate.Api/App_Start/BundleConfig.cs
C#
mit
1,123
39.035714
112
0.580731
false
// // YYBaseLib.h // YYBaseLib // // Created by 银羽网络 on 16/7/19. // Copyright © 2016年 银羽网络. All rights reserved. // #import <UIKit/UIKit.h> #import "AppConfig.h" #import "BaseViewController.h" #import "CommonTool.h" #import "DataVerify.h" #import "FSMediaPicker.h" #import "MBProgressHUD+MBProgressHUD_Category.h" #import "EnumModel.h" #import "UsersModel.h" #import "NSDataAdditions.h" #import "NSDate_Extensions.h" #import "NSDictionary_Extensions.h" #import "NSObject_Extensions.h" #import "NSString_Extensions.h" #import "UIImageExtentions.h" #import "UILabel_Extensions.h" #import "PopupBaseView.h" #import "SDCycleScrollView.h" #import "UIButton+FillColor.h" #import "UIColor_Extensions.h" #import "UIImage+UIImage.h" #import "UIImage+UIImageScale.h" #import "UITableView+FDTemplateLayoutCell.h" #import "UITextView+Placeholder.h" #import "UIView+extensions.h" #import "UIView+Masonry.h" #import "AuthService.h" #import "AppManager.h" #import "ApiService.h" #import "GTMBase64.h" #import "GTMDefines.h" #import "ConsultGradeModel.h" #import "CategoryModel.h" #import "CityModel.h" #import "MenuModel.h" //! Project version number for YYBaseLib. FOUNDATION_EXPORT double YYBaseLibVersionNumber; //! Project version string for YYBaseLib. FOUNDATION_EXPORT const unsigned char YYBaseLibVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <YYBaseLib/PublicHeader.h>
chuanxiaoshi/YYBaseLib
YYBaseLib.framework/Headers/YYBaseLib.h
C
mit
1,471
25.888889
134
0.76584
false
<table id="member_table" class="mainTable padTable" style="width:100%;" cellspacing="0" cellpadding="0" border="0"> <thead> <tr> <th style="width:3%;" ><?=$lang_id?></th> <th style="width:22%;"><?=$lang_name?></th> <th style="width:15%;"><?=$lang_total_friends?></th> <th style="width:15%;"><?=$lang_total_reciprocal_friends?></th> <th style="width:15%;"><?=$lang_total_blocked_friends?></th> <th style="width:15%;"><?=$lang_friends_groups_public?></th> <th style="width:15%;"><?=$lang_friends_groups_private?></th> </tr> </thead> <tbody> <tr class="odd"> <td><?=$member['member_id']?></td> <td><?=$member['screen_name']?></td> <td><?=$member['total_friends']?></td> <td><?=$member['total_reciprocal_friends']?></td> <td><?=$member['total_blocked_friends']?></td> <td><?=$member['friends_groups_public']?></td> <td><?=$member['friends_groups_private']?></td> </tr> </tbody> </table> <?php if ( count( $friends ) == 0 ) : ?> <p><span class="notice"><?=$member['screen_name']?><?=$lang__added_no_friends_yet?></span></p> <?php else: ?> <form action="<?=$form_uri?>" method="post" id="delete_friend_form"> <input type="hidden" name="XID" value="<?=$XID_SECURE_HASH?>" /> <input type="hidden" name="member_id" value="<?=$member['member_id']?>" /> <table class="mainTable padTable magicCheckboxTable" style="width:100%;" cellspacing="0" cellpadding="0" border="0"> <thead> <tr> <th style="width:3%;">&nbsp;</th> <th style="width:7%;"> <input class="checkbox" type="checkbox" name="toggle_all_checkboxes" value="" />&nbsp;<?=$lang_delete?> </th> <th style="width:30%;"><?=$lang_name?></th> <th style="width:20%;"><?=$lang_date?></th> <th style="width:15%;"><?=$lang_reciprocal?></th> <th style="width:15%;"><?=$lang_blocked?></th> <th style="width:10%;"><?=$lang_total_friends?></th> </tr> </thead> <tbody> <?php foreach ( $friends as $key => $val ) : $key = $key + 1 + $row_count; $switch = $this->cycle('odd', 'even'); ?> <tr class="<?=$switch?>"> <td><?=$key?></td> <td> <input class="checkbox" type="checkbox" name="toggle[]" value="<?=$val['entry_id']?>" id="delete_box_<?=$key?>" /> </td> <td> <a href="<?=$val['friend_uri']?>" title="<?=$lang_view_friends_of_?><?=$val['screen_name']?>"> <?=$val['screen_name']; ?></a> </td> <td><?=$val['date']?></td> <td><?=$val['reciprocal']?></td> <td><?=$val['block']?></td> <td><?=$val['total_friends']?></td> </tr> <?php endforeach; ?> <?php $switch = $this->cycle('odd', 'even'); ?> <tr class="<?=$switch?>"> <td>&nbsp;</td> <td colspan="6"> <input class="checkbox" type="checkbox" name="toggle_all_checkboxes" value="" />&nbsp;<strong><?=$lang_delete?></strong> </td> </tr> <?php if ( $paginate !== '' ) : ?> <?php $switch = $this->cycle('odd', 'even'); ?> <tr class="<?=$switch?>"> <td colspan="7"> <?=$paginate?> </td> </tr> <?php endif; ?> </tbody> </table> <p><input type="submit" class="submit" value="<?=$lang_delete?>" /></p> </form> <?php endif; ?>
ProJobless/nyus
nyusocial/expressionengine/third_party/friends/views/members_friends.html
HTML
mit
3,351
35.255556
116
0.506118
false
package redes3.proyecto.nagiosalert; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class InfoServiceActivity extends Activity { String nombre; int status; String duracion; String revision; String info; ImageView image ; TextView tvNombre ; TextView tvStatus ; TextView tvDuracion ; TextView tvRevision ; TextView tvInfo ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info_service); nombre = new String(); status = 0 ; duracion = new String(); revision = new String(); info = new String(); image = (ImageView) findViewById(R.id.image); tvNombre = (TextView)this.findViewById(R.id.tvNombreServicio); tvStatus = (TextView)this.findViewById(R.id.status); tvDuracion = (TextView)this.findViewById(R.id.duracion); tvRevision = (TextView)this.findViewById(R.id.revision); tvInfo = (TextView)this.findViewById(R.id.info); Bundle extras = getIntent().getExtras(); nombre = extras.getString("nombre"); status = extras.getInt("status"); duracion = extras.getString("duracion"); revision = extras.getString("revision"); info = extras.getString("info"); tvNombre.setText(nombre); tvDuracion.setText("Duracion : \n"+duracion); tvRevision.setText("Revision : \n"+revision); tvInfo.setText("Descripción : \n"+info); if(status== 0){ tvStatus.setText("Estado : \nOk"); image.setImageResource(R.drawable.fine); }else if(status== 1){ tvStatus.setText("Estado : \nFail"); image.setImageResource(R.drawable.fail); }if(status== 2){ tvStatus.setText("Estado : \nWarning"); image.setImageResource(R.drawable.warning); }if(status== 3){ tvStatus.setText("Estado : \nUnknown"); image.setImageResource(R.drawable.unknown); } } }
caat91/NagiosAlert
NagiosAlert-App/src/redes3/proyecto/nagiosalert/InfoServiceActivity.java
Java
mit
2,141
27.945946
69
0.666978
false
--- layout: post title: !binary |- Rm9vbOKAmXMgV29ybGQgTWFw tags: - micrographic --- Hoy me he encontrado en Microsiervos y en Halón disparado una cosa realmente curiosa, una revisión freakie del mapa del mundo! Se trata de un mapa donde los países están colocados donde la gente (yanquis, claro) cree que están. El resultado es impagable, de verdad.
cuellarfr/cuellarfr.github.io
_posts/2004-08-13-fool-s-world-map.md
Markdown
mit
358
43.125
265
0.776204
false
#include "MultiSelection.h" #include "ofxCogEngine.h" #include "EnumConverter.h" #include "Node.h" namespace Cog { void MultiSelection::Load(Setting& setting) { string group = setting.GetItemVal("selection_group"); if (group.empty()) CogLogError("MultiSelection", "Error while loading MultiSelection behavior: expected parameter selection_group"); this->selectionGroup = StrId(group); // load all attributes string defaultImg = setting.GetItemVal("default_img"); string selectedImg = setting.GetItemVal("selected_img"); if (!defaultImg.empty() && !selectedImg.empty()) { this->defaultImg = CogGet2DImage(defaultImg); this->selectedImg = CogGet2DImage(selectedImg); } else { string defaultColorStr = setting.GetItemVal("default_color"); string selectedColorStr = setting.GetItemVal("selected_color"); if (!defaultColorStr.empty() && !selectedColorStr.empty()) { this->defaultColor = EnumConverter::StrToColor(defaultColorStr); this->selectedColor = EnumConverter::StrToColor(selectedColorStr); } } } void MultiSelection::OnInit() { SubscribeForMessages(ACT_OBJECT_HIT_ENDED, ACT_STATE_CHANGED); } void MultiSelection::OnStart() { CheckState(); owner->SetGroup(selectionGroup); } void MultiSelection::OnMessage(Msg& msg) { if (msg.HasAction(ACT_OBJECT_HIT_ENDED) && msg.GetContextNode()->IsInGroup(selectionGroup)) { // check if the object has been clicked (user could hit a different area and release touch over the button) auto evt = msg.GetDataPtr<InputEvent>(); if (evt->input->handlerNodeId == msg.GetContextNode()->GetId()) { ProcessHit(msg, false); } } else if (msg.HasAction(ACT_STATE_CHANGED) && msg.GetContextNode()->IsInGroup(selectionGroup)) { ProcessHit(msg, true); // set directly, because STATE_CHANGED event has been already invoked } } void MultiSelection::ProcessHit(Msg& msg, bool setDirectly) { if (msg.GetContextNode()->GetId() == owner->GetId()) { // selected actual node if (!owner->HasState(selectedState)) { if (setDirectly) owner->GetStates().SetState(selectedState); else owner->SetState(selectedState); SendMessage(ACT_OBJECT_SELECTED); CheckState(); } else { CheckState(); } } else { if (owner->HasState(selectedState)) { if (setDirectly) owner->GetStates().ResetState(selectedState); else owner->ResetState(selectedState); CheckState(); } } } void MultiSelection::CheckState() { if (owner->HasState(selectedState)) { if (selectedImg) { owner->GetMesh<Image>()->SetImage(selectedImg); } else { owner->GetMesh()->SetColor(selectedColor); } } else if (!owner->HasState(selectedState)) { if (defaultImg) { owner->GetMesh<Image>()->SetImage(defaultImg); } else { owner->GetMesh()->SetColor(defaultColor); } } } }// namespace
dormantor/ofxCogEngine
COGengine/src/Behaviors/MultiSelection.cpp
C++
mit
2,863
27.929293
134
0.694027
false
// The MIT License (MIT) // // Copyright (c) 2016 Tim Jones // // 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 io.github.jonestimd.finance.file; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Collectors; import io.github.jonestimd.finance.domain.transaction.Transaction; import io.github.jonestimd.finance.swing.transaction.TransactionTableModel; import static io.github.jonestimd.util.JavaPredicates.*; public class Reconciler { private final TransactionTableModel tableModel; private final List<Transaction> uncleared; public Reconciler(TransactionTableModel tableModel) { this.tableModel = tableModel; this.uncleared = tableModel.getBeans().stream() .filter(not(Transaction::isCleared)).filter(not(Transaction::isNew)) .collect(Collectors.toList()); } public void reconcile(Collection<Transaction> transactions) { transactions.forEach(this::reconcile); } private void reconcile(Transaction transaction) { Transaction toClear = select(transaction); if (toClear.isNew()) { toClear.setCleared(true); tableModel.queueAdd(tableModel.getBeanCount()-1, toClear); } else { tableModel.setValueAt(true, tableModel.rowIndexOf(toClear), tableModel.getClearedColumn()); } } private Transaction select(Transaction transaction) { return uncleared.stream().filter(sameProperties(transaction)).min(nearestDate(transaction)).orElse(transaction); } private Predicate<Transaction> sameProperties(Transaction transaction) { return t2 -> transaction.getAmount().compareTo(t2.getAmount()) == 0 && transaction.getAssetQuantity().compareTo(t2.getAssetQuantity()) == 0 && Objects.equals(transaction.getPayee(), t2.getPayee()) && Objects.equals(transaction.getSecurity(), t2.getSecurity()); } private Comparator<Transaction> nearestDate(Transaction transaction) { return Comparator.comparingInt(t -> transaction.getDate().compareTo(t.getDate())); } }
jonestimd/finances
src/main/java/io/github/jonestimd/finance/file/Reconciler.java
Java
mit
3,250
41.763158
120
0.723385
false
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class AddTemplatesToEvents extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('events', function (Blueprint $table) { $table->string('template')->default('show'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('events', function ($table) { $table->dropColumn('template'); }); } }
ayimdomnic/Qicksite
src/PublishedAssets/Migrations/2016_03_20_186046_add_templates_to_events.php
PHP
mit
605
18.516129
61
0.54876
false
package plugin_test import ( "path/filepath" "code.cloudfoundry.org/cli/utils/testhelpers/pluginbuilder" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestPlugin(t *testing.T) { RegisterFailHandler(Fail) pluginbuilder.BuildTestBinary(filepath.Join("..", "fixtures", "plugins"), "test_1") RunSpecs(t, "Plugin Suite") }
jabley/cf-metrics
vendor/src/code.cloudfoundry.org/cli/plugin/plugin_suite_test.go
GO
mit
355
19.882353
84
0.723944
false
var express = require('express'), compression = require('compression'), path = require('path'), favicon = require('serve-favicon'), logger = require('morgan'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'), session = require('express-session'), session = require('express-session'), flash = require('connect-flash'), moment = require('moment'), mongoose = require('mongoose'), MongoStore = require('connect-mongo')(session), Pclog = require('./models/pclog.js'), configDB = require('./config/database.js'); mongoose.Promise = global.Promise = require('bluebird'); mongoose.connect(configDB.uri); var routes = require('./routes/index'), reports = require('./routes/reports'), statistics = require('./routes/statistics'), charts = require('./routes/charts'), logs = require('./routes/logs'), organization = require('./routes/organization'), users = require('./routes/users'); var app = express(); //var rootFolder = __dirname; // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compression()); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ secret: 'safe_session_cat', resave: true, rolling: true, saveUninitialized: false, cookie: {secure: false, maxAge: 900000}, store: new MongoStore({ url: configDB.uri }) })); app.use(flash()); app.use(express.static(path.join(__dirname, 'public'))); app.use('/', function(req,res,next){ app.locals.currentUrl = req.path; app.locals.moment = moment; res.locals.messages = require('express-messages')(req, res); if(req.session & req.session.user){ app.locals.user = req.session.user; } console.log(app.locals.user); next(); }); app.use('/', routes); app.use('/reports', reports); app.use('/statistics', statistics); app.use('/charts', charts); app.use('/logs', logs); app.use('/organization', organization); app.use('/users', users); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Page Not Found.'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace // if (app.get('env') === 'development') { // app.use(function(err, req, res, next) { // res.status(err.status || 500); // res.render('error', { // message: err.message, // error: err // }); // }); // } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { if(err.status){ res.status(err.status); }else{ err.status = 500; err.message = "Internal Server Error." res.status(500); } res.render('404', {error: err}); }); module.exports = app;
EdmonJiang/FA_Inventory
app.js
JavaScript
mit
2,979
26.583333
64
0.644512
false
/** * CircularLinkedList implementation * @author Tyler Smith * @version 1.0 */ public class CircularLinkedList<T> implements LinkedListInterface<T> { private Node<T> head = null, tail = head; private int size = 0; @Override public void addAtIndex(int index, T data) { if (index < 0 || index > this.size()) { throw new IndexOutOfBoundsException(); } if (index == 0) { this.addToFront(data); } else if (index == this.size()) { this.addToBack(data); } else { Node<T> current = head; if (index == 1) { current.setNext(new Node<T>(data, current.getNext())); } else { for (int i = 0; i < index - 1; i++) { current = current.getNext(); } Node<T> temp = current; current = new Node<T>(data, temp); } size++; } } @Override public T get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(); } Node<T> current = head; for (int i = 0; i < index; i++) { current = current.getNext(); } return current.getData(); } @Override public T removeAtIndex(int index) { if (index < 0 || index >= this.size()) { throw new IndexOutOfBoundsException(); } if (index == 0) { T data = head.getData(); head = head.getNext(); tail.setNext(head); size--; return data; } else { Node<T> before = tail; Node<T> current = head; for (int i = 0; i < index; i++) { before = current; current = current.getNext(); } T data = current.getData(); before.setNext(current.getNext()); size--; return data; } } @Override public void addToFront(T t) { if (this.isEmpty()) { head = new Node<T>(t, tail); tail = head; tail.setNext(head); size++; return; } Node<T> node = new Node<T>(t, head); head = node; tail.setNext(head); size++; } @Override public void addToBack(T t) { if (this.isEmpty()) { tail = new Node<T>(t); head = tail; tail.setNext(head); head.setNext(tail); size++; } else { Node<T> temp = tail; tail = new Node<T>(t, head); temp.setNext(tail); size++; } } @Override public T removeFromFront() { if (this.isEmpty()) { return null; } Node<T> ret = head; head = head.getNext(); tail.setNext(head); size--; return ret.getData(); } @Override public T removeFromBack() { if (this.isEmpty()) { return null; } Node<T> iterate = head; while (iterate.getNext() != tail) { iterate = iterate.getNext(); } iterate.setNext(head); Node<T> ret = tail; tail = iterate; size--; return ret.getData(); } @SuppressWarnings("unchecked") @Override public T[] toList() { Object[] list = new Object[this.size()]; int i = 0; Node<T> current = head; while (i < this.size()) { list[i] = current.getData(); current = current.getNext(); i++; } return ((T[]) list); } @Override public boolean isEmpty() { return (this.size() == 0); } @Override public int size() { return size; } @Override public void clear() { head = null; tail = null; size = 0; } /** * Reference to the head node of the linked list. * Normally, you would not do this, but we need it * for grading your work. * * @return Node representing the head of the linked list */ public Node<T> getHead() { return head; } /** * Reference to the tail node of the linked list. * Normally, you would not do this, but we need it * for grading your work. * * @return Node representing the tail of the linked list */ public Node<T> getTail() { return tail; } /** * This method is for your testing purposes. * You may choose to implement it if you wish. */ @Override public String toString() { return ""; } }
tsmith328/Homework
Java/CS 1332/Homework 01/CircularLinkedList.java
Java
mit
4,722
23.340206
70
0.466963
false
--- name: Bug上报 about: 提交Bug让框架更加健壮 title: '' labels: bug assignees: '' --- 🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶 😁为了能够更好地复现问题和修复问题, 请提供 Demo 和详细的 bug 重现步骤😭 🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶🥶 > 记得删除以上内容 **描述bug** 清晰简单地描述这个bug是啥 **必现/偶发?** 必现 **怎么样重现这个bug** 1. 显示哪个页面 2. 点击哪个位置 3. 滚动到哪个位置 4. 发生了什么错误 **你期望的结果是什么?** 你本来期望得到的正确结果是怎样的?就是解决bug之后的结果 **截图** 如果有必要的话,请上传几张截图 **运行环境** - iPhone6 - iOS8.1 - Xcode10 **额外的** 最好能提供出现bug的Demo
CoderMJLee/MJRefresh
.github/ISSUE_TEMPLATE/bug--.md
Markdown
mit
942
9.487805
42
0.581395
false
import { Component, OnInit } from '@angular/core'; // import { TreeModule, TreeNode } from "primeng/primeng"; import { BlogPostService } from '../shared/blog-post.service'; import { BlogPostDetails } from '../shared/blog-post.model'; @Component({ selector: 'ejc-blog-archive', templateUrl: './blog-archive.component.html', styleUrls: ['./blog-archive.component.scss'] }) export class BlogArchiveComponent implements OnInit { constructor( // private postService: BlogPostService ) { } ngOnInit() { } // // it would be best if the data in the blog post details file was already organized into tree nodes // private buildTreeNodes(): TreeNode[] {} }
ejchristie/ejchristie.github.io
src/app/blog/blog-archive/blog-archive.component.ts
TypeScript
mit
676
26.04
104
0.699704
false
require 'active_record' module ActiveRecord class Migration def migrate_with_multidb(direction) if defined? self.class::DATABASE_NAME ActiveRecord::Base.establish_connection(self.class::DATABASE_NAME.to_sym) migrate_without_multidb(direction) ActiveRecord::Base.establish_connection(Rails.env.to_sym) else migrate_without_multidb(direction) end end alias_method_chain :migrate, :multidb end end
sinsoku/banana
lib/banana/migration.rb
Ruby
mit
462
27.875
81
0.705628
false
const os = require("os"); const fs = require("fs"); const config = { } let libs; switch (os.platform()) { case "darwin": { libs = [ "out/Debug_x64/libpvpkcs11.dylib", "out/Debug/libpvpkcs11.dylib", "out/Release_x64/libpvpkcs11.dylib", "out/Release/libpvpkcs11.dylib", ]; break; } case "win32": { libs = [ "out/Debug_x64/pvpkcs11.dll", "out/Debug/pvpkcs11.dll", "out/Release_x64/pvpkcs11.dll", "out/Release/pvpkcs11.dll", ]; break; } default: throw new Error("Cannot get pvpkcs11 compiled library. Unsupported OS"); } config.lib = libs.find(o => fs.existsSync(o)); if (!config.lib) { throw new Error("config.lib is empty"); } module.exports = config;
PeculiarVentures/pvpkcs11
test/config.js
JavaScript
mit
742
19.081081
76
0.606469
false
class RenameMembers < ActiveRecord::Migration[5.1] def change rename_table :members, :memberships end end
miljinx/helpdo-api
db/migrate/20170613234831_rename_members.rb
Ruby
mit
114
21.8
50
0.745614
false
using System; using Xunit; using System.Linq; using hihapi.Models; using hihapi.Controllers; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.OData.Results; using hihapi.test.common; namespace hihapi.unittest.Finance { [Collection("HIHAPI_UnitTests#1")] public class FinanceDocumentTypesControllerTest { private SqliteDatabaseFixture fixture = null; public FinanceDocumentTypesControllerTest(SqliteDatabaseFixture fixture) { this.fixture = fixture; } [Theory] [InlineData("")] [InlineData(DataSetupUtility.UserA)] public async Task TestCase_Read(string strusr) { var context = fixture.GetCurrentDataContext(); // 1. Read it without User assignment var control = new FinanceDocumentTypesController(context); if (String.IsNullOrEmpty(strusr)) { var userclaim = DataSetupUtility.GetClaimForUser(strusr); control.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userclaim } }; } var getresult = control.Get(); Assert.NotNull(getresult); var getokresult = Assert.IsType<OkObjectResult>(getresult); var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value); Assert.NotNull(getqueryresult); if (String.IsNullOrEmpty(strusr)) { var dbcategories = (from tt in context.FinDocumentTypes where tt.HomeID == null select tt).ToList<FinanceDocumentType>(); Assert.Equal(dbcategories.Count, getqueryresult.Count()); } await context.DisposeAsync(); } [Theory] [InlineData(DataSetupUtility.UserA, DataSetupUtility.Home1ID, "Test 1")] [InlineData(DataSetupUtility.UserB, DataSetupUtility.Home2ID, "Test 2")] public async Task TestCase_CRUD(string currentUser, int hid, string name) { var context = fixture.GetCurrentDataContext(); // 1. Read it out before insert. var control = new FinanceDocumentTypesController(context); var userclaim = DataSetupUtility.GetClaimForUser(currentUser); control.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userclaim } }; var getresult = control.Get(); Assert.NotNull(getresult); var getokresult = Assert.IsType<OkObjectResult>(getresult); var getqueryresult = Assert.IsAssignableFrom<IQueryable<FinanceDocumentType>>(getokresult.Value); Assert.NotNull(getqueryresult); // 2. Insert a new one. FinanceDocumentType ctgy = new FinanceDocumentType(); ctgy.HomeID = hid; ctgy.Name = name; ctgy.Comment = name; var postresult = await control.Post(ctgy); var createdResult = Assert.IsType<CreatedODataResult<FinanceDocumentType>>(postresult); Assert.NotNull(createdResult); short nctgyid = createdResult.Entity.ID; Assert.Equal(hid, createdResult.Entity.HomeID); Assert.Equal(ctgy.Name, createdResult.Entity.Name); Assert.Equal(ctgy.Comment, createdResult.Entity.Comment); // 3. Read it out var getsingleresult = control.Get(nctgyid); Assert.NotNull(getsingleresult); var getctgy = Assert.IsType<FinanceDocumentType>(getsingleresult); Assert.Equal(hid, getctgy.HomeID); Assert.Equal(ctgy.Name, getctgy.Name); Assert.Equal(ctgy.Comment, getctgy.Comment); // 4. Change it getctgy.Comment += "Changed"; var putresult = control.Put(nctgyid, getctgy); Assert.NotNull(putresult); // 5. Delete it var deleteresult = control.Delete(nctgyid); Assert.NotNull(deleteresult); await context.DisposeAsync(); } } }
alvachien/achihapi
test/hihapi.test/UnitTests/Finance/Config/FinanceDocumentTypesControllerTest.cs
C#
mit
4,350
37.821429
109
0.607636
false
<?php # MantisBT - a php based bugtracking system # MantisBT is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # MantisBT is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with MantisBT. If not, see <http://www.gnu.org/licenses/>. /** * @package MantisBT * @copyright Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org * @copyright Copyright (C) 2002 - 2011 MantisBT Team - mantisbt-dev@lists.sourceforge.net * @link http://www.mantisbt.org */ /** * MantisBT Core API's */ require_once( 'core.php' ); require_once( 'email_api.php' ); form_security_validate( 'signup' ); $f_username = strip_tags( gpc_get_string( 'username' ) ); $f_email = strip_tags( gpc_get_string( 'email' ) ); $f_captcha = gpc_get_string( 'captcha', '' ); $f_public_key = gpc_get_int( 'public_key', '' ); $f_username = trim( $f_username ); $f_email = email_append_domain( trim( $f_email ) ); $f_captcha = utf8_strtolower( trim( $f_captcha ) ); # force logout on the current user if already authenticated if( auth_is_user_authenticated() ) { auth_logout(); } # Check to see if signup is allowed if ( OFF == config_get_global( 'allow_signup' ) ) { print_header_redirect( 'login_page.php' ); exit; } if( ON == config_get( 'signup_use_captcha' ) && get_gd_version() > 0 && helper_call_custom_function( 'auth_can_change_password', array() ) ) { # captcha image requires GD library and related option to ON $t_key = utf8_strtolower( utf8_substr( md5( config_get( 'password_confirm_hash_magic_string' ) . $f_public_key ), 1, 5) ); if ( $t_key != $f_captcha ) { trigger_error( ERROR_SIGNUP_NOT_MATCHING_CAPTCHA, ERROR ); } } email_ensure_not_disposable( $f_email ); # notify the selected group a new user has signed-up if( user_signup( $f_username, $f_email ) ) { email_notify_new_account( $f_username, $f_email ); } form_security_purge( 'signup' ); html_page_top1(); html_page_top2a(); ?> <br /> <div align="center"> <table class="width50" cellspacing="1"> <tr> <td class="center"> <b><?php echo lang_get( 'signup_done_title' ) ?></b><br /> <?php echo "[$f_username - $f_email] " ?> </td> </tr> <tr> <td> <br /> <?php echo lang_get( 'password_emailed_msg' ) ?> <br /><br /> <?php echo lang_get( 'no_reponse_msg') ?> <br /><br /> </td> </tr> </table> <br /> <?php print_bracket_link( 'login_page.php', lang_get( 'proceed' ) ); ?> </div> <?php html_page_bottom1a( __FILE__ );
eazulay/mantis
signup.php
PHP
mit
2,896
28.252525
124
0.651243
false
team_mapping = { "SY": "Sydney", "WB": "Western Bulldogs", "WC": "West Coast", "HW": "Hawthorn", "GE": "Geelong", "FR": "Fremantle", "RI": "Richmond", "CW": "Collingwood", "CA": "Carlton", "GW": "Greater Western Sydney", "AD": "Adelaide", "GC": "Gold Coast", "ES": "Essendon", "ME": "Melbourne", "NM": "North Melbourne", "PA": "Port Adelaide", "BL": "Brisbane Lions", "SK": "St Kilda" } def get_team_name(code): return team_mapping[code] def get_team_code(full_name): for code, name in team_mapping.items(): if name == full_name: return code return full_name def get_match_description(response): match_container = response.xpath("//td[@colspan = '5' and @align = 'center']")[0] match_details = match_container.xpath(".//text()").extract() return { "round": match_details[1], "venue": match_details[3], "date": match_details[6], "attendance": match_details[8], "homeTeam": response.xpath("(//a[contains(@href, 'teams/')])[1]/text()").extract_first(), "awayTeam": response.xpath("(//a[contains(@href, 'teams/')])[2]/text()").extract_first(), "homeScore": int(response.xpath("//table[1]/tr[2]/td[5]/b/text()").extract_first()), "awayScore": int(response.xpath("//table[1]/tr[3]/td[5]/b/text()").extract_first()) } def get_match_urls(response): for match in response.xpath("//a[contains(@href, 'stats/games/')]/@href").extract(): yield response.urljoin(match)
bairdj/beveridge
src/scrapy/afltables/afltables/common.py
Python
mit
1,563
32.276596
97
0.566859
false
from keras.applications import imagenet_utils from keras.applications import mobilenet def dummyPreprocessInput(image): image -= 127.5 return image def getPreprocessFunction(preprocessType): if preprocessType == "dummy": return dummyPreprocessInput elif preprocessType == "mobilenet": return mobilenet.preprocess_input elif preprocessType == "imagenet": return imagenet_utils.preprocess_input else: raise Exception(preprocessType + " not supported")
SlipknotTN/Dogs-Vs-Cats-Playground
deep_learning/keras/lib/preprocess/preprocess.py
Python
mit
511
25.894737
58
0.72407
false
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace TheS.Runtime { internal class CallbackException : FatalException { public CallbackException() { } public CallbackException(string message, Exception innerException) : base(message, innerException) { // This can't throw something like ArgumentException because that would be worse than // throwing the callback exception that was requested. Fx.Assert(innerException != null, "CallbackException requires an inner exception."); Fx.Assert(!Fx.IsFatal(innerException), "CallbackException can't be used to wrap fatal exceptions."); } } }
teerachail/SoapWithAttachments
JavaWsBinding/TheS.ServiceModel/_Runtime/CallbackException.cs
C#
mit
874
35.333333
112
0.68578
false
<?php namespace App\Http\Controllers; use App\Jobs\GetInstance; use App\Models\Build; use App\Models\Commit; use App\Models\Repository; use App\RepositoryProviders\GitHub; use Illuminate\Support\Facades\DB; class DashboardController extends Controller { public function index() { $repositories = Repository::all(); $commits = Commit::select('branch', DB::raw('max(created_at) as created_at')) ->orderBy('created_at', 'desc') ->groupBy('branch') ->get(); $masterInfo = Commit::getBranchInfo('master'); $branches = []; foreach ($commits as $commit) { $info = Commit::getBranchInfo($commit->branch); $branches[] = [ 'branch' => $commit->branch, 'status' => $info['status'], 'label' => $info['label'], 'last_commit_id' => $info['last_commit_id'], ]; } return view('dashboard', compact('repositories', 'branches', 'masterInfo')); } public function build(Commit $commit, $attempt = null) { $count = Build::where(['commit_id' => $commit->id])->count(); $query = Build::where(['commit_id' => $commit->id]) ->orderBy('attempt', 'desc'); if ($attempt) { $query->where(['attempt' => $attempt]); } $build = $query->first(); $logs = json_decode($build->log, true); $next = $build->attempt < $count ? "/build/$build->id/" . ($build->attempt + 1) : null; return view('build', compact('build', 'commit', 'attempt', 'logs', 'count', 'next')); } public function rebuild(Build $build) { $rebuild = new Build(); $rebuild->commit_id = $build->commit_id; $rebuild->attempt = $build->attempt + 1; $rebuild->status = 'QUEUED'; $rebuild->save(); $github = new GitHub( $rebuild->commit->repository->name, $rebuild->commit->commit_id, env('PROJECT_URL') . '/build/' . $rebuild->commit_id ); $github->notifyPendingBuild(); dispatch(new GetInstance($rebuild->id)); return redirect("/build/$rebuild->commit_id"); } }
michaelst/ci
app/Http/Controllers/DashboardController.php
PHP
mit
2,283
28.269231
95
0.5265
false
#pragma once /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief OpenGL。 */ /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../types/types.h" #pragma warning(pop) /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../actionbatching/actionbatching.h" #pragma warning(pop) /** include */ #include "./opengl_impl.h" #include "./opengl_impl_include.h" /** NBsys::NOpengl */ #if(BSYS_OPENGL_ENABLE) #pragma warning(push) #pragma warning(disable:4710) namespace NBsys{namespace NOpengl { /** バーテックスバッファ作成。 */ class Opengl_Impl_ActionBatching_Shader_Load : public NBsys::NActionBatching::ActionBatching_ActionItem_Base { private: /** opengl_impl */ Opengl_Impl& opengl_impl; /** shaderlayout */ sharedptr<Opengl_ShaderLayout> shaderlayout; /** asyncresult */ AsyncResult<bool> asyncresult; public: /** constructor */ Opengl_Impl_ActionBatching_Shader_Load(Opengl_Impl& a_opengl_impl,const sharedptr<Opengl_ShaderLayout>& a_shaderlayout,AsyncResult<bool>& a_asyncresult) : opengl_impl(a_opengl_impl), shaderlayout(a_shaderlayout), asyncresult(a_asyncresult) { } /** destructor */ virtual ~Opengl_Impl_ActionBatching_Shader_Load() { } private: /** copy constructor禁止。 */ Opengl_Impl_ActionBatching_Shader_Load(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete; /** コピー禁止。 */ void operator =(const Opengl_Impl_ActionBatching_Shader_Load& a_this) = delete; public: /** アクション開始。 */ virtual void Start() { } /** アクション中。 */ virtual s32 Do(f32& a_delta,bool a_endrequest) { if(a_endrequest == true){ //中断。 } if(this->shaderlayout->IsBusy() == true){ //継続。 a_delta -= 1.0f; return 0; } //Render_LoadShader this->opengl_impl.Render_LoadShader(this->shaderlayout); //asyncresult this->asyncresult.Set(true); //成功。 return 1; } }; }} #pragma warning(pop) #endif
bluebackblue/brownie
source/bsys/opengl/opengl_impl_actionbatching_shader_load.h
C
mit
2,340
16.096774
154
0.634581
false
<?php namespace Vich\UploaderBundle\Mapping; use Vich\UploaderBundle\Naming\NamerInterface; /** * PropertyMapping. * * @author Dustin Dobervich <ddobervich@gmail.com> */ class PropertyMapping { /** * @var \ReflectionProperty $property */ protected $property; /** * @var \ReflectionProperty $fileNameProperty */ protected $fileNameProperty; /** * @var NamerInterface $namer */ protected $namer; /** * @var array $mapping */ protected $mapping; /** * @var string $mappingName */ protected $mappingName; /** * Gets the reflection property that represents the * annotated property. * * @return \ReflectionProperty The property. */ public function getProperty() { return $this->property; } /** * Sets the reflection property that represents the annotated * property. * * @param \ReflectionProperty $property The reflection property. */ public function setProperty(\ReflectionProperty $property) { $this->property = $property; $this->property->setAccessible(true); } /** * Gets the reflection property that represents the property * which holds the file name for the mapping. * * @return \ReflectionProperty The reflection property. */ public function getFileNameProperty() { return $this->fileNameProperty; } /** * Sets the reflection property that represents the property * which holds the file name for the mapping. * * @param \ReflectionProperty $fileNameProperty The reflection property. */ public function setFileNameProperty(\ReflectionProperty $fileNameProperty) { $this->fileNameProperty = $fileNameProperty; $this->fileNameProperty->setAccessible(true); } /** * Gets the configured namer. * * @return null|NamerInterface The namer. */ public function getNamer() { return $this->namer; } /** * Sets the namer. * * @param \Vich\UploaderBundle\Naming\NamerInterface $namer The namer. */ public function setNamer(NamerInterface $namer) { $this->namer = $namer; } /** * Determines if the mapping has a custom namer configured. * * @return bool True if has namer, false otherwise. */ public function hasNamer() { return null !== $this->namer; } /** * Sets the configured configuration mapping. * * @param array $mapping The mapping; */ public function setMapping(array $mapping) { $this->mapping = $mapping; } /** * Gets the configured configuration mapping name. * * @return string The mapping name. */ public function getMappingName() { return $this->mappingName; } /** * Sets the configured configuration mapping name. * * @param $mappingName The mapping name. */ public function setMappingName($mappingName) { $this->mappingName = $mappingName; } /** * Gets the name of the annotated property. * * @return string The name. */ public function getPropertyName() { return $this->property->getName(); } /** * Gets the value of the annotated property. * * @param object $obj The object. * @return UploadedFile The file. */ public function getPropertyValue($obj) { return $this->property->getValue($obj); } /** * Gets the configured file name property name. * * @return string The name. */ public function getFileNamePropertyName() { return $this->fileNameProperty->getName(); } /** * Gets the configured upload directory. * * @return string The configured upload directory. */ public function getUploadDir() { return $this->mapping['upload_dir']; } /** * Determines if the file should be deleted upon removal of the * entity. * * @return bool True if delete on remove, false otherwise. */ public function getDeleteOnRemove() { return $this->mapping['delete_on_remove']; } /** * Determines if the uploadable field should be injected with a * Symfony\Component\HttpFoundation\File\File instance when * the object is loaded from the datastore. * * @return bool True if the field should be injected, false otherwise. */ public function getInjectOnLoad() { return $this->mapping['inject_on_load']; } }
marius1092/test
vendor/bundles/Vich/UploaderBundle/Mapping/PropertyMapping.php
PHP
mit
4,671
21.456731
78
0.600514
false
------------------------------------------------------------------- -- The Long night -- The night gives me black eyes, but I use it to find the light. -- In 2017 -- 公共状态 ------------------------------------------------------------------- L_StatePublic = {} setmetatable(L_StatePublic, {__index = _G}) local _this = L_StatePublic _this.stateNone = function (o , eNtity) local state = L_State.New(o , eNtity) function state:Enter() print("------进入None状态------") end function state:Execute(nTime) --do thing end function state:Exit() print("------退出None状态------") end return state end _this.stateLoad = function (o , eNtity) local state = L_State.New(o , eNtity) function state:Enter() print("------进入Load状态------") self.m_nTimer = 0 self.m_nTick = 0 end function state:Execute(nTime) --do thing if 0 == self.m_nTick then self.m_nTimer = self.m_nTimer + nTime print(self.m_nTimer) if self.m_nTimer > 3 then self.m_eNtity:ChangeToState(self.m_eNtity.stateNone) end end end function state:Exit() print("------退出Load状态------") end return state end _this.stateExit = function (o , eNtity) local state = L_State.New(o , eNtity) function state:Enter() print("------进入Exit状态------") self.m_nTimer = 0 self.m_nTick = 0 end function state:Execute(nTime) --do thing if 0 == self.m_nTick then self.m_nTimer = self.m_nTimer + nTime print(self.m_nTimer) if self.m_nTimer > 3 then self.m_eNtity:ChangeToState(self.m_eNtity.stateNone) end end end function state:Exit() print("------退出Exit状态------") end return state end
cheney247689848/Cloud-edge
Assets/Script_Lua/scene/L_StatePublic.lua
Lua
mit
2,033
19.810526
68
0.477491
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>18 --> 19</title> <link href="./../../assets/style.css" rel="stylesheet"> </head> <body> <h2>You have to be fast</h2> <a href="./ed6c3fe87a92e6b0939903db98d3209d32dcf2e96bee3586c1c6da3985c58ae4.html">Teleport</a> <hr> <a href="./../../about.md">About</a> (Spoilers! ) <script src="./../../assets/md5.js"></script> <script> window.currentLevel = 7; </script> <script src="./../../assets/script.js"></script> </body> </html>
simonmysun/praxis
TAIHAO2019/pub/SmallGame/AsFastAsYouCan2/287e3522261d64438d0e0f0d0ab25b1bbc0d4b902207719bf1a7761ee019b24a.html
HTML
mit
550
28
98
0.581818
false
personalprojects ================ A bunch of little things I made in my freetime ### PyPong A simple pong game made in Python and Pygame. **Changes Made**: Made the AI a bit (a lot) worse, you can actually win now. ### Maze Runner A maze app that uses Deep Field Search (DFS) to make a perfect maze and then uses the same algorithm in reverse to solve. Requires PyGame. **Usage**: Run it, enter your resolution, and let it run! Press "Escape" at anytime to quit. **Changes Made**: Exits more elegantly, colors are more visible. ### Find the Cow A joke of a game inspired by a conversation at dinner with friends. I challenged myself to keep it under 100 lines of code. Requires PyGame. **Usage**: Click to guess where the cow is. The volume of the "moo" indicates how far away the cow is. Once the cow is found, press spacebar to go to the next level. **ToDo**: Add a menu, although, I want to keep this under 100 lines of code. ### Binary Clock Something I thought I would finish, but never had the initative. It was supposed to be a simple 5 row binary clock. Maybe someday it will get a life.
tanishq-dubey/personalprojects
README.md
Markdown
mit
1,102
49.090909
165
0.733212
false
// Copyright (c) 2020 The Firo Core Developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef FIRO_ELYSIUM_SIGMAWALLETV0_H #define FIRO_ELYSIUM_SIGMAWALLETV0_H #include "sigmawallet.h" namespace elysium { class SigmaWalletV0 : public SigmaWallet { public: SigmaWalletV0(); protected: uint32_t BIP44ChangeIndex() const; SigmaPrivateKey GeneratePrivateKey(uint512 const &seed); class Database : public SigmaWallet::Database { public: Database(); public: bool WriteMint(SigmaMintId const &id, SigmaMint const &mint, CWalletDB *db = nullptr); bool ReadMint(SigmaMintId const &id, SigmaMint &mint, CWalletDB *db = nullptr) const; bool EraseMint(SigmaMintId const &id, CWalletDB *db = nullptr); bool HasMint(SigmaMintId const &id, CWalletDB *db = nullptr) const; bool WriteMintId(uint160 const &hash, SigmaMintId const &mintId, CWalletDB *db = nullptr); bool ReadMintId(uint160 const &hash, SigmaMintId &mintId, CWalletDB *db = nullptr) const; bool EraseMintId(uint160 const &hash, CWalletDB *db = nullptr); bool HasMintId(uint160 const &hash, CWalletDB *db = nullptr) const; bool WriteMintPool(std::vector<MintPoolEntry> const &mints, CWalletDB *db = nullptr); bool ReadMintPool(std::vector<MintPoolEntry> &mints, CWalletDB *db = nullptr); void ListMints(std::function<void(SigmaMintId&, SigmaMint&)> const&, CWalletDB *db = nullptr); }; public: using SigmaWallet::GeneratePrivateKey; }; } #endif // FIRO_ELYSIUM_SIGMAWALLETV0_H
zcoinofficial/zcoin
src/elysium/sigmawalletv0.h
C
mit
1,664
33.6875
102
0.711538
false
# Gears # *Documentation may be outdated or incomplete as some URLs may no longer exist.* *Warning! This codebase is deprecated and will no longer receive support; excluding critical issues.* A PHP class that loads template files, binds variables to a single file or globally without the need for custom placeholders/variables, allows for parent-child hierarchy and parses the template structure. Gear is a play on words for: Engine + Gears + Structure. * Loads any type of file into the system * Binds variables to a single file or to all files globally * Template files DO NOT need custom markup and placeholders for variables * Can access and use variables in a template just as you would a PHP file * Allows for parent-child hierarchy * Parse a parent template to parse all children, and their children, and so on * Can destroy template indexes on the fly * No eval() or security flaws * And much more... ## Introduction ## Most of the template systems today use a very robust setup where the template files contain no server-side code. Instead they use a system where they use custom variables and markup to get the job done. For example, in your template you may have a variable called {pageTitle} and in your code you assign that variable a value of "Welcome". This is all well and good, but to be able to parse this "system", it requires loads of regex and matching/replacing/looping which can be quite slow and cumbersome. It also requires you to learn a new markup language, specific for the system you are using. Why would you want to learn a new markup language and structure simply to do an if statement or go through a loop? In Gears, the goal is to remove all that custom code, separate your markup from your code, allow the use of standard PHP functions, loops, statements, etc within templates, and much more! ## Installation ## Install by manually downloading the library or defining a [Composer dependency](http://getcomposer.org/). ```javascript { "require": { "mjohnson/gears": "4.0.0" } } ``` Once available, instantiate the class and create template files. ```php // index.php $temp = new mjohnson\gears\Gears(dirname(__FILE__) . 'templates/'); $temp->setLayout('layouts/default'); // templates/layouts/default.tpl <!DOCTYPE html> <html> <head> <title><?php echo $pageTitle; ?></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <?php echo $this->getContent(); ?> </body> </html> ``` Within the code block above I am initiating the class by calling `new mjohnson\gears\Gears($path)` (where `$path` is the path to your templates directory) and storing it within a `$temp` variable. Next I am setting the layout I want to use; a layout is the outer HTML that will wrap the inner content pages. Within a layout you can use `getContent()` which will output the inner HTML wherever you please. ## Binding Variables ## It's now time to bind data to variables within your templates; to do this we use the `bind()` method. The bind method will take an array of key value pairs, or key value arguments. ```php $temp->bind(array( 'pageTitle' => 'Gears - Template Engine', 'description' => 'A PHP class that loads template files, binds variables, allows for parent-child hierarchy all the while rendering the template structure.' )); ``` The way binding variables works is extremely easy to understand. In the data being binded, the key is the name of the variable within the template, and the value is what the variable will be output. For instance the variable pageTitle (Gears - Template Engine) above will be assigned to the variable `$pageTitle` within the `layouts/default.tpl`. Variables are binded globally to all templates, includes and the layout. ## Displaying the Templates ## To render templates, use the `display()` method. The display method takes two arguments, the name of the template you want to display and the key to use for caching. ```php echo $temp->display('index'); ``` The second argument defines the name of the key to use for caching. Generally it will be the same name as the template name, but you do have the option to name it whatever you please. ```php echo $temp->display('index', 'index'); ``` It's also possible to display templates within folders by separating the path with a forward slash. ```php echo $temp->display('users/login'); ``` ## Opening a Template ## To render a template within another template you would use the `open()` method. The `open()` method takes 3 arguments: the path to the template (relative to the templates folder), an array of key value pairs to define as custom scoped variables and an array of cache settings. ```php echo $this->open('includes/footer', array('date' => date('Y')); ``` By default, includes are not cached but you can enable caching by passing true as the third argument or an array of settings. The viable settings are key and duration, where key is the name of the cached file (usually the path) and duration is the length of the cache. ```php echo $this->open('includes/footer', array('date' => date('Y')), true); // Custom settings echo $this->open('includes/footer', array('date' => date('Y')), array( 'key' => 'cacheKey', 'duration' => '+10 minutes' )); ``` ## Caching ## Gears comes packaged with a basic caching mechanism. By default caching is disabled, but to enable caching you can use `setCaching()`. This method will take the cache location as its 1st argument (best to place it in the same templates folder) and the expiration duration as the 2nd argument (default +1 day). ```php $temp->setCaching(dirname(__FILE__) . '/templates/cache/'); ``` You can customize the duration by using the strtotime() format. You can also pass null as the first argument and the system will place the cache files within your template path. ```php $temp->setCaching(null, '+15 minutes'); ``` To clear all cached files, you can use `flush()`. ```php $temp->flush(); ``` For a better example of how to output cached data, refer to the tests folder within the Gears package.
milesj/gears
docs/usage.md
Markdown
mit
6,088
44.432836
898
0.740802
false
/* * @Author: justinwebb * @Date: 2015-09-24 21:08:23 * @Last Modified by: justinwebb * @Last Modified time: 2015-09-24 22:19:45 */ (function (window) { 'use strict'; window.JWLB = window.JWLB || {}; window.JWLB.View = window.JWLB.View || {}; //-------------------------------------------------------------------- // Event handling //-------------------------------------------------------------------- var wallOnClick = function (event) { if (event.target.tagName.toLowerCase() === 'img') { var id = event.target.parentNode.dataset.id; var selectedPhoto = this.photos.filter(function (photo) { if (photo.id === id) { photo.portrait.id = id; return photo; } })[0]; this.sendEvent('gallery', selectedPhoto.portrait); } }; //-------------------------------------------------------------------- // View overrides //-------------------------------------------------------------------- var addUIListeners = function () { this.ui.wall.addEventListener('click', wallOnClick.bind(this)); }; var initUI = function () { var isUIValid = false; var comp = document.querySelector(this.selector); this.ui.wall = comp; if (this.ui.wall) { this.reset(); isUIValid = true; } return isUIValid; }; //-------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------- var Gallery = function (domId) { // Overriden View class methods this.initUI = initUI; this.addUIListeners = addUIListeners; this.name = 'Gallery'; // Instance properties this.photos = []; // Initialize View JWLB.View.call(this, domId); }; //-------------------------------------------------------------------- // Inheritance //-------------------------------------------------------------------- Gallery.prototype = Object.create(JWLB.View.prototype); Gallery.prototype.constructor = Gallery; //-------------------------------------------------------------------- // Instance methods //-------------------------------------------------------------------- Gallery.prototype.addThumb = function (data, id) { // Store image data for future reference var photo = { id: id, thumb: null, portrait: data.size[0] }; data.size.forEach(function (elem) { if (elem.label === 'Square') { photo.thumb = elem; } if (elem.height > photo.portrait.height) { photo.portrait = elem; } }); this.photos.push(photo); // Build thumbnail UI var node = document.createElement('div'); node.setAttribute('data-id', id); node.setAttribute('class', 'thumb'); var img = document.createElement('img'); img.setAttribute('src', photo.thumb.source); img.setAttribute('title', 'id: '+ id); node.appendChild(img); this.ui.wall.querySelector('article[name=foobar]').appendChild(node); }; Gallery.prototype.reset = function () { if (this.ui.wall.children.length > 0) { var article = this.ui.wall.children.item(0) article.parentElement.removeChild(article); } var article = document.createElement('article'); article.setAttribute('name', 'foobar'); this.ui.wall.appendChild(article); }; window.JWLB.View.Gallery = Gallery; })(window);
JustinWebb/lightbox-demo
app/js/helpers/view/gallery.js
JavaScript
mit
3,410
28.145299
73
0.48563
false
module InfinityTest module Core class Base # Specify the Ruby Version Manager to run cattr_accessor :strategy # ==== Options # * :rvm # * :rbenv # * :ruby_normal (Use when don't pass any rubies to run) # * :auto_discover(defaults) self.strategy = :auto_discover # Specify Ruby version(s) to test against # # ==== Examples # rubies = %w(ree jruby) # cattr_accessor :rubies self.rubies = [] # Options to include in the command. # cattr_accessor :specific_options self.specific_options = '' # Test Framework to use Rspec, Bacon, Test::Unit or AutoDiscover(defaults) # ==== Options # * :rspec # * :bacon # * :test_unit (Test unit here apply to this two libs: test/unit and minitest) # * :auto_discover(defaults) # # This will load a exactly a class constantize by name. # cattr_accessor :test_framework self.test_framework = :auto_discover # Framework to know the folders and files that need to monitoring by the observer. # # ==== Options # * :rails # * :rubygems # * :auto_discover(defaults) # # This will load a exactly a class constantize by name. # cattr_accessor :framework self.framework = :auto_discover # Framework to observer watch the dirs. # # ==== Options # * watchr # cattr_accessor :observer self.observer = :watchr # Ignore test files. # # ==== Examples # ignore_test_files = [ 'spec/generators/controller_generator_spec.rb' ] # cattr_accessor :ignore_test_files self.ignore_test_files = [] # Ignore test folders. # # ==== Examples # # Imagine that you don't want to run integration specs. # ignore_test_folders = [ 'spec/integration' ] # cattr_accessor :ignore_test_folders self.ignore_test_folders = [] # Verbose Mode. Print commands before executing them. # cattr_accessor :verbose self.verbose = true # Set the notification framework to use with Infinity Test. # # ==== Options # * :growl # * :lib_notify # * :auto_discover(defaults) # # This will load a exactly a class constantize by name. # cattr_writer :notifications self.notifications = :auto_discover # You can set directory to show images matched by the convention names. # => http://github.com/tomas-stefano/infinity_test/tree/master/images/ ) # # Infinity test will work on these names in the notification framework: # # * success (png, gif, jpeg) # * failure (png, gif, jpeg) # * pending (png, gif, jpeg) # cattr_accessor :mode # # => This will show images in the folder: # http://github.com/tomas-stefano/infinity_test/tree/master/images/simpson # self.mode = :simpson # Success Image to show after the tests run. # cattr_accessor :success_image # Pending Image to show after the tests run. # cattr_accessor :pending_image # Failure Image to show after the tests run. # cattr_accessor :failure_image # Use a specific gemset for each ruby. # OBS.: This only will work for RVM strategy. # cattr_accessor :gemset # InfinityTest try to use bundler if Gemfile is present. # Set to false if you don't want use bundler. # cattr_accessor :bundler self.bundler = true # Callbacks accessor to handle before or after all run and for each ruby! cattr_accessor :callbacks self.callbacks = [] # Run the observer to monitor files. # If set to false will just <b>Run tests and exit</b>. # Defaults to true: run tests and monitoring the files. # cattr_accessor :infinity_and_beyond self.infinity_and_beyond = true # The extension files that Infinity Test will search. # You can observe python, erlang, etc files. # cattr_accessor :extension self.extension = :rb # Setup Infinity Test passing the ruby versions and others setting. # <b>See the class accessors for more information.</b> # # ==== Examples # # InfinityTest::Base.setup do |config| # config.strategy = :rbenv # config.rubies = %w(ree jruby rbx 1.9.2) # end # def self.setup yield self end # Receives a object that quacks like InfinityTest::Options and do the merge with self(Base class). # def self.merge!(options) ConfigurationMerge.new(self, options).merge! end def self.start_continuous_test_server continuous_test_server.start end def self.continuous_test_server @continuous_test_server ||= ContinuousTestServer.new(self) end # Just a shortcut to bundler class accessor. # def self.using_bundler? bundler end # Just a shortcut to bundler class accessor. # def self.verbose? verbose end # Callback method to handle before all run and for each ruby too! # # ==== Examples # # before(:all) do # # ... # end # # before(:each_ruby) do |environment| # # ... # end # # before do # if you pass not then will use :all option # # ... # end # def self.before(scope, &block) # setting_callback(Callbacks::BeforeCallback, scope, &block) end # Callback method to handle after all run and for each ruby too! # # ==== Examples # # after(:all) do # # ... # end # # after(:each_ruby) do # # ... # end # # after do # if you pass not then will use :all option # # ... # end # def self.after(scope, &block) # setting_callback(Callbacks::AfterCallback, scope, &block) end # Clear the terminal (Useful in the before callback) # def self.clear_terminal system('clear') end ###### This methods will be removed in the Infinity Test v2.0.1 or 2.0.2 ###### # <b>DEPRECATED:</b> Please use <tt>.notification=</tt> instead. # def self.notifications(notification_name = nil, &block) if notification_name.blank? self.class_variable_get(:@@notifications) else message = <<-MESSAGE .notifications is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.notifications = :growl end MESSAGE ActiveSupport::Deprecation.warn(message) self.notifications = notification_name self.instance_eval(&block) if block_given? end end # <b>DEPRECATED:</b> Please use: # <tt>success_image=</tt> or # <tt>pending_image=</tt> or # <tt>failure_image=</tt> or # <tt>mode=</tt> instead. # def self.show_images(options) message = <<-MESSAGE .show_images is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.success_image = 'some_image.png' config.pending_image = 'some_image.png' config.failure_image = 'some_image.png' config.mode = 'infinity_test_dir_that_contain_images' end MESSAGE ActiveSupport::Deprecation.warn(message) self.success_image = options[:success_image] || options[:sucess_image] if options[:success_image].present? || options[:sucess_image].present? # for fail typo in earlier versions. self.pending_image = options[:pending_image] if options[:pending_image].present? self.failure_image = options[:failure_image] if options[:failure_image].present? self.mode = options[:mode] if options[:mode].present? end # <b>DEPRECATED:</b> Please use: # .rubies = or # .specific_options = or # .test_framework = or # .framework = or # .verbose = or # .gemset = instead # def self.use(options) message = <<-MESSAGE .use is DEPRECATED. Use this instead: InfinityTest.setup do |config| config.rubies = %w(2.0 jruby) config.specific_options = '-J' config.test_framework = :rspec config.framework = :padrino config.verbose = true config.gemset = :some_gemset end MESSAGE ActiveSupport::Deprecation.warn(message) self.rubies = options[:rubies] if options[:rubies].present? self.specific_options = options[:specific_options] if options[:specific_options].present? self.test_framework = options[:test_framework] if options[:test_framework].present? self.framework = options[:app_framework] if options[:app_framework].present? self.verbose = options[:verbose] unless options[:verbose].nil? self.gemset = options[:gemset] if options[:gemset].present? end # <b>DEPRECATED:</b> Please use .clear_terminal instead. # def self.clear(option) message = '.clear(:terminal) is DEPRECATED. Please use .clear_terminal instead.' ActiveSupport::Deprecation.warn(message) clear_terminal end def self.heuristics(&block) # There is a spec pending. end def self.replace_patterns(&block) # There is a spec pending. end private # def self.setting_callback(callback_class, scope, &block) # callback_instance = callback_class.new(scope, &block) # self.callbacks.push(callback_instance) # callback_instance # end end end end
tomas-stefano/infinity_test
lib/infinity_test/core/base.rb
Ruby
mit
10,064
29.044776
186
0.575219
false
<?php session_start(); require_once('../php/conexion.php'); $conect = connect::conn(); $user = $_SESSION['usuario']; if($_SERVER['REQUEST_METHOD'] == 'POST'){ $sql = "insert into cotidiano (dir_origen,dir_destino,semana,hora,usuario,estado) values (?,?,?,?,?,?);"; $favo = sqlsrv_query($conect,$sql,array($_POST['Dir_o'],$_POST['Dir_d'],$_POST['semana'],$_POST['reloj'],$user['usuario'],1)); if($favo){ echo 'Inserccion correcta'; } else{ if( ($errors = sqlsrv_errors() ) != null) { foreach( $errors as $error ) { echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />"; echo "code: ".$error[ 'code']."<br />"; echo "message: ".$error[ 'message']."<br />"; } } } }else{ print "aqui la estabas cagando"; } ?>
smukideejeah/GaysonTaxi
cpanel/nuevoCotidiano.php
PHP
mit
822
33.25
130
0.513382
false
holiwish ========
aldarondo/holiwish
README.md
Markdown
mit
18
8
8
0.444444
false
python -m unittest
nrdhm/max_dump
test.sh
Shell
mit
20
19
19
0.75
false
using System; using NetOffice; using NetOffice.Attributes; namespace NetOffice.MSProjectApi.Enums { /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> ///<remarks> MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff863548(v=office.14).aspx </remarks> [SupportByVersion("MSProject", 11,12,14)] [EntityType(EntityType.IsEnum)] public enum PjMonthLabel { /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>57</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mm = 57, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>86</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mm_yy = 86, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>85</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mm_yyy = 85, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>11</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_m = 11, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>10</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmm = 10, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>8</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmm_yyy = 8, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>9</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmmm = 9, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>7</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonth_mmmm_yyyy = 7, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>59</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromEnd_mm = 59, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>58</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromEnd_Mmm = 58, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>45</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromEnd_Month_mm = 45, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>61</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromStart_mm = 61, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>60</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromStart_Mmm = 60, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>44</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelMonthFromStart_Month_mm = 44, /// <summary> /// SupportByVersion MSProject 11, 12, 14 /// </summary> /// <remarks>35</remarks> [SupportByVersion("MSProject", 11,12,14)] pjMonthLabelNoDateFormat = 35 } }
NetOfficeFw/NetOffice
Source/MSProject/Enums/PjMonthLabel.cs
C#
mit
3,276
26.521008
132
0.634698
false
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CircleAreaAndCircumference")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CircleAreaAndCircumference")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("24a850d9-a2e2-4979-a7f8-47602b439978")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
frostblooded/TelerikHomework
C# Part 1/ConsoleInputOutput/CircleAreaAndCircumference/Properties/AssemblyInfo.cs
C#
mit
1,428
38.583333
84
0.750175
false
//#define USE_TOUCH_SCRIPT using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; /* * ドラッグ操作でのカメラの移動コントロールクラス * マウス&タッチ対応 */ namespace GarageKit { [RequireComponent(typeof(Camera))] public class FlyThroughCamera : MonoBehaviour { public static bool winTouch = false; public static bool updateEnable = true; // フライスルーのコントロールタイプ public enum FLYTHROUGH_CONTROLL_TYPE { DRAG = 0, DRAG_HOLD } public FLYTHROUGH_CONTROLL_TYPE controllType; // 移動軸の方向 public enum FLYTHROUGH_MOVE_TYPE { XZ = 0, XY } public FLYTHROUGH_MOVE_TYPE moveType; public Collider groundCollider; public Collider limitAreaCollider; public bool useLimitArea = false; public float moveBias = 1.0f; public float moveSmoothTime = 0.1f; public bool dragInvertX = false; public bool dragInvertY = false; public float rotateBias = 1.0f; public float rotateSmoothTime = 0.1f; public bool rotateInvert = false; public OrbitCamera combinationOrbitCamera; private GameObject flyThroughRoot; public GameObject FlyThroughRoot { get{ return flyThroughRoot; } } private GameObject shiftTransformRoot; public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } } private bool inputLock; public bool IsInputLock { get{ return inputLock; } } private object lockObject; private Vector3 defaultPos; private Quaternion defaultRot; private bool isFirstTouch; private Vector3 oldScrTouchPos; private Vector3 dragDelta; private Vector3 velocitySmoothPos; private Vector3 dampDragDelta = Vector3.zero; private Vector3 pushMoveDelta = Vector3.zero; private float velocitySmoothRot; private float dampRotateDelta = 0.0f; private float pushRotateDelta = 0.0f; public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } } public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } } void Awake() { } void Start() { // 設定ファイルより入力タイプを取得 if(!ApplicationSetting.Instance.GetBool("UseMouse")) winTouch = true; inputLock = false; // 地面上視点位置に回転ルートを設定する Ray ray = new Ray(this.transform.position, this.transform.forward); RaycastHit hitInfo; if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity)) { flyThroughRoot = new GameObject(this.gameObject.name + " FlyThrough Root"); flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false); flyThroughRoot.transform.position = hitInfo.point; flyThroughRoot.transform.rotation = Quaternion.identity; shiftTransformRoot = new GameObject(this.gameObject.name + " ShiftTransform Root"); shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true); shiftTransformRoot.transform.localPosition = Vector3.zero; shiftTransformRoot.transform.localRotation = Quaternion.identity; this.gameObject.transform.SetParent(shiftTransformRoot.transform, true); } else { Debug.LogWarning("FlyThroughCamera :: not set the ground collider !!"); return; } // 初期値を保存 defaultPos = flyThroughRoot.transform.position; defaultRot = flyThroughRoot.transform.rotation; ResetInput(); } void Update() { if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0) GetInput(); else ResetInput(); UpdateFlyThrough(); UpdateOrbitCombination(); } private void ResetInput() { isFirstTouch = true; oldScrTouchPos = Vector3.zero; dragDelta = Vector3.zero; } private void GetInput() { // for Touch if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer) { if(Input.touchCount == 1) { // ドラッグ量を計算 Vector3 currentScrTouchPos = Input.GetTouch(0).position; if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } #if UNITY_STANDALONE_WIN else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch) { #if !USE_TOUCH_SCRIPT if(Input.touchCount == 1) { // ドラッグ量を計算 Vector3 currentScrTouchPos = Input.touches[0].position; #else if(TouchScript.TouchManager.Instance.PressedPointersCount == 1) { // ドラッグ量を計算 Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position; #endif if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } #endif // for Mouse else { if(Input.GetMouseButton(0)) { // ドラッグ量を計算 Vector3 currentScrTouchPos = Input.mousePosition; if(isFirstTouch) { oldScrTouchPos = currentScrTouchPos; isFirstTouch = false; return; } dragDelta = currentScrTouchPos - oldScrTouchPos; if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG) oldScrTouchPos = currentScrTouchPos; } else ResetInput(); } } /// <summary> /// Input更新のLock /// </summary> public void LockInput(object sender) { if(!inputLock) { lockObject = sender; inputLock = true; } } /// <summary> /// Input更新のUnLock /// </summary> public void UnlockInput(object sender) { if(inputLock && lockObject == sender) inputLock = false; } /// <summary> /// フライスルーを更新 /// </summary> private void UpdateFlyThrough() { if(!FlyThroughCamera.updateEnable || flyThroughRoot == null) return; // 位置 float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f); float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f); if(moveType == FLYTHROUGH_MOVE_TYPE.XZ) dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime); else if(moveType == FLYTHROUGH_MOVE_TYPE.XY) dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime); flyThroughRoot.transform.Translate(dampDragDelta, Space.Self); pushMoveDelta = Vector3.zero; if(useLimitArea) { // 移動範囲限界を設定 if(limitAreaCollider != null) { Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position; Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position; if(moveType == FLYTHROUGH_MOVE_TYPE.XZ) { float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x); float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z); flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ); } else if(moveType == FLYTHROUGH_MOVE_TYPE.XY) { float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x); float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y); flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z); } } } // 方向 dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime); if(moveType == FLYTHROUGH_MOVE_TYPE.XZ) flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self); else if(moveType == FLYTHROUGH_MOVE_TYPE.XY) flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self); pushRotateDelta = 0.0f; } private void UpdateOrbitCombination() { // 連携機能 if(combinationOrbitCamera != null && combinationOrbitCamera.OrbitRoot != null) { Vector3 lookPoint = combinationOrbitCamera.OrbitRoot.transform.position; Transform orbitParent = combinationOrbitCamera.OrbitRoot.transform.parent; combinationOrbitCamera.OrbitRoot.transform.parent = null; flyThroughRoot.transform.LookAt(lookPoint, Vector3.up); flyThroughRoot.transform.rotation = Quaternion.Euler( 0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f); combinationOrbitCamera.OrbitRoot.transform.parent = orbitParent; } } /// <summary> /// 目標位置にカメラを移動させる /// </summary> public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f) { dampDragDelta = Vector3.zero; flyThroughRoot.transform.DOMove(targetPosition, time) .SetEase(Ease.OutCubic) .Play(); } /// <summary> /// 指定値でカメラを移動させる /// </summary> public void TranslateToFlyThrough(Vector3 move) { dampDragDelta = Vector3.zero; flyThroughRoot.transform.Translate(move, Space.Self); } /// <summary> /// 目標方向にカメラを回転させる /// </summary> public void RotateToFlyThrough(float targetAngle, float time = 1.0f) { dampRotateDelta = 0.0f; Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles; targetEulerAngles.y = targetAngle; flyThroughRoot.transform.DORotate(targetEulerAngles, time) .SetEase(Ease.OutCubic) .Play(); } /// <summary> /// 外部トリガーで移動させる /// </summary> public void PushMove(Vector3 move) { pushMoveDelta = move; } /// <summary> /// 外部トリガーでカメラ方向を回転させる /// </summary> public void PushRotate(float rotate) { pushRotateDelta = rotate; } /// <summary> /// フライスルーを初期化 /// </summary> public void ResetFlyThrough() { ResetInput(); MoveToFlyThrough(defaultPos); RotateToFlyThrough(defaultRot.eulerAngles.y); } } }
sharkattack51/GarageKit_for_Unity
UnityProject/Assets/__ProjectName__/Scripts/Utils/CameraContorol/FlyThroughCamera.cs
C#
mit
13,347
33.687332
165
0.551791
false
"use strict"; const readdir = require("../../"); const dir = require("../utils/dir"); const { expect } = require("chai"); const through2 = require("through2"); const fs = require("fs"); let nodeVersion = parseFloat(process.version.substr(1)); describe("Stream API", () => { it("should be able to pipe to other streams as a Buffer", done => { let allData = []; readdir.stream("test/dir") .pipe(through2((data, enc, next) => { try { // By default, the data is streamed as a Buffer expect(data).to.be.an.instanceOf(Buffer); // Buffer.toString() returns the file name allData.push(data.toString()); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir") .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // In "object mode", the data is a string expect(data).to.be.a("string"); allData.push(data); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", err => { done(err); }); }); it('should be able to pipe fs.Stats to other streams in "object mode"', done => { let allData = []; readdir.stream("test/dir", { stats: true }) .pipe(through2({ objectMode: true }, (data, enc, next) => { try { // The data is an fs.Stats object expect(data).to.be.an("object"); expect(data).to.be.an.instanceOf(fs.Stats); allData.push(data.path); next(null, data); } catch (e) { next(e); } })) .on("finish", () => { try { expect(allData).to.have.same.members(dir.shallow.data); done(); } catch (e) { done(e); } }) .on("error", done); }); it("should be able to pause & resume the stream", done => { let allData = []; let stream = readdir.stream("test/dir") .on("data", data => { allData.push(data); // The stream should not be paused expect(stream.isPaused()).to.equal(false); if (allData.length === 3) { // Pause for one second stream.pause(); setTimeout(() => { try { // The stream should still be paused expect(stream.isPaused()).to.equal(true); // The array should still only contain 3 items expect(allData).to.have.lengthOf(3); // Read the rest of the stream stream.resume(); } catch (e) { done(e); } }, 1000); } }) .on("end", () => { expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to use "readable" and "read"', done => { let allData = []; let nullCount = 0; let stream = readdir.stream("test/dir") .on("readable", () => { // Manually read the next chunk of data let data = stream.read(); while (true) { // eslint-disable-line if (data === null) { // The stream is done nullCount++; break; } else { // The data should be a string (the file name) expect(data).to.be.a("string").with.length.of.at.least(1); allData.push(data); data = stream.read(); } } }) .on("end", () => { if (nodeVersion >= 12) { // In Node >= 12, the "readable" event fires twice, // and stream.read() returns null twice expect(nullCount).to.equal(2); } else if (nodeVersion >= 10) { // In Node >= 10, the "readable" event only fires once, // and stream.read() only returns null once expect(nullCount).to.equal(1); } else { // In Node < 10, the "readable" event fires 13 times (once per file), // and stream.read() returns null each time expect(nullCount).to.equal(13); } expect(allData).to.have.same.members(dir.shallow.data); done(); }) .on("error", done); }); it('should be able to subscribe to custom events instead of "data"', done => { let allFiles = []; let allSubdirs = []; let stream = readdir.stream("test/dir"); // Calling "resume" is required, since we're not handling the "data" event stream.resume(); stream .on("file", filename => { expect(filename).to.be.a("string").with.length.of.at.least(1); allFiles.push(filename); }) .on("directory", subdir => { expect(subdir).to.be.a("string").with.length.of.at.least(1); allSubdirs.push(subdir); }) .on("end", () => { expect(allFiles).to.have.same.members(dir.shallow.files); expect(allSubdirs).to.have.same.members(dir.shallow.dirs); done(); }) .on("error", done); }); it('should handle errors that occur in the "data" event listener', done => { testErrorHandling("data", dir.shallow.data, 7, done); }); it('should handle errors that occur in the "file" event listener', done => { testErrorHandling("file", dir.shallow.files, 3, done); }); it('should handle errors that occur in the "directory" event listener', done => { testErrorHandling("directory", dir.shallow.dirs, 2, done); }); it('should handle errors that occur in the "symlink" event listener', done => { testErrorHandling("symlink", dir.shallow.symlinks, 5, done); }); function testErrorHandling (eventName, expected, expectedErrors, done) { let errors = [], data = []; let stream = readdir.stream("test/dir"); // Capture all errors stream.on("error", error => { errors.push(error); }); stream.on(eventName, path => { data.push(path); if (path.indexOf(".txt") >= 0 || path.indexOf("dir-") >= 0) { throw new Error("Epic Fail!!!"); } else { return true; } }); stream.on("end", () => { try { // Make sure the correct number of errors were thrown expect(errors).to.have.lengthOf(expectedErrors); for (let error of errors) { expect(error.message).to.equal("Epic Fail!!!"); } // All of the events should have still been emitted, despite the errors expect(data).to.have.same.members(expected); done(); } catch (e) { done(e); } }); stream.resume(); } });
BigstickCarpet/readdir-enhanced
test/specs/stream.spec.js
JavaScript
mit
7,232
25.884758
83
0.508158
false
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Font; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class PreferredSubfamily extends AbstractTag { protected $Id = 17; protected $Name = 'PreferredSubfamily'; protected $FullName = 'Font::Name'; protected $GroupName = 'Font'; protected $g0 = 'Font'; protected $g1 = 'Font'; protected $g2 = 'Document'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Preferred Subfamily'; }
romainneutron/PHPExiftool
lib/PHPExiftool/Driver/Tag/Font/PreferredSubfamily.php
PHP
mit
792
17.857143
74
0.680556
false
<!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 (10.0.2) on Fri Sep 21 22:00:31 PDT 2018 --> <title>U-Index</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="date" content="2018-09-21"> <link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style"> <link rel="stylesheet" type="text/css" href="../jquery/jquery-ui.css" title="Style"> <script type="text/javascript" src="../script.js"></script> <script type="text/javascript" src="../jquery/jszip/dist/jszip.min.js"></script> <script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils.min.js"></script> <!--[if IE]> <script type="text/javascript" src="../jquery/jszip-utils/dist/jszip-utils-ie.min.js"></script> <![endif]--> <script type="text/javascript" src="../jquery/jquery-1.10.2.js"></script> <script type="text/javascript" src="../jquery/jquery-ui.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="U-Index"; } } catch(err) { } //--> var pathtoroot = "../";loadScripts(document, 'script');</script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="fixedNav"> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../main/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../main/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-1.html">Prev Letter</a></li> <li>Next Letter</li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li> <li><a href="index-2.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <ul class="navListSearch"> <li><label for="search">SEARCH:</label> <input type="text" id="search" value="search" disabled="disabled"> <input type="reset" id="reset" value="reset" disabled="disabled"> </li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> </div> <div class="navPadding">&nbsp;</div> <script type="text/javascript"><!-- $('.navPadding').css('padding-top', $('.fixedNav').css("height")); //--> </script> <div class="contentContainer"><a href="index-1.html">M</a>&nbsp;<a href="index-2.html">U</a>&nbsp;<a name="I:U"> <!-- --> </a> <h2 class="title">U</h2> <dl> <dt><a href="../main/UsingTheGridLayout.html" title="class in main"><span class="typeNameLink">UsingTheGridLayout</span></a> - Class in <a href="../main/package-summary.html">main</a></dt> <dd>&nbsp;</dd> <dt><span class="memberNameLink"><a href="../main/UsingTheGridLayout.html#UsingTheGridLayout--">UsingTheGridLayout()</a></span> - Constructor for class main.<a href="../main/UsingTheGridLayout.html" title="class in main">UsingTheGridLayout</a></dt> <dd>&nbsp;</dd> </dl> <a href="index-1.html">M</a>&nbsp;<a href="index-2.html">U</a>&nbsp;</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../main/package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li><a href="../main/package-tree.html">Tree</a></li> <li><a href="../deprecated-list.html">Deprecated</a></li> <li class="navBarCell1Rev">Index</li> <li><a href="../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="index-1.html">Prev Letter</a></li> <li>Next Letter</li> </ul> <ul class="navList"> <li><a href="../index.html?index-files/index-2.html" target="_top">Frames</a></li> <li><a href="index-2.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
tliang1/Java-Practice
Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-12/Chapter12P03/doc/index-files/index-2.html
HTML
mit
5,390
33.33121
248
0.637477
false
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.synapse.v2019_06_01_preview; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonCreator; import com.microsoft.rest.ExpandableStringEnum; /** * Defines values for IntegrationRuntimeState. */ public final class IntegrationRuntimeState extends ExpandableStringEnum<IntegrationRuntimeState> { /** Static value Initial for IntegrationRuntimeState. */ public static final IntegrationRuntimeState INITIAL = fromString("Initial"); /** Static value Stopped for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPED = fromString("Stopped"); /** Static value Started for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTED = fromString("Started"); /** Static value Starting for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STARTING = fromString("Starting"); /** Static value Stopping for IntegrationRuntimeState. */ public static final IntegrationRuntimeState STOPPING = fromString("Stopping"); /** Static value NeedRegistration for IntegrationRuntimeState. */ public static final IntegrationRuntimeState NEED_REGISTRATION = fromString("NeedRegistration"); /** Static value Online for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ONLINE = fromString("Online"); /** Static value Limited for IntegrationRuntimeState. */ public static final IntegrationRuntimeState LIMITED = fromString("Limited"); /** Static value Offline for IntegrationRuntimeState. */ public static final IntegrationRuntimeState OFFLINE = fromString("Offline"); /** Static value AccessDenied for IntegrationRuntimeState. */ public static final IntegrationRuntimeState ACCESS_DENIED = fromString("AccessDenied"); /** * Creates or finds a IntegrationRuntimeState from its string representation. * @param name a name to look for * @return the corresponding IntegrationRuntimeState */ @JsonCreator public static IntegrationRuntimeState fromString(String name) { return fromString(name, IntegrationRuntimeState.class); } /** * @return known IntegrationRuntimeState values */ public static Collection<IntegrationRuntimeState> values() { return values(IntegrationRuntimeState.class); } }
selvasingh/azure-sdk-for-java
sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/IntegrationRuntimeState.java
Java
mit
2,607
39.107692
99
0.755274
false
// Copyright 2015 Peter Beverloo. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. // Base class for a module. Stores the environment and handles magic such as route annotations. export class Module { constructor(env) { this.env_ = env; let decoratedRoutes = Object.getPrototypeOf(this).decoratedRoutes_; if (!decoratedRoutes) return; decoratedRoutes.forEach(route => { env.dispatcher.addRoute(route.method, route.route_path, ::this[route.handler]); }); } }; // Annotation that can be used on modules to indicate that the annotated method is the request // handler for a |method| (GET, POST) request for |route_path|. export function route(method, route_path) { return (target, handler) => { if (!target.hasOwnProperty('decoratedRoutes_')) target.decoratedRoutes_ = []; target.decoratedRoutes_.push({ method, route_path, handler }); }; }
beverloo/node-home-server
src/module.js
JavaScript
mit
981
32.827586
95
0.701325
false
<?php /* * This file is part of PHP CS Fixer. * * (c) Fabien Potencier <fabien@symfony.com> * Dariusz Rumiński <dariusz.ruminski@gmail.com> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace PhpCsFixer\Fixer\PhpUnit; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\Tokenizer\Tokens; /** * @author Roland Franssen <franssen.roland@gmail.com> */ final class PhpUnitFqcnAnnotationFixer extends AbstractFixer { /** * {@inheritdoc} */ public function getDefinition() { return new FixerDefinition( 'PHPUnit annotations should be a FQCNs including a root namespace.', array(new CodeSample( '<?php final class MyTest extends \PHPUnit_Framework_TestCase { /** * @expectedException InvalidArgumentException * @covers Project\NameSpace\Something * @coversDefaultClass Project\Default * @uses Project\Test\Util */ public function testSomeTest() { } } ' )) ); } /** * {@inheritdoc} */ public function getPriority() { // should be run before NoUnusedImportsFixer return -9; } /** * {@inheritdoc} */ public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_DOC_COMMENT); } /** * {@inheritdoc} */ protected function applyFix(\SplFileInfo $file, Tokens $tokens) { foreach ($tokens as $token) { if ($token->isGivenKind(T_DOC_COMMENT)) { $token->setContent(preg_replace( '~^(\s*\*\s*@(?:expectedException|covers|coversDefaultClass|uses)\h+)(\w.*)$~m', '$1\\\\$2', $token->getContent() )); } } } }
cedricleblond35/capvisu-site_supervision
vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php
PHP
mit
1,919
22.390244
112
0.599583
false
--- layout: post title: "从头学算法(二、搞算法你必须知道的OJ)" date: 2016-12-20 11:36:52 categories: 数据结构及算法 tags: OJ algorithms mathjax: true --- 在没接触算法之前,我从没听说过OJ这个缩写,没关系,现在开始认识还来得及。等你真正开始研究算法,你才发现你又进入了一个新的世界。 这个世界,你不关注它的时候,它好像并不存在,而一旦你关注它了,每一个花草都让你叹为观止。 来看看百度百科是怎么说的吧: OJ是Online Judge系统的简称,用来在线检测程序源代码的正确性。著名的OJ有TYVJ、RQNOJ、URAL等。国内著名的题库有北京大学题库、浙江大学题库、电子科技大学题库、杭州电子科技大学等。国外的题库包括乌拉尔大学、瓦拉杜利德大学题库等。 而作为程序员,你必须知道Leetcode这个OJ,相比起国内各大著名高校的OJ,为什么我更推荐程序员们选择LeetCode OJ呢?原因有两点: 第一,大学OJ上的题目一般都是为ACM选手做准备的,难度大,属于竞技范畴;LeetCode的题相对简单,更为实用,更适合以后从事开发等岗位的程序员们。 第二,LeetCode非常流行,用户的量级几乎要比其他OJ高出将近三到五个级别。大量的活跃用户,将会为我们提供数不清的经验交流和可供参考的GitHub源代码。 刷LeetCode不是为了学会某些牛逼的算法,也不是为了突破某道难题而可能获得的智趣上的快感。学习和练习正确的思考方法,锻炼考虑各种条件的能力,在代码实现前就已经尽可能避免大多数常见错误带来的bug,养成简洁代码的审美习惯。 通过OJ刷题,配合算法的相关书籍进行理解,对算法的学习是很有帮助的,作为一个程序员,不刷几道LeetCode,真的说不过去。 最后LeetCode网址:https://leetcode.com/ 接下来注册开始搞吧! ![image_1bf90k08d19p01391i8pfvkqhbm.png-65.6kB][1] ![image_1bf90orko1ccn1opj29j93cc7f13.png-91.4kB][2] LeetCode刷过一阵子之后,发现很多都是收费的,这就很不友好了。本着方便大家的原则,向大家推荐lintcode,题目相对也很全,支持中、英双语,最重要是免费。 [1]: http://static.zybuluo.com/coldxiangyu/j2xlu88omsuprk7c7qinubug/image_1bf90k08d19p01391i8pfvkqhbm.png [2]: http://static.zybuluo.com/coldxiangyu/fztippzc74u7j9ww7av2vvn3/image_1bf90orko1ccn1opj29j93cc7f13.png
coldxiangyu/coldxiangyu.github.io
_posts/2016-12-20-从头学算法(二、搞算法你必须知道的OJ).md
Markdown
mit
2,556
32.157895
129
0.842857
false
package com.timotheteus.raincontrol.handlers; import com.timotheteus.raincontrol.tileentities.IGUITile; import com.timotheteus.raincontrol.tileentities.TileEntityInventoryBase; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraftforge.fml.common.network.IGuiHandler; import net.minecraftforge.fml.network.FMLPlayMessages; import net.minecraftforge.fml.network.NetworkHooks; import javax.annotation.Nullable; public class GuiHandler implements IGuiHandler { public static GuiScreen openGui(FMLPlayMessages.OpenContainer openContainer) { BlockPos pos = openContainer.getAdditionalData().readBlockPos(); // new GUIChest(type, (IInventory) Minecraft.getInstance().player.inventory, (IInventory) Minecraft.getInstance().world.getTileEntity(pos)); TileEntityInventoryBase te = (TileEntityInventoryBase) Minecraft.getInstance().world.getTileEntity(pos); if (te != null) { return te.createGui(Minecraft.getInstance().player); } return null; } //TODO can remove these, I think @Nullable @Override public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createContainer(player); } return null; } @Nullable @Override public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { BlockPos pos = new BlockPos(x, y, z); TileEntity te = world.getTileEntity(pos); if (te instanceof IGUITile) { return ((IGUITile) te).createGui(player); } return null; } }
kristofersokk/RainControl
src/main/java/com/timotheteus/raincontrol/handlers/GuiHandler.java
Java
mit
2,028
36.555556
147
0.718935
false
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2015, British Columbia Institute of Technology * * 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 CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 1.0.0 * @filesource */ /* *--------------------------------------------------------------- * APPLICATION ENVIRONMENT *--------------------------------------------------------------- * * You can load different configurations depending on your * current environment. Setting the environment also influences * things like logging and error reporting. * * This can be set to anything, but default usage is: * * development * testing * production * * NOTE: If you change these, also change the error_reporting() code below */ define('ENVIRONMENT', isset($_SERVER['CI_ENV']) ? $_SERVER['CI_ENV'] : 'development'); /* *--------------------------------------------------------------- * ERROR REPORTING *--------------------------------------------------------------- * * Different environments will require different levels of error reporting. * By default development will show errors but testing and live will hide them. */ switch (ENVIRONMENT) { case 'development': error_reporting(-1); ini_set('display_errors', 1); break; case 'testing': case 'production': ini_set('display_errors', 0); if (version_compare(PHP_VERSION, '5.3', '>=')) { error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT & ~E_USER_NOTICE & ~E_USER_DEPRECATED); } else { error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_USER_NOTICE); } break; default: header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'The application environment is not set correctly.'; exit(1); // EXIT_ERROR } /* *--------------------------------------------------------------- * SYSTEM FOLDER NAME *--------------------------------------------------------------- * * This variable must contain the name of your "system" folder. * Include the path if the folder is not in the same directory * as this file. */ $system_path = 'system'; /* *--------------------------------------------------------------- * APPLICATION FOLDER NAME *--------------------------------------------------------------- * * If you want this front controller to use a different "application" * folder than the default one you can set its name here. The folder * can also be renamed or relocated anywhere on your server. If * you do, use a full server path. For more info please see the user guide: * http://codeigniter.com/user_guide/general/managing_apps.html * * NO TRAILING SLASH! */ $application_folder = 'application'; /* *--------------------------------------------------------------- * VIEW FOLDER NAME *--------------------------------------------------------------- * * If you want to move the view folder out of the application * folder set the path to the folder here. The folder can be renamed * and relocated anywhere on your server. If blank, it will default * to the standard location inside your application folder. If you * do move this, use the full server path to this folder. * * NO TRAILING SLASH! */ $view_folder = ''; $templates = $view_folder . '/templates/'; /* * -------------------------------------------------------------------- * DEFAULT CONTROLLER * -------------------------------------------------------------------- * * Normally you will set your default controller in the routes.php file. * You can, however, force a custom routing by hard-coding a * specific controller class/function here. For most applications, you * WILL NOT set your routing here, but it's an option for those * special instances where you might want to override the standard * routing in a specific front controller that shares a common CI installation. * * IMPORTANT: If you set the routing here, NO OTHER controller will be * callable. In essence, this preference limits your application to ONE * specific controller. Leave the function name blank if you need * to call functions dynamically via the URI. * * Un-comment the $routing array below to use this feature */ // The directory name, relative to the "controllers" folder. Leave blank // if your controller is not in a sub-folder within the "controllers" folder // $routing['directory'] = ''; // The controller class file name. Example: mycontroller // $routing['controller'] = ''; // The controller function you wish to be called. // $routing['function'] = ''; /* * ------------------------------------------------------------------- * CUSTOM CONFIG VALUES * ------------------------------------------------------------------- * * The $assign_to_config array below will be passed dynamically to the * config class when initialized. This allows you to set custom config * items or override any default config values found in the config.php file. * This can be handy as it permits you to share one application between * multiple front controller files, with each file containing different * config values. * * Un-comment the $assign_to_config array below to use this feature */ // $assign_to_config['name_of_config_item'] = 'value of config item'; // -------------------------------------------------------------------- // END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE // -------------------------------------------------------------------- /* * --------------------------------------------------------------- * Resolve the system path for increased reliability * --------------------------------------------------------------- */ // Set the current directory correctly for CLI requests if (defined('STDIN')) { chdir(dirname(__FILE__)); } if (($_temp = realpath($system_path)) !== FALSE) { $system_path = $_temp . '/'; } else { // Ensure there's a trailing slash $system_path = rtrim($system_path, '/') . '/'; } // Is the system path correct? if (!is_dir($system_path)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your system folder path does not appear to be set correctly. Please open the following file and correct this: ' . pathinfo(__FILE__, PATHINFO_BASENAME); exit(3); // EXIT_CONFIG } /* * ------------------------------------------------------------------- * Now that we know the path, set the main path constants * ------------------------------------------------------------------- */ // The name of THIS file define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); // Path to the system folder define('BASEPATH', str_replace('\\', '/', $system_path)); // Path to the front controller (this file) define('FCPATH', dirname(__FILE__) . '/'); // Name of the "system folder" define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/')); // The path to the "application" folder if (is_dir($application_folder)) { if (($_temp = realpath($application_folder)) !== FALSE) { $application_folder = $_temp; } define('APPPATH', $application_folder . DIRECTORY_SEPARATOR); } else { if (!is_dir(BASEPATH . $application_folder . DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your application folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF; exit(3); // EXIT_CONFIG } define('APPPATH', BASEPATH . $application_folder . DIRECTORY_SEPARATOR); } // The path to the "views" folder if (!is_dir($view_folder)) { if (!empty($view_folder) && is_dir(APPPATH . $view_folder . DIRECTORY_SEPARATOR)) { $view_folder = APPPATH . $view_folder; } elseif (!is_dir(APPPATH . 'views' . DIRECTORY_SEPARATOR)) { header('HTTP/1.1 503 Service Unavailable.', TRUE, 503); echo 'Your view folder path does not appear to be set correctly. Please open the following file and correct this: ' . SELF; exit(3); // EXIT_CONFIG } else { $view_folder = APPPATH . 'views'; } } if (($_temp = realpath($view_folder)) !== FALSE) { $view_folder = $_temp . DIRECTORY_SEPARATOR; } else { $view_folder = rtrim($view_folder, '/\\') . DIRECTORY_SEPARATOR; } define('VIEWPATH', $view_folder); /* * -------------------------------------------------------------------- * LOAD THE BOOTSTRAP FILE * -------------------------------------------------------------------- * * And away we go... */ require_once BASEPATH . 'core/CodeIgniter.php';
dayanstef/perfect-php-framework
index.php
PHP
mit
10,005
36.335821
162
0.581909
false
version https://git-lfs.github.com/spec/v1 oid sha256:be847f24aac166b803f1ff5ccc7e4d7bc3fb5d960543e35f779068a754294c94 size 1312
yogeshsaroya/new-cdnjs
ajax/libs/extjs/4.2.1/src/app/domain/Direct.js
JavaScript
mit
129
42
75
0.883721
false
<?php namespace Matthimatiker\CommandLockingBundle\Locking; use Symfony\Component\Filesystem\LockHandler; /** * Uses files to create locks. * * @see \Symfony\Component\Filesystem\LockHandler * @see http://symfony.com/doc/current/components/filesystem/lock_handler.html */ class FileLockManager implements LockManagerInterface { /** * The directory that contains the lock files. * * @var string */ private $lockDirectory = null; /** * Contains the locks that are currently active. * * The name of the lock is used as key. * * @var array<string, LockHandler> */ private $activeLocksByName = array(); /** * @param string $lockDirectory Path to the directory that contains the locks. */ public function __construct($lockDirectory) { $this->lockDirectory = $lockDirectory; } /** * Obtains a lock for the provided name. * * The lock must be released before it can be obtained again. * * @param string $name * @return boolean True if the lock was obtained, false otherwise. */ public function lock($name) { if ($this->isLocked($name)) { return false; } $lock = new LockHandler($name . '.lock', $this->lockDirectory); if ($lock->lock()) { // Obtained lock. $this->activeLocksByName[$name] = $lock; return true; } return false; } /** * Releases the lock with the provided name. * * If the lock does not exist, then this method will do nothing. * * @param string $name */ public function release($name) { if (!$this->isLocked($name)) { return; } /* @var $lock LockHandler */ $lock = $this->activeLocksByName[$name]; $lock->release(); unset($this->activeLocksByName[$name]); } /** * Checks if a lock with the given name is active. * * @param string $name * @return boolean */ private function isLocked($name) { return isset($this->activeLocksByName[$name]); } }
Matthimatiker/CommandLockingBundle
Locking/FileLockManager.php
PHP
mit
2,166
23.337079
82
0.578486
false
// Core is a collection of helpers // Nothing specific to the emultor application "use strict"; // all code is defined in this namespace window.te = window.te || {}; // te.provide creates a namespace if not previously defined. // Levels are seperated by a `.` Each level is a generic JS object. // Example: // te.provide("my.name.space"); // my.name.foo = function(){}; // my.name.space.bar = function(){}; te.provide = function(ns /*string*/ , root) { var parts = ns.split('.'); var lastLevel = root || window; for (var i = 0; i < parts.length; i++) { var p = parts[i]; if (!lastLevel[p]) { lastLevel = lastLevel[p] = {}; } else if (typeof lastLevel[p] !== 'object') { throw new Error('Error creating namespace.'); } else { lastLevel = lastLevel[p]; } } }; // A simple UID generator. Returned UIDs are guaranteed to be unique to the page load te.Uid = (function() { var id = 1; function next() { return id++; } return { next: next }; })(); // defaultOptionParse is a helper for functions that expect an options // var passed in. This merges the passed in options with a set of defaults. // Example: // foo function(options) { // tf.defaultOptionParse(options, {bar:true, fizz:"xyz"}); // } te.defaultOptionParse = function(src, defaults) { src = src || {}; var keys = Object.keys(defaults); for (var i = 0; i < keys.length; i++) { var k = keys[i]; if (src[k] === undefined) { src[k] = defaults[k]; } } return src; }; // Simple string replacement, eg: // tf.sprintf('{0} and {1}', 'foo', 'bar'); // outputs: foo and bar te.sprintf = function(str) { for (var i = 1; i < arguments.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, arguments[i]); } return str; };
tyleregeto/8bit-emulator
src/core.js
JavaScript
mit
1,772
23.287671
85
0.615688
false
## # Backup v4.x Configuration # # Documentation: http://meskyanichi.github.io/backup # Issue Tracker: https://github.com/meskyanichi/backup/issues ## # Config Options # # The options here may be overridden on the command line, but the result # will depend on the use of --root-path on the command line. # # If --root-path is used on the command line, then all paths set here # will be overridden. If a path (like --tmp-path) is not given along with # --root-path, that path will use it's default location _relative to --root-path_. # # If --root-path is not used on the command line, a path option (like --tmp-path) # given on the command line will override the tmp_path set here, but all other # paths set here will be used. # # Note that relative paths given on the command line without --root-path # are relative to the current directory. The root_path set here only applies # to relative paths set here. # # --- # # Sets the root path for all relative paths, including default paths. # May be an absolute path, or relative to the current working directory. # # root_path 'my/root' # # Sets the path where backups are processed until they're stored. # This must have enough free space to hold apx. 2 backups. # May be an absolute path, or relative to the current directory or +root_path+. # # tmp_path 'my/tmp' # # Sets the path where backup stores persistent information. # When Backup's Cycler is used, small YAML files are stored here. # May be an absolute path, or relative to the current directory or +root_path+. # # data_path 'my/data' ## # Utilities # # If you need to use a utility other than the one Backup detects, # or a utility can not be found in your $PATH. # # Utilities.configure do # tar '/usr/bin/gnutar' # redis_cli '/opt/redis/redis-cli' # end ## # Logging # # Logging options may be set on the command line, but certain settings # may only be configured here. # # Logger.configure do # console.quiet = true # Same as command line: --quiet # logfile.max_bytes = 2_000_000 # Default: 500_000 # syslog.enabled = true # Same as command line: --syslog # syslog.ident = 'my_app_backup' # Default: 'backup' # end # # Command line options will override those set here. # For example, the following would override the example settings above # to disable syslog and enable console output. # backup perform --trigger my_backup --no-syslog --no-quiet ## # Component Defaults # # Set default options to be applied to components in all models. # Options set within a model will override those set here. # # Storage::S3.defaults do |s3| # s3.access_key_id = "my_access_key_id" # s3.secret_access_key = "my_secret_access_key" # end # # Notifier::Mail.defaults do |mail| # mail.from = 'sender@email.com' # mail.to = 'receiver@email.com' # mail.address = 'smtp.gmail.com' # mail.port = 587 # mail.domain = 'your.host.name' # mail.user_name = 'sender@email.com' # mail.password = 'my_password' # mail.authentication = 'plain' # mail.encryption = :starttls # end ## # Preconfigured Models # # Create custom models with preconfigured components. # Components added within the model definition will # +add to+ the preconfigured components. # # preconfigure 'MyModel' do # archive :user_pictures do |archive| # archive.add '~/pictures' # end # # notify_by Mail do |mail| # mail.to = 'admin@email.com' # end # end # # MyModel.new(:john_smith, 'John Smith Backup') do # archive :user_music do |archive| # archive.add '~/music' # end # # notify_by Mail do |mail| # mail.to = 'john.smith@email.com' # end # end
dockerizedrupal/backer
src/backer/build/modules/build/files/root/Backup/config.rb
Ruby
mit
3,832
30.669421
82
0.658142
false
import Ember from 'ember'; let __TRANSLATION_MAP__ = {}; export default Ember.Service.extend({ map: __TRANSLATION_MAP__ });
alexBaizeau/ember-fingerprint-translations
app/services/translation-map.js
JavaScript
mit
126
24.2
66
0.674603
false
import React from 'react'; <<<<<<< HEAD import { Switch, Route } from 'react-router-dom'; import Home from './Home'; import About from './About'; import Blog from './Blog'; import Resume from './Resume'; import Error404 from './Error404'; ======= // import GithubForm from './forms/github/GithubForm'; import GithubRecent from './forms/github/RecentList'; import './Content.css'; >>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a class Content extends React.Component { render() { return ( <div className="app-content"> <<<<<<< HEAD <Switch> <Route exact path="/" component={Home} /> {/* <Route exact path="/about" component={About} /> */} <Route component={Error404} /> </Switch> ======= <div className="content-description"> <br />College Student. Love Coding. Interested in Web and Machine Learning. </div> <hr /> <div className="content-list"> <div className="list-projects"> <h3>Recent Projects</h3> {/* <GithubRecent userName="slkjse9" standardDate={5259492000} /> */} <GithubRecent userName="hejuby" standardDate={3.154e+10} /> {/* <h2>Activity</h2> */} <h3>Experience</h3> <h3>Education</h3> <ul> <li><h4>Computer Science</h4>Colorado State University, Fort Collins (2017 -)</li> </ul> <br /> </div> </div> {/* <div className="content-home-github-recent-title"> <h2>Recent Works</h2> <h3>updated in 2 months</h3> </div> */} {/* <h3>Recent</h3> <GithubForm contentType="recent"/> */} {/* <h3>Lifetime</h3> {/* <GithubForm contentType="life"/> */} {/* <div className="content-home-blog-recent-title"> <h2>Recent Posts</h2> <h3>written in 2 months</h3> </div> <BlogRecent /> */} >>>>>>> 23d814bedfd5c07e05ea49d9a90053074a4c829a </div> ); } } export default Content;
slkjse9/slkjse9.github.io
src/components/Content.js
JavaScript
mit
2,049
30.045455
96
0.553441
false
package cmd import ( "github.com/fatih/color" out "github.com/plouc/go-gitlab-client/cli/output" "github.com/spf13/cobra" ) func init() { getCmd.AddCommand(getProjectVarCmd) } var getProjectVarCmd = &cobra.Command{ Use: resourceCmd("project-var", "project-var"), Aliases: []string{"pv"}, Short: "Get the details of a project's specific variable", RunE: func(cmd *cobra.Command, args []string) error { ids, err := config.aliasIdsOrArgs(currentAlias, "project-var", args) if err != nil { return err } color.Yellow("Fetching project variable (id: %s, key: %s)…", ids["project_id"], ids["var_key"]) loader.Start() variable, meta, err := client.ProjectVariable(ids["project_id"], ids["var_key"]) loader.Stop() if err != nil { return err } out.Variable(output, outputFormat, variable) printMeta(meta, false) return nil }, }
plouc/go-gitlab-client
cli/cmd/get_project_var_cmd.go
GO
mit
873
21.921053
97
0.673938
false
export interface IContact { id?: number; email: string; listName: string; name: string; }
SimpleCom/simplecom-web
src/interfaces/contacts.interface.ts
TypeScript
mit
98
15.333333
27
0.673469
false
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // 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. // This file was automatically generated and should not be edited directly. using System; using System.Runtime.InteropServices; namespace SharpVk.Interop { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public unsafe partial struct ExternalMemoryImageCreateInfo { /// <summary> /// The type of this structure. /// </summary> public SharpVk.StructureType SType; /// <summary> /// Null or an extension-specific structure. /// </summary> public void* Next; /// <summary> /// /// </summary> public SharpVk.ExternalMemoryHandleTypeFlags HandleTypes; } }
FacticiusVir/SharpVk
src/SharpVk/Interop/ExternalMemoryImageCreateInfo.gen.cs
C#
mit
1,882
35.901961
81
0.694474
false
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterCreditException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.*; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; /** * Created by jorgegonzalez on 2015.07.14.. */ @RunWith(MockitoJUnitRunner.class) public class CreditTest { @Mock private Database mockDatabase; @Mock private DatabaseTable mockWalletTable; @Mock private DatabaseTable mockBalanceTable; @Mock private DatabaseTransaction mockTransaction; private List<DatabaseTableRecord> mockRecords; private DatabaseTableRecord mockBalanceRecord; private DatabaseTableRecord mockWalletRecord; private BitcoinWalletTransactionRecord mockTransactionRecord; private BitcoinWalletBasicWalletAvailableBalance testBalance; @Before public void setUpMocks(){ mockTransactionRecord = new MockBitcoinWalletTransactionRecord(); mockBalanceRecord = new MockDatabaseTableRecord(); mockWalletRecord = new MockDatabaseTableRecord(); mockRecords = new ArrayList<>(); mockRecords.add(mockBalanceRecord); setUpMockitoRules(); } public void setUpMockitoRules(){ when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable); when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable); when(mockBalanceTable.getRecords()).thenReturn(mockRecords); when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord); when(mockDatabase.newTransaction()).thenReturn(mockTransaction); } @Before public void setUpAvailableBalance(){ testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase); } @Test public void Credit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{ catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()).isNull(); } @Test public void Credit_OpenDatabaseCantOpenDatabase_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_OpenDatabaseDatabaseNotFound_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_DaoCantCalculateBalanceException_ThrowsCantRegisterCreditException() throws Exception{ doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory(); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } @Test public void Credit_GeneralException_ThrowsCantRegisterCreditException() throws Exception{ when(mockBalanceTable.getRecords()).thenReturn(null); catchException(testBalance).credit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterCreditException.class); } }
fvasquezjatar/fermat-unused
DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/CreditTest.java
Java
mit
5,641
43.417323
158
0.777699
false
using System; namespace Sherlock { /// <summary> /// A reader than can read values from a pipe. /// </summary> /// <typeparam name="T">The type of value to read.</typeparam> public interface IPipeReader<T> : IDisposable { /// <summary> /// Attempts to read a value from the pipe. /// </summary> /// <param name="item">The read value.</param> /// <returns>A value indicating success.</returns> bool Read(out T item); /// <summary> /// Closes the reader. /// </summary> void Close(); /// <summary> /// Gets a value indicating whether the reader is closed. /// </summary> bool IsClosed { get; } } }
tessellator/sherlock
Sherlock/IPipeReader.cs
C#
mit
742
25.428571
66
0.533784
false
# Nitrogen 2.0 New Features ### New Elements, Actions, and API functions * wf:wire can now act upon CSS classes or full JQuery Paths, not just Nitrogen elements. For example, wf:wire(".people > .address", Actions) will wire actions to any HTML elements with an "address" class underneath a "people" class. Anything on http://api.jquery.com/category/selectors/ is supported * Added wf:replace(ID, Elements), remove an element from the page, put new elements in their place. * Added wf:remove(ID), remove an element from the page. * New #api{} action allows you to define a javascript method that takes parameters and will trigger a postback. Javascript parameters are automatically translated to Erlang, allowing for pattern matching. * New #grid{} element provides a Nitrogen interface to the 960 Grid System (http://960.gs) for page layouts. * The #upload{} event callbacks have changed. Event fires both on start of upload and when upload finishes. * Upload callbacks take a Node parameter so that file uploads work even when a postback hits a different node. * Many methods that used to be in 'nitrogen.erl' are now in 'wf.erl'. Also, some method signatures in wf.erl have changed. * wf:get_page_module changed to wf:page_module * wf:q(ID) no longer returns a list, just the value. * wf:qs(ID) returns a list. * wf:depickle(Data, TTL) returns undefined if expired. ### Comet Pools * Behind the scenes, combined logic for comet and continue events. This now all goes through the same channel. You can switch async mode between comet and intervalled polling by calling wf:switch_to_comet() or wf:switch_to_polling(IntervalMS), respectively. * Comet processes can now register in a local pool (for a specific session) or a global pool (across the entire Nitrogen cluster). All other processes in the pool are alerted when a process joins or leaves. The first process in a pool gets a special init message. * Use wf:send(Pool, Message) or wf:send_global(Pool, Message) to broadcast a message to the entire pool. * wf:comet_flush() is now wf:flush() ### Architectural Changes * Nitrogen now runs _under_ other web frameworks (inets, mochiweb, yaws, misultin) using simple_bridge. In other words, you hook into the other frameworks like normal (mochiweb loop, yaws appmod, etc.) and then call nitrogen:run() from within that process. * Handlers are the new mechanism to extend the inner parts of Nitrogen, such as session storage, authentication, etc. * New route handler code means that pages can exist in any namespace, don't have to start with /web/... (see dynamic_route_handler and named_route_handler) * Changed interface to elements and actions, any custom elements and actions will need tweaks. * sync:go() recompiles any changed files more intelligently by scanning for Emakefiles. * New ability to package Nitrogen projects as self-contained directories using rebar. # Nitrogen 1.0 Changelog 2009-05-02 - Added changes and bugfixes by Tom McNulty. 2009-04-05 - Added a templateroot setting in .app file, courtesy of Ville Koivula. 2009-03-28 - Added file upload support. 2009-03-22 - Added alt text support to #image elements by Robert Schonberger. - Fixed bug, 'nitrogen create (PROJECT)' now does a recursive copy of the Nitrogen support files, by Jay Doane. - Added radio button support courtesy of Benjamin Nortier and Tom McNulty. 2009-03-16 - Added .app configuration setting to bind Nitrogen to a specific IP address, by Tom McNulty. 2009-03-08 - Added DatePicker element by Torbjorn Tornkvist. - Upgrade to JQuery 1.3.2 and JQuery UI 1.7. - Created initial VERSIONS file. - Added code from Tom McNulty to expose Mochiweb loop. - Added coverage code from Michael Mullis, including lib/coverize submodule. - Added wf_platform:get_peername/0 code from Marius A. Eriksen. 2009-03-07 - Added code by Torbjorn Tornkvist: Basic Authentication, Hostname settings, access to HTTP Headers, and a Max Length validator. 2009-01-26 - Added Gravatar support by Dan Bravender. 2009-01-24 - Add code-level documentation around comet. - Fix bug where comet functions would continue running after a user left the page. - Apply patch by Tom McNulty to allow request object access within the route/1 function. - Apply patch by Tom McNulty to correctly bind binaries. - Apply patch by Tom McNulty for wf_tags library to correctly handle binaries. 2009-01-16 - Clean up code around timeout events. (Events that will start running after X seconds on the browser.) 2009-01-08 - Apply changes by Jon Gretar to support 'nitrogen create PROJECT' and 'nitrogen page /web/page' scripts. - Finish putting all properties into .app file. Put request/1 into application module file. - Add ability to route through route/1 in application module file. - Remove need for wf_global.erl - Start Yaws process underneath the main Nitrogen supervisor. (Used to be separate.) 2009-01-06 - Make Nitrogen a supervised OTP application, startable and stoppable via nitrogen:start() and nitrogen:stop(). - Apply changes by Dave Peticolas to fix session bugs and turn sessions into supervised processes. 2009-01-04 - Update sync module, add mirror module. These tools allow you to deploy and start applications on a bare remote node. 2009-01-03 - Allow Nitrogen to be run as an OTP application. See Quickstart project for example. - Apply Tom McNulty's patch to create and implement wf_tags library. Emit html tags more cleanly. - Change templates to allow multiple callbacks, and use first one that is defined. Basic idea and starter code by Tom McNulty. - Apply Martin Scholl's patch to optimize copy_to_baserecord in wf_utils.
kbaldyga/Bazy
CHANGELOG.markdown
Markdown
mit
5,623
57.572917
299
0.776098
false
package gogo import ( "net/http" "net/http/httptest" "testing" "github.com/golib/assert" ) func Test_NewResponse(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) it.Implements((*Responser)(nil), response) it.Equal(http.StatusOK, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func Test_ResponseWriteHeader(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.StatusRequestTimeout) it.Equal(http.StatusRequestTimeout, response.Status()) it.Equal(nonHeaderFlushed, response.Size()) } func Test_ResponseFlushHeader(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() response := NewResponse(recorder) response.WriteHeader(http.StatusRequestTimeout) response.FlushHeader() it.Equal(http.StatusRequestTimeout, recorder.Code) it.NotEqual(nonHeaderFlushed, response.Size()) // no effect after flushed headers response.WriteHeader(http.StatusOK) it.Equal(http.StatusOK, response.Status()) response.FlushHeader() it.NotEqual(http.StatusOK, recorder.Code) } func Test_ResponseWrite(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() hello := []byte("Hello,") world := []byte("world!") expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(hello) response.Write(world) it.True(response.HeaderFlushed()) it.Equal(len(expected), response.Size()) it.Equal(expected, recorder.Body.Bytes()) } func Benchmark_ResponseWrite(b *testing.B) { b.ReportAllocs() b.ResetTimer() hello := []byte("Hello,") world := []byte("world!") recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Write(hello) response.Write(world) } } func Test_ResponseHijack(t *testing.T) { it := assert.New(t) recorder := httptest.NewRecorder() expected := []byte("Hello,world!") response := NewResponse(recorder) response.Write(expected) it.True(response.HeaderFlushed()) it.Equal(recorder, response.(*Response).ResponseWriter) it.Equal(len(expected), response.Size()) response.Hijack(httptest.NewRecorder()) it.False(response.HeaderFlushed()) it.NotEqual(recorder, response.(*Response).ResponseWriter) it.Equal(nonHeaderFlushed, response.Size()) } func Benchmark_ResponseHijack(b *testing.B) { b.ReportAllocs() b.ResetTimer() recorder := httptest.NewRecorder() response := NewResponse(recorder) for i := 0; i < b.N; i++ { response.Hijack(recorder) } }
dolab/gogo
response_test.go
GO
mit
2,566
23.673077
59
0.725643
false
#if !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_) #define AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // Dialog3.h : header file // ///////////////////////////////////////////////////////////////////////////// // CDialog3 dialog class CDialog3 : public CDialog { // Construction public: CDialog3(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CDialog3) enum { IDD = IDD_DIALOG3 }; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDialog3) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CDialog3) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DIALOG3_H__8EF7DE42_F33E_4217_87B0_FE9ACBCE3E84__INCLUDED_)
Hao-Wu/MEDA
Dialog3.h
C
mit
1,146
23.466667
97
0.642234
false
# Load DSL and set up stages require 'capistrano/setup' # Include default deployment tasks require 'capistrano/deploy' # Include tasks from other gems included in your Gemfile require 'capistrano/rvm' require 'capistrano/bundler' require 'capistrano/rails' require 'capistrano/rails/migrations' require 'capistrano/nginx_unicorn' require 'capistrano/rails/assets' # Load custom tasks from `lib/capistrano/tasks` if you have any defined Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }
a11ejandro/project_prototype
Capfile.rb
Ruby
mit
501
30.3125
71
0.784431
false
var mongoose = require('mongoose'); var bcrypt = require('bcrypt'); var saltRounds = 10; var userSchema = new mongoose.Schema({ email: { type: String, index: {unique: true} }, password: String, name: String }); //hash password userSchema.methods.generateHash = function(password){ return bcrypt.hashSync(password, bcrypt.genSaltSync(saltRounds)); } userSchema.methods.validPassword = function(password){ return bcrypt.compareSync(password, this.password); } var User = mongoose.model('User',userSchema); module.exports = User;
zymokey/mission-park
models/user/user.js
JavaScript
mit
541
20.68
66
0.737523
false
<?php namespace Wolphy\Jobs; use Illuminate\Bus\Queueable; abstract class Job { /* |-------------------------------------------------------------------------- | Queueable Jobs |-------------------------------------------------------------------------- | | This job base class provides a central location to place any logic that | is shared across all of your jobs. The trait included with the class | provides access to the "queueOn" and "delay" queue helper methods. | */ use Queueable; }
lezhnev74/wolphy
app/Jobs/Job.php
PHP
mit
538
24.619048
79
0.472119
false
#!/bin/sh echo "Stopping web-server ..." COUNT_PROCESS=1 while [ $COUNT_PROCESS -gt 0 ] do COUNT_PROCESS=`ps -Aef | grep node | grep -c server.js` if [ $COUNT_PROCESS -gt 0 ]; then PID_PROCESS=`ps -Aef | grep node | grep server.js | awk '{print $2}'` if [ ! -z "$PID_PROCESS" ]; then echo "Killing web server PID=$PID_PROCESS" kill "$PID_PROCESS" fi fi echo "Waiting on web-server to stop ..." sleep 1 done echo "This web-server is stopped" exit 0
stefanreichhart/tribe
src/scripts/stopServer.sh
Shell
mit
468
21.333333
71
0.643162
false
<?php namespace RectorPrefix20210615; if (\class_exists('t3lib_collection_StaticRecordCollection')) { return; } class t3lib_collection_StaticRecordCollection { } \class_alias('t3lib_collection_StaticRecordCollection', 't3lib_collection_StaticRecordCollection', \false);
RectorPHP/Rector
vendor/ssch/typo3-rector/stubs/t3lib_collection_StaticRecordCollection.php
PHP
mit
276
24.090909
107
0.793478
false
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("RedditImageDownloader.GUI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RedditImageDownloader.GUI")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] //Um mit dem Erstellen lokalisierbarer Anwendungen zu beginnen, legen Sie //<UICulture>ImCodeVerwendeteKultur</UICulture> in der .csproj-Datei //in einer <PropertyGroup> fest. Wenn Sie in den Quelldateien beispielsweise Deutsch //(Deutschland) verwenden, legen Sie <UICulture> auf \"de-DE\" fest. Heben Sie dann die Auskommentierung //des nachstehenden NeutralResourceLanguage-Attributs auf. Aktualisieren Sie "en-US" in der nachstehenden Zeile, //sodass es mit der UICulture-Einstellung in der Projektdatei übereinstimmt. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //Speicherort der designspezifischen Ressourcenwörterbücher //(wird verwendet, wenn eine Ressource auf der Seite // oder in den Anwendungsressourcen-Wörterbüchern nicht gefunden werden kann.) ResourceDictionaryLocation.SourceAssembly //Speicherort des generischen Ressourcenwörterbuchs //(wird verwendet, wenn eine Ressource auf der Seite, in der Anwendung oder einem // designspezifischen Ressourcenwörterbuch nicht gefunden werden kann.) )] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Aniel/RedditImageDownloader
RedditImageDownloader.GUI/Properties/AssemblyInfo.cs
C#
mit
2,715
47.945455
128
0.735141
false
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ar' from layers_basic import LW_Layer, default_data_format from layers_convolutional import conv_output_length ############################################### class _LW_Pooling1D(LW_Layer): input_dim = 3 def __init__(self, pool_size=2, strides=None, padding='valid'): if strides is None: strides = pool_size assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.pool_length = pool_size self.stride = strides self.border_mode = padding def get_output_shape_for(self, input_shape): length = conv_output_length(input_shape[1], self.pool_length, self.border_mode, self.stride) return (input_shape[0], length, input_shape[2]) class LW_MaxPooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_MaxPooling1D, self).__init__(pool_size, strides, padding) class LW_AveragePooling1D(_LW_Pooling1D): def __init__(self, pool_size=2, strides=None, padding='valid'): super(LW_AveragePooling1D, self).__init__(pool_size, strides, padding) ############################################### class _LW_Pooling2D(LW_Layer): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): if data_format == 'default': data_format = default_data_format assert data_format in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert padding in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = padding self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': rows = input_shape[2] cols = input_shape[3] elif self.dim_ordering == 'channels_last': rows = input_shape[1] cols = input_shape[2] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) rows = conv_output_length(rows, self.pool_size[0], self.border_mode, self.strides[0]) cols = conv_output_length(cols, self.pool_size[1], self.border_mode, self.strides[1]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], rows, cols) elif self.dim_ordering == 'channels_last': return (input_shape[0], rows, cols, input_shape[3]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_MaxPooling2D, self).__init__(pool_size, strides, padding, data_format) class LW_AveragePooling2D(_LW_Pooling2D): def __init__(self, pool_size=(2, 2), strides=None, padding='valid', data_format='default'): super(LW_AveragePooling2D, self).__init__(pool_size, strides, padding, data_format) ############################################### class _LW_Pooling3D(LW_Layer): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): if dim_ordering == 'default': dim_ordering = default_data_format assert dim_ordering in {'channels_last', 'channels_first'}, 'data_format must be in {channels_last, channels_first}' self.pool_size = tuple(pool_size) if strides is None: strides = self.pool_size self.strides = tuple(strides) assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' self.border_mode = border_mode self.dim_ordering = dim_ordering def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_first': len_dim1 = input_shape[2] len_dim2 = input_shape[3] len_dim3 = input_shape[4] elif self.dim_ordering == 'channels_last': len_dim1 = input_shape[1] len_dim2 = input_shape[2] len_dim3 = input_shape[3] else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) len_dim1 = conv_output_length(len_dim1, self.pool_size[0], self.border_mode, self.strides[0]) len_dim2 = conv_output_length(len_dim2, self.pool_size[1], self.border_mode, self.strides[1]) len_dim3 = conv_output_length(len_dim3, self.pool_size[2], self.border_mode, self.strides[2]) if self.dim_ordering == 'channels_first': return (input_shape[0], input_shape[1], len_dim1, len_dim2, len_dim3) elif self.dim_ordering == 'channels_last': return (input_shape[0], len_dim1, len_dim2, len_dim3, input_shape[4]) else: raise Exception('Invalid dim_ordering: ' + self.dim_ordering) class LW_MaxPooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_MaxPooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) class LW_AveragePooling3D(_LW_Pooling3D): def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', dim_ordering='default'): super(LW_AveragePooling3D, self).__init__(pool_size, strides, border_mode, dim_ordering) ############################################### class _LW_GlobalPooling1D(LW_Layer): def __init__(self): pass def get_output_shape_for(self, input_shape): return (input_shape[0], input_shape[2]) class LW_GlobalAveragePooling1D(_LW_GlobalPooling1D): pass class LW_GlobalMaxPooling1D(_LW_GlobalPooling1D): pass ############################################### class _LW_GlobalPooling2D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[3]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling2D(_LW_GlobalPooling2D): pass class LW_GlobalMaxPooling2D(_LW_GlobalPooling2D): pass ############################################### class _LW_GlobalPooling3D(LW_Layer): def __init__(self, data_format='default'): if data_format == 'default': data_format = default_data_format self.dim_ordering = data_format def get_output_shape_for(self, input_shape): if self.dim_ordering == 'channels_last': return (input_shape[0], input_shape[4]) else: return (input_shape[0], input_shape[1]) class LW_GlobalAveragePooling3D(_LW_GlobalPooling3D): pass class LW_GlobalMaxPooling3D(_LW_GlobalPooling3D): pass ############################################### if __name__ == '__main__': pass
SummaLabs/DLS
app/backend/core/models-keras-2x-api/lightweight_layers/layers_pooling.py
Python
mit
7,111
42.631902
124
0.599494
false
class CreateEventTypes < ActiveRecord::Migration def change create_table :event_types do |t| t.string :name, :limit => 80 t.timestamps end end end
nac13k/iAdmin
db/migrate/20140408042944_create_event_types.rb
Ruby
mit
172
18.111111
48
0.656977
false
/* * Copyright 2013 MongoDB, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef BSON_COMPAT_H #define BSON_COMPAT_H #if !defined (BSON_INSIDE) && !defined (BSON_COMPILATION) # error "Only <bson.h> can be included directly." #endif #if defined(__MINGW32__) # if defined(__USE_MINGW_ANSI_STDIO) # if __USE_MINGW_ANSI_STDIO < 1 # error "__USE_MINGW_ANSI_STDIO > 0 is required for correct PRI* macros" # endif # else # define __USE_MINGW_ANSI_STDIO 1 # endif #endif #include "bson-config.h" #include "bson-macros.h" #ifdef BSON_OS_WIN32 # if defined(_WIN32_WINNT) && (_WIN32_WINNT < 0x0600) # undef _WIN32_WINNT # endif # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0600 # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <winsock2.h> # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # include <windows.h> # undef WIN32_LEAN_AND_MEAN # else # include <windows.h> # endif #include <direct.h> #include <io.h> #endif #ifdef BSON_OS_UNIX # include <unistd.h> # include <sys/time.h> #endif #include "bson-macros.h" #include <errno.h> #include <ctype.h> #include <limits.h> #include <fcntl.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> BSON_BEGIN_DECLS #ifdef _MSC_VER # include "bson-stdint-win32.h" # ifndef __cplusplus /* benign redefinition of type */ # pragma warning (disable :4142) # ifndef _SSIZE_T_DEFINED # define _SSIZE_T_DEFINED typedef SSIZE_T ssize_t; # endif typedef SIZE_T size_t; # pragma warning (default :4142) # else /* * MSVC++ does not include ssize_t, just size_t. * So we need to synthesize that as well. */ # pragma warning (disable :4142) # ifndef _SSIZE_T_DEFINED # define _SSIZE_T_DEFINED typedef SSIZE_T ssize_t; # endif # pragma warning (default :4142) # endif # define PRIi32 "d" # define PRId32 "d" # define PRIu32 "u" # define PRIi64 "I64i" # define PRId64 "I64i" # define PRIu64 "I64u" #else # include "bson-stdint.h" # include <inttypes.h> #endif #if defined(__MINGW32__) && ! defined(INIT_ONCE_STATIC_INIT) # define INIT_ONCE_STATIC_INIT RTL_RUN_ONCE_INIT typedef RTL_RUN_ONCE INIT_ONCE; #endif #ifdef BSON_HAVE_STDBOOL_H # include <stdbool.h> #elif !defined(__bool_true_false_are_defined) # ifndef __cplusplus typedef signed char bool; # define false 0 # define true 1 # endif # define __bool_true_false_are_defined 1 #endif #if defined(__GNUC__) # if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) # define bson_sync_synchronize() __sync_synchronize() # elif defined(__i386__ ) || defined( __i486__ ) || defined( __i586__ ) || \ defined( __i686__ ) || defined( __x86_64__ ) # define bson_sync_synchronize() asm volatile("mfence":::"memory") # else # define bson_sync_synchronize() asm volatile("sync":::"memory") # endif #elif defined(_MSC_VER) # define bson_sync_synchronize() MemoryBarrier() #endif #if !defined(va_copy) && defined(__va_copy) # define va_copy(dst,src) __va_copy(dst, src) #endif #if !defined(va_copy) # define va_copy(dst,src) ((dst) = (src)) #endif BSON_END_DECLS #endif /* BSON_COMPAT_H */
kangseung/JSTrader
include/mongoc-win/libbson/bson-compat.h
C
mit
3,827
21.193939
76
0.644892
false
require "empty_port/version" require 'socket' require 'timeout' # ## Example # require 'empty_port' # class YourServerTest < Test::Unit::TestCase # def setup # @port = EmptyPort.get # @server_pid = Process.fork do # server = TCPServer.open('localhost', @port) # end # EmptyPort.wait(@port) # end # # def test_something_with_server # end # # def teardown # Process.kill(@server_pid) # end # end # module EmptyPort class NotFoundException < Exception; end module ClassMethods # SEE http://www.iana.org/assignments/port-numbers MIN_PORT_NUMBER = 49152 MAX_PORT_NUMBER = 65535 # get an empty port except well-known-port. def get random_port = MIN_PORT_NUMBER + ( rand() * 1000 ).to_i while random_port < MAX_PORT_NUMBER begin sock = TCPSocket.open('localhost', random_port) sock.close rescue Errno::ECONNREFUSED => e return random_port end random_port += 1 end raise NotFoundException end def listened?(port) begin sock = TCPSocket.open('localhost', port) sock.close return true rescue Errno::ECONNREFUSED return false end end DEFAULT_TIMEOUT = 2 DEFAULT_INTERVAL = 0.1 def wait(port, options={}) options[:timeout] ||= DEFAULT_TIMEOUT options[:interval] ||= DEFAULT_INTERVAL timeout(options[:timeout]) do start = Time.now loop do if self.listened?(port) finished = Time.now return finished - start end sleep(options[:interval]) end end end end extend ClassMethods end
walf443/empty_port
lib/empty_port.rb
Ruby
mit
1,760
21.278481
60
0.577273
false
module.exports = { 'throttle': 10, 'hash': true, 'gzip': false, 'baseDir': 'public', 'buildDir': 'build', 'prefix': '' };
wunderlist/bilder-aws
lib/defaults.js
JavaScript
mit
133
15.75
22
0.541353
false
.vertical-center { min-height: 100%; /* Fallback for browsers do NOT support vh unit */ min-height: 100vh; /* These two lines are counted as one :-) */ display: flex; align-items: center; } @media (min-width: 768px){ #wrapper {/*padding-right: 225px;*/ padding-left: 0;} .side-nav{right: 0;left: auto;} } /*! * Start Bootstrap - SB Admin (http://startbootstrap.com/) * Copyright 2013-2016 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap/blob/gh-pages/LICENSE) */ /* Global Styles */ body { background-color: #222; } #wrapper { padding-left: 0; } #page-wrapper { width: 100%; padding: 0; background-color: #fff; } .huge { font-size: 50px; line-height: normal; } @media(min-width:768px) { #wrapper { padding-left: 225px; } #page-wrapper { padding: 10px; margin-top: 20px; } } /* Top Navigation */ .top-nav { padding: 0 15px; } .top-nav>li { display: inline-block; float: left; } .top-nav>li>a { padding-top: 15px; padding-bottom: 15px; line-height: 20px; color: #999; } .top-nav>li>a:hover, .top-nav>li>a:focus, .top-nav>.open>a, .top-nav>.open>a:hover, .top-nav>.open>a:focus { color: #fff; background-color: #000; } .top-nav>.open>.dropdown-menu { float: left; position: absolute; margin-top: 0; border: 1px solid rgba(0,0,0,.15); border-top-left-radius: 0; border-top-right-radius: 0; background-color: #fff; -webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175); box-shadow: 0 6px 12px rgba(0,0,0,.175); } .top-nav>.open>.dropdown-menu>li>a { white-space: normal; } ul.message-dropdown { padding: 0; max-height: 250px; overflow-x: hidden; overflow-y: auto; } li.message-preview { width: 275px; border-bottom: 1px solid rgba(0,0,0,.15); } li.message-preview>a { padding-top: 15px; padding-bottom: 15px; } li.message-footer { margin: 5px 0; } ul.alert-dropdown { width: 200px; } .alert-danger { margin-top: 50px; } /* Side Navigation */ @media(min-width:768px) { .side-nav { position: fixed; top: 51px; /* left: 225px;*/ left: 0px; width: 225px; /* margin-left: -225px;*/ border: none; border-radius: 0; overflow-y: auto; background-color: #222; bottom: 0; overflow-x: hidden; padding-bottom: 40px; } .side-nav>li>a { width: 225px; } .side-nav li a:hover, .side-nav li a:focus { outline: none; background-color: #000 !important; } } .side-nav>li>ul { padding: 0; } .side-nav>li>ul>li>a { display: block; padding: 10px 15px 10px 38px; text-decoration: none; color: #999; } .side-nav>li>ul>li>a:hover { color: #fff; } /* Flot Chart Containers */ .flot-chart { display: block; height: 400px; } .flot-chart-content { width: 100%; height: 100%; } /* Custom Colored Panels */ .huge { font-size: 40px; } .panel-green { border-color: #5cb85c; } .panel-green > .panel-heading { border-color: #5cb85c; color: #fff; background-color: #5cb85c; } .panel-green > a { color: #5cb85c; } .panel-green > a:hover { color: #3d8b3d; } .panel-red { border-color: #d9534f; } .panel-red > .panel-heading { border-color: #d9534f; color: #fff; background-color: #d9534f; } .panel-red > a { color: #d9534f; } .panel-red > a:hover { color: #b52b27; } .panel-yellow { border-color: #f0ad4e; } .panel-yellow > .panel-heading { border-color: #f0ad4e; color: #fff; background-color: #f0ad4e; } .panel-yellow > a { color: #f0ad4e; } .panel-yellow > a:hover { color: #df8a13; } .navbar-nav > li > ul > li.active { background: rgba(9, 9, 9, 0.57); }
antodoms/beaconoid
app/assets/stylesheets/admin.css
CSS
mit
3,884
14.857143
96
0.582647
false
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>使用 button 定义按钮</title> </head> <body> <form action="http://www.baidu.com" method="get"> <button type="button"><b>提交</b></button><br/> <button type="submit"><img sec="./img/3.jpg" alt="图片"></button><br/> </form> </body> </html>
llinmeng/learn-fe
src/ex/crazy-fe-book/2017/H5/03/3-1-4.html
HTML
mit
351
21.066667
76
0.561934
false
--- layout: post title: Tweets date: 2019-08-08 summary: These are the tweets for August 8, 2019. categories: ---
alexlitel/congresstweets
_posts/2019-08-08--tweets.md
Markdown
mit
115
13.375
49
0.704348
false
import type { FormatRelativeFn } from '../../../types' // Source: https://www.unicode.org/cldr/charts/32/summary/te.html const formatRelativeLocale = { lastWeek: "'గత' eeee p", // CLDR #1384 yesterday: "'నిన్న' p", // CLDR #1393 today: "'ఈ రోజు' p", // CLDR #1394 tomorrow: "'రేపు' p", // CLDR #1395 nextWeek: "'తదుపరి' eeee p", // CLDR #1386 other: 'P', } const formatRelative: FormatRelativeFn = (token, _date, _baseDate, _options) => formatRelativeLocale[token] export default formatRelative
date-fns/date-fns
src/locale/te/_lib/formatRelative/index.ts
TypeScript
mit
557
29.176471
79
0.645224
false
INSERT INTO customers(id, name) VALUES (1, 'Jane Woods'); INSERT INTO customers(id, name) VALUES (2, 'Michael Li'); INSERT INTO customers(id, name) VALUES (3, 'Heidi Hasselbach'); INSERT INTO customers(id, name) VALUES (4, 'Rahul Pour');
afh/yabab
pre-populate.sql
SQL
mit
238
28.75
31
0.714286
false
/* * * BitcoinLikeKeychain * ledger-core * * Created by Pierre Pollastri on 17/01/2017. * * The MIT License (MIT) * * Copyright (c) 2016 Ledger * * 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. * */ #ifndef LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #define LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP #include "../../../bitcoin/BitcoinLikeExtendedPublicKey.hpp" #include <string> #include <vector> #include <utils/DerivationScheme.hpp> #include "../../../utils/Option.hpp" #include "../../../preferences/Preferences.hpp" #include "../../../api/Configuration.hpp" #include "../../../api/DynamicObject.hpp" #include <api/Currency.hpp> #include <api/AccountCreationInfo.hpp> #include <api/ExtendedKeyAccountCreationInfo.hpp> #include <api/Keychain.hpp> #include <bitcoin/BitcoinLikeAddress.hpp> namespace ledger { namespace core { class BitcoinLikeKeychain: public api::Keychain { public: enum KeyPurpose { RECEIVE, CHANGE }; public: using Address = std::shared_ptr<BitcoinLikeAddress>; BitcoinLikeKeychain( const std::shared_ptr<api::DynamicObject>& configuration, const api::Currency& params, int account, const std::shared_ptr<Preferences>& preferences); virtual bool markAsUsed(const std::vector<std::string>& addresses); virtual bool markAsUsed(const std::string& address, bool needExtendKeychain = true); virtual bool markPathAsUsed(const DerivationPath& path, bool needExtendKeychain = true) = 0; virtual std::vector<Address> getAllObservableAddresses(uint32_t from, uint32_t to) = 0; virtual std::vector<std::string> getAllObservableAddressString(uint32_t from, uint32_t to) = 0; virtual std::vector<Address> getAllObservableAddresses(KeyPurpose purpose, uint32_t from, uint32_t to) = 0; virtual Address getFreshAddress(KeyPurpose purpose) = 0; virtual std::vector<Address> getFreshAddresses(KeyPurpose purpose, size_t n) = 0; virtual Option<KeyPurpose> getAddressPurpose(const std::string& address) const = 0; virtual Option<std::string> getAddressDerivationPath(const std::string& address) const = 0; virtual bool isEmpty() const = 0; int getAccountIndex() const; const api::BitcoinLikeNetworkParameters& getNetworkParameters() const; const api::Currency& getCurrency() const; virtual Option<std::vector<uint8_t>> getPublicKey(const std::string& address) const = 0; std::shared_ptr<api::DynamicObject> getConfiguration() const; const DerivationScheme& getDerivationScheme() const; const DerivationScheme& getFullDerivationScheme() const; std::string getKeychainEngine() const; bool isSegwit() const; bool isNativeSegwit() const; virtual std::string getRestoreKey() const = 0; virtual int32_t getObservableRangeSize() const = 0; virtual bool contains(const std::string& address) const = 0; virtual std::vector<Address> getAllAddresses() = 0; virtual int32_t getOutputSizeAsSignedTxInput() const = 0; static bool isSegwit(const std::string &keychainEngine); static bool isNativeSegwit(const std::string &keychainEngine); std::shared_ptr<Preferences> getPreferences() const; protected: DerivationScheme& getDerivationScheme(); private: const api::Currency _currency; DerivationScheme _scheme; DerivationScheme _fullScheme; int _account; std::shared_ptr<Preferences> _preferences; std::shared_ptr<api::DynamicObject> _configuration; }; } } #endif //LEDGER_CORE_BITCOINLIKEKEYCHAIN_HPP
LedgerHQ/lib-ledger-core
core/src/wallet/bitcoin/keychains/BitcoinLikeKeychain.hpp
C++
mit
4,962
40.35
119
0.672511
false
<?php namespace AppBundle\Repository; /** * Buyers_PropertiesRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class Buyers_PropertiesRepository extends \Doctrine\ORM\EntityRepository { }
asimo124/MLSSite
src/AppBundle/Repository/Buyers_PropertiesRepository.php
PHP
mit
257
18.769231
72
0.766537
false
#!/usr/bin/env ruby #Example handler file.. infile = ARGV.first outfile = File.basename(infile, ".tif") + ".jpg.tif" system("~/cm/processing_scripts/rgb_to_jpeg_tif.rb --internal-mask #{infile} #{outfile}")
spruceboy/jays_geo_tools
examples/sample_handler_for_do_several_at_once.rb
Ruby
mit
210
29
90
0.685714
false
using Newtonsoft.Json; using ProtoBuf; using ITK.ModelManager; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Steam.Models { [Model("SteamPlayerBans")] [ProtoContract] [JsonObject(MemberSerialization.OptIn)] public class PlayerBans { /// <summary> /// A string containing the player's 64 bit ID. /// </summary> [JsonProperty("SteamID")] [ProtoMember(1, IsRequired = true)] public ulong SteamId {get; set;} /// <summary> /// Boolean indicating whether or not the player is banned from Community /// </summary> [JsonProperty("CommunityBanned")] [ProtoMember(2)] public bool IsCommunityBanned {get; set;} /// <summary> /// Boolean indicating whether or not the player has VAC bans on record. /// </summary> [JsonProperty("VACBanned")] [ProtoMember(3)] public bool IsVACBanned {get; set;} /// <summary> /// Amount of VAC bans on record. /// </summary> [JsonProperty("NumberOfVACBans")] [ProtoMember(4)] public int VACBanCount {get; set;} /// <summary> /// Amount of days since last ban. /// </summary> [JsonProperty("DaysSinceLastBan")] [ProtoMember(5)] public int DaysSinceLastBan {get; set;} /// <summary> /// String containing the player's ban status in the economy. If the player has no bans on record the string will be "none", if the player is on probation it will say "probation", and so forth. /// </summary> [JsonProperty("EconomyBan")] [ProtoMember(6)] public string EconomyBan {get; set;} public override int GetHashCode() { return SteamId.GetHashCode(); } public override bool Equals(object obj) { var other = obj as PlayerBans; return other != null && SteamId.Equals(other.SteamId); } } }
inlinevoid/Overust
Steam/Models/PlayerBans.cs
C#
mit
2,083
28.742857
201
0.590101
false
/* * Business.h * UsersService * * Copyright 2011 QuickBlox team. All rights reserved. * */ #import "QBUsersModels.h"
bluecitymoon/demo-swift-ios
demo-swift/Quickblox.framework/Versions/A/Headers/QBUsersBusiness.h
C
mit
128
11.9
55
0.65625
false
--- layout: post title: ESPN took a picture of me categories: link --- Check [this link](http://espn.go.com/college-football/story/_/id/9685394/how-do-nebraska-fans-feel-bo-pelini-recent-behavior) for some story about Bo Pelini's goofing off, and -- look there in the last photo! -- it's some goofball in a Nebraska trilby.
samervin/blog.samerv.in
_posts/link/2013-09-17-espn-picture.md
Markdown
mit
332
45.428571
252
0.725904
false
// // GFTestAppDelegate.h // TestChaosApp // // Created by Michael Charkin on 2/26/14. // Copyright (c) 2014 GitFlub. All rights reserved. // #import <UIKit/UIKit.h> @interface GFTestAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
firemuzzy/GFChaos
TestChaosApp/TestChaosApp/GFTestAppDelegate.h
C
mit
294
18.6
66
0.72449
false