code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M5 20v2h5v2l3-3-3-3v2zm9 0h5v2h-5zm3-20H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zm0 16H7V2h10v14zm-5-9c1.1 0 2-.9 1.99-2 0-1.1-.9-2-2-2S10 3.9 10 5s.89 2 2 2z" }), 'CameraRearOutlined');
AlloyTeam/Nuclear
components/icon/esm/camera-rear-outlined.js
JavaScript
mit
337
package gpg import "context" type contextKey int const ( ctxKeyAlwaysTrust contextKey = iota ctxKeyUseCache ) // WithAlwaysTrust will return a context with the flag for always trust set. func WithAlwaysTrust(ctx context.Context, at bool) context.Context { return context.WithValue(ctx, ctxKeyAlwaysTrust, at) } // IsAlwaysTrust will return the value of the always trust flag or the default // (false). func IsAlwaysTrust(ctx context.Context) bool { bv, ok := ctx.Value(ctxKeyAlwaysTrust).(bool) if !ok { return false } return bv } // WithUseCache returns a context with the value of NoCache set. func WithUseCache(ctx context.Context, nc bool) context.Context { return context.WithValue(ctx, ctxKeyUseCache, nc) } // UseCache returns true if this request should ignore the cache. func UseCache(ctx context.Context) bool { nc, ok := ctx.Value(ctxKeyUseCache).(bool) if !ok { return false } return nc }
gopasspw/gopass
internal/backend/crypto/gpg/context.go
GO
mit
924
using System; using System.Runtime.InteropServices; using EnvDTE; namespace ManuelNaujoks.VSChat { [Guid("173cbcde-e728-442c-82ee-1c29ae3e00af")] public class MyToolWindow : SolutionAwareToolWindowPane { public MyToolWindow() { Caption = Resources.ToolWindowTitle; BitmapResourceID = 301; BitmapIndex = 1; base.Content = new MyControl { GetRelativeCodePosition = MakeRelativeCodePosition, GoToFileAndLine = GoToFileAndLine }; } protected override void OnClose() { var chat = (MyControl)base.Content; chat.Closing(); base.OnClose(); } private void MakeRelativeCodePosition(Action<RelativeCodePosition> callback) { try { var activeDocument = MasterObjekt.ActiveDocument; if (activeDocument != null) { var selection = (TextSelection)activeDocument.Selection; if (selection != null) { if (RawSolution != null) { callback(new RelativeCodePosition(solutionFile: RawSolution.FileName, file: activeDocument.FullName, line: selection.AnchorPoint.Line)); } } } } catch (Exception) { } } private void GoToFileAndLine(string shortcut) { if (RawSolution != null) { var relativeCodePosition = new RelativeCodePosition(solutionFile: RawSolution.FileName, shortcut: shortcut); MasterObjekt.ItemOperations.OpenFile(relativeCodePosition.File, Constants.vsViewKindTextView); var activeDocument = MasterObjekt.ActiveDocument; if (activeDocument != null) { var selection = (TextSelection)activeDocument.Selection; if (selection != null) { selection.GotoLine(relativeCodePosition.Line); } } } } } }
halllo/ManuelsChat
VSChat/MyToolWindow.cs
C#
mit
1,689
'use strict'; module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine'], files: [ // bower:js 'public/components/jquery/dist/jquery.js', 'public/components/angular/angular.js', 'public/components/bootstrap/dist/js/bootstrap.js', 'public/components/angular-route/angular-route.js', 'public/components/angular-bootstrap/ui-bootstrap-tpls.js', 'public/components/angular-sanitize/angular-sanitize.js', 'public/components/marked/lib/marked.js', 'public/components/angular-marked/dist/angular-marked.js', 'public/components/highlightjs/highlight.pack.js', 'public/components/angular-clipboard/angular-clipboard.js', 'public/components/angular-toastr/dist/angular-toastr.tpls.js', 'public/components/angular-animate/angular-animate.js', 'public/components/jquery-ui/jquery-ui.js', 'public/components/angular-ui-sortable/sortable.js', 'public/components/ngstorage/ngStorage.js', // endbower 'public/components/angular-mocks/angular-mocks.js', 'public/*.js', 'public/controllers/*.js', 'public/services/*.js', 'public/directives/*.js', 'test/client/*Spec.js' ], exclude: [ ], preprocessors: { }, reporters: ['progress'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: false, browsers: ['PhantomJS'], singleRun: false, concurrency: Infinity }); };
us10096698/spmemo
karma.conf.js
JavaScript
mit
1,492
'use strict'; /** * controller for angular-ladda * An angular directive wrapper for Ladda buttons. */ angular.module('core').controller('LaddaCtrl', ["$scope", "$timeout", function ($scope, $timeout) { $scope.ldloading = {}; $scope.clickBtn = function (style) { $scope.ldloading[style.replace('-', '_')] = true; $timeout(function () { $scope.ldloading[style.replace('-', '_')] = false; }, 2000); }; $scope.clickProgressBtn = function (style) { $scope.ldloading[style.replace('-', '_') + "_progress"] = true; $timeout(function () { $scope.ldloading[style.replace('-', '_') + "_progress"] = 0.1; }, 500); $timeout(function () { $scope.ldloading[style.replace('-', '_') + "_progress"] += 0.1; }, 1000); $timeout(function () { $scope.ldloading[style.replace('-', '_') + "_progress"] += 0.1; }, 1500); $timeout(function () { $scope.ldloading[style.replace('-', '_') + "_progress"] = false; }, 2000); }; }]);
mchammabc/sites
public/modules/core/controllers/laddaCtrl.js
JavaScript
mit
1,099
from distutils.core import setup, Extension setup( name="tentacle_pi.TSL2561", version="1.0", packages = ["tentacle_pi"], ext_modules = [ Extension("tentacle_pi.TSL2561", sources = ["src/tsl2561.c", "src/tsl2561_ext.c"]) ] )
lexruee/tsl2561
setup.py
Python
mit
237
import React, {PureComponent} from "react"; import "./fill-view.css"; export class FillView extends PureComponent { divRef = null; state = { scale: 1.0 }; setDivRef = (ref) => { this.divRef = ref; }; componentDidMount() { const {percentMargin = 6} = this.props; const adjust = (100 - percentMargin) * 0.01; const {width: contentWidth, height: contentHeight} = this.divRef.getBoundingClientRect(); const {width: parentWidth, height: parentHeight} = this.divRef.parentNode.parentNode.getBoundingClientRect(); const availableWidth = parentWidth * adjust; const availableHeight = parentHeight * adjust; const scale = Math.min(availableWidth / contentWidth, availableHeight / contentHeight); this.setState(() => ({ scale })); } render() { const {children} = this.props; const {scale} = this.state; const contentProps = { ref: this.setDivRef, style: { transform: `scale(${scale})`, } }; return ( <div className="fill-view"> <div {...contentProps}> {children} </div> </div> ) } }
dfbaskin/react-higher-order-components
packages/presentation/src/shared/fill-view.js
JavaScript
mit
1,272
<?php header("Content-type: text/html; charset=utf-8"); if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Matricula extends CI_Controller { public function __construct(){ parent::__construct(); if(!isset($_SESSION['login'])) die("Sesion terminada. <a href='". base_url()."'>Registrarse e ingresar.</a> "); $this->load->model(ventas.'matricula_model'); $this->load->model(ventas.'alumno_model'); $this->load->model(ventas.'actividad_model'); $this->load->model(maestros.'persona_model'); $this->load->model(seguridad.'permiso_model'); $this->load->model(almacen.'curso_model'); $this->load->model(maestros.'ciclo_model'); $this->load->model(maestros.'aula_model'); $this->load->model(maestros.'tipoestudiociclo_model'); $this->load->model(maestros.'local_model'); $this->load->model(ventas.'apertura_model'); $this->load->helper('menu'); $this->configuracion = $this->config->item('conf_pagina'); $this->login = $this->session->userdata('login'); } public function index() { $this->load->view('seguridad/inicio'); } public function listar($j=0){ $filter = new stdClass(); $filter->rol = $this->session->userdata('rolusu'); $filter->order_by = array("m.MENU_Orden"=>"asc"); $menu = get_menu($filter); $filter = new stdClass(); //$filter->order_by = array("c.CICLOP_Codigo"=>"desc","e.PERSC_ApellidoPaterno"=>"asc","e.PERSC_ApellidoMaterno"=>"asc"); $filter_not = new stdClass(); $registros = count($this->matricula_model->listar($filter,$filter_not)); $matricula = $this->matricula_model->listar($filter,$filter_not,$this->configuracion['per_page'],$j); $item = 1; $lista = array(); if(count($matricula)>0){ foreach($matricula as $indice => $value){ $lista[$indice] = new stdClass(); $lista[$indice]->codigo = $value->ORDENP_Codigo; $lista[$indice]->nombres = $value->PERSC_Nombre; $lista[$indice]->paterno = $value->PERSC_ApellidoPaterno; $lista[$indice]->materno = $value->PERSC_ApellidoMaterno; $lista[$indice]->tipoestudio = $value->TIPC_Nombre; $lista[$indice]->ciclo = $value->COMPC_Nombre; $lista[$indice]->aula = $value->AULAC_Nombre; $lista[$indice]->estado = $value->ORDENC_FlagEstado; $lista[$indice]->fechareg = ($value->fechareg); $lista[$indice]->fecha = date_sql($value->ORDENC_Fecot); } } $configuracion = $this->configuracion; $configuracion['base_url'] = base_url()."index.php/ventas/orden/listar"; $configuracion['total_rows'] = $registros; $this->pagination->initialize($configuracion); /*Enviamos los datos a la vista*/ $data['lista'] = $lista; $data['menu'] = $menu; $data['header'] = get_header(); $data['form_open'] = form_open('',array("name"=>"frmPersona","id"=>"frmPersona","onsubmit"=>"return valida_guiain();")); $data['form_close'] = form_close(); $data['j'] = $j; $data['registros'] = $registros; $data['paginacion'] = $this->pagination->create_links(); $this->load->view("ventas/matricula_index",$data); } public function editar($accion,$codigo=""){ $ciclo = $this->input->get_post('ciclo'); $local = $this->input->get_post('local'); $aula = $this->input->get_post('aula'); $user_id = $this->input->get_post('user_id'); $nombres = $this->input->get_post('nombres'); $tipoestudiociclo = $this->input->get_post('tipoestudiociclo'); $lista = new stdClass(); if($accion == "e"){ $filter = new stdClass(); $filter->matricula = $codigo; $orden = $this->matricula_model->obtener($filter); $lista->nombres = $nombres!=""?$nombres:$orden->firstname." ".$orden->lastname; $lista->tipoestudiociclo = $tipoestudio!=""?$tipoestudio:$orden->TIPP_Codigo; $lista->fecha = date_sql($orden->ORDENC_Fecot); $lista->user_id = $user_id!==""?$user_id:$orden->user_id; $lista->matricula = $orden->ORDENP_Codigo; $lista->estado = $orden->ORDENC_FlagEstado; $lista->ciclo = $ciclo!=""?$ciclo:$orden->CICLOP_Codigo; $lista->local = $local!=""?$local:$orden->LOCP_Codigo; $lista->aula = $aula!=""?$aula:$orden->AULAP_Codigo; $filter = new stdClass(); $filter->ciclo = $ciclo; $filter->order_by = array("d.PERSC_ApellidoPaterno"=>"asc","d.PERSC_ApellidoMaterno"=>"asc","d.PERSC_Nombre"=>"asc"); $lista->alumnos = $this->alumno_model->listar($filter); } elseif($accion == "n"){ $lista->apellidos = ""; $lista->nombres = ""; $lista->tipoestudiociclo = $tipoestudiociclo; $lista->fecha = date("d/m/Y",time()); $lista->user_id = $user_id; $lista->matricula = ""; $lista->estado = 1; $lista->ciclo = $ciclo; $lista->local = $local; $lista->aula = $aula; $filter = new stdClass(); $filter->ciclo = $ciclo; $filter->order_by = array("d.PERSC_ApellidoPaterno"=>"asc","d.PERSC_ApellidoMaterno"=>"asc","d.PERSC_Nombre"=>"asc"); $lista->alumnos = $this->alumno_model->seleccionar("0",$filter); } $arrEstado = array("0"=>"::Seleccione::","1"=>"ACTIVO","2"=>"INACTIVO"); $data['titulo'] = $accion=="e"?"Editar Matricula":"Nueva Matricula"; $data['form_open'] = form_open('',array("name"=>"frmPersona","id"=>"frmPersona")); $data['form_close'] = form_close(); $data['lista'] = $lista; $data['accion'] = $accion; $filter = new stdClass(); $filter->ciclo = $lista->ciclo; $data['seltipoestudiociclo'] = form_dropdown('tipoestudiociclo',$this->tipoestudiociclo_model->seleccionar('0',$filter),$lista->tipoestudiociclo,"id='tipoestudiociclo' class='comboMedio'"); $filter2 = new stdClass(); $filter2->local = $lista->local; $filter2->ciclo = $lista->local; $filter2->tipoestudiociclo = $lista->tipoestudiociclo; $data['selaula'] = form_dropdown('apertura',$this->apertura_model->seleccionar('0',$filter2),$lista->aula,"id='apertura' class='comboMedio'"); $data['selciclo'] = form_dropdown('ciclo',$this->ciclo_model->seleccionar('0'),$lista->ciclo,"id='ciclo' class='comboMedio'"); $data['sellocal'] = form_dropdown('local',$this->local_model->seleccionar('0'),$lista->local,"id='local' class='comboMedio'"); $data['selestado'] = form_dropdown('estado',$arrEstado,$lista->estado,"id='estado' class='comboMedio'"); $data['selalum_total'] = form_multiselect('alum_total[]',$lista->alumnos,$lista->estado,"id='alum_total' class='comboMultipleGrande'"); $data['selalum_matri'] = form_multiselect('alum_matriculados[]',array(),$lista->estado,"id='alum_matriculados' class='comboMultipleGrande'"); $data['oculto'] = form_hidden(array("accion"=>$accion,"codigo"=>$codigo)); $this->load->view("ventas/matricula_nuevo",$data); } public function grabar(){ $accion = $this->input->get_post('accion'); $codigo = $this->input->get_post('codigo'); $data = array( "CICLOP_Codigo" => $this->input->post('ciclo'), "CLIP_Codigo" => $this->input->post('alumno'), "AULAP_Codigo" => $this->input->post('aula'), "TIPP_Codigo" => $this->input->post('tipoestudio'), "ORDENC_Fecot" => date_sql_ret($this->input->post('fecha')), "ORDENC_FlagEstado" => $this->input->post('estado'), "ORDENC_FechaModificacion" => date("Y-m-d",time()) ); $resultado = false; $filter = new stdClass(); $filter->cliente = $this->input->post('alumno'); $filter->curso = $this->input->post('curso'); $ordenes = $this->matricula_model->listar($filter); if($accion == "n"){ if(count($ordenes)==0){ $resultado = true; $this->matricula_model->insertar($data); } } elseif($accion == "e"){ if(count($ordenes)==0){ $resultado = true; $this->matricula_model->modificar($codigo,$data); } else{ $numero = $ordenes[0]->ORDENP_Codigo; if($numero==$this->input->post('matricula')){ $resultado = true; $this->matricula_model->modificar($codigo,$data); } } } echo json_encode($resultado); } public function eliminar(){ $codigo = $this->input->post('codigo'); $filter = new stdClass(); $filter->orden = $codigo; $actividades = $this->actividad_model->listar($filter); $resultado = false; if(count($actividades)==0){ $this->matricula_model->eliminar($codigo); $resultado = true; } echo json_encode($resultado); } public function ver($codigo){ $filter = new stdClass(); $filter->orden = $codigo; $ordenes = $this->matricula_model->obtener($filter); $codproducto = $ordenes->PROD_Codigo; $codcliente = $ordenes->CLIP_Codigo; $filter = new stdClass(); $filter->cliente = $codcliente; $clientes = $this->alumno_model->obtener($filter); $filter = new stdClass(); $filter->curso = $codproducto; $productos = $this->curso_model->obtener($filter); $this->load->library("fpdf/pdf"); $CI = & get_instance(); $CI->pdf->FPDF('P'); $CI->pdf->AliasNbPages(); $CI->pdf->AddPage(); $CI->pdf->SetTextColor(0,0,0); $CI->pdf->SetFillColor(216,216,216); $CI->pdf->SetFont('Arial','B',11); $CI->pdf->Image('img/puertosaber.jpg',10,8,10); $CI->pdf->Cell(0,13,"MATRICULA Nro ".$ordenes->ORDENC_Numero,0,1,"C",0); $CI->pdf->SetFont('Arial','B',7); $CI->pdf->Cell(120,10, "" ,0,1,"L",0); $CI->pdf->Cell(90,5, "CURSO : " ,1,0,"L",0); $CI->pdf->Cell(1,1, "" ,0,0,"L",0); $CI->pdf->Cell(90,5,$productos->PROD_Nombre,1,1,"L",0); $CI->pdf->Cell(90,1, "" ,0,1,"L",0); $CI->pdf->Cell(90,5, "APELLIDOS Y NOMBRES: " ,1,0,"L",0); $CI->pdf->Cell(1,1, "" ,0,0,"L",0); $CI->pdf->Cell(90,5,$clientes->PERSC_ApellidoPaterno." ".$clientes->PERSC_ApellidoMaterno.", ".$clientes->PERSC_Nombre,1,1,"L",0); $CI->pdf->Cell(90,1, "" ,0,1,"L",0); $CI->pdf->Cell(90,5, "USUARIO: " ,1,0,"L",0); $CI->pdf->Cell(1,1, "" ,0,0,"L",0); $CI->pdf->Cell(90,5,$ordenes->ORDENC_Usuario ,1,1,"L",0); $CI->pdf->Cell(90,1, "" ,0,1,"L",0); $CI->pdf->Cell(90,5, "CLAVE: " ,1,0,"L",0); $CI->pdf->Cell(1,1,$ordenes->ORDENC_Password,0,0,"L",0); $CI->pdf->Cell(90,5, "" ,1,1,"L",0); $CI->pdf->Cell(90,1, "" ,0,1,"L",0); $CI->pdf->Cell(90,5, "RESPONSABLE: " ,1,0,"L",0); $CI->pdf->Cell(1,1, "" ,0,0,"L",0); $CI->pdf->Cell(90,5, "" ,1,1,"L",0); $CI->pdf->Cell(90,1, "" ,0,1,"L",0); $CI->pdf->SetTextColor(0,0,0); $CI->pdf->SetFillColor(255,255,255); $CI->pdf->Cell(181,5, "OBSERVACION : " ,0,1,"L",1); $CI->pdf->Cell(181,5,$ordenes->ORDENC_Observacion,1,1,"L",1); $CI->pdf->Output(); } public function buscar($n=""){ $tipo = $this->input->get_post('tipo'); $ot = $this->input->get_post('ot'); $rsocial = $this->input->get_post('rsocial'); $filter = new stdClass(); $filter->anio = date('Y',time()); $filter->tipo = "OT"; $tipoots = $this->tipoot_model->listar($filter); if($tipo=='') $tipo = isset($tipoots->cod_argumento)?$tipoots->cod_argumento:""; $fila = ""; $filter = new stdClass(); $filter->tipoot = $tipo; if($ot!='') $filter->nroot = $ot; if($rsocial!='') $filter->codcliente = $rsocial; if($tipo=="04") $filter->estado = "P"; $ots = $this->ot_model->listarg($filter,array('ot.nroOt'=>'asc')); $tipoOt = form_dropdown('tipo',$this->tipoot_model->seleccionar('',''),$tipo,"id='tipo' class='comboMedio' onchange='busca_tipoOt();'"); if(count($ots)>0){ foreach($ots as $indice=>$value){ $nroot = $value->NroOt; $site = $value->DirOt; $codcli = $value->CodCli; $codot = $value->CodOt; $finot = $value->FinOt; $ftermino = $value->FteOt; $razon_social = $tipo=='04'?$site:$value->razcli; // quitar esto { $finot_envia = $tipo=='04'?date("d/m/Y",time()):$value->FinOt; // } $fila .= "<tr title='Fecha Termino: ".$ftermino."' id='".$codot."' id2='".$tipo."' id3='".$finot."' onclick='listadoot(this);'>"; $fila .= "<td style='width:10%;' align='center'><p class='listadoot'>".$nroot."</p></td>"; $fila .= "<td style='width:35%;' align='left'><p class='listadoot'>".$site."</p></td>"; $fila .= "<td style='width:12%;' align='left'><p class='listadoot'>".$finot."</p></td>"; $fila .= "<td style='width:12%;' align='left'><p class='listadoot'>".$ftermino."</p></td>"; $fila .= "<td style='width:31%;' align='left'><p class='listadoot'>".$razon_social."</p></td>"; $fila .= "</tr>"; } } else{ $fila.="<tr>"; $fila.="<td colspan='3'>NO EXISTEN RESULTADOS</td>"; $fila.="</tr>"; } $data['ot'] = $ot; $data['n'] = $n; $data['fila'] = $fila; $data['tipoot'] = $tipoOt; $data['rsocial'] = $rsocial; $this->load->view(ventas."ot_buscar",$data); } // public function obtener_tipOt($tipoOt){ // $this->load->model(maestros.'tipoot_model'); // $tipoOt = $this->tipoot_model->obtener($tipoOt); // echo json_encode($tipoOt); // } public function export_excel($type) { if($this->session->userdata('data_'.$type)){ $result = $this->session->userdata('data_'.$type); $arr_columns = array(); switch ($type) { case 'listar_requisiciones_ot': $this->reports_model->rpt_general('rpt_'.$type, 'REQUISICIONES POR OT', $result["columns"], $result["rows"],$result["group"]); break; case 'listar_control_pesos1': case 'listar_control_pesos2': case 'listar_control_pesos3': case 'listar_control_pesos4': case 'listar_control_pesos5': case 'listar_control_pesos': $arr_export_detalle = array(); $arr_columns[]['STRING'] = 'NRO.OT'; $arr_columns[]['STRING'] = 'NOMBRE'; $arr_columns[]['STRING'] = 'PROYECTO'; $arr_columns[]['STRING'] = 'TIPO PRODUCTO'; $arr_columns[]['DATE'] = 'F.INICIO'; $arr_columns[]['DATE'] = 'F.TERMINO'; $arr_columns[]['NUMERIC'] = 'W.REQUISICION'; $arr_columns[]['NUMERIC'] = 'W.PPTO.'; //$arr_columns[]['NUMERIC'] = 'W.METRADO'; $arr_columns[]['NUMERIC'] = 'W.O.TECNICA'; $arr_columns[]['NUMERIC'] = 'W.GALVANIZADO'; $arr_columns[]['NUMERIC'] = 'W.PRODUCCION'; $arr_columns[]['NUMERIC'] = 'W.ALMACEN'; $arr_group = array(); $this->reports_model->rpt_general('rpt_'.$type,'Control de pesos',$arr_columns,$result["rows"],$arr_group); break; case'productos_x_ot': $arr_export_detalle = array(); $arr_columns[]['STRING'] = 'NRO.OT'; $arr_columns[]['STRING'] = 'T.TORRE'; $arr_columns[]['STRING'] = 'CODIGO'; $arr_columns[]['STRING'] = 'FAMILIA'; $arr_columns[]['STRING'] = 'DESCRIPCION'; $arr_columns[]['NUMERIC'] = 'INGRESO'; $arr_columns[]['NUMERIC'] = 'SALIDA'; $arr_columns[]['NUMERIC'] = 'SALDO'; $arr_columns[]['NUMERIC'] = 'INGRESO'; $arr_columns[]['NUMERIC'] = 'SALIDA'; $arr_columns[]['NUMERIC'] = 'SALDO'; $arr_group = array('E5:G5'=>'CANTIDAD','H5:K5'=>'MONTO'); $arr_group = array(); $this->reports_model->rpt_general('rpt_'.$type,'pRODUCTOS POR OT',$arr_columns,$result["rows"],$arr_group); break; } }else{ echo "<div style='color:rgb(150,150,150);padding:10px;width:560px;height:160px;border:1px solid rgb(210,210,210);'> No hay datos para exportar </div>"; } } }
ccjuantrujillo/cepreadm
application/controllers/ventas/matricula.php
PHP
mit
18,373
#include "Pch.h" #include "EngineCore.h" #include "GetTextDialog.h" #include "KeyStates.h" //----------------------------------------------------------------------------- GetTextDialog* GetTextDialog::self; //================================================================================================= GetTextDialog::GetTextDialog(const DialogInfo& info) : DialogBox(info), singleline(true) { } //================================================================================================= void GetTextDialog::Draw(ControlDrawData* cdd/* =nullptr */) { GUI.DrawSpriteFull(tBackground, Color::Alpha(128)); GUI.DrawItem(tDialog, global_pos, size, Color::Alpha(222), 16); for(int i = 0; i < 2; ++i) bts[i].Draw(); Rect r = { global_pos.x + 16,global_pos.y + 16,global_pos.x + size.x,global_pos.y + size.y }; GUI.DrawText(GUI.default_font, text, DTF_CENTER, Color::Black, r); textBox.Draw(); } //================================================================================================= void GetTextDialog::Update(float dt) { textBox.mouse_focus = focus; if(Key.Focus() && focus) { for(int i = 0; i < 2; ++i) { bts[i].mouse_focus = focus; bts[i].Update(dt); if(result != -1) goto got_result; } textBox.focus = true; textBox.Update(dt); if(textBox.GetText().empty()) bts[1].state = Button::DISABLED; else if(bts[1].state == Button::DISABLED) bts[1].state = Button::NONE; if(result == -1) { if(Key.PressedRelease(VK_ESCAPE)) result = BUTTON_CANCEL; else if(Key.PressedRelease(VK_RETURN)) { if(!textBox.IsMultiline() || Key.Down(VK_SHIFT)) { Key.SetState(VK_RETURN, IS_UP); result = BUTTON_OK; } } } if(result != -1) { got_result: if(result == BUTTON_OK) *input = textBox.GetText(); GUI.CloseDialog(this); if(event) event(result); } } } //================================================================================================= void GetTextDialog::Event(GuiEvent e) { if(e == GuiEvent_GainFocus) { textBox.focus = true; textBox.Event(GuiEvent_GainFocus); } else if(e == GuiEvent_LostFocus || e == GuiEvent_Close) { textBox.focus = false; textBox.Event(GuiEvent_LostFocus); } else if(e == GuiEvent_WindowResize) { self->pos = self->global_pos = (GUI.wnd_size - self->size) / 2; self->bts[0].global_pos = self->bts[0].pos + self->global_pos; self->bts[1].global_pos = self->bts[1].pos + self->global_pos; self->textBox.global_pos = self->textBox.pos + self->global_pos; } else if(e >= GuiEvent_Custom) { if(e == Result_Ok) result = BUTTON_OK; else if(e == Result_Cancel) result = BUTTON_CANCEL; } } //================================================================================================= GetTextDialog* GetTextDialog::Show(const GetTextDialogParams& params) { if(!self) { DialogInfo info; info.event = nullptr; info.name = "GetTextDialog"; info.parent = nullptr; info.pause = false; info.order = ORDER_NORMAL; info.type = DIALOG_CUSTOM; self = new GetTextDialog(info); self->bts.resize(2); Button& bt1 = self->bts[0], &bt2 = self->bts[1]; bt1.id = Result_Cancel; bt1.size = Int2(100, 40); bt1.parent = self; bt2.id = Result_Ok; bt2.size = Int2(100, 40); bt2.parent = self; self->textBox.pos = Int2(25, 60); } self->Create(params); GUI.ShowDialog(self); return self; } //================================================================================================= void GetTextDialog::Create(const GetTextDialogParams& params) { Button& bt1 = bts[0], &bt2 = bts[1]; int lines = params.lines; if(!params.multiline || params.lines < 1) lines = 1; size = Int2(params.width, 180 + lines * 20); textBox.size = Int2(params.width - 50, 15 + lines * 20); textBox.SetMultiline(params.multiline); textBox.limit = params.limit; textBox.SetText(params.input->c_str()); // ustaw przyciski bt1.pos = Int2(size.x - 100 - 16, size.y - 40 - 16); bt2.pos = Int2(16, size.y - 40 - 16); if(params.custom_names) { bt1.text = (params.custom_names[0] ? params.custom_names[0] : GUI.txCancel); bt2.text = (params.custom_names[1] ? params.custom_names[1] : GUI.txOk); } else { bt1.text = GUI.txCancel; bt2.text = GUI.txOk; } // ustaw parametry result = -1; parent = params.parent; order = parent ? static_cast<DialogBox*>(parent)->order : ORDER_NORMAL; event = params.event; text = params.text; input = params.input; // ustaw pozycjê pos = global_pos = (GUI.wnd_size - size) / 2; bt1.global_pos = bt1.pos + global_pos; bt2.global_pos = bt2.pos + global_pos; textBox.global_pos = textBox.pos + global_pos; }
lcs2/carpg
project/source/engine/gui/GetTextDialog.cpp
C++
mit
4,677
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { currentURL, visit, fillIn, click } from '@ember/test-helpers'; import hasEmberVersion from 'ember-test-helpers/has-ember-version'; import Pretender from 'pretender'; import { invalidateSession, authenticateSession, currentSession } from 'ember-simple-auth/test-support'; import config from '../../config/environment'; module('Acceptance: Authentication', function(hooks) { setupApplicationTest(hooks); let server; hooks.afterEach(function() { if (server) { server.shutdown(); } }); test('logging in with correct credentials works', async function(assert) { server = new Pretender(function() { this.post(`${config.apiHost}/token`, () => [200, { 'Content-Type': 'application/json' }, '{ "access_token": "secret token!", "account_id": 1 }']); this.get(`${config.apiHost}/accounts/1`, () => [200, { 'Content-Type': 'application/json' }, '{ "data": { "type": "accounts", "id": "1", "attributes": { "login": "letme", "name": "Some person" } } }']); }); await invalidateSession(); await visit('/login'); await fillIn('[data-test-identification]', 'identification'); await fillIn('[data-test-password]', 'password'); await click('button[type="submit"]'); assert.equal(currentURL(), '/'); }); test('logging in with incorrect credentials shows an error', async function(assert) { server = new Pretender(function() { this.post(`${config.apiHost}/token`, () => [400, { 'Content-Type': 'application/json' }, '{ "error": "invalid_grant" }']); }); await invalidateSession(); await visit('/login'); await fillIn('[data-test-identification]', 'identification'); await fillIn('[data-test-password]', 'wrong-password!'); await click('button[type="submit"]'); assert.equal(currentURL(), '/login'); assert.ok(document.querySelector('[data-test-error-message]')); }); module('the protected route', function() { if (!hasEmberVersion(2, 4)) { // guard against running test module on unsupported version (before 2.4) return; } test('cannot be visited when the session is not authenticated', async function(assert) { await invalidateSession(); await visit('/protected'); assert.equal(currentURL(), '/login'); }); test('can be visited when the session is authenticated', async function(assert) { server = new Pretender(function() { this.get(`${config.apiHost}/posts`, () => [200, { 'Content-Type': 'application/json' }, '{"data":[]}']); }); await authenticateSession({ userId: 1, otherData: 'some-data' }); await visit('/protected'); let session = currentSession(); assert.equal(currentURL(), '/protected'); assert.equal(session.get('data.authenticated.userId'), 1); assert.equal(session.get('data.authenticated.otherData'), 'some-data'); }); }); module('the protected route in the engine', function() { test('cannot be visited when the session is not authenticated', async function(assert) { await invalidateSession(); await visit('/engine'); assert.equal(currentURL(), '/login'); }); test('can be visited when the session is authenticated', async function(assert) { server = new Pretender(function() { this.get(`${config.apiHost}/posts`, () => [200, { 'Content-Type': 'application/json' }, '{"data":[]}']); }); await authenticateSession({ userId: 1, otherData: 'some-data' }); await visit('/engine'); assert.equal(currentURL(), '/engine'); let session = currentSession(); assert.equal(session.get('data.authenticated.userId'), 1); assert.equal(session.get('data.authenticated.otherData'), 'some-data'); }); test('can invalidate the session', async function(assert) { server = new Pretender(function() { this.get(`${config.apiHost}/posts`, () => [200, { 'Content-Type': 'application/json' }, '{"data":[]}']); }); await authenticateSession({ userId: 1, otherData: 'some-data' }); await visit('/engine'); await click('[data-test-logout-button]'); let session = currentSession(); assert.notOk(session.get('isAuthenticated')); }); }); module('the login route', function() { if (!hasEmberVersion(2, 4)) { // guard against running test module on unsupported version (before 2.4) return; } test('can be visited when the session is not authenticated', async function(assert) { await invalidateSession(); await visit('/login'); assert.equal(currentURL(), '/login'); }); test('cannot be visited when the session is authenticated', async function(assert) { await authenticateSession(); await visit('/login'); assert.equal(currentURL(), '/'); }); }); });
simplabs/ember-simple-auth
packages/classic-test-app/tests/acceptance/authentication-test.js
JavaScript
mit
4,913
import * as React from 'react'; import {SvgIconProps} from '../../SvgIcon'; export default function SpeakerNotes(props: SvgIconProps): React.ReactElement<SvgIconProps>;
mattiamanzati/typings-material-ui
svg-icons/action/speaker-notes.d.ts
TypeScript
mit
170
require 'ostruct' module AmberbitConfig # Main class that holds whole configuration, acts as open struct, with few tune ups class HashStruct < ::OpenStruct # Initialize with check for conflicts within hash keys def initialize(hash = nil) check_hash_for_conflicts hash if hash super end # Adds access to existing keys through hash operator def [](key) self.send key unless key == nil end # Generates a nested Hash object which is a copy of existing configuration def to_hash _copy = {} @table.each { |key, value| _copy[key] = value.is_a?(HashStruct) ? value.to_hash : value } _copy end # Raise an error if method/configuration isn't set yet. It should prevent typos, because normally it will just # return a nil. With this check you can spot those earlier. def method_missing(method, *args, &block) if method =~ /=\z/ || self.respond_to?(method) super else raise ConfigNotSetError, "Configuration option: '#{method}' was not set" end end # Creates a deeply nested HashStruct from hash. def self.create(object) case object when Array object.map { |item| create(item) } when Hash mapped = {} object.each { |key, value| mapped[key] = create(value) } HashStruct.new mapped else object end end private # Checks if provided option is a hash and if the keys are not in confict with OpenStruct public methods. def check_hash_for_conflicts(hash) raise HashArgumentError, 'It must be a hash' unless hash.is_a?(Hash) unless (conflicts = self.public_methods & hash.keys.map(&:to_sym)).empty? raise HashArgumentError, "Rename keys in order to avoid conflicts with internal calls: #{conflicts.join(', ')}" end end end end
amberbit/amberbit-config
lib/amberbit-config/hash_struct.rb
Ruby
mit
1,867
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::RecoveryServicesBackup::Mgmt::V2019_05_13 module Models # # Yearly retention schedule. # class YearlyRetentionSchedule include MsRestAzure # @return [RetentionScheduleFormat] Retention schedule format for yearly # retention policy. Possible values include: 'Invalid', 'Daily', 'Weekly' attr_accessor :retention_schedule_format_type # @return [Array<MonthOfYear>] List of months of year of yearly retention # policy. attr_accessor :months_of_year # @return [DailyRetentionFormat] Daily retention format for yearly # retention policy. attr_accessor :retention_schedule_daily # @return [WeeklyRetentionFormat] Weekly retention format for yearly # retention policy. attr_accessor :retention_schedule_weekly # @return [Array<DateTime>] Retention times of retention policy. attr_accessor :retention_times # @return [RetentionDuration] Retention duration of retention Policy. attr_accessor :retention_duration # # Mapper for YearlyRetentionSchedule class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'YearlyRetentionSchedule', type: { name: 'Composite', class_name: 'YearlyRetentionSchedule', model_properties: { retention_schedule_format_type: { client_side_validation: true, required: false, serialized_name: 'retentionScheduleFormatType', type: { name: 'String' } }, months_of_year: { client_side_validation: true, required: false, serialized_name: 'monthsOfYear', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'MonthOfYearElementType', type: { name: 'Enum', module: 'MonthOfYear' } } } }, retention_schedule_daily: { client_side_validation: true, required: false, serialized_name: 'retentionScheduleDaily', type: { name: 'Composite', class_name: 'DailyRetentionFormat' } }, retention_schedule_weekly: { client_side_validation: true, required: false, serialized_name: 'retentionScheduleWeekly', type: { name: 'Composite', class_name: 'WeeklyRetentionFormat' } }, retention_times: { client_side_validation: true, required: false, serialized_name: 'retentionTimes', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'DateTimeElementType', type: { name: 'DateTime' } } } }, retention_duration: { client_side_validation: true, required: false, serialized_name: 'retentionDuration', type: { name: 'Composite', class_name: 'RetentionDuration' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_recovery_services_backup/lib/2019-05-13/generated/azure_mgmt_recovery_services_backup/models/yearly_retention_schedule.rb
Ruby
mit
4,112
<?php /** * Created by PhpStorm. * User: lenovo * Date: 02/08/2016 * Time: 16.37 */ class News_m extends CI_Model{ function m_get_news($limit=null,$offset=null){ if($limit!==null && $offset !== null){ $this->db->limit($limit,$offset); } if(isset($_GET["id"])) { return $this->db->order_by("date_created","desc") ->where("news_category_id", $_GET["id"]) ->get("sc_news") ->result_array(); } return $this->db->order_by("date_created","desc") ->get("sc_news") ->result_array(); } function m_get_news_by_id($news_id){ return $this->db->where("news_id",$news_id) ->get("sc_news")->row_array(); } function m_get_detail($id) { return $this->db->where("news_id", $id) ->from("sc_news") ->join("sc_news_category", "sc_news.news_category_id = sc_news_category.news_category_id") ->get()->row_array(); } function m_get_category() { return $this->db->get("sc_news_category")->result_array(); } } //asdn
Calvinn097/servermedan
application/models/MAIN/News_m.php
PHP
mit
1,108
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("ExtractEmails")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExtractEmails")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("06f60f4e-3cf1-432e-b0e8-edf4c7631b37")] // 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")]
zdzdz/CSharp-Part-2-Homeworks
06. Strings-And-Text-Processing-HW/ExtractEmails/Properties/AssemblyInfo.cs
C#
mit
1,402
from flask import Flask, jsonify, request, redirect, url_for import subprocess import os import json from cross_domain import * app = Flask(__name__) ALLOWED_EXTENSIONS = set(['mol', 'smi']) try: TARGET = os.environ['TARGET'] except Exception: print 'export TARGET=<path to data>' exit(1) try: AlGDock = os.environ['AlGDock_Pref'] except Exception: print 'export AlGDock_Pref=<path to BindingPMF_arguments.py>' exit(1) import sys sys.path.insert(0, AlGDock) from BindingPMF_arguments import * #File system functions @app.route('/api/v1.0/proteins', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_protein_names(): proteins = os.walk(TARGET).next()[1] protein_lst = [{"filename": protein} for protein in sorted(proteins) if protein != "scripts"] return jsonify({"files": protein_lst}) @app.route('/api/v1.0/ligands/<protein>', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_ligand_names(protein): ligands = os.walk(os.path.join(TARGET, protein, "ligand")).next()[2] ligand_lst = [{"filename": ligand} for ligand in sorted(ligands) if ".ism" in ligand] return jsonify({"files": ligand_lst}) @app.route('/api/v1.0/ligandSelection/<protein>/<library>', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_ligand_selections(protein, library): trimmed_library = library.split(".ism")[0] + ".A__" try: ligand_selections = sorted(os.walk(os.path.join(TARGET, protein, "AlGDock/cool", trimmed_library)).next()[1]) except Exception: ligand_selections = None return jsonify({"ligandSelections": ligand_selections}) @app.route('/api/v1.0/ligandLine/<protein>/<library>/<lineNumber>', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_ligand_line(protein, library, lineNumber): try: path = os.path.join(TARGET, protein, "ligand", library) library_f = open(path, 'r') for i, line in enumerate(library_f): if i == int(lineNumber) - 1: return line.split()[0] library_f.close() except Exception: return None @app.route('/api/v1.0/addToLibrary/<protein>/', methods=['POST', 'OPTIONS']) @crossdomain(origin='*') def add_to_library(protein): fileJson = request.get_json() libraryName = fileJson["libraryName"] smiles = fileJson["smiles"] path = os.path.join(TARGET, protein, "ligand", libraryName) library_f = open(path, 'a') library_f.write(smiles) library_f.write("\n") library_f.close() return "Added ligand to library." #Gets for preference dropdowns @app.route('/api/v1.0/protocols', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_protocols(): choices = arguments['protocol']['choices'] choice_lst = [{"choice": choice} for choice in choices] return jsonify({"protocol": choice_lst}) @app.route('/api/v1.0/samplers', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_samplers(): choices = arguments['sampler']['choices'] choice_lst = [{"choice": choice} for choice in choices] return jsonify({"sampler": choice_lst}) @app.route('/api/v1.0/sites', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_sites(): choices = arguments['site']['choices'] choice_lst = [{"choice": choice} for choice in choices] return jsonify({"site": choice_lst}) @app.route('/api/v1.0/phases', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_phases(): choices = allowed_phases choice_lst = [{"choice": choice} for choice in choices] return jsonify({"phase": choice_lst}) @app.route('/api/v1.0/runtypes', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def get_runtype(): choices = arguments['run_type']['choices'] choice_lst = [{"choice": choice} for choice in choices] return jsonify({"runtype": choice_lst}) #Saving preferences file @app.route('/api/v1.0/run/<protein>/<protocol>/<runtype>/<cthermspeed>/<dthermspeed>/<sampler>/<mcmc>/<seedsperstate>/<stepsperseed>/<sweepspercycle>/<attemptspersweep>/<stepspersweep>/<crepxcycles>/<drepxcycles>/<site>/<sxcenter>/<sycenter>/<szcenter>/<sradius>/<sdensity>/<phase>/<cores>/<score>/<from_reps>/<to_reps>/<rmsd>', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def save_preferences(protein, protocol, runtype, cthermspeed, dthermspeed, sampler, mcmc, seedsperstate, stepsperseed, sweepspercycle, attemptspersweep, stepspersweep, crepxcycles, drepxcycles, site, sxcenter, sycenter, szcenter, sradius, sdensity, phase, cores, score, from_reps, to_reps, rmsd): rmsd_n = " " score_n = " " if rmsd == "false": rmsd_n = "#" if score == "Score" or score == "None": score_n = "#" args = ["./create_saved_args.sh", runtype, protocol, cthermspeed, dthermspeed, sampler, mcmc, seedsperstate, stepsperseed, sweepspercycle, attemptspersweep, stepspersweep, crepxcycles, drepxcycles, site, sxcenter, sycenter, szcenter, sradius, sdensity, phase, cores, score, from_reps, to_reps, rmsd, score_n, rmsd_n] p = subprocess.Popen(args, stdout=subprocess.PIPE) f = open(os.path.join(TARGET, protein, "AlGDock/saved_arguments.py"), 'w') f.write(p.stdout.read()) f.close() return "Preferences File Saved" #Run button @app.route('/api/v1.0/run/<protein>/<ligand>/<email>', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def run(protein, ligand, email): run_string = "python " + os.path.join(AlGDock, "../Pipeline/run_anchor_and_grow.py") + " --max_jobs 20 --email " + email + " --ligand " + os.path.join(TARGET, protein, "ligand/dock_in", ligand.split(".ism")[0] + ".A__") os.chdir(os.path.join(TARGET, protein, "dock6")) print run_string os.system(run_string) return "Job Sent to Cluster" #Prepare ligands button @app.route('/api/v1.0/prepLigandLibrary/<protein>/<ligand>/<email>', methods=['GET', 'OPTIONS']) @crossdomain(origin='*') def prepareLigandLibrary(protein, ligand, email): run_string = "python " + os.path.join(AlGDock, "../Pipeline/run_prep_ligand_for_dock.py") + " " + ligand + " --email " + email os.chdir(os.path.join(TARGET, protein, "ligand")) print run_string os.system(run_string) return "Ligand is being prepared." if __name__ == '__main__': app.run(debug=True)
gkumar7/AlGDock
gui/api/REST.py
Python
mit
6,256
const crypto = require('crypto'); const passwordHashAlgorithm = 'sha1'; module.exports = function(client) { var computeSHA1 = function(str) { return crypto.createHash(passwordHashAlgorithm).update(str).digest('hex'); }; var user = { addUser: function(email, password, callback) { client.incr('global:userId', function(error, id) { if(error) { callback(false); return; }; id --; console.log('Dodaje user z id ' + id); client.setnx('user:' + email + ':id', id, function(error, set) { if (error) { console.log('Error ' + error); callback(false); return; }; console.log('Set ' + set); if (set == 0) { callback(false, 'User ' + email + ' is registred'); return; }; client .multi() .set('user:'+id+':email', email) .set('user:' + id + ':password', computeSHA1(password)) .exec(function(error, results) { if (error) { callback(false); return; }; callback(true); return; }); }); }); }, getUserWithEmail: function(email, callback) { client.get('user:' + email.toLowerCase() + ':id', function(error,id) { if(error) { callback(null); return; } if (id == null) { callback(null); return; } user.getUserWithId(id, callback); }); }, getUserWithId: function(id, callback) { client .multi() .get('user:' + id + ':email') .exec(function(error, results) { if (error) { callback(null); return; } callback({ id: id, email: results[0] }); }); }, validateUser: function(email, password, callback) { user.getUserWithEmail(email, function(user) { if(user == null) { callback(false); return; } client.get('user:' + user.id + ':password', function(error, passwordF) { if(error) { callback(false); return; } callback(computeSHA1(password) == passwordF); }); }); }, }; return user; }; // //user.addUser('test2@o2.pl', 'test', function(result, msg) { // if(result) { // console.log('jest ok'); // } else { // console.log('Error: ' + msg); // } //}); // //user.validateUser('test3@o2.pl', 'test', function(result) { // console.log('Validate: ' + result); //}); // client.set("string key", "string val", redis.print); // client.hset("hash key", "hashtest 1", "some value", redis.print); // client.hset(["hash key", "hashtest 2", "some other value"], redis.print); // client.hkeys("hash key", function (err, replies) { // console.log(replies.length + " replies:"); // replies.forEach(function (reply, i) { // console.log(" " + i + ": " + reply); // }); // client.quit(); // });
yoman07/GeoChatServer
db.js
JavaScript
mit
3,170
const { validateLocaleId } = require(".."); describe("validateLocaleId", () => { it("validateLocaleId", () => { validateLocaleId("en").should.eql(true); validateLocaleId(null).should.eql(true); }); });
node-opcua/node-opcua
packages/node-opcua-basic-types/test/test_locale_id.js
JavaScript
mit
227
var Q = require('q'); /* ** @param [object | array] object: is the object that needs to be iterated, can be an Object or an array @param [integer] index: is the index of argument obtained from the object element and to be added to asyncFunc arguments, starting from 1 @param [function] asyncFunc: is the asynchronous function that needs to be called at every iteration. ** */ var iterate = function(object, index, asyncFunc /* 1...n args */){ var item = null; var args = Array.prototype.slice.call(arguments, 3); if(Object.prototype.toString.call(object) === "[object Array]"){ asyncIterateArray(object, 0, asyncFunc, args, index); }else if(Object.prototype.toString.call(object) === "[object Object]"){ asyncIterateObjectKeys(object, 0, asyncFunc, args, index); } } function asyncIterateObjectKeys(object, i, func, args, index){ var keys = Object.keys(object); if( i < keys.length){ var tmpargs = args.slice(); tmpargs.splice(index - 1, 0, object[keys[i]]); Q.fcall(asyncRun, func, tmpargs) .then(function() { asyncIterateObjectKeys(object, i = i+ 1, func, args, index); }) .catch(function(err){ console.log(err); }); } } function asyncIterateArray(object, i, func, args, index){ if(i < object.length){ var tmpargs = args.slice(); tmpargs.splice(index - 1, 0, object[i]); Q.fcall(asyncRun, func, tmpargs) .then(function() { asyncIterateArray(object, i = i+ 1, func, args, index); }) .catch(function(err){ console.log(err); }); } } function asyncRun(asyncFunc, args){ var def = Q.defer(); Q.fcall(function(){ return asyncFunc.apply(this, args) }) .then(function(ret){ def.resolve(ret); }) .catch(function(err){ def.reject(err); }); return def.promise; } module.exports = iterate;
m-arch/for-async
index.js
JavaScript
mit
1,825
package name.reidmiller.iesoreports.client; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import ca.ieso.reports.schema.nislshadowprices.DocBody; import ca.ieso.reports.schema.nislshadowprices.DocHeader; import ca.ieso.reports.schema.nislshadowprices.Document; public class NetInterchangeSchedulingLimitClient extends DailyReportClient { private Logger logger = LogManager.getLogger(this.getClass()); public NetInterchangeSchedulingLimitClient(String defaultUrlString, String jaxb2ContextPath) { super.setDefaultUrlString(defaultUrlString); super.setJaxb2ContextPath(jaxb2ContextPath); } /** * Unmarshals XML text from {@link #getDefaultUrlString()} into a * {@link Document} using JAXB2. This method is a wrapper around * {@link #getDocument(String)}. * * @return {@link Document} * @throws MalformedURLException * @throws IOException * */ public Document getDefaultDocument() throws MalformedURLException, IOException, ClassCastException { return this.getDocument(super.getDefaultUrlString()); } /** * This method uses {@link #getDefaultUrlString()} to request the current * (default) {@link DocBody}. * * @return {@link DocBody} for the current (default) report. * @throws MalformedURLException * * @throws IOException */ public DocBody getDefaultDocBody() throws MalformedURLException, IOException { Document document = this.getDefaultDocument(); return this.getDocBody(document); } /** * This method uses {@link #getDefaultUrlString()} to request the current * (default) {@link DocHeader}. * * @return {@link DocHeader} for the current (default) report. * @throws MalformedURLException * @throws IOException */ public DocHeader getDefaultDocHeader() throws MalformedURLException, IOException { Document document = this.getDefaultDocument(); return this.getDocHeader(document); } /** * Returns only the {@link DocBody} portion of the {@link Document}. * * @param document * {@link Document} comprised of two parts: {@link DocHeader} and * {@link DocBody}. * @return {@link DocBody} */ public DocBody getDocBody(Document document) { List<Object> docHeaderAndDocBody = document.getDocHeaderAndDocBody(); return super.getDocPart(docHeaderAndDocBody, DocBody.class); } /** * Get a {@link DocBody} for a date in past. * * @param historyDate * Date in the past that a report is being requested for. * @return Returns the {@link DocBody} of a past report. * @throws MalformedURLException * @throws IOException */ public DocBody getDocBodyForDate(Date historyDate) throws MalformedURLException, IOException { Document document = super.getDocumentForDate(historyDate, Document.class); return this.getDocBody(document); } /** * Makes a request for each Date in the provided range (inclusive) building * out a {@link List} of {@link DocBody} objects. * * @param startDate * Start point (inclusive) of the date range (ie. date furthest * in the past). * @param endDate * End point (inclusive) of the date range (ie. date closest to * present). * @return If the startDate is in the future, a one-item {@link List} of * {@link DocBody} Objects will be returned. If endDate is in the * future the {@link List} will stop at the current (default) * report. * @throws MalformedURLException * @throws IOException */ public List<DocBody> getDocBodiesInDateRange(Date startDate, Date endDate) throws MalformedURLException, IOException { List<DocBody> docBodies = new ArrayList<DocBody>(); List<Document> documents = super.getDocumentsInDateRange(startDate, endDate, Document.class); for (Document document : documents) { docBodies.add(this.getDocBody(document)); } return docBodies; } /** * Returns only the {@link DocHeader} portion of the {@link Document}. * * @param document * {@link Document} comprised of two parts: {@link DocHeader} and * {@link DocBody}. * * @return {@link DocHeader} */ public DocHeader getDocHeader(Document document) { List<Object> docHeaderAndDocBody = document.getDocHeaderAndDocBody(); return super.getDocPart(docHeaderAndDocBody, DocHeader.class); } /** * Get a {@link DocHeader} for a date in past. * * @param historyDate * Date in the past that a report header is being requested for. * @return Returns the {@link DocHeader} of a past report. * @throws MalformedURLException * * @throws IOException */ public DocHeader getDocHeaderForDate(Date historyDate) throws MalformedURLException, IOException { Document document = super.getDocumentForDate(historyDate, Document.class); return this.getDocHeader(document); } /** * Makes a request for each Date in the provided range (inclusive) building * out a {@link List} of {@link DocHeader} Objects. * * @param startDate * Start point (inclusive) of the date range (ie. date furthest * in the past). * @param endDate * End point (inclusive) of the date range (ie. date closest to * present). * @return If the startDate is in the future, a one-item {@link List} of * {@link DocHeader} Objects will be returned. If endDate is in the * future the {@link List} will stop at the current (default) * report. * @throws MalformedURLException * @throws IOException */ public List<DocHeader> getDocHeadersInDateRange(Date startDate, Date endDate) throws MalformedURLException, IOException { List<DocHeader> docHeaders = new ArrayList<DocHeader>(); List<Document> documents = super.getDocumentsInDateRange(startDate, endDate, Document.class); for (Document document : documents) { docHeaders.add(this.getDocHeader(document)); } return docHeaders; } /** * Unmarshals XML text into a {@link Document} using JAXB2, into the package * name specified by {@link #getJaxb2ContextPath()}. * * @param urlString * The URL that will be unmarshalled into a {@link Document}. * @return {@link Document} * @throws MalformedURLException * @throws IOException * */ private Document getDocument(String urlString) throws MalformedURLException, IOException { return super.getDocument(urlString, Document.class); } }
r24mille/IesoPublicReportBindings
src/main/java/name/reidmiller/iesoreports/client/NetInterchangeSchedulingLimitClient.java
Java
mit
6,803
# -*- encoding: utf-8 -*- # The MIT License (MIT) # # Copyright (c) 2014-2015 Haltu Oy, http://haltu.fi # # 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. import csv import codecs from optparse import make_option from collections import OrderedDict from django.core.management.base import BaseCommand, CommandError from django.db import IntegrityError from django.core.exceptions import ObjectDoesNotExist from authdata.models import User, Role, Attribute, UserAttribute, Municipality, School, Attendance, Source class Command(BaseCommand): help = """Imports data from CSV file to the database. Do not put any header to the CSV file. Only provide data separated by commas and quoted with \". You need to provide at least two arguments: the name of the input file and list of attributes for the User. For example: manage.py csv_import file.csv dreamschool,facebook,twitter,linkedin,mepin """ args = '<csvfile> <attr1,attr2...>' option_list = BaseCommand.option_list + ( make_option('--source', action='store', dest='source', default='manual', help='Source value for this run'), make_option('--municipality', action='store', dest='municipality', default='-', help='Source value for this run'), make_option('--run', action='store_true', dest='really_do_this', default=False, help='Really run the command'), make_option('--verbose', action='store_true', dest='verbose', default=False, help='Verbose'), ) def handle(self, *args, **options): if len(args) != 2: raise CommandError('Wrong parameters, try reading --help') self.verbose = options['verbose'] self.municipality = options['municipality'] # Create needed Attribute objects to the database # These are the attributes which can be used to query for User objects in the API # attribute names are defined in the commandline as the second parameter # for example: manage.py csv_import file.csv dreamschool,facebook,twitter,linkedin,mepin self.attribute_names = OrderedDict() for key in args[1].split(','): self.attribute_names[key], _ = Attribute.objects.get_or_create(name=key) self.source, _ = Source.objects.get_or_create(name=options['source']) # If you need more roles, add them here self.role_names = OrderedDict() for r in ['teacher', 'student']: self.role_names[r], _ = Role.objects.get_or_create(name=r) csv_data = csv.reader(codecs.open(args[0], 'rb'), delimiter=',', quotechar='"') for r in csv_data: # These are the fixed fields for the User. These are returned from the API. data = { 'username': r[0], # OID 'school': r[1], # School 'group': r[2], # Class 'role': r[3], # Role 'first_name': r[4], # First name 'last_name': r[5], # Last name } # This is not mandatory, but it would be nice. Can be changed to error by terminating the script here. if data['role'] not in self.role_names.keys(): print 'WARNING, role not in:', repr(self.role_names.keys()) attributes = {} i = 6 # Next csv_data row index is 6 :) for a in self.attribute_names: attributes[a] = r[i] i = i + 1 try: if self.verbose: print repr(data) print repr(attributes) if options['really_do_this']: self.really_do_this(data.copy(), attributes.copy()) except IntegrityError, e: print "ERR IE", e print repr(data) print repr(attributes) except ObjectDoesNotExist, e: print "ERR ODN", e print repr(data) print repr(attributes) def really_do_this(self, d, a): # Create User # User is identified from username and other fields are updated user, _ = User.objects.get_or_create(username=d['username']) user.first_name = d['first_name'] user.last_name = d['last_name'] user.save() # Assign attributes for User # There can be multiple attributes with the same name and different value. # This is one of the reasons we have the source parameter to tell where the data came from. for k, v in a.iteritems(): UserAttribute.objects.get_or_create(user=user, attribute=self.attribute_names[k], value=v, source=self.source) # Create Municipality # If you leave this empty on the CLI it will default to '-' municipality, _ = Municipality.objects.get_or_create(name=self.municipality) # Create School # School data is not updated after it is created. Data can be then changed in the admin. school, _ = School.objects.get_or_create(school_id=d['school'], defaults={'municipality': municipality, 'name': d['school']}) # Create Attendance object for User. There can be more than one Attendance per User. Attendance.objects.get_or_create(user=user, school=school, role=self.role_names[d['role']], group=d['group'], source=self.source) # vim: tabstop=2 expandtab shiftwidth=2 softtabstop=2
educloudalliance/eca-auth-data
authdata/management/commands/csv_import.py
Python
mit
6,066
package br.ifcibirama.dell_pc.javaisfun; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class Objetos2 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_objetos2); setTitle("Orientação à Objetos"); } @Override public void onBackPressed() { super.onBackPressed(); overridePendingTransition( R.anim.rigth_in, R.anim.rigth_out); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_go_back_red, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case R.id.menu_go: Intent intent = new Intent(this, Objetos3.class); startActivity(intent); overridePendingTransition(R.anim.left_in, R.anim.left_out); finishAffinity(); return true; case R.id.menu_home: AlertDialog.Builder builder; builder = new AlertDialog.Builder(this); builder.setTitle("Home") .setMessage("Você tem certeza que quer voltar ao menu principal?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Objetos2.this, MainActivity.class); startActivity(intent); finishAffinity(); overridePendingTransition( R.anim.rigth_in, R.anim.rigth_out); } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .setIcon(R.drawable.warning) .show(); return true; case R.id.menu_back: Intent intent2 = new Intent(this, Objetos.class); startActivity(intent2); overridePendingTransition(R.anim.rigth_in, R.anim.rigth_out); finishAffinity(); return true; default: return super.onOptionsItemSelected(item); } } }
jvbeltra/JavaIsFun
app/src/main/java/br/ifcibirama/dell_pc/javaisfun/Objetos2.java
Java
mit
2,904
package ru.otus.java_2017_04.golovnin.hw11.Cache; public interface CacheEngine<K, V> { void put(K key, V element); V get(K key); int getHitCount(); int getMissCount(); void dispose(); }
vladimir-golovnin/otus-java-2017-04-golovnin
hw11/src/main/java/ru/otus/java_2017_04/golovnin/hw11/Cache/CacheEngine.java
Java
mit
207
# こっちのURLで放送予定の番組情報取得できるけど視聴者数ないので使わない # http://live.nicovideo.jp/rss require File.expand_path('./lib/readers/channel_list_reader') class NicoOfficialReader < ChannelListReader def read_rows @doc.css('#rank .active .detail') end def read_channel_name(row) row.css('p a').text.slice(0, 10) end def read_contact_url(row) 'http://live.nicovideo.jp/' << row.css('p a')[0][:href] end def read_genre(row) '【ニコ生公式】' end def read_detail(row) row.css('p a').text end # 10分あたりの平均コメ数を返す def read_listener_count(row) hour, min = read_elapsed_hour_and_min(row) elapsed_minutes = (hour.to_i * 60) + min.to_i comment_count = row.css('.count .coment').text.gsub!(/\s|,/, '').to_i (comment_count / (elapsed_minutes / 10)).to_i rescue ZeroDivisionError 0 end def read_relay_count(row) row.css('.count .audience').text.gsub!(/\s|,/, '').to_i end def read_time(row) hour, min = read_elapsed_hour_and_min(row) sprintf('%02d', hour) + ':' + sprintf('%02d', min) end def read_elapsed_hour_and_min(row) unless @hour && @min time = row.css('.time').text if time.include?('時間') time = time.split('時間') @hour = time[0] @min = time[1].sub('分', '') else @hour = '00' @min = time.sub('分', '') end end return @hour, @min end end
masu-kawa/nyp
lib/readers/nico_official_reader.rb
Ruby
mit
1,554
'use strict'; var kraken = require('kraken-js'), app = require('express')(), options = require('./lib/spec')(app), port = process.env.PORT || 8000; app.use(kraken(options)); app.listen(port, function(err) { console.log('[%s] Listening on http://localhost:%d', app.settings.env, port); });
NaveenAttri/TestProject
index.js
JavaScript
mit
310
<?php return array ( 'id' => 'kddi_sn3q_ver1', 'fallback' => 'kddi_sn3p_ver1', 'capabilities' => array ( 'model_name' => 'S005', 'release_date' => '2010_november', 'max_image_width' => '234', 'resolution_height' => '854', 'resolution_width' => '480', 'max_image_height' => '375', 'flash_lite_version' => '3_0', ), );
cuckata23/wurfl-data
data/kddi_sn3q_ver1.php
PHP
mit
356
<?php namespace daVerona\Texting\Contracts; interface TextingRequest { public function getSender(); public function getReceiver(); }
daverona/texting
src/Contracts/TextingRequest.php
PHP
mit
148
/* global __phantom_writeFile */ (function(global) { var UNDEFINED, exportObject; if (typeof module !== "undefined" && module.exports) { exportObject = exports; } else { exportObject = global.jasmineReporters = global.jasmineReporters || {}; } function trim(str) { return str.replace(/^\s+/, "" ).replace(/\s+$/, "" ); } function elapsed(start, end) { return (end - start)/1000; } function isFailed(obj) { return obj.status === "failed"; } function isSkipped(obj) { return obj.status === "pending"; } function isDisabled(obj) { return obj.status === "disabled"; } function pad(n) { return n < 10 ? '0'+n : n; } function extend(dupe, obj) { // performs a shallow copy of all props of `obj` onto `dupe` for (var prop in obj) { if (obj.hasOwnProperty(prop)) { dupe[prop] = obj[prop]; } } return dupe; } function ISODateString(d) { return d.getFullYear() + '-' + pad(d.getMonth()+1) + '-' + pad(d.getDate()) + 'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()); } function escapeInvalidXmlChars(str) { return str.replace(/</g, "&lt;") .replace(/\>/g, "&gt;") .replace(/\"/g, "&quot;") .replace(/\'/g, "&apos;") .replace(/\&/g, "&amp;"); } function getQualifiedFilename(path, filename, separator) { if (path && path.substr(-1) !== separator && filename.substr(0) !== separator) { path += separator; } return path + filename; } function log(str) { var con = global.console || console; if (con && con.log) { con.log(str); } } /** * Generates JUnit XML for the given spec run. There are various options * to control where the results are written, and the default values are * set to create as few .xml files as possible. It is possible to save a * single XML file, or an XML file for each top-level `describe`, or an * XML file for each `describe` regardless of nesting. * * Usage: * * jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter(options); * * @param {object} [options] * @param {string} [savePath] directory to save the files (default: '') * @param {boolean} [consolidateAll] whether to save all test results in a * single file (default: true) * NOTE: if true, {filePrefix} is treated as the full filename (excluding * extension) * @param {boolean} [consolidate] whether to save nested describes within the * same file as their parent (default: true) * NOTE: true does nothing if consolidateAll is also true. * NOTE: false also sets consolidateAll to false. * @param {boolean} [useDotNotation] whether to separate suite names with * dots instead of spaces, ie "Class.init" not "Class init" (default: true) * @param {string} [filePrefix] is the string value that is prepended to the * xml output file (default: junitresults-) * NOTE: if consolidateAll is true, the default is simply "junitresults" and * this becomes the actual filename, ie "junitresults.xml" */ exportObject.JUnitXmlReporter = function(options) { var self = this; self.started = false; self.finished = false; // sanitize arguments options = options || {}; self.savePath = options.savePath || ''; self.consolidate = options.consolidate === UNDEFINED ? true : options.consolidate; self.consolidateAll = self.consolidate !== false && (options.consolidateAll === UNDEFINED ? true : options.consolidateAll); self.useDotNotation = options.useDotNotation === UNDEFINED ? true : options.useDotNotation; self.filePrefix = options.filePrefix || (self.consolidateAll ? 'junitresults' : 'junitresults-'); var suites = [], currentSuite = null, totalSpecsExecuted = 0, totalSpecsDefined, // when use use fit, jasmine never calls suiteStarted / suiteDone, so make a fake one to use fakeFocusedSuite = { id: 'focused', description: 'focused specs', fullName: 'focused specs' }; var __suites = {}, __specs = {}; function getSuite(suite) { __suites[suite.id] = extend(__suites[suite.id] || {}, suite); return __suites[suite.id]; } function getSpec(spec) { __specs[spec.id] = extend(__specs[spec.id] || {}, spec); return __specs[spec.id]; } self.jasmineStarted = function(summary) { totalSpecsDefined = summary && summary.totalSpecsDefined || NaN; exportObject.startTime = new Date(); self.started = true; }; self.suiteStarted = function(suite) { suite = getSuite(suite); suite._startTime = new Date(); suite._specs = []; suite._suites = []; suite._failures = 0; suite._skipped = 0; suite._disabled = 0; suite._parent = currentSuite; if (!currentSuite) { suites.push(suite); } else { currentSuite._suites.push(suite); } currentSuite = suite; }; self.specStarted = function(spec) { if (!currentSuite) { // focused spec (fit) -- suiteStarted was never called self.suiteStarted(fakeFocusedSuite); } spec = getSpec(spec); spec._startTime = new Date(); spec._suite = currentSuite; currentSuite._specs.push(spec); }; self.specDone = function(spec) { spec = getSpec(spec); spec._endTime = new Date(); if (isSkipped(spec)) { spec._suite._skipped++; } if (isDisabled(spec)) { spec._suite._disabled++; } if (isFailed(spec)) { spec._suite._failures++; } totalSpecsExecuted++; }; self.suiteDone = function(suite) { suite = getSuite(suite); if (suite._parent === UNDEFINED) { // disabled suite (xdescribe) -- suiteStarted was never called self.suiteStarted(suite); } suite._endTime = new Date(); currentSuite = suite._parent; }; self.jasmineDone = function() { if (currentSuite) { // focused spec (fit) -- suiteDone was never called self.suiteDone(fakeFocusedSuite); } var output = ''; for (var i = 0; i < suites.length; i++) { output += self.getOrWriteNestedOutput(suites[i]); } // if we have anything to write here, write out the consolidated file if (output) { wrapOutputAndWriteFile(self.filePrefix, output); } //log("Specs skipped but not reported (entire suite skipped or targeted to specific specs)", totalSpecsDefined - totalSpecsExecuted + totalSpecsDisabled); self.finished = true; // this is so phantomjs-testrunner.js can tell if we're done executing exportObject.endTime = new Date(); }; self.getOrWriteNestedOutput = function(suite) { var output = suiteAsXml(suite); for (var i = 0; i < suite._suites.length; i++) { output += self.getOrWriteNestedOutput(suite._suites[i]); } if (self.consolidateAll || self.consolidate && suite._parent) { return output; } else { // if we aren't supposed to consolidate output, just write it now wrapOutputAndWriteFile(generateFilename(suite), output); return ''; } }; self.writeFile = function(filename, text) { var errors = []; var path = self.savePath; function phantomWrite(path, filename, text) { // turn filename into a qualified path filename = getQualifiedFilename(path, filename, window.fs_path_separator); // write via a method injected by phantomjs-testrunner.js __phantom_writeFile(filename, text); } function nodeWrite(path, filename, text) { var fs = require("fs"); var nodejs_path = require("path"); require("mkdirp").sync(path); // make sure the path exists var filepath = nodejs_path.join(path, filename); var xmlfile = fs.openSync(filepath, "w"); fs.writeSync(xmlfile, text, 0); fs.closeSync(xmlfile); return; } // Attempt writing with each possible environment. // Track errors in case no write succeeds try { phantomWrite(path, filename, text); return; } catch (e) { errors.push(' PhantomJs attempt: ' + e.message); } try { nodeWrite(path, filename, text); return; } catch (f) { errors.push(' NodeJS attempt: ' + f.message); } // If made it here, no write succeeded. Let user know. log("Warning: writing junit report failed for '" + path + "', '" + filename + "'. Reasons:\n" + errors.join("\n") ); }; /******** Helper functions with closure access for simplicity ********/ function generateFilename(suite) { return self.filePrefix + getFullyQualifiedSuiteName(suite, true) + '.xml'; } function getFullyQualifiedSuiteName(suite, isFilename) { var fullName; if (self.useDotNotation || isFilename) { fullName = suite.description; for (var parent = suite._parent; parent; parent = parent._parent) { fullName = parent.description + '.' + fullName; } } else { fullName = suite.fullName; } // Either remove or escape invalid XML characters if (isFilename) { var fileName = "", rFileChars = /[\w\.]/, chr; while (fullName.length) { chr = fullName[0]; fullName = fullName.substr(1); if (rFileChars.test(chr)) { fileName += chr; } } return fileName; } else { return escapeInvalidXmlChars(fullName); } } function suiteAsXml(suite) { var xml = '\n <testsuite name="' + getFullyQualifiedSuiteName(suite) + '"'; xml += ' timestamp="' + ISODateString(suite._startTime) + '"'; xml += ' hostname="localhost"'; // many CI systems like Jenkins don't care about this, but junit spec says it is required xml += ' time="' + elapsed(suite._startTime, suite._endTime) + '"'; xml += ' errors="0"'; xml += ' tests="' + suite._specs.length + '"'; xml += ' skipped="' + suite._skipped + '"'; xml += ' disabled="' + suite._disabled + '"'; // Because of JUnit's flat structure, only include directly failed tests (not failures for nested suites) xml += ' failures="' + suite._failures + '"'; xml += '>'; for (var i = 0; i < suite._specs.length; i++) { xml += specAsXml(suite._specs[i]); } xml += '\n </testsuite>'; return xml; } function specAsXml(spec) { var xml = '\n <testcase classname="' + getFullyQualifiedSuiteName(spec._suite) + '"'; xml += ' name="' + escapeInvalidXmlChars(spec.description) + '"'; xml += ' time="' + elapsed(spec._startTime, spec._endTime) + '"'; xml += '>'; if (isSkipped(spec) || isDisabled(spec)) { xml += '<skipped />'; } else if (isFailed(spec)) { for (var i = 0, failure; i < spec.failedExpectations.length; i++) { failure = spec.failedExpectations[i]; xml += '\n <failure type="' + (failure.matcherName || "exception") + '"'; xml += ' message="' + trim(escapeInvalidXmlChars(failure.message))+ '"'; xml += '>'; xml += '<![CDATA[' + trim(failure.stack || failure.message) + ']]>'; xml += '\n </failure>'; } } xml += '\n </testcase>'; return xml; } // To remove complexity and be more DRY about the silly preamble and <testsuites> element var prefix = '<?xml version="1.0" encoding="UTF-8" ?>'; prefix += '\n<testsuites>'; var suffix = '\n</testsuites>'; function wrapOutputAndWriteFile(filename, text) { if (filename.substr(-4) !== '.xml') { filename += '.xml'; } self.writeFile(filename, (prefix + text + suffix)); } }; })(this);
Zack-Tillotson/open-door-the-game
node_modules/jasmine-reporters/src/junit_reporter.js
JavaScript
mit
13,510
<?php $textImage = imagecreate(200,100); $white = imagecolorallocate($textImage, 255, 255, 255); $black = imagecolorallocate($textImage, 0, 0, 0); $yOffset = 0; for ($i = 1; $i <=5; $i++) { imagestring($textImage, $i, 5, $yOffset, "This is system font $i", $black); $yOffset += imagefontheight($i); } header("Content-type: image/png"); imagepng($textImage); imagedestroy($textImage); ?>
inest-us/php
PHP5/Ch16/drawstring.php
PHP
mit
389
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { Injectable } from '@angular/core'; @Injectable() export class Service386Service { constructor() { } }
angular/angular-cli-stress-test
src/app/services/service-386.service.ts
TypeScript
mit
320
/** * Copyright (c) 2015-2018, CJ Hare All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * * Neither the name of [project] nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.systematic.trading.backtest.output.elastic.dao; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Response; import com.systematic.trading.backtest.BacktestBatchId; import com.systematic.trading.backtest.output.elastic.model.ElasticIndexName; /** * Connectivity to Elastic search. * * @author CJ Hare */ public interface ElasticDao { Response index( ElasticIndexName indexName ); Response mapping( ElasticIndexName indexName, BacktestBatchId id ); void postTypes( ElasticIndexName indexName, Entity<?> requestBody ); void putMapping( ElasticIndexName indexName, BacktestBatchId id, Entity<?> requestBody ); void put( ElasticIndexName indexName, Entity<?> requestBody ); void putSetting( ElasticIndexName indexName, Entity<?> requestBody ); }
CjHare/systematic-trading
systematic-trading-backtest-output-elastic/src/main/java/com/systematic/trading/backtest/output/elastic/dao/ElasticDao.java
Java
mit
2,322
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; namespace FluentAssertions.Analyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StringShouldNotBeNullOrWhiteSpaceAnalyzer : StringAnalyzer { public const string DiagnosticId = Constants.Tips.Strings.StringShouldNotBeNullOrWhiteSpace; public const string Category = Constants.Tips.Category; public const string Message = "Use .Should() followed by .NotBeNullOrWhiteSpace() instead."; protected override DiagnosticDescriptor Rule => new DiagnosticDescriptor(DiagnosticId, Title, Message, Category, DiagnosticSeverity.Info, true); protected override IEnumerable<FluentAssertionsCSharpSyntaxVisitor> Visitors { get { yield return new StringShouldNotBeNullOrWhiteSpaceSyntaxVisitor(); } } public class StringShouldNotBeNullOrWhiteSpaceSyntaxVisitor : FluentAssertionsCSharpSyntaxVisitor { public StringShouldNotBeNullOrWhiteSpaceSyntaxVisitor() : base(new MemberValidator("IsNullOrWhiteSpace"), MemberValidator.Should, new MemberValidator("BeFalse")) { } } } [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(StringShouldNotBeNullOrWhiteSpaceCodeFix)), Shared] public class StringShouldNotBeNullOrWhiteSpaceCodeFix : FluentAssertionsCodeFixProvider { public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(StringShouldNotBeNullOrWhiteSpaceAnalyzer.DiagnosticId); protected override ExpressionSyntax GetNewExpression(ExpressionSyntax expression, FluentAssertionsDiagnosticProperties properties) { var remove = NodeReplacement.RemoveAndExtractArguments("IsNullOrWhiteSpace"); var newExpression = GetNewExpression(expression, remove); var rename = NodeReplacement.Rename("BeFalse", "NotBeNullOrWhiteSpace"); newExpression = GetNewExpression(newExpression, rename); var stringKeyword = newExpression.DescendantNodes().OfType<PredefinedTypeSyntax>().Single(); var subject = remove.Arguments.First().Expression; return newExpression.ReplaceNode(stringKeyword, subject.WithTriviaFrom(stringKeyword)); } } }
fluentassertions/fluentassertions.analyzers
src/FluentAssertions.Analyzers/Tips/Strings/StringShouldNotBeNullOrWhiteSpace.cs
C#
mit
2,544
package com.pedanov.departments.dao; /** * Created by Anfel on 16.02.2017. */ public class DepartmentDao { }
anfel4life/departments
src/main/java/com/pedanov/departments/dao/DepartmentDao.java
Java
mit
112
package intersectables; import base.HitRecord; import base.Intersectable; import base.Material; import base.Ray; /** * Any Primitive Geometry is an intersectable and has a certain material assigned to. * Created by simplaY on 06.01.2015. */ public abstract class PrimitiveGeometry implements Intersectable { // material assigned to any PrimitiveGeometry. // NB: Cannot be set after initialization. protected final Material material; /** * Material that should be set to Geometry. * * @param material */ public PrimitiveGeometry(Material material) { this.material = material; } public Material getMaterial() { return material; } @Override public abstract HitRecord intersect(Ray ray); }
simplay/aptRenderer
src/main/java/intersectables/PrimitiveGeometry.java
Java
mit
771
var Handlebars = require("handlebars"); export default class Lean { constructor() { this.name = this.constructor.name; this.id = `${this.name}-${Lean.INCREMENTAL_ID++}`; this.children = {}; this.props = {}; this.element = null; this.view = this.name; Lean.registerInstance(this); } render() { return Lean.Templates[this.view](this); } postrender() { this.element = document.getElementById(this.id); this.element.self = this; this.postrenderRecursive(this.children); } postrenderRecursive(component) { if(!component) { return; } else if(typeof component.postrender === "function") { component.postrender(); } else if(Array.isArray(component)) { component.forEach(this.postrenderRecursive.bind(this)); } else if(typeof component === "object" && component !== null) { for(let childName in component) { this.postrenderRecursive(component[childName]); } } } rerender(selector) { if(selector) { var wrapperElement = document.createElement("div"); wrapperElement.innerHTML = this.render(); this.element.querySelector(selector).outerHTML = wrapperElement.querySelector(selector).outerHTML; } else { this.element.outerHTML = this.render(); this.postrender(); } } static precompileAllInPage() { var allTemplates = document.querySelectorAll('script[type="text/x-handlebars-template"]'); for (let i = 0; i < allTemplates.length; i++) { let template = allTemplates[i], isPartial = false; if(template.classList.contains("partial")) { isPartial = true; } Lean.precompile(template.id, template.innerHTML, isPartial); } } static precompileAllFiles(baseDir, extension, templates, partials, done) { var promises = []; for (let i = 0; i < templates.length; i++) { let template = templates[i], templateName = Lean.getBaseName(template), isPartial = partials.indexOf(templateName) > -1 ? true : false; promises.push(Lean.precompileFile(baseDir + template + extension, templateName, isPartial)); } $.when.apply($, promises).done(done); } static precompileFile(templatePath, templateName, isPartial) { return $.get(templatePath).done((data) => { Lean.precompile(templateName, data, isPartial); }); } static precompile(id, innerHTML, isPartial) { Lean.Templates[id] = Handlebars.compile(innerHTML); if(isPartial) { Handlebars.registerPartial(id, Lean.Templates[id]); } } static registerInstance(instance) { Lean.AllInstances[instance.id] = instance; } static findInstance(id) { return document.getElementById(id).self; } static getBaseName(str) { var base = new String(str).substring(str.lastIndexOf('/') + 1); if(base.lastIndexOf(".") != -1) { base = base.substring(0, base.lastIndexOf(".")); } return base; } } Lean.INCREMENTAL_ID = 0; Lean.Templates = {}; Handlebars.registerHelper("render", (template) => { if(template && typeof template.render === "function") { return template.render(); } else { return "" } }); Handlebars.registerHelper("call", (context, func, ...params) => { return func.apply(context, params); });
amirmohsen/lean
lib/Lean.js
JavaScript
mit
3,109
# Changed the semantics of writing values to custom attributes to ensure that they require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper')) describe Snowflake::Node do describe "Custom Attributes" do it "indicates whether an attribute name represents a custom attribute" do TestNodeWithCustomAttributes.custom_attribute?( :counter ).should be_true TestNodeWithCustomAttributes.custom_attribute?( :stuff ).should be_true TestNodeWithCustomAttributes.custom_attribute?( :name ).should be_false TestNodeWithCustomAttributes.custom_attribute?( :foo ).should be_false end it "retrieves a list of all custom attributes" do TestNodeWithCustomAttributes.custom_attributes.should == Set.new([:counter, :stuff]) end it "will overwrite and persist custom attribute values" do @test_node = TestNodeWithCustomAttributes.create(:name => 'rolly', :mood => 'Awesome') @test_node.should be_valid @test_node.stuff = ['foo', 'bar'] @test_node.should be_valid @test_node = TestNodeWithCustomAttributes.get( @test_node.key ) @test_node.stuff.to_set.should == Set.new(['foo', 'bar']) end it "will raise an exception if errors occur when overwriting custom attribute values with the wrong format" do @test_node = TestNodeWithCustomAttributes.create(:name => 'rolly', :mood => 'Awesome') @test_node.should be_valid lambda { @test_node.stuff = "Yo" }.should raise_error(Snowflake::CouldNotPersistCustomAttributeError) @test_node = TestNodeWithCustomAttributes.get( @test_node.key ) @test_node.stuff.to_set.should == Set.new end it "will not allow custom attributes to be overwritten when there are existing errors" do @test_node = TestNodeWithCustomAttributes.create(:name => 'rolly', :mood => 'Awesome') @test_node.should be_valid @test_node.name = nil lambda { @test_node.stuff = ['foo', 'bar'] }.should raise_error(Snowflake::CustomAttributeError) end end end
luma/snowflake
spec/public/node_custom_attributes_spec.rb
Ruby
mit
2,072
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; namespace SocketLibrary { /// <summary> /// SocketµÄ¿Í»§¶Ë /// </summary> public class Client : SocketBase { //ÊÇ·ñÐÄÌø¼ì²â private const bool _isSendHeartbeat = true; /// <summary> /// ³¬Ê±Ê±¼ä /// </summary> /// public const int CONNECTTIMEOUT = 10; private TcpClient client; private IPAddress ipAddress; private int port; private Thread _listenningClientThread; private string _clientName; /// <summary> /// Á¬½ÓµÄKey /// </summary> public string ClientName { get { return _clientName; } } /// <summary> /// ³õʼ»¯ /// </summary> /// <param name="ipaddress">µØÖ·</param> /// <param name="port">¶Ë¿Ú</param> public Client(string ipaddress, int port) : this(IPAddress.Parse(ipaddress), port) { } /// <summary> ///³õʼ»¯ /// </summary> /// <param name="ipaddress">µØÖ·</param> /// <param name="port">¶Ë¿Ú</param> public Client(IPAddress ipaddress, int port) : base(_isSendHeartbeat) { this.ipAddress = ipaddress; this.port = port; this._clientName = ipAddress + ":" + port; } /// <summary> /// ´ò¿ªÁ´½Ó /// </summary> public void StartClient() { _listenningClientThread = new Thread(new ThreadStart(Start)); _listenningClientThread.Start(); } /// <summary> /// ¹Ø±ÕÁ¬½Ó²¢ÊÍ·Å×ÊÔ´ /// </summary> public void StopClient() { this.EndListenAndSend(); //ȱÉÙ֪ͨ¸ø·þÎñ¶Ë ×Ô¼ºÖ÷¶¯¹Ø±ÕÁË _listenningClientThread.Abort(); } /// <summary> /// »ñȡָ¶¨Á¬½ÓÃûµÄÁ¬½Ó,²éѯ²»µ½·µ»Ønull /// </summary> /// <returns></returns> public Connection GetConnection() { Connection connection = null; this.Connections.TryGetValue(this.ClientName, out connection); return connection; } private void Start() { while (true) { if (!this.Connections.ContainsKey(this._clientName)) { try { client = new TcpClient(); client.SendTimeout = CONNECTTIMEOUT; client.ReceiveTimeout = CONNECTTIMEOUT; client.Connect(ipAddress, port); Connection conn = new Connection(client, this._clientName); this.Connections.TryAdd(this._clientName, conn); this.OnConnected(this, conn); } catch (Exception ex) { this.connClose(this._clientName, new List<Message>() { }, ex); } } //½ÓÊÕÊý¾Ý¡¢·¢ËÍÊý¾Ý ÐÄÌø¼ì²â this.SenRecMsg(); Thread.Sleep(1000); } } } }
Harbour9354/Socket.Harbour
SocketLibrary/Client.cs
C#
mit
3,300
<?php /** * This file is part of ClassMocker. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @package JSiefer\ClassMocker */ namespace JSiefer\ClassMocker\Footprint; /** * Class ClassFootprintTest * * @covers \JSiefer\ClassMocker\Footprint\ClassFootprint */ class ClassFootprintTest extends \PHPUnit_Framework_TestCase { /** * Test type methods * * @return void * @test */ public function testType() { $footprint = new ClassFootprint(); $this->assertEquals( ClassFootprint::TYPE_CLASS, $footprint->getType(), 'Class should be the default type' ); $this->assertFalse( $footprint->isInterface(), 'Should not be an interface by default' ); $footprint->setType(ClassFootprint::TYPE_INTERFACE); $this->assertTrue( $footprint->isInterface(), 'Should be an interface' ); } /** * Test Parent Setter and Getter * * @return void * @test */ public function testParentSetter() { $footprint = new ClassFootprint(); $footprint->setParent(''); $this->assertNull( $footprint->getParent(), 'Empty parent class must result in NULL' ); $footprint->setParent('Test'); $this->assertEquals( '\Test', $footprint->getParent(), 'Add root back-slash if missing' ); $footprint->setParent('\Test'); $this->assertEquals( '\Test', $footprint->getParent(), 'Only add root back-slash if missing' ); } /** * Test interface setter methods * * @return void * @test */ public function testInterfaceSetter() { $footprint = new ClassFootprint(); $footprint->setInterfaces(['InterfaceA', '\InterfaceB']); $this->assertEquals( ['\InterfaceA', '\InterfaceB'], $footprint->getInterfaces(), 'Add root back-slash if missing' ); $footprint->setInterfaces(['Foobar']); $this->assertEquals( ['\Foobar'], $footprint->getInterfaces(), 'Set must overwrite existing interfaces' ); $footprint->addInterface('Barfoo'); $this->assertEquals( ['\Foobar', '\Barfoo'], $footprint->getInterfaces(), 'Add must NOT overwrite existing interfaces' ); $footprint->addInterface(''); $this->assertEquals( ['\Foobar', '\Barfoo'], $footprint->getInterfaces(), 'Add must ignore empty interfaces' ); } /** * Test constant setter methods * * @return void * @test */ public function testConstantSetter() { $footprint = new ClassFootprint(); $footprint->setConstants(['FOO' => 'foo', 'TWO' => '2']); $this->assertSame( ['FOO' => 'foo', 'TWO' => 2.0], $footprint->getConstants(), 'Strings must be checked vor number values' ); $footprint->setConstants(['FOO' => 'foo']); $this->assertEquals( ['FOO' => 'foo'], $footprint->getConstants(), 'Set must replace existing constants' ); $footprint->addConstant('BAR', 'bar'); $this->assertEquals( ['FOO' => 'foo', 'BAR' => 'bar'], $footprint->getConstants(), 'Add must NOT replace existing constants' ); } /** * Simple export and import test * * Footprint can be exported to simple arrays and then * re-imported * * The exported footprint data should be as small as possible * to later easily create small json reference files * * @return void * @test */ public function testExportAndImport() { $source = new ClassFootprint(); $source->setType(ClassFootprint::TYPE_INTERFACE); $source->setParent('Test'); $source->addConstant('A', '1'); $source->addConstant('B', '1.5'); $source->addConstant('C', 'test'); $source->setInterfaces(['InterfaceA', 'InterfaceB']); $data = $source->export(); $this->assertInternalType( 'array', $data, 'Exported data should be an array' ); $target = new ClassFootprint($data); $this->assertSame( $target->getType(), $source->getType(), 'Should have copied type' ); $this->assertSame( $target->getParent(), $source->getParent(), 'Should have copied parent class' ); $this->assertSame( $target->getConstants(), $source->getConstants(), 'Should have copied constants' ); $this->assertSame( $target->getInterfaces(), $source->getInterfaces(), 'Should have copied interface' ); } /** * Should fail on invalid data * * The footprint data must be an array of size 4 * * @test * @expectedException \InvalidArgumentException * @expectedExceptionMessage Invalid footprint array */ public function shouldFailOnInvalidData() { new ClassFootprint([0,0]); } }
jsiefer/class-mocker
tests/Footprint/ClassFootprintTest.php
PHP
mit
5,555
/** * File: Command.java<br/> * Author: Peter M. Corcoran, pmcorcor@uab.edu<br/> * Assignment: EE433 Research Project<br/> * Version: 1.0.0 11/27/2015 pmc - initial coding<br/> * Structure Component: Abstract Command Object */ package ee433.behavior.command; public abstract class Command { public abstract void execute(); }
corcoranp/ee433
src/ee433/behavior/command/Command.java
Java
mit
337
class BitsInterpreter < ActiveRecord::Base validates_presence_of :name, :length validates_numericality_of :length, :only_integer => true validates_inclusion_of :length, :in => [16, 32, 48, 64, 1024], :message => "valid value [16, 32, 48, 64, 1024]" validates_length_of :name, :maximum => 255 validates_uniqueness_of :name validates_length_of :description, :maximum => 255, :allow_nil => true has_many :bits_segments, -> {order :start_bit} def validate name.strip! end end
rli9/vims
app/models/bits_interpreter.rb
Ruby
mit
498
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require 'icheck' //= require highcharts //= require highcharts/highcharts-more //= require_tree . function icheck(){ if($(".icheck-me").length > 0){ $(".icheck-me").each(function(){ var $el = $(this); var skin = ($el.attr('data-skin') !== undefined) ? "_" + $el.attr('data-skin') : "", color = ($el.attr('data-color') !== undefined) ? "-" + $el.attr('data-color') : ""; var opt = { checkboxClass: 'icheckbox' + skin + color, radioClass: 'iradio' + skin + color, } $el.iCheck(opt); }); } } $(function(){ icheck(); })
MaSys/natumex
app/assets/javascripts/application.js
JavaScript
mit
1,227
<?php namespace Tests\DependencyInjectorTests; return [ ServiceWithDependency::class, TestService::class, BaseService::class, ExtendedService::class ];
martinbrom/trip-hatch
tests/DependencyInjectorTests/service_list.php
PHP
mit
170
using System.Xml.Serialization; namespace WebApiDavExtension.CalDav { [XmlRoot("href", Namespace = "DAV:")] public class HRef { public HRef() { } public HRef(string reference) { Reference = reference; } [XmlText] public string Reference { get; set; } } }
medocheck/WebApiDavExtension
WebApiDavExtension/CalDav/HRef.cs
C#
mit
353
import asyncio import rocat.message import rocat.actor import rocat.globals class BaseActorRef(object): def tell(self, m, *, sender=None): raise NotImplementedError def ask(self, m, *, timeout=None): raise NotImplementedError def error(self, e): raise NotImplementedError class LocalActorRef(BaseActorRef): def __init__(self, q, loop): self._q = q self._loop = loop def _send(self, envel): self._loop.call_soon_threadsafe(self._q.put_nowait, envel) def tell(self, m, *, sender=None): if sender is None: sender = _guess_current_sender() self._send(rocat.message.Envelope.for_tell(m, sender=sender)) async def ask(self, m, *, timeout=None): fut = asyncio.get_event_loop().create_future() sender = FunctionRef(fut, asyncio.get_event_loop()) self._send(rocat.message.Envelope.for_ask(m, sender=sender)) if timeout is None: timeout = _guess_default_timeout() if timeout > 0: reply = await asyncio.wait_for(fut, timeout) else: reply = await fut if reply.is_error: raise reply.msg return reply.msg def error(self, e): raise NotImplementedError('You can tell error only when you reply') class FunctionRef(BaseActorRef): def __init__(self, fut, loop): self._fut = fut self._loop = loop def _send(self, envel): self._loop.call_soon_threadsafe(self._try_set_future, envel) def _try_set_future(self, result): if not self._fut.done(): self._fut.set_result(result) def tell(self, m, *, sender=None): if sender is None: sender = _guess_current_sender() self._send(rocat.message.Envelope.for_ask(m, sender=sender)) def ask(self, m, *, sender=None, timeout=None): raise NotImplementedError('You cannot ask back to ask request') def error(self, e): self._send(rocat.message.Envelope.for_error(e)) def _guess_current_sender(): current_ctx = rocat.actor.ActorContext.current() if current_ctx is not None: return current_ctx.sender def _guess_default_timeout(): current_ctx = rocat.actor.ActorContext.current() if current_ctx is not None: return current_ctx.default_timeout or -1 return -1
chongkong/rocat
rocat/ref.py
Python
mit
2,370
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2017-2018 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "plasticbrdf.h" // appleseed.renderer headers. #include "renderer/kernel/lighting/scatteringmode.h" #include "renderer/kernel/shading/directshadingcomponents.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/modeling/bsdf/bsdf.h" #include "renderer/modeling/bsdf/bsdfsample.h" #include "renderer/modeling/bsdf/bsdfwrapper.h" #include "renderer/modeling/bsdf/fresnel.h" #include "renderer/modeling/bsdf/microfacethelper.h" #include "renderer/utility/paramarray.h" // appleseed.foundation headers. #include "foundation/containers/dictionary.h" #include "foundation/math/basis.h" #include "foundation/math/dual.h" #include "foundation/math/fresnel.h" #include "foundation/math/microfacet.h" #include "foundation/math/sampling/mappings.h" #include "foundation/math/vector.h" #include "foundation/utility/api/specializedapiarrays.h" #include "foundation/utility/makevector.h" // Standard headers. #include <algorithm> #include <cmath> #include <cstddef> #include <string> // Forward declarations. namespace foundation { class IAbortSwitch; } namespace renderer { class Assembly; } namespace renderer { class Project; } using namespace foundation; namespace renderer { namespace { // // Plastic BRDF. // // References: // // [1] A Physically-Based Reflectance Model Combining Reflection and Diffraction // https://hal.inria.fr/hal-01386157 // // [2] Mitsuba renderer // https://github.com/mitsuba-renderer/mitsuba // const char* Model = "plastic_brdf"; class PlasticBRDFImpl : public BSDF { public: PlasticBRDFImpl( const char* name, const ParamArray& params) : BSDF(name, Reflective, ScatteringMode::Diffuse | ScatteringMode::Glossy | ScatteringMode::Specular, params) { m_inputs.declare("diffuse_reflectance", InputFormatSpectralReflectance); m_inputs.declare("diffuse_reflectance_multiplier", InputFormatFloat, "1.0"); m_inputs.declare("specular_reflectance", InputFormatSpectralReflectance); m_inputs.declare("specular_reflectance_multiplier", InputFormatFloat, "1.0"); m_inputs.declare("roughness", InputFormatFloat, "0.15"); m_inputs.declare("ior", InputFormatFloat, "1.5"); m_inputs.declare("internal_scattering", InputFormatFloat, "1.0"); } void release() override { delete this; } const char* get_model() const override { return Model; } size_t compute_input_data_size() const override { return sizeof(InputValues); } void prepare_inputs( Arena& arena, const ShadingPoint& shading_point, void* data) const override { InputValues* values = static_cast<InputValues*>(data); // Apply multipliers to input values. values->m_specular_reflectance *= values->m_specular_reflectance_multiplier; values->m_diffuse_reflectance *= values->m_diffuse_reflectance_multiplier; values->m_roughness = std::max(values->m_roughness, shading_point.get_ray().m_min_roughness); new (&values->m_precomputed) InputValues::Precomputed(); const float outside_ior = shading_point.get_ray().get_current_ior(); values->m_precomputed.m_eta = outside_ior / values->m_ior; values->m_precomputed.m_specular_weight = std::max(max_value(values->m_specular_reflectance), 0.0f); values->m_precomputed.m_diffuse_weight = std::max(max_value(values->m_diffuse_reflectance), 0.0f); } void sample( SamplingContext& sampling_context, const void* data, const bool adjoint, const bool cosine_mult, const LocalGeometry& local_geometry, const Dual3f& outgoing, const int modes, BSDFSample& sample) const override { const InputValues* values = static_cast<const InputValues*>(data); const float alpha = microfacet_alpha_from_roughness(values->m_roughness); // Compute the microfacet normal by sampling the MDF. const Vector3f wo = local_geometry.m_shading_basis.transform_to_local(outgoing.get_value()); sampling_context.split_in_place(3, 1); const Vector3f s = sampling_context.next2<Vector3f>(); const Vector3f m = alpha == 0.0f ? Vector3f(0.0f, 1.0f, 0.0f) : GGXMDF::sample(wo, Vector2f(s[0], s[1]), alpha); const float F = fresnel_reflectance(wo, m, values->m_precomputed.m_eta); const float specular_probability = choose_specular_probability(*values, F); Vector3f wi; // Choose between specular/glossy and diffuse. if (ScatteringMode::has_glossy(modes) && (!ScatteringMode::has_diffuse(modes) || s[2] < specular_probability)) { wi = improve_normalization(reflect(wo, m)); if (wi.y <= 0.0f) return; if (alpha == 0.0f) { if (!ScatteringMode::has_specular(modes)) return; sample.set_to_scattering(ScatteringMode::Specular, DiracDelta); sample.m_value.m_glossy = values->m_specular_reflectance; sample.m_value.m_glossy *= F; sample.m_value.m_beauty = sample.m_value.m_glossy; sample.m_incoming = Dual3f(local_geometry.m_shading_basis.transform_to_parent(wi)); sample.m_min_roughness = values->m_roughness; sample.compute_glossy_reflected_differentials(local_geometry, values->m_roughness, outgoing); } else { const float probability = specular_pdf(alpha, wo, m) * specular_probability; assert(probability >= 0.0f); if (probability > 1.0e-6f) { sample.set_to_scattering(ScatteringMode::Glossy, probability); sample.m_incoming = Dual3f(local_geometry.m_shading_basis.transform_to_parent(wi)); sample.m_min_roughness = values->m_roughness; evaluate_specular( values->m_specular_reflectance, alpha, wi, wo, m, F, sample.m_value.m_glossy); sample.m_value.m_beauty = sample.m_value.m_glossy; sample.compute_glossy_reflected_differentials(local_geometry, values->m_roughness, outgoing); } } } else { wi = sample_hemisphere_cosine(Vector2f(s[0], s[1])); const float probability = wi.y * RcpPi<float>() * (1.0f - specular_probability); assert(probability > 0.0f); if (probability > 1.0e-6f) { sample.set_to_scattering(ScatteringMode::Diffuse, probability); sample.m_incoming = Dual3f(local_geometry.m_shading_basis.transform_to_parent(wi)); sample.m_min_roughness = values->m_roughness; const float Fi = fresnel_reflectance(wi, m, values->m_precomputed.m_eta); evaluate_diffuse( values->m_diffuse_reflectance, values->m_precomputed.m_eta, values->m_internal_scattering, F, Fi, sample.m_value.m_diffuse); sample.m_value.m_beauty = sample.m_value.m_diffuse; sample.m_aov_components.m_albedo = values->m_diffuse_reflectance; sample.compute_diffuse_differentials(outgoing); } } } float evaluate( const void* data, const bool adjoint, const bool cosine_mult, const LocalGeometry& local_geometry, const Vector3f& outgoing, const Vector3f& incoming, const int modes, DirectShadingComponents& value) const override { const InputValues* values = static_cast<const InputValues*>(data); const float alpha = microfacet_alpha_from_roughness(values->m_roughness); const Vector3f wo = local_geometry.m_shading_basis.transform_to_local(outgoing); const Vector3f wi = local_geometry.m_shading_basis.transform_to_local(incoming); const Vector3f m = alpha == 0.0f ? Vector3f(0.0f, 1.0f, 0.0f) : normalize(wi + wo); const float Fo = fresnel_reflectance(wo, m, values->m_precomputed.m_eta); const float Fi = fresnel_reflectance(wi, m, values->m_precomputed.m_eta); const float specular_probability = choose_specular_probability(*values, Fo); float pdf_glossy = 0.0f, pdf_diffuse = 0.0f; if (ScatteringMode::has_glossy(modes)) { evaluate_specular( values->m_specular_reflectance, alpha, wi, wo, m, Fo, value.m_glossy); pdf_glossy = specular_pdf(alpha, wo, m); } if (ScatteringMode::has_diffuse(modes)) { evaluate_diffuse( values->m_diffuse_reflectance, values->m_precomputed.m_eta, values->m_internal_scattering, Fo, Fi, value.m_diffuse); pdf_diffuse = std::abs(wi.y) * RcpPi<float>(); } value.m_beauty = value.m_diffuse; value.m_beauty += value.m_glossy; const float pdf = ScatteringMode::has_diffuse_and_glossy(modes) ? lerp(pdf_diffuse, pdf_glossy, specular_probability) : ScatteringMode::has_diffuse(modes) ? pdf_diffuse : ScatteringMode::has_glossy(modes) ? pdf_glossy : 0.0f; assert(pdf >= 0.0f); return pdf; } float evaluate_pdf( const void* data, const bool adjoint, const LocalGeometry& local_geometry, const Vector3f& outgoing, const Vector3f& incoming, const int modes) const override { const InputValues* values = static_cast<const InputValues*>(data); const float alpha = microfacet_alpha_from_roughness(values->m_roughness); const Vector3f wo = local_geometry.m_shading_basis.transform_to_local(outgoing); const Vector3f wi = local_geometry.m_shading_basis.transform_to_local(incoming); const Vector3f m = alpha == 0.0f ? Vector3f(0.0f, 1.0f, 0.0f) : normalize(wi + wo); const float F = fresnel_reflectance(wo, m, values->m_precomputed.m_eta); const float specular_probability = choose_specular_probability(*values, F); const float pdf_glossy = ScatteringMode::has_glossy(modes) ? specular_pdf(alpha, wo, m) : 0.0f; const float pdf_diffuse = ScatteringMode::has_diffuse(modes) ? std::abs(wi.y) * RcpPi<float>() : 0.0f; const float pdf = ScatteringMode::has_diffuse_and_glossy(modes) ? lerp(pdf_diffuse, pdf_glossy, specular_probability) : ScatteringMode::has_diffuse(modes) ? pdf_diffuse : ScatteringMode::has_glossy(modes) ? pdf_glossy : 0.0f; assert(pdf >= 0.0f); return pdf; } private: typedef PlasticBRDFInputValues InputValues; static float choose_specular_probability( const InputValues& values, const float F) { const float specular_weight = F * values.m_precomputed.m_specular_weight; const float diffuse_weight = (1.0f - F) * values.m_precomputed.m_diffuse_weight; const float total_weight = specular_weight + diffuse_weight; return total_weight == 0.0f ? 1.0f : specular_weight / total_weight; } static float fresnel_reflectance( const Vector3f& w, const Vector3f& m, const float eta) { const float cos_wm(dot(w, m)); if (cos_wm < 0.0f) return 0.0f; float F; fresnel_reflectance_dielectric( F, eta, std::min(cos_wm, 1.0f)); return F; } static void evaluate_specular( const Spectrum& specular_reflectance, const float alpha, const Vector3f& wi, const Vector3f& wo, const Vector3f& m, const float F, Spectrum& value) { if (alpha == 0.0f) return; const float denom = std::abs(4.0f * wo.y * wi.y); if (denom == 0.0f) { value.set(0.0f); return; } value = specular_reflectance; const float D = GGXMDF::D(m, alpha); const float G = GGXMDF::G(wi, wo, m, alpha); value *= F * D * G / denom; } static float specular_pdf( const float alpha, const Vector3f& wo, const Vector3f& m) { if (alpha == 0.0f) return 0.0f; const float cos_wom = dot(wo, m); if (cos_wom == 0.0f) return 0.0f; const float jacobian = 1.0f / (4.0f * std::abs(cos_wom)); return jacobian * GGXMDF::pdf(wo, m, alpha, alpha); } static void evaluate_diffuse( const Spectrum& diffuse_reflectance, const float eta, const float internal_scattering, const float Fo, const float Fi, Spectrum& value) { const float eta2 = square(eta); const float fdr = fresnel_internal_diffuse_reflectance(1.0f / eta); const float T = (1.0f - Fo) * (1.0f - Fi); for (size_t i = 0, e = Spectrum::size(); i < e; ++i) { const float pd = diffuse_reflectance[i]; const float non_linear_term = 1.0f - lerp(1.0f, pd, internal_scattering) * fdr; value[i] = (T * pd * eta2 * RcpPi<float>()) / non_linear_term; } } }; typedef BSDFWrapper<PlasticBRDFImpl> PlasticBRDF; } // // PlasticBRDFFactory class implementation. // void PlasticBRDFFactory::release() { delete this; } const char* PlasticBRDFFactory::get_model() const { return Model; } Dictionary PlasticBRDFFactory::get_model_metadata() const { return Dictionary() .insert("name", Model) .insert("label", "Plastic BRDF"); } DictionaryArray PlasticBRDFFactory::get_input_metadata() const { DictionaryArray metadata; metadata.push_back( Dictionary() .insert("name", "diffuse_reflectance") .insert("label", "Diffuse Reflectance") .insert("type", "colormap") .insert("entity_types", Dictionary() .insert("color", "Colors") .insert("texture_instance", "Texture Instances")) .insert("use", "required") .insert("default", "0.5")); metadata.push_back( Dictionary() .insert("name", "diffuse_reflectance_multiplier") .insert("label", "Diffuse Reflectance Multiplier") .insert("type", "colormap") .insert("entity_types", Dictionary().insert("texture_instance", "Texture Instances")) .insert("use", "optional") .insert("default", "1.0")); metadata.push_back( Dictionary() .insert("name", "specular_reflectance") .insert("label", "Specular Reflectance") .insert("type", "colormap") .insert("entity_types", Dictionary() .insert("color", "Colors") .insert("texture_instance", "Texture Instances")) .insert("use", "required") .insert("default", "1.0")); metadata.push_back( Dictionary() .insert("name", "specular_reflectance_multiplier") .insert("label", "Specular Reflectance Multiplier") .insert("type", "colormap") .insert("entity_types", Dictionary().insert("texture_instance", "Texture Instances")) .insert("use", "optional") .insert("default", "1.0")); metadata.push_back( Dictionary() .insert("name", "roughness") .insert("label", "Roughness") .insert("type", "colormap") .insert("entity_types", Dictionary() .insert("color", "Colors") .insert("texture_instance", "Texture Instances")) .insert("use", "optional") .insert("min", Dictionary() .insert("value", "0.0") .insert("type", "hard")) .insert("max", Dictionary() .insert("value", "1.0") .insert("type", "hard")) .insert("default", "0.15")); metadata.push_back( Dictionary() .insert("name", "ior") .insert("label", "Index of Refraction") .insert("type", "numeric") .insert("min", Dictionary() .insert("value", "1.0") .insert("type", "hard")) .insert("max", Dictionary() .insert("value", "2.5") .insert("type", "hard")) .insert("use", "required") .insert("default", "1.5")); metadata.push_back( Dictionary() .insert("name", "internal_scattering") .insert("label", "Internal Scattering") .insert("type", "numeric") .insert("min", Dictionary() .insert("value", "0.0") .insert("type", "hard")) .insert("max", Dictionary() .insert("value", "1.0") .insert("type", "hard")) .insert("use", "optional") .insert("default", "1.0")); return metadata; } auto_release_ptr<BSDF> PlasticBRDFFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<BSDF>(new PlasticBRDF(name, params)); } } // namespace renderer
est77/appleseed
src/appleseed/renderer/modeling/bsdf/plasticbrdf.cpp
C++
mit
21,564
#!/usr/bin/env python3.7 # coding=utf-8 """Jerod Gawne, 2018.06.28 https://github.com/jerodg/hackerrank """ import sys import traceback if __name__ == '__main__': try: n, m = map(int, input().split()) for i in range(1, n, 2): print(str('.|.') * i).center(m, '-') print(str('WELCOME').center(m, '-')) for i in range(n - 2, -1, -2): print(str('.|.') * i).center(m, '-') except Exception: print(traceback.print_exception(*sys.exc_info()))
jerodg/hackerrank-python
python/02.Strings/08.DesignerDoorMat/solution1.py
Python
mit
510
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TheWorld.Services { using System.Diagnostics; public class DebugMailService : IMailService { public void SendMail(string to, string from, string subject, string body) { Debug.WriteLine($"Sending Mail: To {to}, From {from}, Subject {subject}"); } } }
tonyisaway/aspdotnetcore-efcore-bootstrap-angular-web-app
TheWorld/Services/DebugMailService.cs
C#
mit
414
'use strict'; const { ManyToManyModifyMixin } = require('./ManyToManyModifyMixin'); const SQLITE_BUILTIN_ROW_ID = '_rowid_'; // We need to override this mixin for sqlite because sqlite doesn't support // multi-column where in statements with subqueries. We need to use the // internal _rowid_ column instead. const ManyToManySqliteModifyMixin = (Operation) => { return class extends ManyToManyModifyMixin(Operation) { applyModifyFilterForRelatedTable(builder) { const tableRef = builder.tableRefFor(this.relation.relatedModelClass); const rowIdRef = `${tableRef}.${SQLITE_BUILTIN_ROW_ID}`; const subquery = this.modifyFilterSubquery.clone().select(rowIdRef); return builder.whereInComposite(rowIdRef, subquery); } applyModifyFilterForJoinTable(builder) { const joinTableOwnerRefs = this.relation.joinTableOwnerProp.refs(builder); const tableRef = builder.tableRefFor(this.relation.getJoinModelClass(builder)); const rowIdRef = `${tableRef}.${SQLITE_BUILTIN_ROW_ID}`; const ownerValues = this.owner.getProps(this.relation); const subquery = this.modifyFilterSubquery.clone().select(rowIdRef); return builder .whereInComposite(rowIdRef, subquery) .whereInComposite(joinTableOwnerRefs, ownerValues); } }; }; module.exports = { ManyToManySqliteModifyMixin, };
Vincit/objection.js
lib/relations/manyToMany/ManyToManySqliteModifyMixin.js
JavaScript
mit
1,361
@extends('layouts.default') @section('content') @include('game.partials.header') <!-- game menu --> <div class="row"> <div class="col-sm-5 movie-production"> <p>Current loan: {{ $currentLoan }} € (max. 2000000 €)</p> {{ Form::open(['route' => 'takeLoan_path']) }} <div class="form-group"> {{ Form::label('amount', 'Loan:') }} {{ Form::input('number', 'amount', 0, ['class' => 'input-sm form-control', 'max' => (2000000 - $currentLoan), 'min' => 0, 'step' => 100000]) }} </div> <div class="form-group div-button-footer"> {{ link_to_route('menu_path', 'Go back', null, ['class' => 'btn btn-sm btn-default']) }} {{ Form::submit('Take loan!', ['class' => 'btn btn-sm btn-success']) }} </div> {{ Form::close() }} </div> </div> @stop
teruk/movbizz
app/views/loan/take.blade.php
PHP
mit
783
class AddIsCommentToAnswers < ActiveRecord::Migration[4.2] def change add_column :answers, :is_comment, :boolean, default: false end end
wested/surveyor_gui
db/migrate/20140531012006_add_is_comment_to_answers.rb
Ruby
mit
145
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /> <title>Onboard Network - Advertise with Music Influencers</title> <link type="text/css" rel="stylesheet" href="<?php echo asset_url();?>css/bootstrap.css" /> <link href="<?php echo asset_url();?>css/bootstrap-slider.css" rel="stylesheet"> <link href="<?php echo asset_url();?>css/style.css" type="text/css" rel="stylesheet" /> <link href='https://fonts.googleapis.com/css?family=Oswald:400,300,700' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic,800,800italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,200,200italic,300,300italic,400italic,600,600italic,700,900,900italic,700italic' rel='stylesheet' type='text/css'> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <link type="text/css" rel="stylesheet" href="<?php echo asset_url();?>css/jquery.bxslider.css" /> <script src="<?php echo asset_url();?>js/bootstrap.js"></script> <script> $(document).ready(function (){ $("#frm_login").submit(function (e){ e.preventDefault(); var url = $(this).attr('action'); var method = $(this).attr('method'); var data = $(this).serialize(); console.log(data); console.log(method); console.log(url); $.ajax({ url:url, type:method, data:data }).done(function(data){ console.log(data); if(data == false){ $("#error_section").html("Incorrect username/password"); } else { window.location.href='<?php echo base_url() ?>Main/members'; } }); }); $("#testt").on("click",function(){ var url = "http://maps.googleapis.com/maps/api/geocode/json?address=95123&sensor=true"; $.ajax({ url: url, method: 'GET', dataType: 'json', success: function(result){ console.log(result); } }) }); $("#find_doctor").on("click",function(){ $("#modal_title").html("Please enter zipcode"); $("#modal_body").html('<div class="form-group"><div class="col-xs-3"></br><input type="zipCode" class="form-control" name="zipCode" id="zipCode" placeholder="Enter your zip code"></div></div><a href="<?php echo base_url() ?>Doctors"><button type="button" name="submit" class="btn btn-default">Submit</button></a>'); }); $("#find_clinic").on("click",function(){ $("#modal_title").html("Please enter zipcode"); $("#modal_body").html('<div class="form-group"><div class="col-xs-3"></br><input type="zipCode" class="form-control" name="zipCode" id="zipCode" placeholder="Enter your zip code"></div></div><a href="<?php echo base_url() ?>Clinics"><button type="button" name="submit" class="btn btn-default">Submit</button></a>'); }); // $("#sign_in").on("click", function(){ // $(".modal-title").html("Please sign in to your account."); // $(".modal-body").html(' <div class="container"> <form method="post" id="frm_login" class="form-inline" role="form" accept-charset="utf-8" action="<?php echo base_url()?>Main/login_validation"> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" value="<?php $this->input->post('email')?>"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" name="password" id="password" placeholder="Enter password"> </div> <button type="submit" name="login_submit" class="btn btn-default">Submit</button> <a href="<?php echo base_url()?>main/signup"> Sign up!</a> <div class="form_validation_error" id="error_section"><?php echo validation_errors();?></div> </form> </div>'); // }); }); </script> </head> <body ng-app="fertility"> <section id="clinic"> </section> <section id="header" class="inner clinic"> <div class="container"> <nav class="navbar navbar-default navbar-static-top responsive col-lg-12" role="navigation"> <div class="navbar-header responsive"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div id="logo" class="navbar-brand"> <a href="<?php echo base_url() ?>">FERTILITY COUNSELORS</a> </div> </div> <div id="navbar" class="navbar-collapse text-right collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="<?php echo base_url() ?>">HOME</a></li> <li><a href="#">ABOUT</a></li> <li><a href="#">CONTACT</a></li> <li><a data-toggle="modal" data-target="#myModal2" id="find_clinic">CLINICS</a></li> <li><a data-toggle="modal" data-target="#myModal2" id="find_doctor">DOCTORS</a></li> <li><a data-toggle="modal" data-target="#myModal">SIGN IN</a></li> </ul> </div><!--/.nav-collapse --> </nav> </div> </section> <!-- Modal --> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header" style="background-color: #335764;color: white;"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Please sign in to your account.</h4> </div> <div class="modal-body"> <div class="container"> <form method="post" id="frm_login" class="form-inline" role="form" accept-charset="utf-8" action="<?php echo base_url()?>Main/login_validation"> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" value="<?php $this->input->post('email')?>"> </div> <div class="form-group"> <label for="pwd">Password:</label> <input type="password" class="form-control" name="password" id="password" placeholder="Enter password"> </div> <button type="submit" name="login_submit" class="btn btn-default">Submit</button> <a href="<?php echo base_url()?>main/signup"> Sign up!</a> <div class="form_validation_error" id="error_section"><?php echo validation_errors();?></div> </form> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!-- Modal --> <div id="myModal2" class="modal fade" role="dialog"> <div class="modal-dialog modal-lg"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header" style="background-color: #335764;color: white;"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title" id="modal_title"></h4> </div> <div class="modal-body" id="modal_body"> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div>
shahin1986/fertility_dev
application/views/header2.php
PHP
mit
7,983
'use strict'; var Sequelize = require('sequelize'); var sq_config = require('../sequelize-config-mysql'); sq_config.database = 's06'; sq_config.options.sync.match = /s06/; var sq = new Sequelize(sq_config.database, sq_config.username, sq_config.password, sq_config.options); var models = { entry: sq.define('entry', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, validate: { isUUID: 4 }, primaryKey: true }, date: { type: Sequelize.DATE, allowNull: false, validate: { isDate: true, } }, body: { type: Sequelize.TEXT, allowNull: false, validate: { notEmpty: true, } } }, { }), tag: sq.define('tag', { id: { type: Sequelize.UUID, defaultValue: Sequelize.UUIDV4, allowNull: false, validate: { isUUID: 4 }, primaryKey: true }, value: { type: Sequelize.STRING(255), allowNull: false, unique: true, validate: { } } }, { }) }; models.tag.belongsToMany(models.entry, { through: 'entry_tag' }); models.entry.belongsToMany(models.tag, { through: 'entry_tag' }); sq.sync({ force: true }) .then(function() { var hard_coded_tag_promises = Promise.all([ models.tag.create({value: 'foo'}), models.tag.create({value: 'bar'}), models.tag.create({value: 'baz'}) ]); var hard_coded_entry_promises = Promise.all([ models.entry.create({ body: 'This is entry 0. Here is some text.', date: new Date(2015, 2, 10) }), models.entry.create({ body: 'This is entry one. Here is some more text.', date: new Date(2015, 2, 10) }), models.entry.create({ body: 'This is entry tertius III. Here is interesting text.', date: new Date(2015, 2, 12) }), models.entry.create({ body: 'this is entry iv i dont know punctuation', date: new Date(2015, 2, 11) }), models.entry.create({ body: 'This is entry si4 with id 5 and a fullstop.', date: new Date(2015, 2, 13) }), models.entry.create({ body: 'This is entry hex. Should I be a magical curse?', date: new Date(2015, 2, 14) }) ]); return Promise.all([hard_coded_tag_promises, hard_coded_entry_promises]); }) .spread(function(hard_coded_tags, hard_coded_entries) { return Promise.all([ hard_coded_entries[0].setTags([hard_coded_tags[0], hard_coded_tags[1]]), hard_coded_entries[1].setTags([hard_coded_tags[2]]), hard_coded_entries[2].setTags([hard_coded_tags[1], hard_coded_tags[2]]), hard_coded_entries[3].setTags([hard_coded_tags[0]]), hard_coded_entries[4].setTags([hard_coded_tags[1]]), hard_coded_entries[5].setTags([hard_coded_tags[0], hard_coded_tags[1], hard_coded_tags[2]]) ]); }) .then(function() { sq.close(); }) .catch(function(err) { console.warn('Rejected promise: ' + err); console.warn(err.stack); }) .done();
cfogelberg/sequelize-playground
tests/06-mysql-demo/01-populate-db.js
JavaScript
mit
2,940
<?php /** * This file is part of the Nette Framework (https://nette.org) * Copyright (c) 2004 David Grudl (https://davidgrudl.com) */ namespace Nette\Templating; use Nette; use Latte; use Nette\Utils\Strings; /** * @deprecated */ class Helpers extends Latte\Runtime\Filters { private static $helpers = array( 'normalize' => 'Nette\Utils\Strings::normalize', 'toascii' => 'Nette\Utils\Strings::toAscii', 'webalize' => 'Nette\Utils\Strings::webalize', 'padleft' => 'Nette\Utils\Strings::padLeft', 'padright' => 'Nette\Utils\Strings::padRight', 'reverse' => 'Nette\Utils\Strings::reverse', 'url' => 'rawurlencode', ); /** * Try to load the requested helper. * @param string helper name * @return callable */ public static function loader($helper) { trigger_error(__CLASS__ . ' is deprecated.', E_USER_DEPRECATED); if (method_exists(__CLASS__, $helper)) { return array(__CLASS__, $helper); } elseif (isset(self::$helpers[$helper])) { return self::$helpers[$helper]; } } /** * Date/time modification. * @param string|int|\DateTime * @param string|int * @param string * @return Nette\Utils\DateTime */ public static function modifyDate($time, $delta, $unit = NULL) { return $time == NULL // intentionally == ? NULL : Nette\Utils\DateTime::from($time)->modify($delta . $unit); } /** * Returns array of string length. * @param mixed * @return int */ public static function length($var) { return is_string($var) ? Strings::length($var) : count($var); } /** * /dev/null. * @param mixed * @return string */ public static function null() { return ''; } public static function optimizePhp($source, $lineLength = 80) { return Latte\Helpers::optimizePhp($source, $lineLength); } }
JanTvrdik/NetteComponentsExample
vendor/nette/deprecated/src/Templating/Helpers.php
PHP
mit
1,793
<?php require_once('includes/config.php'); ?> <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title> <?php echo SITENAME; ?> </title> <meta name="description" content="<?php echo DESCRIPTION ?>" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <link rel="stylesheet" href="css/normalize.css" /> <link rel="stylesheet" href="css/main.css"> <link rel="alternate" href="rss.php" title="My RSS feed" type="application/rss+xml" /> <script type="text/javascript"> window.heap=window.heap||[],heap.load=function(e,t){window.heap.appid=e,window.heap.config=t=t||{};var n=t.forceSSL||"https:"===document.location.protocol,a=document.createElement("script");a.type="text/javascript",a.async=!0,a.src=(n?"https:":"http:")+"//cdn.heapanalytics.com/js/heap-"+e+".js";var o=document.getElementsByTagName("script")[0];o.parentNode.insertBefore(a,o);for(var r=function(e){return function(){heap.push([e].concat(Array.prototype.slice.call(arguments,0)))}},p=["clearEventProperties","identify","setEventProperties","track","unsetEventProperty"],c=0;c<p.length;c++)heap[p[c]]=r(p[c])}; heap.load("14710187"); </script> </head> <body> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div id="wrapper"> <h1><?php echo SITENAME; ?></h1> <div id="nav"> <ul> <?php require_once('nav.php'); ?> </div> <div id='main'> <?php if(isset($_GET['month']) || isset($_GET['year'])) { try { //collect month and year data $month = $_GET['month']; $year = rtrim($_GET['year'], '.html'); //set from and to dates $from = date('Y-m-01 00:00:00', strtotime("$year-$month")); $to = date('Y-m-31 23:59:59', strtotime("$year-$month")); $pages = new Paginator('5', 'p'); $stmt = $db->prepare('SELECT postID FROM blog_posts_seo WHERE postDate >= :from AND postDate <= :to AND published = 1'); $stmt->execute(array( ':from' => $from, ':to' => $to )); //pass number of records to $pages->set_total($stmt->rowCount()); $stmt = $db->prepare('SELECT p.postID, m.username, p.postTitle, p.postDesc, p.postDate, p.postSlug FROM blog_posts_seo p, blog_members m WHERE p.poster = m.memberID AND postDate >= :from AND postDate <= :to AND published = 1 ORDER BY postID DESC ' . $pages->get_limit()); $stmt->execute(array( ':from' => $from, ':to' => $to )); while ($row = $stmt->fetch()) { echo '<h1><a href="viewpost.php?id=' . $row['postID'] . '">' . $row['postTitle'] . '</a></h1>'; echo '<p>Posted on ' . date('jS M Y H:i:s', strtotime($row['postDate'])) . ' by <b>' . $row['username'] . '</b> in '; $stmt2 = $db->prepare('SELECT catTitle, catSlug FROM blog_cats, blog_post_cats WHERE blog_cats.catID = blog_post_cats.catID AND blog_post_cats.postID = :postID'); $stmt2->execute(array(':postID' => $row['postID'])); $catRow = $stmt2->fetchAll(PDO::FETCH_ASSOC); $links = array(); foreach ($catRow as $cat) { $links[] = "<a href='c-" . $cat['catSlug'] . ".html'>" . $cat['catTitle'] . "</a>"; } echo implode(", ", $links); echo '</p>'; echo '<p>' . $row['postDesc'] . '</p>'; echo '<p><a href="' . $row["postSlug"] . '.html">Read More</a></p>'; } echo $pages->page_links("a-$month-$year&"); } catch (PDOException $e) { echo $e->getMessage(); } } else { echo('<p>Please choose a Month to view</p><ul>'); $stmt = $db->query("SELECT count(postDate) as Count, Month(postDate) as Month, Year(postDate) as Year FROM blog_posts_seo GROUP BY Month(postDate), Year(postDate) ORDER BY postDate DESC"); while($row = $stmt->fetch()){ $monthName = date("F", mktime(0, 0, 0, $row['Month'], 10)); $slug = 'a-'.$row['Month'].'-'.$row['Year']; echo '<li><a href="' . $slug . '.html">' . $monthName . ' ' . $row['Year'] . ' (' . $row["Count"] . ' posts)</a></li>'; } echo('</ul>'); } ?> </div> <div id='clear'></div> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> <!-- Piwik --> <script type="text/javascript"> var _paq = _paq || []; _paq.push(["setDocumentTitle", document.domain + "/" + document.title]); _paq.push(["setCookieDomain", "*.marctowler.co.uk"]); _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u=(("https:" == document.location.protocol) ? "https" : "http") + "://marctowler.co.uk/piwik/"; _paq.push(['setTrackerUrl', u+'piwik.php']); _paq.push(['setSiteId', 1]); var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.defer=true; g.async=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); </script> <noscript><p><img src="https://www.marctowler.co.uk/piwik/piwik.php?idsite=1" style="border:0;" alt="" /></p></noscript> <!-- End Piwik Code --> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-37729517-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
MarcTowler/blog
archives.php
PHP
mit
6,940
<?php namespace AwsUpload\Tests; use PHPUnit\Framework\TestCase; use Symfony\Component\Filesystem\Filesystem; abstract class BaseTestCase extends TestCase { protected $main_external; protected $main_aws_home; /** * The directory that contain the AWSUPLOAD_HOME. * * Foreach test we want this folder clean. * So, each time we use the class to make it unique. * * @var string */ protected $aws_home; /** * The directory to simulate outside of AWSUPLOAD_HOME. * * @var string */ protected $external; /** * {@inheritdoc} */ public function setUp() { $uid = strtolower(get_class($this)); $uid = str_replace('\\', '-', $uid); $this->main_aws_home = __DIR__ . '/../../aws_upload/'; $this->aws_home = $this->main_aws_home . $uid; putenv("AWSUPLOAD_HOME=" . $this->aws_home); $this->main_external = __DIR__ . '/../../external/'; $this->external = $this->main_external . $uid; $filesystem = new Filesystem(); $filesystem->mkdir($this->aws_home); $filesystem->mkdir($this->external); } /** * {@inheritdoc} */ public function tearDown() { unset($_ENV['AWSUPLOAD_HOME']); $filesystem = new Filesystem(); $filesystem->remove($this->main_aws_home); $filesystem->remove($this->main_external); } /** * Clear the $_SERVER['argv'] array */ public static function clearArgv() { $_SERVER['argv'] = array(); $_SERVER['argc'] = 0; } /** * Add one or more element(s) at the end of the $_SERVER['argv'] array * * @param string[] $args Value to add to the argv array. */ public static function pushToArgv($args) { if (is_string($args)) { $args = explode(' ', $args); } foreach ($args as $arg) { array_push($_SERVER['argv'], $arg); } $_SERVER['argc'] += count($args); } }
borracciaBlu/aws-upload
tests/AwsUpload/BaseTestCase.php
PHP
mit
2,048
/* * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved */ #include "../StroikaPreComp.h" #include "TimeOutException.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; /* ******************************************************************************** ********************************* TimeOutException ***************************** ******************************************************************************** */ #if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy const TimeOutException TimeOutException::kThe; #endif TimeOutException::TimeOutException () : TimeOutException{L"Timeout Expired"sv} { } TimeOutException::TimeOutException (error_code ec) : TimeOutException{ec, L"Timeout Expired"sv} { } TimeOutException::TimeOutException (const Characters::String& message) : TimeOutException{make_error_code (errc::timed_out), message} { } /* ******************************************************************************** ************************ Execution::ThrowTimeOutException ********************** ******************************************************************************** */ void Execution::ThrowTimeOutException () { Throw (TimeOutException::kThe); }
SophistSolutions/Stroika
Library/Sources/Stroika/Foundation/Execution/TimeOutException.cpp
C++
mit
1,274
import { Component } from '@angular/core'; @Component({ templateUrl: './login.html' }) export class Login { }
aikin/ghsm
app/src/pages/login/login.ts
TypeScript
mit
117
class AppointmentCanceledNotification attr_accessor :appointment def initialize(appointment) @appointment = appointment end def message { message: 'Seu horário foi cancelado :/', data: { appointment_id: appointment.id, type: 'appointment_canceled' } } end def channel "Customer_#{appointment.customer.token}" end end
BarberHour/barber-hour-api
app/notifications/appointment_canceled_notification.rb
Ruby
mit
385
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("uWebshop.DataAccess")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("uWebshop")] [assembly: AssemblyProduct("uWebshop.DataAccess")] [assembly: AssemblyCopyright("Copyright © uWebshop 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("df6aa836-1eb3-47b5-ac04-746221102822")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("2.6.1.0")] [assembly: AssemblyFileVersion("2.6.1.0")]
uWebshop/uWebshop-Releases
Core/uWebshop.DataAccess/Properties/AssemblyInfo.cs
C#
mit
1,269
Liquid::Template.register_filter(YetAnotherTagCloud)
vaudoc/jk
vendor/plugins/yet_another_tag_cloud/init.rb
Ruby
mit
53
var searchData= [ ['bullet_2ecpp',['bullet.cpp',['../bullet_8cpp.html',1,'']]], ['bullet_2eh',['bullet.h',['../bullet_8h.html',1,'']]] ];
SineJunky/ascii-game
ASCII-Game/docs/html/search/files_62.js
JavaScript
mit
142
import React, { Component } from "react"; import { browserHistory, Link } from "react-router"; import update from "react-addons-update"; class AuthoredPost extends Component { constructor(props) { super(props); this.state = { isVisible: { display: "block" }, post: {} }; } handleChange(event) { let newState = update(this.state, { $merge: { [event.target.name]: event.target.value } }); this.setState(newState); } handleDelete() { fetch(`http://localhost:3000/posts/${this.props.id}/${this.props.user_id}`, { method: "DELETE" }) .then(() => { this.setState({ isVisible: { display: "none"}}); browserHistory.push('/dashboard'); }) .catch((err) => { console.log("ERROR:", err); }); } render() { return( <div key={this.props.id} style={this.state.isVisible}> <div className="authored_posts"> <h3>{this.props.title}</h3> <img src={this.props.image_url} width="250px" /> <p>{this.props.post_text}</p> <div className="source-category"> <p><a href={this.props.source_url} target="_blank">Source URL</a></p> <p className="dashboard-category-icon">{this.props.category}</p> </div> <div className="dashboard-button-container"> <Link to={`/${this.props.id}/edit`}> <button>Edit Post</button> </Link> <Link to="/dashboard"> <button onClick={this.handleDelete.bind(this)}>&times;</button> </Link> </div> </div> </div> ); } } export default AuthoredPost;
jeremypross/lcjr-frontend
src/components/Dashboard/AuthoredPost.js
JavaScript
mit
1,691
<?php namespace Sokil\State; class Transition { private $name; /** * @var string */ private $initialStateName; /** * @var string */ private $resultingStateName; /** * @var callable which checks if transition acceptable */ private $acceptConditionCallable; /** * @var array Transition metadata */ private $metadata; public function __construct($name, $initialState, $resultingState, callable $acceptConditionCallable = null, array $metadata = []) { $this->name = $name; $this->initialStateName = $initialState; $this->resultingStateName = $resultingState; $this->acceptConditionCallable = $acceptConditionCallable; $this->metadata = $metadata; } public function getName() { return $this->name; } /** * @return string */ public function getInitialStateName() { return $this->initialStateName; } /** * @return string */ public function getResultingStateName() { return $this->resultingStateName; } public function isAcceptable() { if (!$this->acceptConditionCallable) { return true; } return call_user_func($this->acceptConditionCallable); } public function getMetadata($key = null) { if (!$key) { return $this->metadata; } if (!isset($this->metadata[$key])) { return null; } return $this->metadata[$key]; } public function __toString() { return $this->name; } }
sokil/php-state
src/Transition.php
PHP
mit
1,636
using System.Collections; using System.Collections.Generic; using UnityEngine; // タックル それは 自機と同じ当たり判定を持った自爆攻撃 public class Tackle : BulletBase { [SerializeField] GameObject hitEffectPrefab; void Start() { OnStart(); } void Update() { if (shooter == null) { Destroy(this.gameObject); return; } if (trans == null) return; // 敵と同じ位置に移動する trans.localPosition = shooter.localPosition; } void OnTriggerEnter2D(Collider2D other) { if (hitEffectPrefab != null) { var go = GameObject.Instantiate(hitEffectPrefab); var effectTrans = go.transform; effectTrans.SetParent(transform.parent); // 弾は消えるので親オブジェクトに関連付ける effectTrans.localPosition = transform.localPosition; effectTrans.localScale = Vector3.one; } HitSE.Play(); Destroy(this.gameObject); Hp hp = shooter.gameObject.GetComponent<Hp> (); if (hp != null) hp.OnDamage(hp.MaxHP); else Destroy(shooter.gameObject); } }
enpel/ggj2017-deliciousset
UnityProject/Assets/Scripts/Battle/Tackle.cs
C#
mit
1,051
dependsOn("dependencyCircular2.js");
SoloVid/grunt-ordered-concat
test/fixtures/dependencyCircular1.js
JavaScript
mit
37
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var aurelia_pal_1 = require("aurelia-pal"); function configure(config, spinnerConfig) { config.globalResources(aurelia_pal_1.PLATFORM.moduleName('./spinner')); config.container.registerInstance('spinner-config', spinnerConfig); } exports.configure = configure; var spinner_config_1 = require("./spinner-config"); exports.spinnerViews = spinner_config_1.spinnerViews;
ne0guille/aurelia-spinner
dist/commonjs/index.js
JavaScript
mit
452
import { FETCH_POSTS_REQUEST_VIDEO, FETCH_POSTS_SUCCESS_VIDEO, FETCH_POSTS_FAILURE_VIDEO, } from '../actions/VideoAction'; const initialState = { videoAssets: [], isFetching: false, failure: false, } const fetchVideoAssets = (state = initialState, action) => { switch (action.type) { case FETCH_POSTS_REQUEST_VIDEO: return { ...state, isFetching: true }; case FETCH_POSTS_SUCCESS_VIDEO: return { ...state, isFetching: false, videoAssets: action.videoAssets }; case FETCH_POSTS_FAILURE_VIDEO: return { ...state, failure: true }; default: return state; } } export default fetchVideoAssets;
sikamedia/idol
src/reducers/VideoReducer.js
JavaScript
mit
649
import math d = int(input()) for _ in range(d): t, a, b, c = [int(x) for x in input().split()] l = [a, b, c] l.sort() if l[0] + l[1] < l[2]: l[2] = l[0] + l[1] print(min(t, math.floor((l[0]+l[1]+l[2])/2)))
madeinqc/IEEEXtreme9.0
06-tacostand-moderate/main.py
Python
mit
238
const React = require('react'); export default ({onQuantityChange, productId}) => ( <div className="product__element"> <img /> <input className="quantity" onChange={(e) => { e.preventDefault(); const inputValue = e.target.value; onQuantityChange({ id: productId, // in case of manual deleted input number (value === '') quantity: inputValue !== '' ? parseInt(inputValue, 10) : 0 }); }} type="number" min="1" defaultValue="1" /> <img /> </div> );
unam3/oshop_i
src/components/Quantity/Quantity.js
JavaScript
mit
545
package com.devotedmc.ExilePearl.util; import java.util.ArrayList; /** * String List class with an override for seeing if * it contains a string value, ignoring case * @author Gordon * */ @SuppressWarnings("serial") public class StringListIgnoresCase extends ArrayList<String> { @Override public boolean contains(Object o) { String paramStr = (String)o; for (String s : this) { if (paramStr.equalsIgnoreCase(s)) return true; } return false; } }
DevotedMC/ExilePearl
src/main/java/com/devotedmc/ExilePearl/util/StringListIgnoresCase.java
Java
mit
506
// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // 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. // // ======================================================================== // #include "scene.h" #include "../bvh/bvh4_factory.h" #include "../bvh/bvh8_factory.h" namespace embree { /* error raising rtcIntersect and rtcOccluded functions */ void missing_rtcCommit() { throw_RTCError(RTC_INVALID_OPERATION,"scene got not committed"); } void invalid_rtcIntersect1() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect and rtcOccluded not enabled"); } void invalid_rtcIntersect4() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect4 and rtcOccluded4 not enabled"); } void invalid_rtcIntersect8() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect8 and rtcOccluded8 not enabled"); } void invalid_rtcIntersect16() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersect16 and rtcOccluded16 not enabled"); } void invalid_rtcIntersectN() { throw_RTCError(RTC_INVALID_OPERATION,"rtcIntersectN and rtcOccludedN not enabled"); } Scene::Scene (Device* device, RTCSceneFlags sflags, RTCAlgorithmFlags aflags) : Accel(AccelData::TY_UNKNOWN), device(device), commitCounter(0), commitCounterSubdiv(0), numMappedBuffers(0), flags(sflags), aflags(aflags), needTriangleIndices(false), needTriangleVertices(false), needQuadIndices(false), needQuadVertices(false), needBezierIndices(false), needBezierVertices(false), needLineIndices(false), needLineVertices(false), needSubdivIndices(false), needSubdivVertices(false), is_build(false), modified(true), progressInterface(this), progress_monitor_function(nullptr), progress_monitor_ptr(nullptr), progress_monitor_counter(0), numIntersectionFilters1(0), numIntersectionFilters4(0), numIntersectionFilters8(0), numIntersectionFilters16(0), numIntersectionFiltersN(0) { #if defined(TASKING_INTERNAL) scheduler = nullptr; #else group = new tbb::task_group; #endif intersectors = Accel::Intersectors(missing_rtcCommit); if (device->scene_flags != -1) flags = (RTCSceneFlags) device->scene_flags; if (aflags & RTC_INTERPOLATE) { needTriangleIndices = true; needQuadIndices = true; needBezierIndices = true; needLineIndices = true; //needSubdivIndices = true; // not required for interpolation needTriangleVertices = true; needQuadVertices = true; needBezierVertices = true; needLineVertices = true; needSubdivVertices = true; } createTriangleAccel(); createTriangleMBAccel(); createQuadAccel(); createQuadMBAccel(); createSubdivAccel(); createHairAccel(); createHairMBAccel(); createLineAccel(); createLineMBAccel(); #if defined(EMBREE_GEOMETRY_TRIANGLES) accels.add(device->bvh4_factory->BVH4InstancedBVH4Triangle4ObjectSplit(this)); #endif #if defined(EMBREE_GEOMETRY_USER) accels.add(device->bvh4_factory->BVH4UserGeometry(this)); // has to be the last as the instID field of a hit instance is not invalidated by other hit geometry accels.add(device->bvh4_factory->BVH4UserGeometryMB(this)); // has to be the last as the instID field of a hit instance is not invalidated by other hit geometry #endif } void Scene::createTriangleAccel() { #if defined(EMBREE_GEOMETRY_TRIANGLES) if (device->tri_accel == "default") { if (isStatic()) { int mode = 2*(int)isCompact() + 1*(int)isRobust(); switch (mode) { case /*0b00*/ 0: #if defined (__TARGET_AVX__) if (device->hasISA(AVX)) { if (isHighQuality()) { /* new spatial split builder is now active per default */ accels.add(device->bvh8_factory->BVH8Triangle4SpatialSplit(this)); } else accels.add(device->bvh8_factory->BVH8Triangle4ObjectSplit(this)); } else #endif { if (isHighQuality()) { /* new spatial split builder is now active per default */ accels.add(device->bvh4_factory->BVH4Triangle4SpatialSplit(this)); } else accels.add(device->bvh4_factory->BVH4Triangle4ObjectSplit(this)); } break; case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4Triangle4vObjectSplit(this)); break; case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Triangle4iObjectSplit(this)); break; case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Triangle4iObjectSplit(this)); break; } } else { int mode = 2*(int)isCompact() + 1*(int)isRobust(); switch (mode) { case /*0b00*/ 0: accels.add(device->bvh4_factory->BVH4Triangle4Twolevel(this)); break; case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4Triangle4vTwolevel(this)); break; case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Triangle4iTwolevel(this)); break; case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Triangle4iTwolevel(this)); break; } } } else if (device->tri_accel == "bvh4.triangle4") accels.add(device->bvh4_factory->BVH4Triangle4(this)); else if (device->tri_accel == "bvh4.triangle4v") accels.add(device->bvh4_factory->BVH4Triangle4v(this)); else if (device->tri_accel == "bvh4.triangle4i") accels.add(device->bvh4_factory->BVH4Triangle4i(this)); #if defined (__TARGET_AVX__) else if (device->tri_accel == "bvh8.triangle4") accels.add(device->bvh8_factory->BVH8Triangle4(this)); else if (device->tri_accel == "qbvh8.triangle4i") accels.add(device->bvh8_factory->BVH8QuantizedTriangle4i(this)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown triangle acceleration structure "+device->tri_accel); #endif } void Scene::createQuadAccel() { #if defined(EMBREE_GEOMETRY_QUADS) if (device->quad_accel == "default") { int mode = 2*(int)isCompact() + 1*(int)isRobust(); switch (mode) { case /*0b00*/ 0: #if defined (__TARGET_AVX__) if (device->hasISA(AVX)) accels.add(device->bvh8_factory->BVH8Quad4v(this)); else #endif accels.add(device->bvh4_factory->BVH4Quad4v(this)); break; case /*0b01*/ 1: #if defined (__TARGET_AVX__) && 1 if (device->hasISA(AVX)) accels.add(device->bvh8_factory->BVH8Quad4i(this)); else #endif accels.add(device->bvh4_factory->BVH4Quad4i(this)); break; case /*0b10*/ 2: #if defined (__TARGET_AVX__) if (device->hasISA(AVX)) { // FIXME: reduce performance overhead of 10% compared to uncompressed bvh8 // if (isExclusiveIntersect1Mode()) // accels.add(device->bvh8_factory->BVH8QuantizedQuad4i(this)); // else accels.add(device->bvh8_factory->BVH8Quad4i(this)); } else #endif { accels.add(device->bvh4_factory->BVH4Quad4i(this)); } break; case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Quad4i(this)); break; } } else if (device->quad_accel == "bvh4.quad4v") accels.add(device->bvh4_factory->BVH4Quad4v(this)); else if (device->quad_accel == "bvh4.quad4i") accels.add(device->bvh4_factory->BVH4Quad4i(this)); else if (device->quad_accel == "qbvh4.quad4i") accels.add(device->bvh4_factory->BVH4QuantizedQuad4i(this)); #if defined (__TARGET_AVX__) else if (device->quad_accel == "bvh8.quad4v") accels.add(device->bvh8_factory->BVH8Quad4v(this)); else if (device->quad_accel == "bvh8.quad4i") accels.add(device->bvh8_factory->BVH8Quad4i(this)); else if (device->quad_accel == "qbvh8.quad4i") accels.add(device->bvh8_factory->BVH8QuantizedQuad4i(this)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown quad acceleration structure "+device->quad_accel); #endif } void Scene::createQuadMBAccel() { #if defined(EMBREE_GEOMETRY_QUADS) if (device->quad_accel_mb == "default") { int mode = 2*(int)isCompact() + 1*(int)isRobust(); switch (mode) { case /*0b00*/ 0: case /*0b01*/ 1: #if defined (__TARGET_AVX__) if (device->hasISA(AVX)) accels.add(device->bvh8_factory->BVH8Quad4iMB(this)); else #endif accels.add(device->bvh4_factory->BVH4Quad4iMB(this)); break; case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Quad4iMB(this)); break; case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Quad4iMB(this)); break; } } else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown quad acceleration structure "+device->quad_accel); #endif } void Scene::createTriangleMBAccel() { #if defined(EMBREE_GEOMETRY_TRIANGLES) if (device->tri_accel_mb == "default") { #if defined (__TARGET_AVX__) if (device->hasISA(AVX)) { accels.add(device->bvh8_factory->BVH8Triangle4vMB(this)); } else #endif { accels.add(device->bvh4_factory->BVH4Triangle4vMB(this)); } } else if (device->tri_accel_mb == "bvh4.triangle4vmb") accels.add(device->bvh4_factory->BVH4Triangle4vMB(this)); #if defined (__TARGET_AVX__) else if (device->tri_accel_mb == "bvh8.triangle4vmb") accels.add(device->bvh8_factory->BVH8Triangle4vMB(this)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown motion blur triangle acceleration structure "+device->tri_accel_mb); #endif } void Scene::createHairAccel() { #if defined(EMBREE_GEOMETRY_HAIR) if (device->hair_accel == "default") { int mode = 2*(int)isCompact() + 1*(int)isRobust(); if (isStatic()) { #if defined (__TARGET_AVX__) if (device->hasISA(AVX2)) // only enable on HSW machines, for SNB this codepath is slower { switch (mode) { case /*0b00*/ 0: accels.add(device->bvh8_factory->BVH8OBBBezier1v(this,isHighQuality())); break; case /*0b01*/ 1: accels.add(device->bvh8_factory->BVH8OBBBezier1v(this,isHighQuality())); break; case /*0b10*/ 2: accels.add(device->bvh8_factory->BVH8OBBBezier1i(this,isHighQuality())); break; case /*0b11*/ 3: accels.add(device->bvh8_factory->BVH8OBBBezier1i(this,isHighQuality())); break; } } else #endif { switch (mode) { case /*0b00*/ 0: accels.add(device->bvh4_factory->BVH4OBBBezier1v(this,isHighQuality())); break; case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4OBBBezier1v(this,isHighQuality())); break; case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4OBBBezier1i(this,isHighQuality())); break; case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4OBBBezier1i(this,isHighQuality())); break; } } } else { switch (mode) { case /*0b00*/ 0: accels.add(device->bvh4_factory->BVH4Bezier1v(this)); break; case /*0b01*/ 1: accels.add(device->bvh4_factory->BVH4Bezier1v(this)); break; case /*0b10*/ 2: accels.add(device->bvh4_factory->BVH4Bezier1i(this)); break; case /*0b11*/ 3: accels.add(device->bvh4_factory->BVH4Bezier1i(this)); break; } } } else if (device->hair_accel == "bvh4.bezier1v" ) accels.add(device->bvh4_factory->BVH4Bezier1v(this)); else if (device->hair_accel == "bvh4.bezier1i" ) accels.add(device->bvh4_factory->BVH4Bezier1i(this)); else if (device->hair_accel == "bvh4obb.bezier1v" ) accels.add(device->bvh4_factory->BVH4OBBBezier1v(this,false)); else if (device->hair_accel == "bvh4obb.bezier1i" ) accels.add(device->bvh4_factory->BVH4OBBBezier1i(this,false)); #if defined (__TARGET_AVX__) else if (device->hair_accel == "bvh8obb.bezier1v" ) accels.add(device->bvh8_factory->BVH8OBBBezier1v(this,false)); else if (device->hair_accel == "bvh8obb.bezier1i" ) accels.add(device->bvh8_factory->BVH8OBBBezier1i(this,false)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown hair acceleration structure "+device->hair_accel); #endif } void Scene::createHairMBAccel() { #if defined(EMBREE_GEOMETRY_HAIR) if (device->hair_accel_mb == "default") { #if defined (__TARGET_AVX__) if (device->hasISA(AVX2)) // only enable on HSW machines, on SNB this codepath is slower { accels.add(device->bvh8_factory->BVH8OBBBezier1iMB(this,false)); } else #endif { accels.add(device->bvh4_factory->BVH4OBBBezier1iMB(this,false)); } } else if (device->hair_accel_mb == "bvh4obb.bezier1imb") accels.add(device->bvh4_factory->BVH4OBBBezier1iMB(this,false)); #if defined (__TARGET_AVX__) else if (device->hair_accel_mb == "bvh8obb.bezier1imb") accels.add(device->bvh8_factory->BVH8OBBBezier1iMB(this,false)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown motion blur hair acceleration structure "+device->tri_accel_mb); #endif } void Scene::createLineAccel() { #if defined(EMBREE_GEOMETRY_LINES) if (device->line_accel == "default") { if (isStatic()) { #if defined (__TARGET_AVX__) if (device->hasISA(AVX) && !isCompact()) accels.add(device->bvh8_factory->BVH8Line4i(this)); else #endif accels.add(device->bvh4_factory->BVH4Line4i(this)); } else { accels.add(device->bvh4_factory->BVH4Line4iTwolevel(this)); } } else if (device->line_accel == "bvh4.line4i") accels.add(device->bvh4_factory->BVH4Line4i(this)); #if defined (__TARGET_AVX__) else if (device->line_accel == "bvh8.line4i") accels.add(device->bvh8_factory->BVH8Line4i(this)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown line segment acceleration structure "+device->line_accel); #endif } void Scene::createLineMBAccel() { #if defined(EMBREE_GEOMETRY_LINES) if (device->line_accel_mb == "default") { #if defined (__TARGET_AVX__) if (device->hasISA(AVX) && !isCompact()) accels.add(device->bvh8_factory->BVH8Line4iMB(this)); else #endif accels.add(device->bvh4_factory->BVH4Line4iMB(this)); } else if (device->line_accel_mb == "bvh4.line4imb") accels.add(device->bvh4_factory->BVH4Line4iMB(this)); #if defined (__TARGET_AVX__) else if (device->line_accel_mb == "bvh8.line4imb") accels.add(device->bvh8_factory->BVH8Line4iMB(this)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown motion blur line segment acceleration structure "+device->line_accel_mb); #endif } void Scene::createSubdivAccel() { #if defined(EMBREE_GEOMETRY_SUBDIV) if (device->subdiv_accel == "default") { if (isIncoherent(flags) && isStatic()) { #if defined (__TARGET_AVX__) if (device->hasISA(AVX)) accels.add(device->bvh8_factory->BVH8SubdivGridEager(this)); else #endif accels.add(device->bvh4_factory->BVH4SubdivGridEager(this)); } else accels.add(device->bvh4_factory->BVH4SubdivPatch1Cached(this)); } else if (device->subdiv_accel == "bvh4.subdivpatch1cached") accels.add(device->bvh4_factory->BVH4SubdivPatch1Cached(this)); else if (device->subdiv_accel == "bvh4.grid.eager" ) accels.add(device->bvh4_factory->BVH4SubdivGridEager(this)); #if defined (__TARGET_AVX__) else if (device->subdiv_accel == "bvh8.grid.eager" ) accels.add(device->bvh8_factory->BVH8SubdivGridEager(this)); #endif else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown subdiv accel "+device->subdiv_accel); #endif } Scene::~Scene () { for (size_t i=0; i<geometries.size(); i++) delete geometries[i]; #if TASKING_TBB delete group; group = nullptr; #endif } void Scene::clear() { } unsigned Scene::newUserGeometry (size_t items, size_t numTimeSteps) { Geometry* geom = new UserGeometry(this,items,numTimeSteps); return geom->id; } unsigned Scene::newInstance (Scene* scene, size_t numTimeSteps) { Geometry* geom = new Instance(this,scene,numTimeSteps); return geom->id; } unsigned Scene::newGeometryInstance (Geometry* geom) { Geometry* instance = new GeometryInstance(this,geom); return instance->id; } unsigned Scene::newTriangleMesh (RTCGeometryFlags gflags, size_t numTriangles, size_t numVertices, size_t numTimeSteps) { if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) { throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries"); return -1; } if (numTimeSteps == 0 || numTimeSteps > 2) { throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported"); return -1; } Geometry* geom = new TriangleMesh(this,gflags,numTriangles,numVertices,numTimeSteps); return geom->id; } unsigned Scene::newQuadMesh (RTCGeometryFlags gflags, size_t numQuads, size_t numVertices, size_t numTimeSteps) { if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) { throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries"); return -1; } if (numTimeSteps == 0 || numTimeSteps > 2) { throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported"); return -1; } Geometry* geom = new QuadMesh(this,gflags,numQuads,numVertices,numTimeSteps); return geom->id; } unsigned Scene::newSubdivisionMesh (RTCGeometryFlags gflags, size_t numFaces, size_t numEdges, size_t numVertices, size_t numEdgeCreases, size_t numVertexCreases, size_t numHoles, size_t numTimeSteps) { if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) { throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries"); return -1; } if (numTimeSteps == 0 || numTimeSteps > 2) { throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported"); return -1; } Geometry* geom = nullptr; #if defined(__TARGET_AVX__) if (device->hasISA(AVX)) geom = new SubdivMeshAVX(this,gflags,numFaces,numEdges,numVertices,numEdgeCreases,numVertexCreases,numHoles,numTimeSteps); else #endif geom = new SubdivMesh(this,gflags,numFaces,numEdges,numVertices,numEdgeCreases,numVertexCreases,numHoles,numTimeSteps); return geom->id; } unsigned Scene::newBezierCurves (BezierCurves::SubType subtype, RTCGeometryFlags gflags, size_t numCurves, size_t numVertices, size_t numTimeSteps) { if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) { throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries"); return -1; } if (numTimeSteps == 0 || numTimeSteps > 2) { throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported"); return -1; } Geometry* geom = new BezierCurves(this,subtype,gflags,numCurves,numVertices,numTimeSteps); return geom->id; } unsigned Scene::newLineSegments (RTCGeometryFlags gflags, size_t numSegments, size_t numVertices, size_t numTimeSteps) { if (isStatic() && (gflags != RTC_GEOMETRY_STATIC)) { throw_RTCError(RTC_INVALID_OPERATION,"static scenes can only contain static geometries"); return -1; } if (numTimeSteps == 0 || numTimeSteps > 2) { throw_RTCError(RTC_INVALID_OPERATION,"only 1 or 2 time steps supported"); return -1; } Geometry* geom = new LineSegments(this,gflags,numSegments,numVertices,numTimeSteps); return geom->id; } unsigned Scene::add(Geometry* geometry) { Lock<SpinLock> lock(geometriesMutex); if (usedIDs.size()) { unsigned id = usedIDs.back(); usedIDs.pop_back(); geometries[id] = geometry; return id; } else { geometries.push_back(geometry); return unsigned(geometries.size()-1); } } void Scene::deleteGeometry(size_t geomID) { Lock<SpinLock> lock(geometriesMutex); if (isStatic()) throw_RTCError(RTC_INVALID_OPERATION,"rtcDeleteGeometry cannot get called in static scenes"); if (geomID >= geometries.size()) throw_RTCError(RTC_INVALID_OPERATION,"invalid geometry ID"); Geometry* geometry = geometries[geomID]; if (geometry == nullptr) throw_RTCError(RTC_INVALID_OPERATION,"invalid geometry"); geometry->disable(); accels.deleteGeometry(unsigned(geomID)); usedIDs.push_back(unsigned(geomID)); geometries[geomID] = nullptr; delete geometry; } void Scene::updateInterface() { /* update bounds */ is_build = true; bounds = accels.bounds; intersectors = accels.intersectors; /* enable only algorithms choosen by application */ if ((aflags & RTC_INTERSECT_STREAM) == 0) { intersectors.intersectorN = Accel::IntersectorN(&invalid_rtcIntersectN); if ((aflags & RTC_INTERSECT1) == 0) intersectors.intersector1 = Accel::Intersector1(&invalid_rtcIntersect1); if ((aflags & RTC_INTERSECT4) == 0) intersectors.intersector4 = Accel::Intersector4(&invalid_rtcIntersect4); if ((aflags & RTC_INTERSECT8) == 0) intersectors.intersector8 = Accel::Intersector8(&invalid_rtcIntersect8); if ((aflags & RTC_INTERSECT16) == 0) intersectors.intersector16 = Accel::Intersector16(&invalid_rtcIntersect16); } /* update commit counter */ commitCounter++; } void Scene::build_task () { progress_monitor_counter = 0; /* select fast code path if no intersection filter is present */ accels.select(numIntersectionFiltersN+numIntersectionFilters4, numIntersectionFiltersN+numIntersectionFilters8, numIntersectionFiltersN+numIntersectionFilters16, numIntersectionFiltersN); /* build all hierarchies of this scene */ accels.build(0,0); /* make static geometry immutable */ if (isStatic()) { accels.immutable(); for (size_t i=0; i<geometries.size(); i++) if (geometries[i]) geometries[i]->immutable(); } /* clear modified flag */ for (size_t i=0; i<geometries.size(); i++) { Geometry* geom = geometries[i]; if (!geom) continue; if (geom->isEnabled()) geom->clearModified(); // FIXME: should builders do this? } updateInterface(); if (device->verbosity(2)) { std::cout << "created scene intersector" << std::endl; accels.print(2); std::cout << "selected scene intersector" << std::endl; intersectors.print(2); } setModified(false); } #if defined(TASKING_INTERNAL) void Scene::build (size_t threadIndex, size_t threadCount) { Lock<MutexSys> buildLock(buildMutex,false); /* allocates own taskscheduler for each build */ Ref<TaskScheduler> scheduler = nullptr; { Lock<MutexSys> lock(schedulerMutex); scheduler = this->scheduler; if (scheduler == null) { buildLock.lock(); this->scheduler = scheduler = new TaskScheduler; } } /* worker threads join build */ if (!buildLock.isLocked()) { scheduler->join(); return; } /* wait for all threads in rtcCommitThread mode */ if (threadCount != 0) scheduler->wait_for_threads(threadCount); /* fast path for unchanged scenes */ if (!isModified()) { scheduler->spawn_root([&]() { this->scheduler = nullptr; }, 1, threadCount == 0); return; } /* report error if scene not ready */ if (!ready()) { scheduler->spawn_root([&]() { this->scheduler = nullptr; }, 1, threadCount == 0); throw_RTCError(RTC_INVALID_OPERATION,"not all buffers are unmapped"); } /* initiate build */ try { scheduler->spawn_root([&]() { build_task(); this->scheduler = nullptr; }, 1, threadCount == 0); } catch (...) { accels.clear(); updateInterface(); throw; } } #endif #if defined(TASKING_TBB) void Scene::build (size_t threadIndex, size_t threadCount) { /* let threads wait for build to finish in rtcCommitThread mode */ if (threadCount != 0) { if (threadIndex > 0) { group_barrier.wait(threadCount); // FIXME: use barrier that waits in condition group->wait(); return; } } /* try to obtain build lock */ Lock<MutexSys> lock(buildMutex,buildMutex.try_lock()); /* join hierarchy build */ if (!lock.isLocked()) { #if USE_TASK_ARENA device->arena->execute([&]{ group->wait(); }); #else group->wait(); #endif while (!buildMutex.try_lock()) { __pause_cpu(); yield(); #if USE_TASK_ARENA device->arena->execute([&]{ group->wait(); }); #else group->wait(); #endif } buildMutex.unlock(); return; } if (!isModified()) { if (threadCount) group_barrier.wait(threadCount); return; } if (!ready()) { if (threadCount) group_barrier.wait(threadCount); throw_RTCError(RTC_INVALID_OPERATION,"not all buffers are unmapped"); return; } /* for best performance set FTZ and DAZ flags in the MXCSR control and status register */ unsigned int mxcsr = _mm_getcsr(); _mm_setcsr(mxcsr | /* FTZ */ (1<<15) | /* DAZ */ (1<<6)); try { #if TBB_INTERFACE_VERSION_MAJOR < 8 tbb::task_group_context ctx( tbb::task_group_context::isolated, tbb::task_group_context::default_traits); #else tbb::task_group_context ctx( tbb::task_group_context::isolated, tbb::task_group_context::default_traits | tbb::task_group_context::fp_settings ); #endif //ctx.set_priority(tbb::priority_high); #if USE_TASK_ARENA device->arena->execute([&]{ #endif group->run([&]{ tbb::parallel_for (size_t(0), size_t(1), size_t(1), [&] (size_t) { build_task(); }, ctx); }); if (threadCount) group_barrier.wait(threadCount); group->wait(); #if USE_TASK_ARENA }); #endif /* reset MXCSR register again */ _mm_setcsr(mxcsr); } catch (...) { /* reset MXCSR register again */ _mm_setcsr(mxcsr); accels.clear(); updateInterface(); throw; } } #endif void Scene::write(std::ofstream& file) { int magick = 0x35238765LL; file.write((char*)&magick,sizeof(magick)); size_t numGroups = size(); file.write((char*)&numGroups,sizeof(numGroups)); for (size_t i=0; i<numGroups; i++) { if (geometries[i]) geometries[i]->write(file); else { int type = -1; file.write((char*)&type,sizeof(type)); } } } void Scene::setProgressMonitorFunction(RTCProgressMonitorFunc func, void* ptr) { static MutexSys mutex; mutex.lock(); progress_monitor_function = func; progress_monitor_ptr = ptr; mutex.unlock(); } void Scene::progressMonitor(double dn) { if (progress_monitor_function) { size_t n = size_t(dn) + progress_monitor_counter.fetch_add(size_t(dn)); if (!progress_monitor_function(progress_monitor_ptr, n / (double(numPrimitives())))) { throw_RTCError(RTC_CANCELLED,"progress monitor forced termination"); } } } }
01alchemist/x-ray-kernel
src/embree/kernels/common/scene.cpp
C++
mit
28,173
<?php namespace Event\GeneralBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('event_general'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
oachkatzlschwoaf/EVENTS
src/Event/GeneralBundle/DependencyInjection/Configuration.php
PHP
mit
881
/* dont use imports, use require, because errors are coming when we are dynamically using services in the base model*/ let uiTypes = require('../../utils/ui-types'); // let ObjectID = require('mongodb').ObjectID; // const model = require('../../models/trips'); -- wont work as this file is required on model creation const collection = 'Trips'; module.exports = { type: 'form', requestType: 'get', schemaFields: ['pickup.date', 'pickup.address', 'pickup.contact', 'pickup.material', 'drop.date', 'drop.address', 'drop.contact', 'drop.itemsToDrop', 'vehicleRequirements', 'totalWeight', 'totalWeightUnit'], // pick fields configuration from default schema schemaOverrideFeilds: { // 'pickup': { // minItems: 1 // }, }, //override above listed schema fields defaults: { status: 'New' }, prepare: (cacheKey, schema, serviceConfig) => { //on schema prepare - sync call //add any extra fields which are not in schema etc, default values etc //can do based on role, app etc by using the "cacheKey" //cacheKey format 'TRIPS_TRUCKS#ADMIN#TRIPS#FORM#ADDTRIP' // console.log(cacheKey); // console.log(schema); }, get: { preValidate: (serviceConfig, req, res, options, cb) => {//on init hook, will get executed on service request - init console.log('get prevalidate'); cb();//if error, return as first argument }, callback: (schema, serviceConfig, req, res, options, cb) => {//callback hook - after serving the request - forms & grid console.log('get callback', req.params.id); if (req.params.id || req.query.id) { const model = require('mongoose').model(collection); let params = { id: req.params.id || req.query.id }; model.getById(params, { response: { schema: schema } }, cb); } else { cb(null, schema); } } } };
peakhigh/tapi
server/services/trips/getTripStats.js
JavaScript
mit
2,036
module Popmovies module Models class TvShow attr_accessor :title, :url def initialize(title, url) @title = title @url = url end end end end
gntics/popmovies
lib/popmovies/models/tv_show.rb
Ruby
mit
189
import { processErrorSymbol } from "./symbols"; import { flatten } from "./utils/general"; import { buildErrorMaps, getValidatorInput } from "./utils/process"; import skurt from "./utils/skurt"; import * as types from "../types"; export default function asyncProcess<S, A extends types.AnyAction>({ state, action, validatorMap, mode, }: types.AsyncProcessInput<S, A>): Promise<types.ProcessOutput<A>> { function failure(result: types.ValidationResult): boolean { return result !== true; } function binaryProcess(): Promise<types.ProcessOutput<A>> { function getResult<S, A extends types.AnyAction, K extends keyof A>( validator: types.Validator<S, A, K>, fieldKey: K, validatorInput: types.ValidatorInput<S, A, K>, ): Promise<types.ValidationResult> { return new Promise((resolve) => { resolve(validator.check(validatorInput)); }) .catch((externalError) => { return false; }); } const results = []; for (const fieldKey of Object.keys(validatorMap)) { const validatorInput = getValidatorInput({ action, state, fieldKey}); for (const validator of validatorMap[fieldKey]!) { results.push(getResult(validator, fieldKey, validatorInput)); } } return skurt(failure)(1)(results).then((failures) => !failures.length); } function normalProcess(): Promise<types.ProcessOutput<A>> { function getResult<S, A extends types.AnyAction, K extends keyof A>( { check, error }: types.Validator<S, A, K>, fieldKey: K, validatorInput: types.ValidatorInput<S, A, K>, ): Promise<types.ValidationResult> { return new Promise((resolve) => { resolve(check(validatorInput)); }) .then((result) => { if (result === true) { return true; } else { return { fieldKey, error: error(validatorInput), }; } }) .catch((externalError) => { externalError[processErrorSymbol] = true; return { fieldKey, error: externalError, }; }); } function getFieldFailures(): Array<Promise<types.Failure[]>> { const findFailures = skurt(failure)(mode); const fieldResults: Array<Promise<types.Failure[]>> = []; for (const fieldKey of Object.keys(validatorMap)) { const fieldResult: Array<Promise<types.ValidationResult>> = []; const validatorInput = getValidatorInput({ action, state, fieldKey}); for (const validator of validatorMap[fieldKey]!) { const result = getResult(validator, fieldKey, validatorInput); fieldResult.push(result); } fieldResults.push(findFailures(fieldResult)); } return fieldResults; } return Promise.all(getFieldFailures()) .then(flatten) .then((failures) => { if (failures.length) { return buildErrorMaps<A>(failures); } else { return true; } }); } return mode === 0 ? binaryProcess() : normalProcess(); }
contrarian/redux-tsa
src/internal/asyncProcess.ts
TypeScript
mit
3,588
#!/usr/bin/env python #file cogent.parse.mothur.py """Parses Mothur otu list""" from record_finder import is_empty __author__ = "Kyle Bittinger" __copyright__ = "Copyright 2007-2012, The Cogent Project" __credits__ = ["Kyle Bittinger"] __license__ = "GPL" __version__ = "1.5.3" __maintainer__ = "Kyle Bittinger" __email__ = "kylebittinger@gmail.com" __status__ = "Prototype" def parse_otu_list(lines, precision=0.0049): """Parser for mothur *.list file To ensure all distances are of type float, the parser returns a distance of 0.0 for the unique groups. However, if some sequences are very similar, mothur may return a grouping at zero distance. What Mothur really means by this, however, is that the clustering is at the level of Mothur's precision. In this case, the parser returns the distance explicitly. If you are parsing otu's with a non-default precision, you must specify the precision here to ensure that the parsed distances are in order. Returns an iterator over (distance, otu_list) """ for line in lines: if is_empty(line): continue tokens = line.strip().split('\t') distance_str = tokens.pop(0) if distance_str.lstrip().lower().startswith('u'): distance = 0.0 elif distance_str == '0.0': distance = float(precision) else: distance = float(distance_str) num_otus = int(tokens.pop(0)) otu_list = [t.split(',') for t in tokens] yield (distance, otu_list)
sauloal/cnidaria
scripts/venv/lib/python2.7/site-packages/cogent/parse/mothur.py
Python
mit
1,558
import isLocationAction from '../src/pure-utils/isLocationAction' import isServer from '../src/pure-utils/isServer' import objectValues from '../src/pure-utils/objectValues' import nestAction from '../src/pure-utils/nestAction' import pathToAction from '../src/pure-utils/pathToAction' import actionToPath from '../src/pure-utils/actionToPath' import changePageTitle from '../src/pure-utils/changePageTitle' import { NOT_FOUND } from '../src/actions' it('isLocationAction(action) if has meta.location object', () => { let ret = isLocationAction({}) expect(ret).toBeFalsy() ret = isLocationAction({ meta: { location: { } } }) expect(ret).toBeTruthy() }) it('isServer()', () => { expect(isServer()).toEqual(false) global.window.SSRtest = true expect(isServer()).toEqual(true) delete global.window.SSRtest }) it('objectValues(routesMap) converts map of routes to an array of routes without the action type keys', () => { const routesMap = { ACTION_TYPE: '/foo/:bar', ACTION_TYPE_2: { path: '/path/:baz/', capitalizedWords: true }, } const ret = objectValues(routesMap) expect(ret).toEqual([routesMap.ACTION_TYPE, routesMap.ACTION_TYPE_2]) console.log(ret) }) it('nestAction(pathname, action, location)', () => { const pathname = 'path' const receivedAction = { type: 'FOO', payload: { bar: 'baz' }, meta: { info: 'something' } } const location = { pathname: 'previous', type: 'PREV', payload: { bla: 'prev' } } let action = nestAction(pathname, receivedAction, location) expect(action).toMatchSnapshot() expect(action.type).toEqual('FOO') expect(action.payload).toEqual({ bar: 'baz' }) expect(action.type).toEqual(action.meta.location.current.type) expect(action.payload).toEqual(action.meta.location.current.payload) expect(action.meta.location.prev).toEqual(location) expect(action.meta).toMatchObject(receivedAction.meta) expect(action.meta.location.current.pathname).toEqual(pathname) console.log(action) console.log(action.meta.location) expect(action.meta.location.load).not.toBeDefined() action = nestAction(pathname, receivedAction, location, 'load') expect(action.meta.location.load).toEqual(true) }) describe('pathToAction(path, routesMap)', () => { it('parse path into action using routePath without /:param segment', () => { const routesMap = { INFO: '/info', INFO_PARAM: '/info/:param', } const action = pathToAction('/info', routesMap) expect(action).toEqual({ type: 'INFO', payload: {} }) console.log(action) }) it('parse path into action using routePath with /:param segment', () => { const routesMap = { INFO: '/info', INFO_PARAM: '/info/:param', } const action = pathToAction('/info/foo', routesMap) expect(action).toEqual({ type: 'INFO_PARAM', payload: { param: 'foo' } }) console.log(action) }) it('parse path (/info/foo-bar) into action using route object containing capitalizedWords: true: payload: { param: "Foo Bar" }', () => { const path = '/info/foo-bar' const routesMap = { INFO_PARAM: { path: '/info/:param/', capitalizedWords: true }, } const action = pathToAction(path, routesMap) expect(action.payload.param).toEqual('Foo Bar') console.log(action) }) it('parse path into action using route object containing fromPath() function', () => { const path = '/info/foo-bar' const routesMap = { INFO_PARAM: { path: '/info/:param/', fromPath: (segment, key) => (`${segment} ${key}`).replace('-', ' ').toUpperCase() }, } const action = pathToAction(path, routesMap) expect(action.payload.param).toEqual('FOO BAR PARAM') console.log(action) }) it('parse path containing number param into action with payload value set as integer instead of string', () => { const path = '/info/69' const routesMap = { INFO_PARAM: { path: '/info/:param/' }, } const action = pathToAction(path, routesMap) expect(typeof action.payload.param).toEqual('number') expect(action.payload.param).toEqual(69) console.log(action) }) it('parsed path not found and return NOT_FOUND action.type: "@@pure-redux-router/NOT_FOUND"', () => { const path = '/info/foo/bar' const routesMap = { INFO_PARAM: { path: '/info/:param/' }, } const action = pathToAction(path, routesMap) expect(action.type).toEqual(NOT_FOUND) console.log(action) }) }) describe('actionToPath(action, routesMap)', () => { it('parse action into path without payload: /info', () => { const action = { type: 'INFO' } const routesMap = { INFO: '/info', INFO_PARAM: '/info/:param', } const path = actionToPath(action, routesMap) expect(path).toEqual('/info') console.log(path) }) it('parse action payload into path segment: /info/foo', () => { const action = { type: 'INFO_PARAM', payload: { param: 'foo' } } const routesMap = { INFO: '/info', INFO_PARAM: '/info/:param', } const path = actionToPath(action, routesMap) expect(path).toEqual('/info/foo') console.log(path) }) it('parse action into path with numerical payload key value: /info/69', () => { const action = { type: 'INFO_PARAM', payload: { param: 69 } } const routesMap = { INFO: '/info', INFO_PARAM: { path: '/info/:param', capitalizedWords: true }, } const path = actionToPath(action, routesMap) expect(path).toEqual('/info/69') console.log(path) }) it('parse action into path with parameters using route object containing capitalizedWords: true: /info/foo-bar', () => { const action = { type: 'INFO_PARAM', payload: { param: 'Foo Bar' } } const routesMap = { INFO_PARAM: { path: '/info/:param', capitalizedWords: true }, } const path = actionToPath(action, routesMap) expect(path).toEqual('/info/foo-bar') console.log(path) }) it('parse action into path with parameters using route object containing toPath() function: /info/foo-param-bar', () => { const action = { type: 'INFO_PARAM', payload: { param: 'Foo Bar' } } const routesMap = { INFO_PARAM: { path: '/info/:param', toPath: (value, key) => value.replace(' ', `-${key}-`).toLowerCase() }, } const path = actionToPath(action, routesMap) expect(path).toEqual('/info/foo-param-bar') console.log(path) }) it('perform no formatting when route object contains ONLY path key: /info/FooBar', () => { const action = { type: 'INFO_PARAM', payload: { param: 'FooBar' } } const routesMap = { INFO_PARAM: { path: '/info/:param' }, } const path = actionToPath(action, routesMap) expect(path).toEqual('/info/FooBar') console.log(path) }) it('throw error when parsing non-matched action', () => { const routesMap = { INFO: { path: '/info' }, } let performMatch = () => actionToPath({ type: 'MISSED' }, routesMap) expect(performMatch).toThrowError() performMatch = () => actionToPath({ type: 'INFO' }, routesMap) expect(performMatch).not.toThrowError() }) }) describe('changePageTitle()', () => { it('when title changes set it to document.title', () => { const document = { } const title = 'foo' const ret = changePageTitle(document, title) console.log(document) expect(document).toEqual({ title: 'foo' }) expect(ret).toEqual('foo') }) it('when title changes do not set document.title', () => { const document = { title: 'foo' } const title = 'foo' const ret = changePageTitle(document, title) console.log(document) expect(document).toEqual({ title: 'foo' }) expect(ret).toEqual(null) // no return value when title does not change }) })
celebvidy/pure-redux-router
__tests__/pure-utils.js
JavaScript
mit
7,737
using System.Collections.Concurrent; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.LanguageServerProtocol.Handlers { public class DocumentVersions { private readonly ConcurrentDictionary<DocumentUri, int> _documentVersions = new ConcurrentDictionary<DocumentUri, int>(); public int? GetVersion(DocumentUri documentUri) { if (_documentVersions.TryGetValue(documentUri, out var version)) { return version; } return null; } public void Update(VersionedTextDocumentIdentifier identifier) { _documentVersions.AddOrUpdate(identifier.Uri, identifier.Version, (uri, i) => identifier.Version); } public void Update(OptionalVersionedTextDocumentIdentifier identifier) { _documentVersions.AddOrUpdate(identifier.Uri, identifier.Version ?? 0, (uri, i) => identifier.Version ?? 0); } public void Reset(TextDocumentIdentifier identifier) { _documentVersions.AddOrUpdate(identifier.Uri, 0, (uri, i) => 0); } public void Remove(TextDocumentIdentifier identifier) { _documentVersions.TryRemove(identifier.Uri, out _); } } }
OmniSharp/omnisharp-roslyn
src/OmniSharp.LanguageServerProtocol/Handlers/DocumentVersions.cs
C#
mit
1,354
#include <iostream> #include <seqan/graph_types.h> #include <seqan/graph_algorithms.h> #include <seqan/basic/basic_math.h> using namespace seqan; using namespace std; int main () { typedef unsigned int TCargo; typedef unsigned int TSpec; typedef Graph<Directed<TCargo, TSpec> > TGraph; typedef VertexDescriptor<TGraph>::Type TVertexDescriptor; TGraph g; TVertexDescriptor edges[] = {1,0, 0,4, 2,1, 4,1, 5,1, 6,2, 3,2, 2,3, 7,3, 5,4, 6,5, 5,6, 7,6, 7,7}; cout << sizeof(edges)/sizeof(TVertexDescriptor)/2 << endl; addEdges(g, edges, sizeof(edges)/sizeof(TVertexDescriptor)/2); FILE* strmWrite = fopen("/home/stefan/Dokumente/subversion/seqan-trunk/sandbox/my_sandbox/apps/graphs_a1/graph.dot", "w"); write(strmWrite, g, DotDrawing()); fclose(strmWrite); ::std::cout << g << ::std::endl; return 0; }
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/6ndbc4zuiueuaiyv/2013-04-12T10-53-47.940+0200/sandbox/my_sandbox/apps/graphs_a2/graphs_a2.cpp
C++
mit
871
package instructions import "github.com/zxh0/jvm.go/jvmgo/jvm/rtda" // Convert int to byte type i2b struct{ NoOperandsInstruction } func (self *i2b) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() b := int32(int8(i)) stack.PushInt(b) } // Convert int to char type i2c struct{ NoOperandsInstruction } func (self *i2c) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() c := int32(uint16(i)) stack.PushInt(c) } // Convert int to short type i2s struct{ NoOperandsInstruction } func (self *i2s) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() s := int32(int16(i)) stack.PushInt(s) } // Convert int to long type i2l struct{ NoOperandsInstruction } func (self *i2l) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() l := int64(i) stack.PushLong(l) } // Convert int to float type i2f struct{ NoOperandsInstruction } func (self *i2f) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() f := float32(i) stack.PushFloat(f) } // Convert int to double type i2d struct{ NoOperandsInstruction } func (self *i2d) Execute(frame *rtda.Frame) { stack := frame.OperandStack() i := stack.PopInt() d := float64(i) stack.PushDouble(d) }
rednaxelafx/jvm.go
jvmgo/jvm/instructions/i2x.go
GO
mit
1,298
var gulp = require('gulp'); var jade = require('gulp-jade'); var copy = require('gulp-copy'); var sass = require('gulp-sass'); var watch = require('gulp-watch'); //////////WATCH//////////////////////////////////// gulp.task('watch', function () { watch('./app/**/*', function() { gulp.start('build'); }); }); //////////SASS//////////////////////////////////// gulp.task('sass', function () { gulp.src('./app/style/*.scss') .pipe(sass()) .on('error', console.error.bind(console)) .pipe(gulp.dest('./public/css/')); }); //////////COPY//////////////////////////////////// gulp.task('copy', function () { gulp.src('./app/**/*.js') .pipe(copy('./public/', {prefix:1})) }); //////////JADE//////////////////////////////////// gulp.task('jade', function() { gulp.src('./app/**/*.jade') .pipe(jade({pretty: true, doctype: 'html'})) .on('error', console.error.bind(console)) .pipe(gulp.dest('./public/')) }); //////////DEFAULT//////////////////////////////////// gulp.task('build', ['copy', 'jade', 'sass']);
erinpagemd/full-contact
gulpfile.js
JavaScript
mit
1,049
#!/usr/bin/env ruby require 'qiniu' require 'qiniu/utils' # 构建鉴权对象 Qiniu.establish_connection! access_key: 'Access_Key', secret_key: 'Secret_Key' # 要转码的文件所在的空间和文件名。 bucket = 'Bucket_Name' key = '1.mp4' # 转码所使用的队列名称。 pipeline = 'abc' # 需要添加水印的图片UrlSafeBase64,可以参考http://developer.qiniu.com/code/v6/api/dora-api/av/video-watermark.html base64URL = Qiniu::Utils.urlsafe_base64_encode('http://developer.qiniu.com/resource/logo-2.jpg') # 水印参数 fops = "avthumb/mp4/wmImage"+base64URL # 可以对转码后的文件进行使用saveas参数自定义命名,当然也可以不指定文件会默认命名并保存在当间。 saveas_key = Qiniu::Utils.urlsafe_base64_encode("<目标Bucket_Name>:<自定义文件key>") fops = fops+'|saveas/'+saveas_key pfops = Qiniu::Fop::Persistance::PfopPolicy.new( bucket, # 存储空间 key, # 最终资源名,可省略,即缺省为“创建”语义 fops, 'www.baidu.com' ) pfops.pipeline = pipeline code, result, response_headers = Qiniu::Fop::Persistance.pfop(pfops) # 打印返回的状态码以及信息 puts code puts result puts response_headers
qiniu/ruby-sdk
examples/pfop_watermark.rb
Ruby
mit
1,241
<?php // conectar $m = new MongoClient( "mongodb://root:root@ds019482.mlab.com:19482/pokemon"); // seleccionar una base de datos $db = $m->pokemon; // seleccionar una colección (equivalente a una tabla en una base de datos relacional) $colección = $db->Pokedex; $numero = (int) $_GET['id']; $nombre = $_POST['nombre']; $tipo1 = $_POST['tipo1']; $tipo2 = $_POST['tipo2']; $evolucion = $_POST['evolucion']; $imagen = $_POST['imagen']; $newdata = array('$set' => array("nombre" => $nombre, "tipos.0" => $tipo1, "tipos.1" => $tipo2, "evolucion" => $evolucion, "imagen" => $imagen)); $colección->update(array("numero" => $numero), $newdata); header('Location: Pokedex.php?accion=2');
JavierMaldonadoR/Pokedex
pokemonEditado.php
PHP
mit
816
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "MaterialCompiler.h" #include "ModelImmutableData.h" // for MaterialImmutableData #include "Material.h" #include "CompilationThread.h" #include "../../Assets/AssetUtils.h" #include "../../Assets/BlockSerializer.h" #include "../../Assets/ChunkFile.h" #include "../../Assets/IntermediateAssets.h" #include "../../Assets/ConfigFileContainer.h" #include "../../Assets/CompilerHelper.h" #include "../../ConsoleRig/Log.h" #include "../../Utility/IteratorUtils.h" #include "../../Utility/Streams/FileUtils.h" #include "../../Utility/Streams/PathUtils.h" #include "../../Utility/Streams/StreamFormatter.h" #include "../../Utility/Streams/StreamDOM.h" #include "../../Utility/StringFormat.h" #include "../../Utility/ExceptionLogging.h" #include "../../Utility/Conversion.h" #include "../../Utility/IteratorUtils.h" namespace RenderCore { extern char VersionString[]; extern char BuildDateString[]; } namespace RenderCore { namespace Assets { static const unsigned ResolvedMat_ExpectedVersion = 1; /////////////////////////////////////////////////////////////////////////////////////////////////// class RawMatConfigurations { public: std::vector<std::basic_string<utf8>> _configurations; RawMatConfigurations( const ::Assets::IntermediateAssetLocator& locator, const ::Assets::ResChar initializer[]); static const auto CompileProcessType = ConstHash64<'RawM', 'at'>::Value; auto GetDependencyValidation() const -> const std::shared_ptr<::Assets::DependencyValidation>& { return _validationCallback; } protected: std::shared_ptr<::Assets::DependencyValidation> _validationCallback; }; RawMatConfigurations::RawMatConfigurations(const ::Assets::IntermediateAssetLocator& locator, const ::Assets::ResChar initializer[]) { // Get associated "raw" material information. This is should contain the material information attached // to the geometry export (eg, .dae file). size_t sourceFileSize = 0; auto sourceFile = LoadFileAsMemoryBlock(locator._sourceID0, &sourceFileSize); if (!sourceFile || sourceFileSize == 0) Throw(::Assets::Exceptions::InvalidAsset( initializer, StringMeld<128>() << "Missing or empty file: " << locator._sourceID0)); InputStreamFormatter<utf8> formatter( MemoryMappedInputStream(sourceFile.get(), PtrAdd(sourceFile.get(), sourceFileSize))); Document<decltype(formatter)> doc(formatter); for (auto config=doc.FirstChild(); config; config=config.NextSibling()) { auto name = config.Name(); if (name.Empty()) continue; _configurations.push_back(name.AsString()); } _validationCallback = locator._dependencyValidation; } static void AddDep( std::vector<::Assets::DependentFileState>& deps, const char newDep[]) { // we need to call "GetDependentFileState" first, because this can change the // format of the filename. String compares alone aren't working well for us here auto depState = ::Assets::IntermediateAssets::Store::GetDependentFileState(newDep); auto existing = std::find_if( deps.cbegin(), deps.cend(), [&](const ::Assets::DependentFileState& test) { return test._filename == depState._filename; }); if (existing == deps.cend()) deps.push_back(depState); } static ::Assets::CompilerHelper::CompileResult CompileMaterialScaffold( const ::Assets::ResChar sourceMaterial[], const ::Assets::ResChar sourceModel[], const ::Assets::ResChar destination[]) { // Parameters must be stripped off the source model filename before we get here. // the parameters are irrelevant to the compiler -- so if they stay on the request // name, will we end up with multiple assets that are equivalent assert(MakeFileNameSplitter(sourceModel).ParametersWithDivider().Empty()); // note -- we can throw pending & invalid from here... auto& modelMat = ::Assets::GetAssetComp<RawMatConfigurations>(sourceModel); std::vector<::Assets::DependentFileState> deps; // for each configuration, we want to build a resolved material // Note that this is a bit crazy, because we're going to be loading // and re-parsing the same files over and over again! SerializableVector<std::pair<MaterialGuid, ResolvedMaterial>> resolved; SerializableVector<std::pair<MaterialGuid, std::string>> resolvedNames; resolved.reserve(modelMat._configurations.size()); auto searchRules = ::Assets::DefaultDirectorySearchRules(sourceModel); ::Assets::ResChar resolvedSourceMaterial[MaxPath]; ResolveMaterialFilename(resolvedSourceMaterial, dimof(resolvedSourceMaterial), searchRules, sourceMaterial); searchRules.AddSearchDirectoryFromFilename(resolvedSourceMaterial); AddDep(deps, sourceModel); // we need need a dependency (even if it's a missing file) using Meld = StringMeld<MaxPath, ::Assets::ResChar>; for (auto i=modelMat._configurations.cbegin(); i!=modelMat._configurations.cend(); ++i) { ResolvedMaterial resMat; std::basic_stringstream<::Assets::ResChar> resName; auto guid = MakeMaterialGuid(AsPointer(i->cbegin()), AsPointer(i->cend())); // Our resolved material comes from 3 separate inputs: // 1) model:configuration // 2) material:* // 3) material:configuration // // Some material information is actually stored in the model // source data. This is just for art-pipeline convenience -- // generally texture assignments (and other settings) are // set in the model authoring tool (eg, 3DS Max). The .material // files actually only provide overrides for settings that can't // be set within 3rd party tools. // // We don't combine the model and material information until // this step -- this gives us some flexibility to use the same // model with different material files. The material files can // also override settings from 3DS Max (eg, change texture assignments // etc). This provides a path for reusing the same model with // different material settings (eg, when we want one thing to have // a red version and a blue version) TRY { // resolve in model:configuration auto configName = Conversion::Convert<::Assets::rstring>(*i); Meld meld; meld << sourceModel << ":" << configName; resName << meld; auto& rawMat = RawMaterial::GetAsset(meld); rawMat._asset.Resolve(resMat, searchRules, &deps); } CATCH (const ::Assets::Exceptions::InvalidAsset&) { } CATCH_END if (resolvedSourceMaterial[0] != '\0') { AddDep(deps, resolvedSourceMaterial); // we need need a dependency (even if it's a missing file) TRY { // resolve in material:* Meld meld; meld << resolvedSourceMaterial << ":*"; resName << ";" << meld; auto& rawMat = RawMaterial::GetAsset(meld); rawMat._asset.Resolve(resMat, searchRules, &deps); } CATCH (const ::Assets::Exceptions::InvalidAsset&) { } CATCH_END TRY { // resolve in material:configuration Meld meld; meld << resolvedSourceMaterial << ":" << Conversion::Convert<::Assets::rstring>(*i); resName << ";" << meld; auto& rawMat = RawMaterial::GetAsset(meld); rawMat._asset.Resolve(resMat, searchRules, &deps); } CATCH (const ::Assets::Exceptions::InvalidAsset&) { } CATCH_END } resolved.push_back(std::make_pair(guid, std::move(resMat))); resolvedNames.push_back(std::make_pair(guid, resName.str())); } std::sort(resolved.begin(), resolved.end(), CompareFirst<MaterialGuid, ResolvedMaterial>()); std::sort(resolvedNames.begin(), resolvedNames.end(), CompareFirst<MaterialGuid, std::string>()); // "resolved" is now actually the data we want to write out { Serialization::NascentBlockSerializer blockSerializer; ::Serialize(blockSerializer, resolved); ::Serialize(blockSerializer, resolvedNames); auto blockSize = blockSerializer.Size(); auto block = blockSerializer.AsMemoryBlock(); Serialization::ChunkFile::SimpleChunkFileWriter output( 1, VersionString, BuildDateString, std::make_tuple(destination, "wb", 0)); output.BeginChunk(ChunkType_ResolvedMat, ResolvedMat_ExpectedVersion, Meld() << sourceModel << "&" << sourceMaterial); output.Write(block.get(), 1, blockSize); output.FinishCurrentChunk(); } return ::Assets::CompilerHelper::CompileResult { std::move(deps), std::string() }; } static void DoCompileMaterialScaffold(QueuedCompileOperation& op) { TRY { auto compileResult = CompileMaterialScaffold(op._initializer0, op._initializer1, op.GetLocator()._sourceID0); op.GetLocator()._dependencyValidation = op._destinationStore->WriteDependencies( op.GetLocator()._sourceID0, MakeStringSection(compileResult._baseDir), MakeIteratorRange(compileResult._dependencies)); assert(op.GetLocator()._dependencyValidation); op.SetState(::Assets::AssetState::Ready); } CATCH(const ::Assets::Exceptions::PendingAsset&) { throw; } CATCH(...) { op.SetState(::Assets::AssetState::Invalid); } CATCH_END } /////////////////////////////////////////////////////////////////////////////////////////////////// class MaterialScaffoldCompiler::Pimpl { public: Threading::Mutex _threadLock; std::unique_ptr<CompilationThread> _thread; }; class MatCompilerMarker : public ::Assets::ICompileMarker { public: ::Assets::IntermediateAssetLocator GetExistingAsset() const; std::shared_ptr<::Assets::PendingCompileMarker> InvokeCompile() const; StringSection<::Assets::ResChar> Initializer() const; MatCompilerMarker( ::Assets::rstring materialFilename, ::Assets::rstring modelFilename, const ::Assets::IntermediateAssets::Store& store, std::shared_ptr<MaterialScaffoldCompiler> compiler); ~MatCompilerMarker(); private: std::weak_ptr<MaterialScaffoldCompiler> _compiler; ::Assets::rstring _materialFilename, _modelFilename; const ::Assets::IntermediateAssets::Store* _store; void GetIntermediateName(::Assets::ResChar destination[], size_t destinationCount) const; }; void MatCompilerMarker::GetIntermediateName(::Assets::ResChar destination[], size_t destinationCount) const { _store->MakeIntermediateName(destination, (unsigned)destinationCount, _materialFilename.c_str()); StringMeldAppend(destination, &destination[destinationCount]) << "-" << MakeFileNameSplitter(_modelFilename).FileAndExtension().AsString() << "-resmat"; } ::Assets::IntermediateAssetLocator MatCompilerMarker::GetExistingAsset() const { ::Assets::IntermediateAssetLocator result; GetIntermediateName(result._sourceID0, dimof(result._sourceID0)); result._dependencyValidation = _store->MakeDependencyValidation(result._sourceID0); return result; } std::shared_ptr<::Assets::PendingCompileMarker> MatCompilerMarker::InvokeCompile() const { auto c = _compiler.lock(); if (!c) return nullptr; using namespace ::Assets; StringMeld<256,ResChar> debugInitializer; debugInitializer<< _materialFilename << "(material scaffold)"; auto backgroundOp = std::make_shared<QueuedCompileOperation>(); backgroundOp->SetInitializer(debugInitializer); XlCopyString(backgroundOp->_initializer0, _materialFilename); XlCopyString(backgroundOp->_initializer1, _modelFilename); backgroundOp->_destinationStore = _store; GetIntermediateName(backgroundOp->GetLocator()._sourceID0, dimof(backgroundOp->GetLocator()._sourceID0)); { ScopedLock(c->_pimpl->_threadLock); if (!c->_pimpl->_thread) c->_pimpl->_thread = std::make_unique<CompilationThread>( [](QueuedCompileOperation& op) { DoCompileMaterialScaffold(op); }); } c->_pimpl->_thread->Push(backgroundOp); return std::move(backgroundOp); } StringSection<::Assets::ResChar> MatCompilerMarker::Initializer() const { return MakeStringSection(_materialFilename); } MatCompilerMarker::MatCompilerMarker( ::Assets::rstring materialFilename, ::Assets::rstring modelFilename, const ::Assets::IntermediateAssets::Store& store, std::shared_ptr<MaterialScaffoldCompiler> compiler) : _materialFilename(materialFilename), _modelFilename(modelFilename), _compiler(std::move(compiler)), _store(&store) {} MatCompilerMarker::~MatCompilerMarker() {} std::shared_ptr<::Assets::ICompileMarker> MaterialScaffoldCompiler::PrepareAsset( uint64 typeCode, const ::Assets::ResChar* initializers[], unsigned initializerCount, const ::Assets::IntermediateAssets::Store& store) { if (initializerCount != 2 || !initializers[0][0] || !initializers[1][0]) Throw(::Exceptions::BasicLabel("Expecting exactly 2 initializers in MaterialScaffoldCompiler. Material filename first, then model filename")); const auto* materialFilename = initializers[0], *modelFilename = initializers[1]; return std::make_shared<MatCompilerMarker>(materialFilename, modelFilename, store, shared_from_this()); } void MaterialScaffoldCompiler::StallOnPendingOperations(bool cancelAll) { { ScopedLock(_pimpl->_threadLock); if (!_pimpl->_thread) return; } _pimpl->_thread->StallOnPendingOperations(cancelAll); } MaterialScaffoldCompiler::MaterialScaffoldCompiler() { _pimpl = std::make_unique<Pimpl>(); } MaterialScaffoldCompiler::~MaterialScaffoldCompiler() {} /////////////////////////////////////////////////////////////////////////////////////////////////// const MaterialImmutableData& MaterialScaffold::ImmutableData() const { Resolve(); return *(const MaterialImmutableData*)Serialization::Block_GetFirstObject(_rawMemoryBlock.get()); } const MaterialImmutableData* MaterialScaffold::TryImmutableData() const { if (!_rawMemoryBlock) return nullptr; return (const MaterialImmutableData*)Serialization::Block_GetFirstObject(_rawMemoryBlock.get()); } const ResolvedMaterial* MaterialScaffold::GetMaterial(MaterialGuid guid) const { const auto& data = ImmutableData(); auto i = LowerBound(data._materials, guid); if (i!=data._materials.end() && i->first==guid) return &i->second; return nullptr; } const char* MaterialScaffold::GetMaterialName(MaterialGuid guid) const { const auto& data = ImmutableData(); auto i = LowerBound(data._materialNames, guid); if (i!=data._materialNames.end() && i->first==guid) return i->second.c_str(); return nullptr; } static const ::Assets::AssetChunkRequest MaterialScaffoldChunkRequests[] { ::Assets::AssetChunkRequest { "Scaffold", ChunkType_ResolvedMat, ResolvedMat_ExpectedVersion, ::Assets::AssetChunkRequest::DataType::BlockSerializer } }; MaterialScaffold::MaterialScaffold(std::shared_ptr<::Assets::ICompileMarker>&& marker) : ChunkFileAsset("MaterialScaffold") { Prepare(*marker, ResolveOp{MakeIteratorRange(MaterialScaffoldChunkRequests), &Resolver}); } MaterialScaffold::MaterialScaffold(MaterialScaffold&& moveFrom) never_throws : ::Assets::ChunkFileAsset(std::move(moveFrom)) , _rawMemoryBlock(std::move(moveFrom._rawMemoryBlock)) {} MaterialScaffold& MaterialScaffold::operator=(MaterialScaffold&& moveFrom) never_throws { ::Assets::ChunkFileAsset::operator=(std::move(moveFrom)); _rawMemoryBlock = std::move(moveFrom._rawMemoryBlock); return *this; } MaterialScaffold::~MaterialScaffold() { auto* data = TryImmutableData(); if (data) data->~MaterialImmutableData(); } void MaterialScaffold::Resolver(void* obj, IteratorRange<::Assets::AssetChunkResult*> chunks) { assert(chunks.size() == 1); ((MaterialScaffold*)obj)->_rawMemoryBlock = std::move(chunks[0]._buffer); } }}
xlgames-inc/XLE
RenderCore/Assets/MaterialCompiler.cpp
C++
mit
17,643
from django.contrib import admin # Register your models here. from .models import Question, Choice class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class QuestionAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['question_text']}), ('Date information', {'fields': ['pub_date']}), ] inlines = [ChoiceInline] list_display = ('question_text', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] search_fields = ['question_text'] admin.site.register(Question, QuestionAdmin) admin.site.register(Choice)
singh-pratyush96/voter
polls/admin.py
Python
mit
593
import { Container } from "aurelia-framework"; export declare module UIUtils { var auContainer: Container; var dialogContainer: Element; var overlayContainer: Element; var taskbarContainer: Element; function lazy(T: any): any; function newInstance(T: any): any; function toast(options: any): void; function alert(options: any): Promise<{}>; function confirm(options: any): Promise<{}>; function prompt(options: any): Promise<{}>; function eventCallback(fn: any, self: any, ...rest: any[]): Promise<any>; function tether(parent: any, child: any, opts?: any): any; function loadView(url: any, parent: any, model?: any): Promise<{}>; }
avrahamcool/aurelia-ui-framework
dist/typings/utils/ui-utils.d.ts
TypeScript
mit
685
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import todo.mixins class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='TodoItem', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('done', models.BooleanField(default=False)), ('text', models.CharField(max_length=100)), ], bases=(todo.mixins.SelfPublishModel, models.Model), ), migrations.CreateModel( name='TodoList', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('description', models.TextField()), ], bases=(todo.mixins.SelfPublishModel, models.Model), ), migrations.AddField( model_name='todoitem', name='todo_list', field=models.ForeignKey(to='todo.TodoList'), ), ]
aaronbassett/djangocon-pusher
talk/todo/migrations/0001_initial.py
Python
mit
1,191
define(['jquery', 'underscore', 'backbone'], function($, _, Backbone){ var LoaderView = Backbone.View.extend({ tagName : 'div', className : 'loading-wrapper', initialize : function(cfg){ var view = this; if(cfg){ view.title = cfg.title; view.message = cfg.message; view.loadingCls = cfg.loadingCls; view.type = cfg.type; } if(!view.type){ view.type = 'circle'; } view.loaderCfg = { circle : $('<div class="loader"><div class="loader-inner ball-clip-rotate"><div></div></div></div>'), pacman: $('<div class="loader"><div class="loader-inner pacman"><div></div><div></div><div></div><div></div><div></div></div></div>') }; view.$container = (view.type && view.loaderCfg[view.type]) || view.loaderCfg.circle; view.$title = $('<p class="title text-center"/>'); view.$message = $('<p class="sub-title text-center"/>'); view.render(); }, render: function(){ var view = this, $container = view.$container.find('.loader-inner'), title = view.title, message = view.message; view.$el.append(view.$container); if(title){ view.$title.append(title); $container.append(view.$title); } if(message){ view.$message.append(message); $container.append(view.$message); } return view; } }); return LoaderView; });
saswin4u/portfolio.syl
dev/js/views/comps/loader.js
JavaScript
mit
1,703
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.Locale; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Map.Entry; public class Solution implements Runnable { public static void main(String[] args) { (new Thread(new Solution())).start(); } BufferedReader in; PrintWriter out; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } class Vert { double p; String ft; Vert l, r; Vert(double q) { p = q; ft = null; l = r = null; } } String res; int q; Vert tree() { while (res.charAt(q) != '(') q++; while (res.charAt(q) == ' ' || res.charAt(q) == '(') q++; int w = q; while (res.charAt(w) != ' ' && res.charAt(w) != ')') w++; Vert r = new Vert(Double.parseDouble(res.substring(q, w))); q = w; while (res.charAt(q) == ' ') q++; if (res.charAt(q) != ')') { w = q; while (Character.isLetter(res.charAt(w))) w++; r.ft = res.substring(q, w); q = w; r.l = tree(); r.r = tree(); } q++; return r; } TreeSet<String> qq; double dfs(Vert q, double p) { p *= q.p; if (q.ft == null) return p; else { if (qq.contains(q.ft)) return dfs(q.l, p); else return dfs(q.r, p); } } void solve() throws IOException { int l = nextInt(); res = ""; for (int i = 0; i < l; i++) { res += " " + in.readLine(); } q = 0; Vert root = tree(); int a = nextInt(); out.println(); for (int i = 0; i < a; i++) { TreeSet<String> q = new TreeSet<String>(); String s = nextToken(); int nn = nextInt(); for (int j = 0; j < nn; j++) q.add(nextToken()); qq = q; out.println(dfs(root, 1)); } } public void run() { Locale.setDefault(Locale.UK); try { if (System.getProperty("ONLINE_JUDGE") != null) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader(new File("input.txt"))); out = new PrintWriter(new FileWriter(new File("output.txt"))); } int t = nextInt(); for (int nn = 1; nn <= t; nn++) { out.print("Case #" + nn + ": "); solve(); } } catch (IOException e) { e.printStackTrace(); } out.flush(); } }
aas-integration/mini_corpus
benchmarks/09_decision_tree/alexey.enkov_0_1/src/Solution.java
Java
mit
2,990
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package TWoT; import java.io.Serializable; /** * * @author Lagoni */ public class UseableItem extends Item implements Serializable { private int healthRegen; /** * * @param itemName The name of the item * @param itemValue The value for the item * @param itemDescription The item description * @param roomDescription The item description for when you interact with * this item * @param itemId The item id * @param healthRegen The health regen for this item */ public UseableItem(String itemName, int itemValue, String itemDescription, String roomDescription, int itemId, int healthRegen) { super.setItemName(itemName); super.setItemValue(itemValue); super.setItemDescription(itemDescription); super.setRoomDescription(roomDescription); super.setItemId(itemId); this.healthRegen = healthRegen; } /** * @return the healthRegen */ public int getHealthRegen() { return healthRegen; } /** * @param healthRegen the healthRegen to set */ public void setHealthRegen(int healthRegen) { this.healthRegen = healthRegen; } }
jonaslagoni/Wizard-Of-Treldan
zuul-framework/src/TWoT/UseableItem.java
Java
mit
1,375
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.hideSpinner = exports.showSpinner = exports.hideSpinnerType = exports.showSpinnerType = void 0; var _ACTION_HANDLERS; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var showSpinnerType = 'MIDDLEWARE/SHOW_SPINNER'; exports.showSpinnerType = showSpinnerType; var hideSpinnerType = 'MIDDLEWARE/HIDE_SPINNER'; exports.hideSpinnerType = hideSpinnerType; var showSpinner = function (payload) { return { type: showSpinnerType, payload: payload }; }; exports.showSpinner = showSpinner; var hideSpinner = function (payload) { return { type: hideSpinnerType, payload: payload }; }; exports.hideSpinner = hideSpinner; var initialState = { list: [], rendering: null }; var deepCopy = function (state) { return _objectSpread({}, state, { list: _toConsumableArray(state.list) }); }; var ACTION_HANDLERS = (_ACTION_HANDLERS = {}, _defineProperty(_ACTION_HANDLERS, showSpinnerType, function (state, action) { var newState = deepCopy(state); if (action.payload && action.payload.id) { newState.list.push({ params: action.payload, id: action.payload.id }); } else { newState.rendering = { params: action.payload }; } return newState; }), _defineProperty(_ACTION_HANDLERS, hideSpinnerType, function (state, action) { var newState = deepCopy(state); if (action.payload && action.payload.id) { newState.list = newState.list.filter(function (spinnerItem) { return spinnerItem.id !== action.payload.id; }); } else { newState.rendering = null; } return newState; }), _ACTION_HANDLERS); var reducer = function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments.length > 1 ? arguments[1] : undefined; var handler = ACTION_HANDLERS[action.type]; return handler ? handler(state, action) : state; }; var _default = reducer; exports.default = _default;
talibasya/redux-store-ancillary
lib/reducers/spinner.js
JavaScript
mit
3,614
<?php /** * The MIT License (MIT) * * Copyright (c) 2013 Ivo Mandalski * * 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. */ namespace restlt\cache; use restlt\exceptions\ApplicationException; /** * RestLt native cache adapter. * * @author Vo * */ class RestltMemcachedAdapter implements CacheAdapterInterface { /** * * @var \Memcached */ protected $mc = null; /** * Exp in seconds * Default - does not expire * * @var integer */ protected $expiration = 0; /* * (non-PHPdoc) @see \restlt\cache\CacheAdapterInterface::__construct() */ public function __construct($cacheInstance = null) { if (! $cacheInstance instanceof \Memcached) { throw ApplicationException::cacheException ( 'The cache adapter must be of \Memcached type' ); } $this->mc = $cacheInstance; } /* * (non-PHPdoc) @see \restlt\cache\CacheAdapterInterface::test() */ public function test($key) { $res = $this->mc->get ( $key ); if ($this->mc->getResultCode () === \Memcached::RES_NOTFOUND) { $ret = false; } if ($res) { $ret = true; } return $ret; } /* * (non-PHPdoc) @see \restlt\cache\CacheAdapterInterface::set() */ public function set($key, $item) { $this->mc->set ( $key, $item, $this->expiration ); if ($this->mc->getResultCode () == \Memcached::RES_NOTFOUND) { $ret = false; } return true; } /* * (non-PHPdoc) @see \restlt\cache\CacheAdapterInterface::get() */ public function get($key) { $ret = $this->mc->get ( $key ); if ($this->mc->getResultCode () !== \Memcached::RES_SUCCESS) { $ret = null; } return $ret; } }
ivolator/restlt
lib/restlt/cache/RestltMemcachedAdapter.php
PHP
mit
2,618
module.exports = function(config, logger) { "use strict"; var cacheManager = require('cache-manager'); var redisCache = {}; if (process.env.NODE_ENV !== 'production') { redisCache = cacheManager.caching({store: 'memory', max: 1024*64 /*Bytes*/, ttl: 15 /*seconds*/}); } else { var redisStore = require('./redis_store'); redisCache = cacheManager.caching({store: redisStore, db: config.redis.cache, ttl: config.redis.ttl/*seconds*/}); } var mockGetDevice = function(hostname, getDevCallback) { var node = { name: hostname, deactivated: null, catalog_timestamp: '2014-01-22T04:11:05.562Z', facts_timestamp: '2014-01-22T04:10:58.232Z', report_timestamp: '2014-01-22T04:11:04.076Z' }; var puppetDevice = {error: '', node: node, facts: []}; getDevCallback(null, puppetDevice); }; var getDevice = function(hostname, getDevCallback) { redisCache.wrap('puppet:devices:' + hostname, function (cb) { getDeviceFromPuppetDB(hostname, cb); }, function (err, device) { getDevCallback(err, device); }); }; var getPuppetDBNode = function(hostname, callback) { var request = require('request'); var url = config.puppetdb.uri + '/nodes/' + hostname; logger.log('debug', 'getting node from puppetDB', {hostname: hostname, url: url}); request({ url: url, json: true }, function (error, response) { if (error) { callback(error); } else { logger.log('verbose', 'response from puppet', {body: response.body, url: url}); callback(null, response.body); } }); }; var getPuppetDBNodeFacts = function (hostname, callback) { var request = require('request'); var url = config.puppetdb.uri + '/nodes/' + hostname + '/facts'; logger.log('debug', 'getting facts from puppetDB', {hostname: hostname, url: url}); request({ url: url, json: true }, function (error, response) { if (error) { callback(error); } else { logger.log('verbose', 'response from puppet', {body: response.body, url: url}); callback(null, response.body); } }); }; var handlePuppetDBNode = function(hostname, results, callback) { if (results && results.length === 2) { var puppetDevice = {}; if (results[0].error) { var node = { name: hostname, deactivated: null, catalog_timestamp: '2014-01-22T04:11:05.562Z', facts_timestamp: '2014-01-22T04:10:58.232Z', report_timestamp: '2014-01-22T04:11:04.076Z' }; puppetDevice = {error: results[0].error, node: node, facts: []}; } else { var facts = results[1]; var factInfo = {}; for (var i=0; i<facts.length; i++) { var fact = facts[i]; factInfo[fact.name] = fact.value; } puppetDevice = {node: results[0], facts: factInfo, factsArray: facts}; } callback(null, puppetDevice); } else { callback(new Error('could not retrieve host and facts from Puppet')); } }; var getDeviceFromPuppetDB = function(hostname, getDevCallback) { logger.log('debug', 'getting device from puppet', {hostname: hostname}); var async = require('async'); async.parallel([ function (callback) { getPuppetDBNode(hostname, callback); }, function (callback) { getPuppetDBNodeFacts(hostname, callback); } ], function (err, results) { if (err) { getDevCallback(err); } else { handlePuppetDBNode(hostname, results, getDevCallback); } }); }; if (process.env.NODE_ENV === 'test') { module.getDevice = mockGetDevice; } else { module.getDevice = getDevice; } return module; };
CloudyKangaroo/cloudykangaroo
src/lib/puppet.js
JavaScript
mit
3,779
// Load all required engine components R.Engine.define({ "class": "Tutorial4", "requires": [ "R.engine.Game", "R.rendercontexts.CanvasContext" ], // Game class dependencies "depends": [ "StarObject" ] }); // Load the game object R.engine.Game.load("/starObject.js"); /** * @class Tutorial Four. Generate a simple vector drawn object and * allow the player to move it with the keyboard. */ var Tutorial4 = function() { return R.engine.Game.extend({ // The rendering context renderContext: null, /** * Called to set up the game, download any resources, and initialize * the game to its running state. */ setup: function(){ // Create the render context Tutorial4.renderContext = R.rendercontexts.CanvasContext.create("Playfield", 480, 480); Tutorial4.renderContext.setBackgroundColor("black"); // Add the new rendering context to the default engine context R.Engine.getDefaultContext().add(Tutorial4.renderContext); // Create the game object and add it to the render context. // It'll start animating immediately. Tutorial4.renderContext.add(StarObject.create()); }, /** * Return a reference to the playfield box */ getFieldRect: function() { return Tutorial4.renderContext.getViewport(); } }); };
bfattori/TheRenderEngine
tutorials/tutorial4/game.js
JavaScript
mit
1,412
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap.min.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/home.css"> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/font-awesome/css/font-awesome.min.css"> <!-- <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet"> --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet"> </head> <style type="text/css"> table td { text-align: left; } </style> <body> <div id="wrapper"> <!-- Sidebar --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="<?php echo site_url('Users/userHome') ?>" style="font-size: 25px;">STUDENTMATE</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav side-nav"> <img src="<?php echo base_url() ?>assets/images/logoNew.png" alt="logo" class="logo"> <li><a href="<?php echo site_url('Users/userHome') ?>"><i class="fa fa-dashboard"></i> Home</a></li> <li><a href="<?php echo site_url("Users/userAccommodation") ?>"><i class="fa fa-building"></i> Accomodation</a></li> <li><a href="<?php echo site_url("Users/userScholarships") ?>"><i class="fa fa-graduation-cap"></i> Scholarships</a></li> <li><a href="<?php echo site_url('Users/userClubs') ?>"><i class="fa fa-university"></i> Clubs</a></li> <li><a href="bootstrap-elements.html"><i class="fa fa-table"></i> Timetable</a></li> </ul> <ul class="nav navbar-nav navbar-right navbar-user" style="color: black;"> <li class="dropdown messages-dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-envelope"></i> Messages <span class="badge">7</span> <b class="caret"></b></a> <ul class="dropdown-menu"> <li class="dropdown-header">7 New Messages</li> <li class="message-preview"> <a href="#"> <span class="avatar"><img src="http://placehold.it/50x50"></span> <span class="name">John Smith:</span> <span class="message">Hey there, I wanted to ask you something...</span> <span class="time"><i class="fa fa-clock-o"></i> 4:34 PM</span> </a> </li> <li class="divider"></li> <li class="message-preview"> <a href="#"> <span class="avatar"><img src="http://placehold.it/50x50"></span> <span class="name">John Smith:</span> <span class="message">Hey there, I wanted to ask you something...</span> <span class="time"><i class="fa fa-clock-o"></i> 4:34 PM</span> </a> </li> <li class="divider"></li> <li class="message-preview"> <a href="#"> <span class="avatar"><img src="http://placehold.it/50x50"></span> <span class="name">John Smith:</span> <span class="message">Hey there, I wanted to ask you something...</span> <span class="time"><i class="fa fa-clock-o"></i> 4:34 PM</span> </a> </li> <li class="divider"></li> <li><a href="#">View Inbox <span class="badge">7</span></a></li> </ul> </li> <li><a href="<?php echo base_url('Users/signout'); ?>"><i class="fa fa-power-off"></i> Log Out</a></li> </ul> </div><!-- /.navbar-collapse --> </nav> <div id="page-wrapper"> <div class="row"> <div class="col-lg-12"> <h2><?php echo $_SESSION['fname']; ?></h2> <ol class="breadcrumb"> <li class="active"><i class="fa fa-user"></i> User Profile</li> </ol> <div class="row" style="text-align: center;"> <div class="col-md-3"></div> <div class="col-md-6" style="margin: auto; display: block;"> <?php echo validation_errors('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button>','</div>'); ?> <?php if($this->session->flashdata('success')): ?> <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <?php echo $this->session->flashdata('success');?> </div> <?php endif; ?> <?php echo form_open('Users/getPassword/'.$row->user_id) ?> <div class="form-group"> <label>Current Password</label> <input type="password" class="form-control" name="passwordold"> </div> <div class="form-group"> <label>New Password</label> <input type="password" class="form-control" id="password" name="password"> </div> <div class="form-group"> <label>Retype new Password</label> <input type="password" class="form-control" id="cpassword" name="cpassword" onkeyup='check();'> </div> <span id='message'></span><br><br> <button class="btn btn-primary" type="submit" name="updatebtn">Update Password</button> <?php echo form_close() ?> <br> <a href="<?php echo base_url('Users/userProfile') ?>" class="btn btn-link">Back to Profile</a> </div> </div> </div> <div class="col-md-3"></div> </div> </div> </div> </div><!-- /#wrapper --> <footer> <p class="text-right">&copy StudentMate 2017</p> </footer> <!-- JavaScript --> <script type="text/javascript"> var check = function() { if (document.getElementById('password').value == document.getElementById('cpassword').value) { document.getElementById('message').style.color = 'green'; document.getElementById('message').innerHTML = 'Password matching'; } else { document.getElementById('message').style.color = 'red'; document.getElementById('message').innerHTML = 'Password not matching'; } } </script> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script> </body> </html>
SalithaUCSC/StudentMate
application/views/pages/User/userPasswordChange.php
PHP
mit
8,480
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; using CourseWork.Views; namespace CourseWork { class Program { public static DataBase DB; public static MainForm MForm; public static FilmList Films; static void Main(string[] args) { DB = new DataBase(@".\\db.txt"); Films = new FilmList(DB.AllFilms); MForm = new MainForm(); MForm.ShowFilms(); Application.EnableVisualStyles(); Application.Run(MForm); } } class MainForm : Form { public MainPanel mainPanel; public InfoPanel infoPanel; public static int FormWidth = 620; public static int FormHeight = 500; public MainForm() { MinimumSize = new System.Drawing.Size(FormWidth, FormHeight); Width = FormWidth; Height = FormHeight; Resize += new EventHandler(MainForm_Resize); mainPanel = new MainPanel(); Controls.Add(mainPanel); infoPanel = new InfoPanel(); infoPanel.Hide(); Controls.Add(infoPanel); } public void ShowFilms() { mainPanel.ShowFoundFilms(Program.Films); } void MainForm_Resize(object sender, EventArgs e) { MainForm.FormWidth = Width; MainForm.FormHeight = Height; mainPanel.Resize(); infoPanel.Resize(); } } }
JPro173/CourseWork
Project/MainForm.cs
C#
mit
1,636
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v2/errors/keyword_plan_keyword_error.proto package errors import ( fmt "fmt" math "math" proto "github.com/golang/protobuf/proto" _ "google.golang.org/genproto/googleapis/api/annotations" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // Enum describing possible errors from applying a keyword plan keyword. type KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError int32 const ( // Enum unspecified. KeywordPlanKeywordErrorEnum_UNSPECIFIED KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 0 // The received error code is not known in this version. KeywordPlanKeywordErrorEnum_UNKNOWN KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 1 // A keyword or negative keyword has invalid match type. KeywordPlanKeywordErrorEnum_INVALID_KEYWORD_MATCH_TYPE KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 2 // A keyword or negative keyword with same text and match type already // exists. KeywordPlanKeywordErrorEnum_DUPLICATE_KEYWORD KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 3 // Keyword or negative keyword text exceeds the allowed limit. KeywordPlanKeywordErrorEnum_KEYWORD_TEXT_TOO_LONG KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 4 // Keyword or negative keyword text has invalid characters or symbols. KeywordPlanKeywordErrorEnum_KEYWORD_HAS_INVALID_CHARS KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 5 // Keyword or negative keyword text has too many words. KeywordPlanKeywordErrorEnum_KEYWORD_HAS_TOO_MANY_WORDS KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 6 // Keyword or negative keyword has invalid text. KeywordPlanKeywordErrorEnum_INVALID_KEYWORD_TEXT KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError = 7 ) var KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError_name = map[int32]string{ 0: "UNSPECIFIED", 1: "UNKNOWN", 2: "INVALID_KEYWORD_MATCH_TYPE", 3: "DUPLICATE_KEYWORD", 4: "KEYWORD_TEXT_TOO_LONG", 5: "KEYWORD_HAS_INVALID_CHARS", 6: "KEYWORD_HAS_TOO_MANY_WORDS", 7: "INVALID_KEYWORD_TEXT", } var KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError_value = map[string]int32{ "UNSPECIFIED": 0, "UNKNOWN": 1, "INVALID_KEYWORD_MATCH_TYPE": 2, "DUPLICATE_KEYWORD": 3, "KEYWORD_TEXT_TOO_LONG": 4, "KEYWORD_HAS_INVALID_CHARS": 5, "KEYWORD_HAS_TOO_MANY_WORDS": 6, "INVALID_KEYWORD_TEXT": 7, } func (x KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError) String() string { return proto.EnumName(KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError_name, int32(x)) } func (KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError) EnumDescriptor() ([]byte, []int) { return fileDescriptor_599d218080eb4c98, []int{0, 0} } // Container for enum describing possible errors from applying a keyword or a // negative keyword from a keyword plan. type KeywordPlanKeywordErrorEnum struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *KeywordPlanKeywordErrorEnum) Reset() { *m = KeywordPlanKeywordErrorEnum{} } func (m *KeywordPlanKeywordErrorEnum) String() string { return proto.CompactTextString(m) } func (*KeywordPlanKeywordErrorEnum) ProtoMessage() {} func (*KeywordPlanKeywordErrorEnum) Descriptor() ([]byte, []int) { return fileDescriptor_599d218080eb4c98, []int{0} } func (m *KeywordPlanKeywordErrorEnum) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_KeywordPlanKeywordErrorEnum.Unmarshal(m, b) } func (m *KeywordPlanKeywordErrorEnum) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_KeywordPlanKeywordErrorEnum.Marshal(b, m, deterministic) } func (m *KeywordPlanKeywordErrorEnum) XXX_Merge(src proto.Message) { xxx_messageInfo_KeywordPlanKeywordErrorEnum.Merge(m, src) } func (m *KeywordPlanKeywordErrorEnum) XXX_Size() int { return xxx_messageInfo_KeywordPlanKeywordErrorEnum.Size(m) } func (m *KeywordPlanKeywordErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_KeywordPlanKeywordErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_KeywordPlanKeywordErrorEnum proto.InternalMessageInfo func init() { proto.RegisterEnum("google.ads.googleads.v2.errors.KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError", KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError_name, KeywordPlanKeywordErrorEnum_KeywordPlanKeywordError_value) proto.RegisterType((*KeywordPlanKeywordErrorEnum)(nil), "google.ads.googleads.v2.errors.KeywordPlanKeywordErrorEnum") } func init() { proto.RegisterFile("google/ads/googleads/v2/errors/keyword_plan_keyword_error.proto", fileDescriptor_599d218080eb4c98) } var fileDescriptor_599d218080eb4c98 = []byte{ // 395 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x51, 0xcd, 0x6e, 0xd3, 0x30, 0x00, 0xa6, 0x19, 0x6c, 0x92, 0x77, 0xc0, 0x58, 0x4c, 0xb0, 0x31, 0x7a, 0xc8, 0x03, 0x38, 0x52, 0xb8, 0x99, 0x03, 0xf2, 0x12, 0xd3, 0x46, 0xed, 0x92, 0x68, 0x49, 0x33, 0x8a, 0x22, 0x59, 0x81, 0x44, 0x51, 0x45, 0x66, 0x47, 0x71, 0x19, 0xe2, 0xca, 0xa3, 0x70, 0xe4, 0x51, 0x78, 0x0c, 0x8e, 0xbc, 0x00, 0x57, 0xe4, 0x78, 0xae, 0x10, 0x52, 0x77, 0xca, 0x17, 0x7f, 0x7f, 0xd6, 0x67, 0xf0, 0xa6, 0x95, 0xb2, 0xed, 0x1a, 0xaf, 0xaa, 0x95, 0x67, 0xa0, 0x46, 0xb7, 0xbe, 0xd7, 0x0c, 0x83, 0x1c, 0x94, 0xf7, 0xa9, 0xf9, 0xfa, 0x45, 0x0e, 0x35, 0xef, 0xbb, 0x4a, 0x70, 0xfb, 0x33, 0x72, 0xb8, 0x1f, 0xe4, 0x56, 0xa2, 0xa9, 0x71, 0xe1, 0xaa, 0x56, 0x78, 0x17, 0x80, 0x6f, 0x7d, 0x6c, 0x02, 0xce, 0xce, 0x6d, 0x41, 0xbf, 0xf1, 0x2a, 0x21, 0xe4, 0xb6, 0xda, 0x6e, 0xa4, 0x50, 0xc6, 0xed, 0x7e, 0x73, 0xc0, 0x8b, 0x85, 0x49, 0x4d, 0xbb, 0x4a, 0xdc, 0x41, 0xa6, 0xad, 0x4c, 0x7c, 0xbe, 0x71, 0x7f, 0x4d, 0xc0, 0xb3, 0x3d, 0x3c, 0x7a, 0x0c, 0x8e, 0x57, 0x71, 0x96, 0xb2, 0x20, 0x7a, 0x1b, 0xb1, 0x10, 0x3e, 0x40, 0xc7, 0xe0, 0x68, 0x15, 0x2f, 0xe2, 0xe4, 0x3a, 0x86, 0x13, 0x34, 0x05, 0x67, 0x51, 0x5c, 0xd0, 0x65, 0x14, 0xf2, 0x05, 0x5b, 0x5f, 0x27, 0x57, 0x21, 0xbf, 0xa4, 0x79, 0x30, 0xe7, 0xf9, 0x3a, 0x65, 0xd0, 0x41, 0x27, 0xe0, 0x49, 0xb8, 0x4a, 0x97, 0x51, 0x40, 0x73, 0x66, 0x15, 0xf0, 0x00, 0x9d, 0x82, 0x13, 0x2b, 0xcf, 0xd9, 0xbb, 0x9c, 0xe7, 0x49, 0xc2, 0x97, 0x49, 0x3c, 0x83, 0x0f, 0xd1, 0x4b, 0x70, 0x6a, 0xa9, 0x39, 0xcd, 0xb8, 0x4d, 0x0f, 0xe6, 0xf4, 0x2a, 0x83, 0x8f, 0x74, 0xe1, 0xbf, 0xb4, 0x36, 0x5e, 0xd2, 0x78, 0xcd, 0xf5, 0x49, 0x06, 0x0f, 0xd1, 0x73, 0xf0, 0xf4, 0xff, 0x0b, 0xe9, 0x06, 0x78, 0x74, 0xf1, 0x67, 0x02, 0xdc, 0x8f, 0xf2, 0x06, 0xdf, 0xbf, 0xe4, 0xc5, 0xf9, 0x9e, 0x21, 0x52, 0xbd, 0x64, 0x3a, 0x79, 0x1f, 0xde, 0xf9, 0x5b, 0xd9, 0x55, 0xa2, 0xc5, 0x72, 0x68, 0xbd, 0xb6, 0x11, 0xe3, 0xce, 0xf6, 0x69, 0xfb, 0x8d, 0xda, 0xf7, 0xd2, 0xaf, 0xcd, 0xe7, 0xbb, 0x73, 0x30, 0xa3, 0xf4, 0x87, 0x33, 0x9d, 0x99, 0x30, 0x5a, 0x2b, 0x6c, 0xa0, 0x46, 0x85, 0x8f, 0xc7, 0x4a, 0xf5, 0xd3, 0x0a, 0x4a, 0x5a, 0xab, 0x72, 0x27, 0x28, 0x0b, 0xbf, 0x34, 0x82, 0xdf, 0x8e, 0x6b, 0x4e, 0x09, 0xa1, 0xb5, 0x22, 0x64, 0x27, 0x21, 0xa4, 0xf0, 0x09, 0x31, 0xa2, 0x0f, 0x87, 0xe3, 0xed, 0x5e, 0xfd, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x0b, 0x07, 0x3c, 0x9d, 0x86, 0x02, 0x00, 0x00, }
pushbullet/engineer
vendor/google.golang.org/genproto/googleapis/ads/googleads/v2/errors/keyword_plan_keyword_error.pb.go
GO
mit
7,574
package com.lotaris.jee.validation; import java.lang.annotation.Annotation; /** * Defines a constraint converter. * * @author Laurent Prevost <laurent.prevost@lotaris.com> * @author Cristian Calugar <cristian.calugar@fortech.ro> */ public interface IConstraintConverter { /** * Returns the error code, if one was set in the Annotation. * * @param annotationType the annotation. * @return an error code or null. */ IErrorCode getErrorCode(Class<? extends Annotation> annotationType); /** * Returns the location type, if one was set in the annotation. * * @param annotationType the annotation. * @return a location type or null. */ IErrorLocationType getErrorLocationType(Class<? extends Annotation> annotationType); }
lotaris/jee-validation
src/main/java/com/lotaris/jee/validation/IConstraintConverter.java
Java
mit
754
RSpec.describe "ROM.container" do include_context "database setup" with_adapters do let(:rom) do ROM.container(:sql, uri) do |conf| conf.default.create_table(:dragons) do primary_key :id column :name, String end conf.relation(:dragons) do schema(infer: true) end end end after do rom.gateways[:default].connection.drop_table(:dragons) end it "creates tables within the setup block" do expect(rom.relations[:dragons]).to be_kind_of(ROM::SQL::Relation) end end end
rom-rb/rom-sql
spec/integration/setup_spec.rb
Ruby
mit
583
using System.Collections.Generic; using System.Linq; using System.Web.Http; using PaginationSample.Models; using WebApi.Pagination; namespace PaginationSample.Controllers { /// <summary> /// Demonstrates the usage of the <see cref="PaginationAttribute"/>. /// </summary> [RoutePrefix("attributes")] public class AttributesController : ApiController { // This is a stand-in for a real queryable data source, such as a database private static readonly IQueryable<Person> Persons = new[] {new Person("John", "Doe"), new Person("Jane", "Smith")}. AsQueryable(); /// <summary> /// Normal response with no pagination. /// </summary> [HttpGet, Route("normal")] public IEnumerable<Person> Normal() => Persons; /// <summary> /// Response with pagination. /// </summary> [HttpGet, Route("pagination")] [Pagination] public IQueryable<Person> Pagination() => Persons; /// <summary> /// Response with pagination with a limited result set size. /// </summary> [HttpGet, Route("pagination-limited")] [Pagination(MaxCount = 1)] public IQueryable<Person> PaginationLimited() => Persons; /// <summary> /// Response with pagination and long-polling for open ended ranges. /// </summary> [HttpGet, Route("long-polling")] [Pagination(LongPolling = true)] public IQueryable<Person> LongPolling() => Persons; } }
1and1/WebApi.Pagination
Sample/Controllers/AttributesController.cs
C#
mit
1,553