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
// Copyright (c) 2015-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <zmq/zmqabstractnotifier.h> #include <util.h> CZMQAbstractNotifier::~CZMQAbstractNotifier() { assert(!psocket); } bool CZMQAbstractNotifier::NotifyBlock(const CBlockIndex * /*CBlockIndex*/) { return true; } bool CZMQAbstractNotifier::NotifyTransaction(const CTransaction &/*transaction*/) { return true; } bool CZMQAbstractNotifier::NotifyTransactionLock(const CTransactionRef &/*transaction*/) { return true; }
globaltoken/globaltoken
src/zmq/zmqabstractnotifier.cpp
C++
mit
636
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.21-2-15 description: Array.prototype.reduce - 'length' is property of the global object includes: - runTestCase.js - fnGlobalObject.js ---*/ function testcase() { function callbackfn(prevVal, curVal, idx, obj) { return (obj.length === 2); } try { var oldLen = fnGlobalObject().length; fnGlobalObject()[0] = 12; fnGlobalObject()[1] = 11; fnGlobalObject()[2] = 9; fnGlobalObject().length = 2; return Array.prototype.reduce.call(fnGlobalObject(), callbackfn, 1) === true; } finally { delete fnGlobalObject()[0]; delete fnGlobalObject()[1]; delete fnGlobalObject()[2]; fnGlobalObject().length = oldLen; } } runTestCase(testcase);
PiotrDabkowski/Js2Py
tests/test_cases/built-ins/Array/prototype/reduce/15.4.4.21-2-15.js
JavaScript
mit
1,201
import builder = require('botbuilder'); export module Helpers { export class API { public static async DownloadJson(url:string, post:boolean=false, options:any=undefined): Promise<string>{ return new Promise<string>(resolve => { var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var xhr = new XMLHttpRequest(); xhr.onload = function (){ try { resolve(xhr.responseText); } catch(e){ console.log("Error while calling api: " + e.message); } }; xhr.open(options ? "POST" : "GET", url, true); xhr.setRequestHeader('Content-Type', 'application/json') xhr.send(JSON.stringify(options)); }); } } export enum SearchType { "code", "documentation" }; }
meulta/babylonjsbot
Common/Helpers.ts
TypeScript
mit
983
using System; using System.Collections.Generic; using System.Linq; using System.Web; using WingtipToys.Models; namespace WingtipToys.Logic { public class AddProducts { public bool AddProduct(string ProductName, string ProductDesc, string ProductPrice, string ProductCategory, string ProductImagePath) { var myProduct = new Product(); myProduct.ProductName = ProductName; myProduct.Description = ProductDesc; myProduct.UnitPrice = Convert.ToDouble(ProductPrice); myProduct.ImagePath = ProductImagePath; myProduct.CategoryID = Convert.ToInt32(ProductCategory); using (ProductContext _db = new ProductContext()) { // Add product to DB. _db.Products.Add(myProduct); _db.SaveChanges(); } // Success. return true; } } }
zacblazic/wingtip-toys
WingtipToys/Logic/AddProducts.cs
C#
mit
934
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; import com.azure.resourcemanager.security.fluent.models.SecureScoreControlDefinitionItemInner; /** An instance of this class provides access to all the operations defined in SecureScoreControlDefinitionsClient. */ public interface SecureScoreControlDefinitionsClient { /** * List the available security controls, their assessments, and the max score. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> list(); /** * List the available security controls, their assessments, and the max score. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> list(Context context); /** * For a specified subscription, list the available security controls, their assessments, and the max score. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription(); /** * For a specified subscription, list the available security controls, their assessments, and the max score. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of security controls definition. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<SecureScoreControlDefinitionItemInner> listBySubscription(Context context); }
Azure/azure-sdk-for-java
sdk/security/azure-resourcemanager-security/src/main/java/com/azure/resourcemanager/security/fluent/SecureScoreControlDefinitionsClient.java
Java
mit
3,054
<?php namespace Seahinet\Catalog\Indexer; use Seahinet\Catalog\Model\Collection\Product; use Seahinet\Catalog\Model\Product as ProductModel; use Seahinet\Catalog\Model\Collection\Category; use Seahinet\Lib\Db\Sql\Ddl\Column\UnsignedInteger; use Seahinet\Lib\Indexer\Handler\AbstractHandler; use Seahinet\Lib\Indexer\Handler\Database; use Seahinet\Lib\Indexer\Provider; use Seahinet\Lib\Model\Collection\Language; use Zend\Db\Sql\Ddl; class Url implements Provider { use \Seahinet\Lib\Traits\Container; protected $path = []; public function provideStructure(AbstractHandler $handler) { if ($handler instanceof Database) { $adapter = $this->getContainer()->get('dbAdapter'); $platform = $adapter->getPlatform(); $languages = new Language; $languages->columns(['id']); foreach ($languages as $language) { $table = 'catalog_url_' . $language['id'] . '_index'; $adapter->query( 'DROP TABLE IF EXISTS ' . $table, $adapter::QUERY_MODE_EXECUTE ); $ddl = new Ddl\CreateTable($table); $ddl->addColumn(new UnsignedInteger('product_id', true, 0)) ->addColumn(new UnsignedInteger('category_id', false, 0)) ->addColumn(new Ddl\Column\Varchar('path', 512, false)) ->addConstraint(new Ddl\Constraint\UniqueKey(['category_id', 'product_id'], 'UNQ_' . strtoupper($table) . '_CATEGORY_ID_PRODUCT_ID')) ->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '_ID_PRODUCT_ENTITY_ID', 'product_id', 'product_entity', 'id', 'CASCADE', 'CASCADE')) ->addConstraint(new Ddl\Constraint\ForeignKey('FK_' . strtoupper($table) . '_ID_CATEGORY_ENTITY_ID', 'category_id', 'category_entity', 'id', 'CASCADE', 'CASCADE')) ->addConstraint(new Ddl\Index\Index('path', 'IDX_' . strtoupper($table) . '_PATH')); $adapter->query( $ddl->getSqlString($platform), $adapter::QUERY_MODE_EXECUTE ); } } else { $handler->buildStructure([['attr' => 'path', 'is_unique' => 1]]); } return true; } public function provideData(AbstractHandler $handler) { $languages = new Language; $languages->columns(['id']); foreach ($languages as $language) { $categories = new Category($language['id']); $categories->where(['status' => 1]); $categories->load(false); $data = [$language['id'] => []]; $tree = []; foreach ($categories as $category) { $tree[$category['id']] = [ 'object' => $category, 'pid' => (int) $category['parent_id'] ]; } foreach ($categories as $category) { if ($path = $this->getPath($category, $tree)) { $data[$language['id']][$category['id']] = [ 'product_id' => null, 'category_id' => $category['id'], 'path' => $path ]; } } $handler->buildData($data); $products = new Product($language['id']); $products->where(['status' => 1])->limit(50); $init = $data; for ($i = 0;; $i++) { $data = [$language['id'] => []]; $products->reset('offset')->offset(50 * $i); $products->load(false, true); if (!$products->count()) { break; } foreach ($products as $product) { $product = new ProductModel($language['id'], $product); $categories = $product->getCategories(); foreach ($categories as $category) { $data[$language['id']][] = [ 'product_id' => $product['id'], 'category_id' => $category['id'], 'path' => (isset($init[$language['id']][$category['id']]['path']) ? ($init[$language['id']][$category['id']]['path'] . '/') : '') . $product['uri_key'] ]; } } $data[$language['id']] = array_values($data[$language['id']]); $handler->buildData($data); } } return true; } private function getPath($category, $tree) { if (isset($this->path[$category['id'] . '#' . $category['uri_key']])) { return $this->path[$category['id'] . '#' . $category['uri_key']]; } if (!isset($category['uri_key'])) { return ''; } $path = $category['uri_key']; $pid = (int) $category['parent_id']; if ($pid && isset($tree[$pid])) { $path = trim($this->getPath($tree[$pid]['object'], $tree) . '/' . $path, '/'); } $this->path[$category['id'] . '#' . $category['uri_key']] = $path; return $path; } }
peachyang/py_website
app/code/Catalog/Indexer/Url.php
PHP
mit
5,418
package org.superboot.service; import com.querydsl.core.types.Predicate; import org.springframework.data.domain.Pageable; import org.superboot.base.BaseException; import org.superboot.base.BaseResponse; /** * <b> 错误日志服务接口 </b> * <p> * 功能描述: * </p> */ public interface ErrorLogService { /** * 按照微服务模块进行分组统计 * * @return * @throws BaseException */ BaseResponse getErrorLogGroupByAppName() throws BaseException; /** * 获取错误日志列表信息 * * @param pageable 分页信息 * @param predicate 查询参数 * @return * @throws BaseException */ BaseResponse getErrorLogList(Pageable pageable, Predicate predicate) throws BaseException; /** * 获取错误日志记录数 * * @return * @throws BaseException */ BaseResponse getErrorLogCount(Predicate predicate) throws BaseException; /** * 查询错误日志详细信息 * * @param id * @return * @throws BaseException */ BaseResponse getErrorLogItem(String id) throws BaseException; }
7040210/SuperBoot
super-boot-global/src/main/java/org/superboot/service/ErrorLogService.java
Java
mit
1,147
$(function () { var $container = $('#container'); var certificatesInfo = $container.data('certinfo'); var runDate = $container.data('rundate'); $('#created_date').html(runDate); var sorted_certificates = Object.keys(certificatesInfo) .sort(function( a, b ) { return certificatesInfo[a].info.days_left - certificatesInfo[b].info.days_left; }).map(function(sortedKey) { return certificatesInfo[sortedKey]; }); var card_html = String() +'<div class="col-xs-12 col-md-6 col-xl-4">' +' <div class="card text-xs-center" style="border-color:#333;">' +' <div class="card-header" style="overflow:hidden;">' +' <h4 class="text-muted" style="margin-bottom:0;">{{server}}</h4>' +' </div>' +' <div class="card-block {{background}}">' +' <h1 class="card-text display-4" style="margin-top:0;margin-bottom:-1rem;">{{days_left}}</h1>' +' <p class="card-text" style="margin-bottom:.75rem;"><small>days left</small></p>' +' </div>' +' <div class="card-footer">' +' <h6 class="text-muted" style="margin-bottom:.5rem;">Issued by: {{issuer}}</h6>' +' <h6 class="text-muted" style=""><small>{{issuer_cn}}</small></h6>' +' <h6 class="text-muted" style="margin-bottom:0;"><small>{{common_name}}</small></h6>' +' </div>' +' </div>' +'</div>'; function insert_card(json) { var card_template = Handlebars.compile(card_html), html = card_template(json); $('#panel').append(html); }; sorted_certificates.forEach(function(element, index, array){ var json = { 'server': element.server, 'days_left': element.info.days_left, 'issuer': element.issuer.org, 'common_name': element.subject.common_name, 'issuer_cn': element.issuer.common_name } if (element.info.days_left <= 30 ){ json.background = 'card-inverse card-danger'; } else if (element.info.days_left > 30 && element.info.days_left <= 60 ) { json.background = 'card-inverse card-warning'; } else if (element.info.days_left === "??") { json.background = 'card-inverse card-info'; } else { json.background = 'card-inverse card-success'; } insert_card(json); }); });
JensDebergh/certificate-dashboard
public/js/tls-dashboard/scripts.js
JavaScript
mit
2,250
from PIL import Image import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np img1 = Image.open('multipage.tif') # The following approach seems to be having issue with the # current TIFF format data print('The size of each frame is:') print(img1.size) # Plots first frame print('Frame 1') fig1 = plt.figure(1) img1.seek(0) # for i in range(250): # pixA11 = img1.getpixel((1,i)) # print(pixA11) f1 = list(img1.getdata()) print(f1[1000]) plt.imshow(img1) fig1.show() input() # Plots eleventh frame # print('Frame 11') # fig2 = plt.figure(2) # img1.seek(10) # # for i in range(250): # # pixB11 = img1.getpixel((1,i)) # # print(pixB11) # f2 = list(img1.getdata()) # print(f2[10000]) # plt.imshow(img1) # fig2.show() # input() # Create a new image fig3 = plt.figure(3) imgAvg = Image.new(img1.mode, img1.size) print(img1.mode) print(img1.size) fAvg = list() pix = imgAvg.load() for i in range(512): for j in range(512): pixVal = (f1[i*512+j] + f1[i*512+j]) / 2 # fAvg.append(pixVal) fAvg.insert(i*512+j,pixVal) imgAvg.putdata(fAvg) imgAvg.save('avg.tiff') plt.imshow(imgAvg) fig3.show() print('Average') # The following is necessary to keep the above figures 'alive' input() # data = random.random((256, 256)) # img1 = Image.fromarray(data) # img1.save('test.tiff')
johnrocamora/ImagePy
max_tiff.py
Python
mit
1,346
package com.InfinityRaider.AgriCraft.utility; import com.InfinityRaider.AgriCraft.items.ItemAgricraft; import com.InfinityRaider.AgriCraft.items.ItemNugget; import com.InfinityRaider.AgriCraft.reference.Data; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class OreDictHelper { private static final Map<String, Block> oreBlocks = new HashMap<String, Block>(); private static final Map<String, Integer> oreBlockMeta = new HashMap<String, Integer>(); private static final Map<String, Item> nuggets = new HashMap<String, Item>(); private static final Map<String, Integer> nuggetMeta = new HashMap<String, Integer>(); public static Block getOreBlockForName(String name) { return oreBlocks.get(name); } public static int getOreMetaForName(String name) { return oreBlockMeta.get(name); } public static Item getNuggetForName(String name) { return nuggets.get(name); } public static int getNuggetMetaForName(String name) { return nuggetMeta.get(name); } //checks if an itemstack has this ore dictionary entry public static boolean hasOreId(ItemStack stack, String tag) { if(stack==null || stack.getItem()==null) { return false; } int[] ids = OreDictionary.getOreIDs(stack); for(int id:ids) { if(OreDictionary.getOreName(id).equals(tag)) { return true; } } return false; } public static boolean hasOreId(Block block, String tag) { return block != null && hasOreId(new ItemStack(block), tag); } //checks if two blocks have the same ore dictionary entry public static boolean isSameOre(Block block1, int meta1, Block block2, int meta2) { if(block1==block2 && meta1==meta2) { return true; } if(block1==null || block2==null) { return false; } int[] ids1 = OreDictionary.getOreIDs(new ItemStack(block1, 1, meta1)); int[] ids2 = OreDictionary.getOreIDs(new ItemStack(block2, 1, meta2)); for (int id1:ids1) { for (int id2:ids2) { if (id1==id2) { return true; } } } return false; } //finds the ingot for a nugget ore dictionary entry public static ItemStack getIngot(String ore) { ItemStack ingot = null; ArrayList<ItemStack> entries = OreDictionary.getOres("ingot" + ore); if (entries.size() > 0 && entries.get(0).getItem() != null) { ingot = entries.get(0); } return ingot; } //finds what ores and nuggets are already registered in the ore dictionary public static void getRegisteredOres() { //Vanilla for (String oreName : Data.vanillaNuggets) { getOreBlock(oreName); if(oreBlocks.get(oreName)!=null) { getNugget(oreName); } } //Modded for (String[] data : Data.modResources) { String oreName = data[0]; getOreBlock(oreName); if(oreBlocks.get(oreName)!=null) { getNugget(oreName); } } } private static void getOreBlock(String oreName) { for (ItemStack itemStack : OreDictionary.getOres("ore"+oreName)) { if (itemStack.getItem() instanceof ItemBlock) { ItemBlock block = (ItemBlock) itemStack.getItem(); oreBlocks.put(oreName, block.field_150939_a); oreBlockMeta.put(oreName, itemStack.getItemDamage()); break; } } } private static void getNugget(String oreName) { List<ItemStack> nuggets = OreDictionary.getOres("nugget" + oreName); if (!nuggets.isEmpty()) { Item nugget = nuggets.get(0).getItem(); OreDictHelper.nuggets.put(oreName, nugget); nuggetMeta.put(oreName, nuggets.get(0).getItemDamage()); } else { ItemAgricraft nugget = new ItemNugget(oreName); OreDictionary.registerOre("nugget"+oreName, nugget); OreDictHelper.nuggets.put(oreName, nugget); nuggetMeta.put(oreName, 0); } } public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed) { return getFruitsFromOreDict(seed, true); } public static ArrayList<ItemStack> getFruitsFromOreDict(ItemStack seed, boolean sameMod) { String seedModId = IOHelper.getModId(seed); ArrayList<ItemStack> fruits = new ArrayList<ItemStack>(); for(int id:OreDictionary.getOreIDs(seed)) { if(OreDictionary.getOreName(id).substring(0,4).equalsIgnoreCase("seed")) { String name = OreDictionary.getOreName(id).substring(4); ArrayList<ItemStack> fromOredict = OreDictionary.getOres("crop"+name); for(ItemStack stack:fromOredict) { if(stack==null || stack.getItem()==null) { continue; } String stackModId = IOHelper.getModId(stack); if((!sameMod) || stackModId.equals(seedModId)) { fruits.add(stack); } } } } return fruits; } }
HenryLoenwind/AgriCraft
src/main/java/com/InfinityRaider/AgriCraft/utility/OreDictHelper.java
Java
mit
5,607
/** * Module dependencies. */ var express = require('express'); var path = require('path'); var api = require('./lib/api'); var seo = require('./lib/seo'); var app = module.exports = express(); app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.cookieParser('change this value to something unique')); app.use(express.cookieSession()); app.use(express.compress()); app.use(api); app.use(seo); app.use(express.static(path.join(__dirname, '../build'))); app.use(app.router); app.get('/loaderio-995e64d5aae415e1f10d60c9391e37ac/', function(req, res, next) { res.send('loaderio-995e64d5aae415e1f10d60c9391e37ac'); }); if ('development' === app.get('env')) { app.use(express.errorHandler()); } var cacheBuster = function(req, res, next){ res.header("Cache-Control", "no-cache, no-store, must-revalidate"); res.header("Pragma", "no-cache"); res.header("Expires", 0); next(); }; // @todo isolate to api routes... app.use(cacheBuster); // catch all which sends all urls to index page, thus starting our app // @note that because Express routes are registered in order, and we already defined our api routes // this catch all will not effect prior routes. app.use(function(req, res, next) { app.get('*', function(req, res, next) { //return res.ok('catch all'); res.redirect('/#!' + req.url); }); });
brettshollenberger/rootstrikers
server/app.js
JavaScript
mit
1,520
#include <iostream> #include <string> #include <forward_list> using namespace std; void insert(forward_list<string>& fst, const string& to_find, const string& to_add); int main() { forward_list<string> fst{ "pen", "pineapple", "apple", "pen" }; insert(fst, "pen", "and"); for (auto& i : fst) cout << i << " "; cout << endl; return 0; } void insert(forward_list<string>& fst, const string& to_find, const string& to_add) { auto prev = fst.before_begin(); for (auto iter = fst.begin(); iter != fst.end(); prev = iter++) { if (*iter == to_find) { fst.insert_after(iter, to_add); return; } } fst.insert_after(prev, to_add); return; }
sanerror/sanerror-Cpp-Primer-Answers
ch9/ex9_28.cpp
C++
mit
682
/* * MIT License * * Copyright (c) 2017 Alessandro Arcangeli <alessandroarcangeli.rm@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package mrkoopa.jfbx; public interface FbxCameraStereo extends FbxCamera { }
mrkoopa/jfbx
java/mrkoopa/jfbx/FbxCameraStereo.java
Java
mit
1,258
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; namespace LinqToDB.Data { using Linq; using Common; using SqlProvider; using SqlQuery; public partial class DataConnection { IQueryRunner IDataContext.GetQueryRunner(Query query, int queryNumber, Expression expression, object[] parameters) { CheckAndThrowOnDisposed(); return new QueryRunner(query, queryNumber, this, expression, parameters); } internal class QueryRunner : QueryRunnerBase { public QueryRunner(Query query, int queryNumber, DataConnection dataConnection, Expression expression, object[] parameters) : base(query, queryNumber, dataConnection, expression, parameters) { _dataConnection = dataConnection; } readonly DataConnection _dataConnection; readonly DateTime _startedOn = DateTime.UtcNow; readonly Stopwatch _stopwatch = Stopwatch.StartNew(); bool _isAsync; Expression _mapperExpression; public override Expression MapperExpression { get => _mapperExpression; set { _mapperExpression = value; if (value != null && Common.Configuration.Linq.TraceMapperExpression && TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null) { _dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.MapperCreated) { TraceLevel = TraceLevel.Info, DataConnection = _dataConnection, MapperExpression = MapperExpression, StartTime = _startedOn, ExecutionTime = _stopwatch.Elapsed, IsAsync = _isAsync, }); } } } public override string GetSqlText() { SetCommand(false); var sqlProvider = _preparedQuery.SqlProvider ?? _dataConnection.DataProvider.CreateSqlBuilder(); var sb = new StringBuilder(); sb.Append("-- ").Append(_dataConnection.ConfigurationString); if (_dataConnection.ConfigurationString != _dataConnection.DataProvider.Name) sb.Append(' ').Append(_dataConnection.DataProvider.Name); if (_dataConnection.DataProvider.Name != sqlProvider.Name) sb.Append(' ').Append(sqlProvider.Name); sb.AppendLine(); sqlProvider.PrintParameters(sb, _preparedQuery.Parameters); var isFirst = true; foreach (var command in _preparedQuery.Commands) { sb.AppendLine(command); if (isFirst && _preparedQuery.QueryHints != null && _preparedQuery.QueryHints.Count > 0) { isFirst = false; while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r') sb.Length--; sb.AppendLine(); var sql = sb.ToString(); var sqlBuilder = _dataConnection.DataProvider.CreateSqlBuilder(); sql = sqlBuilder.ApplyQueryHints(sql, _preparedQuery.QueryHints); sb = new StringBuilder(sql); } } while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r') sb.Length--; sb.AppendLine(); return sb.ToString(); } public override void Dispose() { if (TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null) { _dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.Completed) { TraceLevel = TraceLevel.Info, DataConnection = _dataConnection, Command = _dataConnection.Command, MapperExpression = MapperExpression, StartTime = _startedOn, ExecutionTime = _stopwatch.Elapsed, RecordsAffected = RowsCount, IsAsync = _isAsync, }); } base.Dispose(); } public class PreparedQuery { public string[] Commands; public List<SqlParameter> SqlParameters; public IDbDataParameter[] Parameters; public SqlStatement Statement; public ISqlBuilder SqlProvider; public List<string> QueryHints; } PreparedQuery _preparedQuery; static PreparedQuery GetCommand(DataConnection dataConnection, IQueryContext query, int startIndent = 0) { if (query.Context != null) { return new PreparedQuery { Commands = (string[])query.Context, SqlParameters = query.Statement.Parameters, Statement = query.Statement, QueryHints = query.QueryHints, }; } var sql = query.Statement.ProcessParameters(dataConnection.MappingSchema); var newSql = dataConnection.ProcessQuery(sql); if (!object.ReferenceEquals(sql, newSql)) { sql = newSql; sql.IsParameterDependent = true; } var sqlProvider = dataConnection.DataProvider.CreateSqlBuilder(); var cc = sqlProvider.CommandCount(sql); var sb = new StringBuilder(); var commands = new string[cc]; for (var i = 0; i < cc; i++) { sb.Length = 0; sqlProvider.BuildSql(i, sql, sb, startIndent); commands[i] = sb.ToString(); } if (!sql.IsParameterDependent) query.Context = commands; return new PreparedQuery { Commands = commands, SqlParameters = sql.Parameters, Statement = sql, SqlProvider = sqlProvider, QueryHints = query.QueryHints, }; } static void GetParameters(DataConnection dataConnection, IQueryContext query, PreparedQuery pq) { var parameters = query.GetParameters(); if (parameters.Length == 0 && pq.SqlParameters.Count == 0) return; var ordered = dataConnection.DataProvider.SqlProviderFlags.IsParameterOrderDependent; var c = ordered ? pq.SqlParameters.Count : parameters.Length; var parms = new List<IDbDataParameter>(c); if (ordered) { for (var i = 0; i < pq.SqlParameters.Count; i++) { var sqlp = pq.SqlParameters[i]; if (sqlp.IsQueryParameter) { var parm = parameters.Length > i && object.ReferenceEquals(parameters[i], sqlp) ? parameters[i] : parameters.First(p => object.ReferenceEquals(p, sqlp)); AddParameter(dataConnection, parms, parm.Name, parm); } } } else { foreach (var parm in parameters) { if (parm.IsQueryParameter && pq.SqlParameters.Contains(parm)) AddParameter(dataConnection, parms, parm.Name, parm); } } pq.Parameters = parms.ToArray(); } static void AddParameter(DataConnection dataConnection, ICollection<IDbDataParameter> parms, string name, SqlParameter parm) { var p = dataConnection.Command.CreateParameter(); var systemType = parm.SystemType; var dataType = parm.DataType; var dbType = parm.DbType; var dbSize = parm.DbSize; var paramValue = parm.Value; if (systemType == null) { if (paramValue != null) systemType = paramValue.GetType(); } if (dataType == DataType.Undefined) { dataType = dataConnection.MappingSchema.GetDataType( parm.SystemType == typeof(object) && paramValue != null ? paramValue.GetType() : systemType).DataType; } dataConnection.DataProvider.SetParameter(p, name, new DbDataType(systemType, dataType, dbType, dbSize), paramValue); parms.Add(p); } public static PreparedQuery SetQuery(DataConnection dataConnection, IQueryContext queryContext, int startIndent = 0) { var preparedQuery = GetCommand(dataConnection, queryContext, startIndent); GetParameters(dataConnection, queryContext, preparedQuery); return preparedQuery; } protected override void SetQuery() { _preparedQuery = SetQuery(_dataConnection, Query.Queries[QueryNumber]); } void SetCommand() { SetCommand(true); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); } #region ExecuteNonQuery static int ExecuteNonQueryImpl(DataConnection dataConnection, PreparedQuery preparedQuery) { if (preparedQuery.Commands.Length == 1) { dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints); if (preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); return dataConnection.ExecuteNonQuery(); } var rowsAffected = -1; for (var i = 0; i < preparedQuery.Commands.Length; i++) { dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[i], null, i == 0 ? preparedQuery.QueryHints : null); if (i == 0 && preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); if (i < preparedQuery.Commands.Length - 1 && preparedQuery.Commands[i].StartsWith("DROP")) { try { dataConnection.ExecuteNonQuery(); } catch (Exception) { } } else { var n = dataConnection.ExecuteNonQuery(); if (i == 0) rowsAffected = n; } } return rowsAffected; } public override int ExecuteNonQuery() { SetCommand(true); return ExecuteNonQueryImpl(_dataConnection, _preparedQuery); } public static int ExecuteNonQuery(DataConnection dataConnection, IQueryContext context) { var preparedQuery = GetCommand(dataConnection, context); GetParameters(dataConnection, context, preparedQuery); return ExecuteNonQueryImpl(dataConnection, preparedQuery); } #endregion #region ExecuteScalar static object ExecuteScalarImpl(DataConnection dataConnection, PreparedQuery preparedQuery) { IDbDataParameter idParam = null; if (dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired) { if (preparedQuery.Statement.NeedsIdentity()) { idParam = dataConnection.Command.CreateParameter(); idParam.ParameterName = "IDENTITY_PARAMETER"; idParam.Direction = ParameterDirection.Output; idParam.DbType = DbType.Decimal; dataConnection.Command.Parameters.Add(idParam); } } if (preparedQuery.Commands.Length == 1) { if (idParam != null) { // This is because the firebird provider does not return any parameters via ExecuteReader // the rest of the providers must support this mode dataConnection.ExecuteNonQuery(); return idParam.Value; } return dataConnection.ExecuteScalar(); } dataConnection.ExecuteNonQuery(); dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[1], null, null); return dataConnection.ExecuteScalar(); } public static object ExecuteScalar(DataConnection dataConnection, IQueryContext context) { var preparedQuery = GetCommand(dataConnection, context); GetParameters(dataConnection, context, preparedQuery); dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints); if (preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); return ExecuteScalarImpl(dataConnection, preparedQuery); } public override object ExecuteScalar() { SetCommand(); return ExecuteScalarImpl(_dataConnection, _preparedQuery); } #endregion #region ExecuteReader public static IDataReader ExecuteReader(DataConnection dataConnection, IQueryContext context) { var preparedQuery = GetCommand(dataConnection, context); GetParameters(dataConnection, context, preparedQuery); dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints); if (preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); return dataConnection.ExecuteReader(); } public override IDataReader ExecuteReader() { SetCommand(true); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); return _dataConnection.ExecuteReader(); } #endregion class DataReaderAsync : IDataReaderAsync { public DataReaderAsync(DbDataReader dataReader) { _dataReader = dataReader; } readonly DbDataReader _dataReader; public IDataReader DataReader => _dataReader; public Task<bool> ReadAsync(CancellationToken cancellationToken) { return _dataReader.ReadAsync(cancellationToken); } public void Dispose() { // call interface method, because at least MySQL provider incorrectly override // methods for .net core 1x DataReader.Dispose(); } } public override async Task<IDataReaderAsync> ExecuteReaderAsync(CancellationToken cancellationToken) { _isAsync = true; await _dataConnection.EnsureConnectionAsync(cancellationToken); base.SetCommand(true); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); var dataReader = await _dataConnection.ExecuteReaderAsync(_dataConnection.GetCommandBehavior(CommandBehavior.Default), cancellationToken); return new DataReaderAsync(dataReader); } public override async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) { _isAsync = true; await _dataConnection.EnsureConnectionAsync(cancellationToken); base.SetCommand(true); if (_preparedQuery.Commands.Length == 1) { _dataConnection.InitCommand( CommandType.Text, _preparedQuery.Commands[0], null, _preparedQuery.QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); return await _dataConnection.ExecuteNonQueryAsync(cancellationToken); } for (var i = 0; i < _preparedQuery.Commands.Length; i++) { _dataConnection.InitCommand( CommandType.Text, _preparedQuery.Commands[i], null, i == 0 ? _preparedQuery.QueryHints : null); if (i == 0 && _preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); if (i < _preparedQuery.Commands.Length - 1 && _preparedQuery.Commands[i].StartsWith("DROP")) { try { await _dataConnection.ExecuteNonQueryAsync(cancellationToken); } catch { } } else { await _dataConnection.ExecuteNonQueryAsync(cancellationToken); } } return -1; } public override async Task<object> ExecuteScalarAsync(CancellationToken cancellationToken) { _isAsync = true; await _dataConnection.EnsureConnectionAsync(cancellationToken); SetCommand(); IDbDataParameter idparam = null; if (_dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired) { if (_preparedQuery.Statement.NeedsIdentity()) { idparam = _dataConnection.Command.CreateParameter(); idparam.ParameterName = "IDENTITY_PARAMETER"; idparam.Direction = ParameterDirection.Output; idparam.DbType = DbType.Decimal; _dataConnection.Command.Parameters.Add(idparam); } } if (_preparedQuery.Commands.Length == 1) { if (idparam != null) { // так сделано потому, что фаерберд провайдер не возвращает никаких параметров через ExecuteReader // остальные провайдеры должны поддерживать такой режим await _dataConnection.ExecuteNonQueryAsync(cancellationToken); return idparam.Value; } return await _dataConnection.ExecuteScalarAsync(cancellationToken); } await _dataConnection.ExecuteNonQueryAsync(cancellationToken); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[1], null, null); return await _dataConnection.ExecuteScalarAsync(cancellationToken); } } } }
ronnyek/linq2db
Source/LinqToDB/Data/DataConnection.QueryRunner.cs
C#
mit
17,014
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include BOSS_WEBRTC_U_rtc_base__win32socketserver_h //original-code:"rtc_base/win32socketserver.h" #include <ws2tcpip.h> // NOLINT #include <algorithm> #include BOSS_WEBRTC_U_rtc_base__byteorder_h //original-code:"rtc_base/byteorder.h" #include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" #include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h" #include BOSS_WEBRTC_U_rtc_base__win32window_h //original-code:"rtc_base/win32window.h" namespace rtc { /////////////////////////////////////////////////////////////////////////////// // Win32Socket /////////////////////////////////////////////////////////////////////////////// // TODO: Enable for production builds also? Use FormatMessage? #if !defined(NDEBUG) LPCSTR WSAErrorToString(int error, LPCSTR* description_result) { LPCSTR string = "Unspecified"; LPCSTR description = "Unspecified description"; switch (error) { case ERROR_SUCCESS: string = "SUCCESS"; description = "Operation succeeded"; break; case WSAEWOULDBLOCK: string = "WSAEWOULDBLOCK"; description = "Using a non-blocking socket, will notify later"; break; case WSAEACCES: string = "WSAEACCES"; description = "Access denied, or sharing violation"; break; case WSAEADDRNOTAVAIL: string = "WSAEADDRNOTAVAIL"; description = "Address is not valid in this context"; break; case WSAENETDOWN: string = "WSAENETDOWN"; description = "Network is down"; break; case WSAENETUNREACH: string = "WSAENETUNREACH"; description = "Network is up, but unreachable"; break; case WSAENETRESET: string = "WSANETRESET"; description = "Connection has been reset due to keep-alive activity"; break; case WSAECONNABORTED: string = "WSAECONNABORTED"; description = "Aborted by host"; break; case WSAECONNRESET: string = "WSAECONNRESET"; description = "Connection reset by host"; break; case WSAETIMEDOUT: string = "WSAETIMEDOUT"; description = "Timed out, host failed to respond"; break; case WSAECONNREFUSED: string = "WSAECONNREFUSED"; description = "Host actively refused connection"; break; case WSAEHOSTDOWN: string = "WSAEHOSTDOWN"; description = "Host is down"; break; case WSAEHOSTUNREACH: string = "WSAEHOSTUNREACH"; description = "Host is unreachable"; break; case WSAHOST_NOT_FOUND: string = "WSAHOST_NOT_FOUND"; description = "No such host is known"; break; } if (description_result) { *description_result = description; } return string; } void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) { LPCSTR description_string; LPCSTR error_string = WSAErrorToString(error, &description_string); RTC_LOG(LS_INFO) << context << " = " << error << " (" << error_string << ":" << description_string << ") [" << address.ToString() << "]"; } #else void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {} #endif ///////////////////////////////////////////////////////////////////////////// // Win32Socket::EventSink ///////////////////////////////////////////////////////////////////////////// #define WM_SOCKETNOTIFY (WM_USER + 50) #define WM_DNSNOTIFY (WM_USER + 51) struct Win32Socket::DnsLookup { HANDLE handle; uint16_t port; char buffer[MAXGETHOSTSTRUCT]; }; class Win32Socket::EventSink : public Win32Window { public: explicit EventSink(Win32Socket* parent) : parent_(parent) {} void Dispose(); bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) override; void OnNcDestroy() override; private: bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result); bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result); Win32Socket* parent_; }; void Win32Socket::EventSink::Dispose() { parent_ = nullptr; if (::IsWindow(handle())) { ::DestroyWindow(handle()); } else { delete this; } } bool Win32Socket::EventSink::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) { switch (uMsg) { case WM_SOCKETNOTIFY: case WM_TIMER: return OnSocketNotify(uMsg, wParam, lParam, result); case WM_DNSNOTIFY: return OnDnsNotify(wParam, lParam, result); } return false; } bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) { result = 0; int wsa_event = WSAGETSELECTEVENT(lParam); int wsa_error = WSAGETSELECTERROR(lParam); // Treat connect timeouts as close notifications if (uMsg == WM_TIMER) { wsa_event = FD_CLOSE; wsa_error = WSAETIMEDOUT; } if (parent_) parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error); return true; } bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result) { result = 0; int error = WSAGETASYNCERROR(lParam); if (parent_) parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error); return true; } void Win32Socket::EventSink::OnNcDestroy() { if (parent_) { RTC_LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink" " hasn't yet been disposed."; } else { delete this; } } ///////////////////////////////////////////////////////////////////////////// // Win32Socket ///////////////////////////////////////////////////////////////////////////// Win32Socket::Win32Socket() : socket_(INVALID_SOCKET), error_(0), state_(CS_CLOSED), connect_time_(0), closing_(false), close_error_(0), sink_(nullptr), dns_(nullptr) {} Win32Socket::~Win32Socket() { Close(); } bool Win32Socket::CreateT(int family, int type) { Close(); int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP; socket_ = ::WSASocket(family, type, proto, nullptr, 0, 0); if (socket_ == INVALID_SOCKET) { UpdateLastError(); return false; } if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) { return false; } return true; } int Win32Socket::Attach(SOCKET s) { RTC_DCHECK(socket_ == INVALID_SOCKET); if (socket_ != INVALID_SOCKET) return SOCKET_ERROR; RTC_DCHECK(s != INVALID_SOCKET); if (s == INVALID_SOCKET) return SOCKET_ERROR; socket_ = s; state_ = CS_CONNECTED; if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE)) return SOCKET_ERROR; return 0; } void Win32Socket::SetTimeout(int ms) { if (sink_) ::SetTimer(sink_->handle(), 1, ms, 0); } SocketAddress Win32Socket::GetLocalAddress() const { sockaddr_storage addr = {0}; socklen_t addrlen = sizeof(addr); int result = ::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen); SocketAddress address; if (result >= 0) { SocketAddressFromSockAddrStorage(addr, &address); } else { RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket=" << socket_; } return address; } SocketAddress Win32Socket::GetRemoteAddress() const { sockaddr_storage addr = {0}; socklen_t addrlen = sizeof(addr); int result = ::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen); SocketAddress address; if (result >= 0) { SocketAddressFromSockAddrStorage(addr, &address); } else { RTC_LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket=" << socket_; } return address; } int Win32Socket::Bind(const SocketAddress& addr) { RTC_DCHECK(socket_ != INVALID_SOCKET); if (socket_ == INVALID_SOCKET) return SOCKET_ERROR; sockaddr_storage saddr; size_t len = addr.ToSockAddrStorage(&saddr); int err = ::bind(socket_, reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len)); UpdateLastError(); return err; } int Win32Socket::Connect(const SocketAddress& addr) { if (state_ != CS_CLOSED) { SetError(EALREADY); return SOCKET_ERROR; } if (!addr.IsUnresolvedIP()) { return DoConnect(addr); } RTC_LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")"; DnsLookup* dns = new DnsLookup; if (!sink_) { // Explicitly create the sink ourselves here; we can't rely on SetAsync // because we don't have a socket_ yet. CreateSink(); } // TODO: Replace with IPv6 compatible lookup. dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY, addr.hostname().c_str(), dns->buffer, sizeof(dns->buffer)); if (!dns->handle) { RTC_LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError(); delete dns; UpdateLastError(); Close(); return SOCKET_ERROR; } dns->port = addr.port(); dns_ = dns; state_ = CS_CONNECTING; return 0; } int Win32Socket::DoConnect(const SocketAddress& addr) { if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) { return SOCKET_ERROR; } if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) { return SOCKET_ERROR; } sockaddr_storage saddr = {0}; size_t len = addr.ToSockAddrStorage(&saddr); connect_time_ = Time(); int result = connect(socket_, reinterpret_cast<SOCKADDR*>(&saddr), static_cast<int>(len)); if (result != SOCKET_ERROR) { state_ = CS_CONNECTED; } else { int code = WSAGetLastError(); if (code == WSAEWOULDBLOCK) { state_ = CS_CONNECTING; } else { ReportWSAError("WSAAsync:connect", code, addr); error_ = code; Close(); return SOCKET_ERROR; } } addr_ = addr; return 0; } int Win32Socket::GetError() const { return error_; } void Win32Socket::SetError(int error) { error_ = error; } Socket::ConnState Win32Socket::GetState() const { return state_; } int Win32Socket::GetOption(Option opt, int* value) { int slevel; int sopt; if (TranslateOption(opt, &slevel, &sopt) == -1) return -1; char* p = reinterpret_cast<char*>(value); int optlen = sizeof(value); return ::getsockopt(socket_, slevel, sopt, p, &optlen); } int Win32Socket::SetOption(Option opt, int value) { int slevel; int sopt; if (TranslateOption(opt, &slevel, &sopt) == -1) return -1; const char* p = reinterpret_cast<const char*>(&value); return ::setsockopt(socket_, slevel, sopt, p, sizeof(value)); } int Win32Socket::Send(const void* buffer, size_t length) { int sent = ::send(socket_, reinterpret_cast<const char*>(buffer), static_cast<int>(length), 0); UpdateLastError(); return sent; } int Win32Socket::SendTo(const void* buffer, size_t length, const SocketAddress& addr) { sockaddr_storage saddr; size_t addr_len = addr.ToSockAddrStorage(&saddr); int sent = ::sendto( socket_, reinterpret_cast<const char*>(buffer), static_cast<int>(length), 0, reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(addr_len)); UpdateLastError(); return sent; } int Win32Socket::Recv(void* buffer, size_t length, int64_t* timestamp) { if (timestamp) { *timestamp = -1; } int received = ::recv(socket_, static_cast<char*>(buffer), static_cast<int>(length), 0); UpdateLastError(); if (closing_ && received <= static_cast<int>(length)) PostClosed(); return received; } int Win32Socket::RecvFrom(void* buffer, size_t length, SocketAddress* out_addr, int64_t* timestamp) { if (timestamp) { *timestamp = -1; } sockaddr_storage saddr; socklen_t addr_len = sizeof(saddr); int received = ::recvfrom(socket_, static_cast<char*>(buffer), static_cast<int>(length), 0, reinterpret_cast<sockaddr*>(&saddr), &addr_len); UpdateLastError(); if (received != SOCKET_ERROR) SocketAddressFromSockAddrStorage(saddr, out_addr); if (closing_ && received <= static_cast<int>(length)) PostClosed(); return received; } int Win32Socket::Listen(int backlog) { int err = ::listen(socket_, backlog); if (!SetAsync(FD_ACCEPT)) return SOCKET_ERROR; UpdateLastError(); if (err == 0) state_ = CS_CONNECTING; return err; } Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) { sockaddr_storage saddr; socklen_t addr_len = sizeof(saddr); SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len); UpdateLastError(); if (s == INVALID_SOCKET) return nullptr; if (out_addr) SocketAddressFromSockAddrStorage(saddr, out_addr); Win32Socket* socket = new Win32Socket; if (0 == socket->Attach(s)) return socket; delete socket; return nullptr; } int Win32Socket::Close() { int err = 0; if (socket_ != INVALID_SOCKET) { err = ::closesocket(socket_); socket_ = INVALID_SOCKET; closing_ = false; close_error_ = 0; UpdateLastError(); } if (dns_) { WSACancelAsyncRequest(dns_->handle); delete dns_; dns_ = nullptr; } if (sink_) { sink_->Dispose(); sink_ = nullptr; } addr_.Clear(); state_ = CS_CLOSED; return err; } void Win32Socket::CreateSink() { RTC_DCHECK(nullptr == sink_); // Create window sink_ = new EventSink(this); sink_->Create(nullptr, L"EventSink", 0, 0, 0, 0, 10, 10); } bool Win32Socket::SetAsync(int events) { if (nullptr == sink_) { CreateSink(); RTC_DCHECK(nullptr != sink_); } // start the async select if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events) == SOCKET_ERROR) { UpdateLastError(); Close(); return false; } return true; } bool Win32Socket::HandleClosed(int close_error) { // WM_CLOSE will be received before all data has been read, so we need to // hold on to it until the read buffer has been drained. char ch; closing_ = true; close_error_ = close_error; return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0); } void Win32Socket::PostClosed() { // If we see that the buffer is indeed drained, then send the close. closing_ = false; ::PostMessage(sink_->handle(), WM_SOCKETNOTIFY, socket_, WSAMAKESELECTREPLY(FD_CLOSE, close_error_)); } void Win32Socket::UpdateLastError() { error_ = WSAGetLastError(); } int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) { switch (opt) { case OPT_DONTFRAGMENT: *slevel = IPPROTO_IP; *sopt = IP_DONTFRAGMENT; break; case OPT_RCVBUF: *slevel = SOL_SOCKET; *sopt = SO_RCVBUF; break; case OPT_SNDBUF: *slevel = SOL_SOCKET; *sopt = SO_SNDBUF; break; case OPT_NODELAY: *slevel = IPPROTO_TCP; *sopt = TCP_NODELAY; break; case OPT_DSCP: RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported."; return -1; default: RTC_NOTREACHED(); return -1; } return 0; } void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) { // Ignore events if we're already closed. if (socket != socket_) return; error_ = error; switch (event) { case FD_CONNECT: if (error != ERROR_SUCCESS) { ReportWSAError("WSAAsync:connect notify", error, addr_); #if !defined(NDEBUG) int64_t duration = TimeSince(connect_time_); RTC_LOG(LS_INFO) << "WSAAsync:connect error (" << duration << " ms), faking close"; #endif state_ = CS_CLOSED; // If you get an error connecting, close doesn't really do anything // and it certainly doesn't send back any close notification, but // we really only maintain a few states, so it is easiest to get // back into a known state by pretending that a close happened, even // though the connect event never did occur. SignalCloseEvent(this, error); } else { #if !defined(NDEBUG) int64_t duration = TimeSince(connect_time_); RTC_LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)"; #endif state_ = CS_CONNECTED; SignalConnectEvent(this); } break; case FD_ACCEPT: case FD_READ: if (error != ERROR_SUCCESS) { ReportWSAError("WSAAsync:read notify", error, addr_); } else { SignalReadEvent(this); } break; case FD_WRITE: if (error != ERROR_SUCCESS) { ReportWSAError("WSAAsync:write notify", error, addr_); } else { SignalWriteEvent(this); } break; case FD_CLOSE: if (HandleClosed(error)) { ReportWSAError("WSAAsync:close notify", error, addr_); state_ = CS_CLOSED; SignalCloseEvent(this, error); } break; } } void Win32Socket::OnDnsNotify(HANDLE task, int error) { if (!dns_ || dns_->handle != task) return; uint32_t ip = 0; if (error == 0) { hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer); uint32_t net_ip = *reinterpret_cast<uint32_t*>(pHost->h_addr_list[0]); ip = NetworkToHost32(net_ip); } RTC_LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString() << ", " << error << ")"; if (error == 0) { SocketAddress address(ip, dns_->port); error = DoConnect(address); } else { Close(); } if (error) { error_ = error; SignalCloseEvent(this, error_); } else { delete dns_; dns_ = nullptr; } } /////////////////////////////////////////////////////////////////////////////// // Win32SocketServer // Provides cricket base services on top of a win32 gui thread /////////////////////////////////////////////////////////////////////////////// static UINT s_wm_wakeup_id = 0; const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window"; Win32SocketServer::Win32SocketServer() : wnd_(this), posted_(false), hdlg_(nullptr) { if (s_wm_wakeup_id == 0) s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP"); if (!wnd_.Create(nullptr, kWindowName, 0, 0, 0, 0, 0, 0)) { RTC_LOG_GLE(LS_ERROR) << "Failed to create message window."; } } Win32SocketServer::~Win32SocketServer() { if (wnd_.handle() != nullptr) { KillTimer(wnd_.handle(), 1); wnd_.Destroy(); } } Socket* Win32SocketServer::CreateSocket(int family, int type) { return CreateAsyncSocket(family, type); } AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) { Win32Socket* socket = new Win32Socket; if (socket->CreateT(family, type)) { return socket; } delete socket; return nullptr; } void Win32SocketServer::SetMessageQueue(MessageQueue* queue) { message_queue_ = queue; } bool Win32SocketServer::Wait(int cms, bool process_io) { BOOL b; if (process_io) { // Spin the Win32 message pump at least once, and as long as requested. // This is the Thread::ProcessMessages case. uint32_t start = Time(); do { MSG msg; SetTimer(wnd_.handle(), 0, cms, nullptr); // Get the next available message. If we have a modeless dialog, give // give the message to IsDialogMessage, which will return true if it // was a message for the dialog that it handled internally. // Otherwise, dispatch as usual via Translate/DispatchMessage. b = GetMessage(&msg, nullptr, 0, 0); if (b == -1) { RTC_LOG_GLE(LS_ERROR) << "GetMessage failed."; return false; } else if (b) { if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } KillTimer(wnd_.handle(), 0); } while (b && TimeSince(start) < cms); } else if (cms != 0) { // Sit and wait forever for a WakeUp. This is the Thread::Send case. RTC_DCHECK(cms == -1); MSG msg; b = GetMessage(&msg, nullptr, s_wm_wakeup_id, s_wm_wakeup_id); { CritScope scope(&cs_); posted_ = false; } } else { // No-op (cms == 0 && !process_io). This is the Pump case. b = TRUE; } return (b != FALSE); } void Win32SocketServer::WakeUp() { if (wnd_.handle()) { // Set the "message pending" flag, if not already set. { CritScope scope(&cs_); if (posted_) return; posted_ = true; } PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0); } } void Win32SocketServer::Pump() { // Clear the "message pending" flag. { CritScope scope(&cs_); posted_ = false; } // Dispatch all the messages that are currently in our queue. If new messages // are posted during the dispatch, they will be handled in the next Pump. // We use max(1, ...) to make sure we try to dispatch at least once, since // this allow us to process "sent" messages, not included in the size() count. Message msg; for (size_t max_messages_to_process = std::max<size_t>(1, message_queue_->size()); max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false); --max_messages_to_process) { message_queue_->Dispatch(&msg); } // Anything remaining? int delay = message_queue_->GetDelay(); if (delay == -1) { KillTimer(wnd_.handle(), 1); } else { SetTimer(wnd_.handle(), 1, delay, nullptr); } } bool Win32SocketServer::MessageWindow::OnMessage(UINT wm, WPARAM wp, LPARAM lp, LRESULT& lr) { bool handled = false; if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) { ss_->Pump(); lr = 0; handled = true; } return handled; } Win32Thread::Win32Thread(SocketServer* ss) : Thread(ss), id_(0) {} Win32Thread::~Win32Thread() { Stop(); } void Win32Thread::Run() { id_ = GetCurrentThreadId(); Thread::Run(); id_ = 0; } void Win32Thread::Quit() { PostThreadMessage(id_, WM_QUIT, 0, 0); } } // namespace rtc
koobonil/Boss2D
Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_base/win32socketserver.cc
C++
mit
22,653
class R: def __init__(self, c): self.c = c self.is_star = False def match(self, c): return self.c == '.' or self.c == c class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ rs = [] """:type: list[R]""" for c in p: if c == '*': rs[-1].is_star = True else: rs.append(R(c)) lr = len(rs) ls = len(s) s += '\0' dp = [[False] * (ls + 1) for _ in range(lr + 1)] dp[0][0] = True for i, r in enumerate(rs): for j in range(ls + 1): c = s[j - 1] if r.is_star: dp[i + 1][j] = dp[i][j] if j and r.match(c): dp[i + 1][j] |= dp[i + 1][j - 1] else: if j and r.match(c): dp[i + 1][j] = dp[i][j - 1] return dp[-1][-1]
SF-Zhou/LeetCode.Solutions
solutions/regular_expression_matching.py
Python
mit
1,032
namespace GameBoySharp.Domain.Contracts { public interface IContiguousMemory : IReadableMemory, IWriteableMemory { } }
taspeotis/GameBoySharp
GameBoySharp.Domain/Contracts/IContiguousMemory.cs
C#
mit
133
public class App { public static void main(String[] args) { System.out.println("Old man, look at my life..."); } }
zelark/test
src/main/java/App.java
Java
mit
119
var score = 0; var scoreText; var map_x = 14; var map_y = 10; var game = new Phaser.Game(map_x * 16, map_y * 16, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { // game.scale.maxWidth = 600; // game.scale.maxHeight = 600; game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.setScreenSize(); game.load.image('cat', 'assets/cat.png', 16, 16); game.load.image('ground', 'assets/darkfloor.png', 16, 16); game.load.image('l_wall', 'assets/l_wall.png', 16, 16); game.load.image('r_wall', 'assets/r_wall.png', 16, 16); game.load.image('t_wall', 'assets/t_wall.png', 16, 16); game.load.image('tr_wall', 'assets/tr_wall_iso.png', 16, 16); game.load.image('tl_wall', 'assets/tl_wall_iso.png', 16, 16); game.load.image('bl_wall', 'assets/bl_wall.png', 16, 16); game.load.image('br_wall', 'assets/br_wall.png', 16, 16); game.load.image('stone_door', 'assets/door_stone.png', 16, 16); game.load.image('star', 'assets/star.png'); } function create() { game.physics.startSystem(Phaser.Physics.ARCADE); // the game world gmap = game.add.tilemap(); gmap.addTilesetImage('ground', 'ground', 16, 16, null, null, 0); gmap.addTilesetImage('l_wall', 'l_wall', 16, 16, null, null, 1); gmap.addTilesetImage('r_wall', 'r_wall', 16, 16, null, null, 2); gmap.addTilesetImage('tr_wall', 'tr_wall', 16, 16, null, null, 3); gmap.addTilesetImage('tl_wall', 'tl_wall', 16, 16, null, null, 4); gmap.addTilesetImage('br_wall', 'br_wall', 16, 16, null, null, 5); gmap.addTilesetImage('bl_wall', 'bl_wall', 16, 16, null, null, 6); gmap.addTilesetImage('t_wall', 't_wall', 16, 16, null, null, 7); gmap.addTilesetImage('stone_door', 'stone_door', 16, 16, null, null, 8); ground_layer = gmap.create('ground_layer', map_x, map_y, 16, 16); wall_layer = gmap.create('wall_layer', map_x, map_y, 16, 16); for (var i=0; i<map_x; i++) { for(var j=0; j<map_y; j++) { if (i==0 && j==0) { gmap.putTile(4, i, j, wall_layer); } else if (i==map_x/2 && j==0) { gmap.putTile(8, i, j, wall_layer); } else if (i==map_x-1 && j == map_y-1) { gmap.putTile(5, i, j, wall_layer); } else if (i==0 && j == map_y-1) { gmap.putTile(6, i, j, wall_layer); } else if (i==map_x-1 && j == 0) { gmap.putTile(3, i, j, wall_layer); } else if (i==map_x-1 && j == map_y-1) { gmap.putTile(6, i, j, wall_layer); } else if (i==0) { gmap.putTile(1, i, j, wall_layer); } else if(i==map_x-1) { gmap.putTile(2, i, j, wall_layer); } else if(j==map_y-1) { gmap.putTile(7, i, j, wall_layer); } else if(j==0) { gmap.putTile(7, i, j, wall_layer); } else { gmap.putTile(0, i, j, ground_layer); } } } wall_layer.resizeWorld(); game.physics.arcade.enable(wall_layer); gmap.setCollision(wall_layer); // the player player = game.add.sprite(32, 32, 'cat'); game.physics.arcade.enable(player); player.body.collideWorldBounds = true; // gmap.setCollisionBetween(0, 100, true, wall_layer); cursors = game.input.keyboard.createCursorKeys(); } function update() { game.physics.arcade.collide(player, wall_layer); player.body.velocity.x = 0; player.body.velocity.y = 0; if (cursors.left.isDown) { player.body.velocity.x = -150; } else if (cursors.right.isDown) { player.body.velocity.x = 150; } else if (cursors.down.isDown) { player.body.velocity.y = 150; } else if (cursors.up.isDown) { player.body.velocity.y = -150; } else { } }
henripal/henripal.github.io
game/game.js
JavaScript
mit
3,879
package com.thebluealliance.androidclient.gcm.notifications; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.thebluealliance.androidclient.Constants; import com.thebluealliance.androidclient.R; import com.thebluealliance.androidclient.Utilities; import com.thebluealliance.androidclient.activities.ViewMatchActivity; import com.thebluealliance.androidclient.datafeed.JSONManager; import com.thebluealliance.androidclient.helpers.EventHelper; import com.thebluealliance.androidclient.helpers.MatchHelper; import com.thebluealliance.androidclient.helpers.MyTBAHelper; import com.thebluealliance.androidclient.listeners.GamedayTickerClickListener; import com.thebluealliance.androidclient.models.BasicModel; import com.thebluealliance.androidclient.models.Match; import com.thebluealliance.androidclient.models.StoredNotification; import com.thebluealliance.androidclient.views.MatchView; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * Created by Nathan on 7/24/2014. */ public class ScoreNotification extends BaseNotification { private String eventName, eventKey, matchKey; private Match match; public ScoreNotification(String messageData) { super("score", messageData); } @Override public void parseMessageData() throws JsonParseException { JsonObject jsonData = JSONManager.getasJsonObject(messageData); if (!jsonData.has("match")) { throw new JsonParseException("Notification data does not contain 'match"); } JsonObject match = jsonData.get("match").getAsJsonObject(); this.match = gson.fromJson(match, Match.class); try { this.matchKey = this.match.getKey(); } catch (BasicModel.FieldNotDefinedException e) { e.printStackTrace(); } this.eventKey = MatchHelper.getEventKeyFromMatchKey(matchKey); if (!jsonData.has("event_name")) { throw new JsonParseException("Notification data does not contain 'event_name"); } eventName = jsonData.get("event_name").getAsString(); } @Override public Notification buildNotification(Context context) { Resources r = context.getResources(); String matchKey; try { matchKey = match.getKey(); this.matchKey = matchKey; } catch (BasicModel.FieldNotDefinedException e) { Log.e(getLogTag(), "Incoming Match object does not have a key. Can't post score update"); e.printStackTrace(); return null; } String matchTitle = MatchHelper.getMatchTitleFromMatchKey(context, matchKey); String matchAbbrevTitle = MatchHelper.getAbbrevMatchTitleFromMatchKey(context, matchKey); JsonObject alliances; try { alliances = match.getAlliances(); } catch (BasicModel.FieldNotDefinedException e) { Log.e(getLogTag(), "Incoming match object does not contain alliance data. Can't post score update"); e.printStackTrace(); return null; } int redScore = Match.getRedScore(alliances); ArrayList<String> redTeamKeys = new ArrayList<>(); JsonArray redTeamsJson = Match.getRedTeams(alliances); for (int i = 0; i < redTeamsJson.size(); i++) { redTeamKeys.add(redTeamsJson.get(i).getAsString()); } int blueScore = Match.getBlueScore(alliances); ArrayList<String> blueTeamKeys = new ArrayList<>(); JsonArray blueTeamsJson = Match.getBlueTeams(alliances); for (int i = 0; i < blueTeamsJson.size(); i++) { blueTeamKeys.add(blueTeamsJson.get(i).getAsString()); } // TODO filter out teams that the user doesn't want notifications about // These arrays hold the numbers of teams that the user cares about ArrayList<String> redTeams = new ArrayList<>(); ArrayList<String> blueTeams = new ArrayList<>(); for (String key : redTeamKeys) { redTeams.add(key.replace("frc", "")); } for (String key : blueTeamKeys) { blueTeams.add(key.replace("frc", "")); } // Make sure the score string is formatted properly with the winning score first String scoreString; if (redScore > blueScore) { scoreString = redScore + "-" + blueScore; } else if (redScore < blueScore) { scoreString = blueScore + "-" + redScore; } else { scoreString = redScore + "-" + redScore; } String redTeamString = Utilities.stringifyListOfStrings(context, redTeams); String blueTeamString = Utilities.stringifyListOfStrings(context, blueTeams); boolean useSpecial2015Format; try { useSpecial2015Format = match.getYear() == 2015 && match.getType() != MatchHelper.TYPE.FINAL; } catch (BasicModel.FieldNotDefinedException e) { useSpecial2015Format = false; Log.w(Constants.LOG_TAG, "Couldn't determine if we should use 2015 score format. Defaulting to no"); } String eventShortName = EventHelper.shortName(eventName); String notificationString; if (redTeams.size() == 0 && blueTeams.size() == 0) { // We must have gotten this GCM message by mistake return null; } else if (useSpecial2015Format) { /* Only for 2015 non-finals matches. Ugh */ notificationString = context.getString(R.string.notification_score_2015_no_winner, eventShortName, matchTitle, redTeamString, redScore, blueTeamString, blueScore); } else if ((redTeams.size() > 0 && blueTeams.size() == 0)) { // The user only cares about some teams on the red alliance if (redScore > blueScore) { // Red won notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, redTeamString, matchTitle, scoreString); } else if (redScore < blueScore) { // Red lost notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, redTeamString, matchTitle, scoreString); } else { // Red tied notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, redTeamString, matchTitle, scoreString); } } else if ((blueTeams.size() > 0 && redTeams.size() == 0)) { // The user only cares about some teams on the blue alliance if (blueScore > redScore) { // Blue won notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, blueTeamString, matchTitle, scoreString); } else if (blueScore < redScore) { // Blue lost notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, blueTeamString, matchTitle, scoreString); } else { // Blue tied notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, blueTeamString, matchTitle, scoreString); } } else if ((blueTeams.size() > 0 && redTeams.size() > 0)) { // The user cares about teams on both alliances if (blueScore > redScore) { // Blue won notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, blueTeamString, redTeamString, matchTitle, scoreString); } else if (blueScore < redScore) { // Blue lost notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString); } else { // Blue tied notificationString = context.getString(R.string.notification_score_teams_tied_with_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString); } } else { // We should never, ever get here but if we do... return null; } // We can finally build the notification! Intent instance = getIntent(context); stored = new StoredNotification(); stored.setType(getNotificationType()); String eventCode = EventHelper.getEventCode(matchKey); String notificationTitle = r.getString(R.string.notification_score_title, eventCode, matchAbbrevTitle); stored.setTitle(notificationTitle); stored.setBody(notificationString); stored.setIntent(MyTBAHelper.serializeIntent(instance)); stored.setTime(Calendar.getInstance().getTime()); NotificationCompat.Builder builder = getBaseBuilder(context, instance) .setContentTitle(notificationTitle) .setContentText(notificationString) .setLargeIcon(getLargeIconFormattedForPlatform(context, R.drawable.ic_info_outline_white_24dp)); NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle().bigText(notificationString); builder.setStyle(style); return builder.build(); } @Override public void updateDataLocally(Context c) { if (match != null) { match.write(c); } } @Override public Intent getIntent(Context c) { return ViewMatchActivity.newInstance(c, matchKey); } @Override public int getNotificationId() { return (new Date().getTime() + ":" + getNotificationType() + ":" + matchKey).hashCode(); } @Override public View getView(Context c, LayoutInflater inflater, View convertView) { ViewHolder holder; if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) { convertView = inflater.inflate(R.layout.list_item_notification_score, null, false); holder = new ViewHolder(); holder.header = (TextView) convertView.findViewById(R.id.card_header); holder.title = (TextView) convertView.findViewById(R.id.title); holder.matchView = (MatchView) convertView.findViewById(R.id.match_details); holder.time = (TextView) convertView.findViewById(R.id.notification_time); holder.summaryContainer = convertView.findViewById(R.id.summary_container); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.header.setText(c.getString(R.string.gameday_ticker_event_title_format, EventHelper.shortName(eventName), EventHelper.getShortCodeForEventKey(eventKey).toUpperCase())); holder.title.setText(c.getString(R.string.notification_score_gameday_title, MatchHelper.getMatchTitleFromMatchKey(c, matchKey))); holder.time.setText(getNotificationTimeString(c)); holder.summaryContainer.setOnClickListener(new GamedayTickerClickListener(c, this)); match.render(false, false, false, true).getView(c, inflater, holder.matchView); return convertView; } private class ViewHolder { public TextView header; public TextView title; public MatchView matchView; public TextView time; private View summaryContainer; } }
Adam8234/the-blue-alliance-android
android/src/main/java/com/thebluealliance/androidclient/gcm/notifications/ScoreNotification.java
Java
mit
11,766
import { expect } from 'chai'; import { Curry } from './curry'; describe('curry', () => { it('should curry the method with default arity', () => { class MyClass { @Curry() add(a: any, b?: any) { return a + b; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5).to.be.an.instanceOf(Function); expect(add5(10)).to.equal(15); }); it('should curry the method with default arity (paramless)', () => { class MyClass { @Curry add(a: any, b?: any) { return a + b; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5).to.be.an.instanceOf(Function); expect(add5(10)).to.equal(15); }); it('should curry the method with fixed arity', () => { class MyClass { @Curry(2) add(a: any, b?: any, c?: any) { return a + b * c; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5).to.be.an.instanceOf(Function); expect(add5(10, 2)).to.equal(25); }); it('should retain the class context', () => { class MyClass { value = 10; @Curry() add(a: any, b?: any): any { return (a + b) * this.value; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5(2)).to.equal(70); }); });
steelsojka/lodash-decorators
src/curry.spec.ts
TypeScript
mit
1,375
module Fog module XenServer class Compute module Models class CrashDumps < Collection model Fog::XenServer::Compute::Models::CrashDump end end end end end
fog/fog-xenserver
lib/fog/xenserver/compute/models/crash_dumps.rb
Ruby
mit
204
using UnityEngine; using UnityEngine.UI; using System.Collections; public class DebugWindow : MonoBehaviour { public Text textWindow; string freshInput; // Use this for initialization void Start () { if (textWindow == null) throw new UnityException ("Debug Window has no text box to output to."); } // Update is called once per frame void Update () { textWindow.text = "Debug:\n" + freshInput; freshInput = ""; } public void LOG(string Text) { freshInput += Text + '\n'; } }
tlsteenWoo/UnityNeedler
New Unity Project/Assets/Game/Scripts/DebugWindow.cs
C#
mit
505
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Storage; using Pomelo.EntityFrameworkCore.MySql.Query.ExpressionTranslators.Internal; using Pomelo.EntityFrameworkCore.MySql.Query.Internal; namespace Pomelo.EntityFrameworkCore.MySql.Json.Microsoft.Query.Internal { public class MySqlJsonMicrosoftMemberTranslatorPlugin : IMemberTranslatorPlugin { public MySqlJsonMicrosoftMemberTranslatorPlugin( IRelationalTypeMappingSource typeMappingSource, ISqlExpressionFactory sqlExpressionFactory, IMySqlJsonPocoTranslator jsonPocoTranslator) { var mySqlSqlExpressionFactory = (MySqlSqlExpressionFactory)sqlExpressionFactory; var mySqlJsonPocoTranslator = (MySqlJsonPocoTranslator)jsonPocoTranslator; Translators = new IMemberTranslator[] { new MySqlJsonMicrosoftDomTranslator( mySqlSqlExpressionFactory, typeMappingSource, mySqlJsonPocoTranslator), jsonPocoTranslator, }; } public virtual IEnumerable<IMemberTranslator> Translators { get; } } }
PomeloFoundation/Pomelo.EntityFrameworkCore.MySql
src/EFCore.MySql.Json.Microsoft/Query/Internal/MySqlJsonMicrosoftMemberTranslatorPlugin.cs
C#
mit
1,377
export { default } from 'ember-flexberry-gis/services/map-store';
Flexberry/ember-flexberry-gis
app/services/map-store.js
JavaScript
mit
66
#!/usr/bin/env python3 from __future__ import print_function, division import numpy as np from sht.grids import standard_grid, get_cartesian_grid def test_grids(): L = 10 thetas, phis = standard_grid(L) # Can't really test much here assert thetas.size == L assert phis.size == L**2 grid = get_cartesian_grid(thetas, phis) assert grid.shape == (L**2, 3)
praveenv253/sht
tests/test_grids.py
Python
mit
386
var Keyboard_Space = new function(){ this.initKeyboard = function(testing){ testmode = testing; return new Keyboard(); } var Keyboard = function(){ for(var i = 0; i < numChains; i++) currentSounds.push([]); var this_obj = this; Zip_Space.loadZip(currentSongData["filename"], function() { this_obj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1); this_obj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2); this_obj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3); this_obj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4); this_obj.backend = BackendSpace.init(); this_obj.keyboardUI = Keyboard_UI_Space.initKeyboardUI(); console.log("New keyboard created"); }) } // link the keyboard and the editor Keyboard.prototype.linkEditor = function(editor){ this.editor = editor; var mainObj = this; setTimeout(function(){mainObj.editor.setBPM(currentSongData.bpm)},500); } Keyboard.prototype.getCurrentSounds = function(){ return currentSounds; } // loads sounds from srcArray for given chain into soundArr Keyboard.prototype.loadSounds = function(srcArr, soundArr, chain){ for(var i = 0; i < srcArr.length; i++) soundArr.push(null); for(var i = 0; i < srcArr.length; i++){ if(srcArr[i] == "") this.checkLoaded(); else this.requestSound(i, srcArr, soundArr, chain); } } // makes request for sounds // if offline version, gets from local files // if online version, gets from public folder Keyboard.prototype.requestSound = function(i, srcArr, soundArr, chain){ var thisObj = this; soundArr[i] = new Howl({ // for online version urls: [Zip_Space.dataArray['sounds/chain'+chain+'/'+srcArr[i]+'.mp3']], // old // urls: [currentSongData["soundUrls"]["chain"+chain][srcArr[i]].replace("www.dropbox.com","dl.dropboxusercontent.com").replace("?dl=0","")], // for offline version // urls: ["audio/chain"+chain+"/"+srcArr[i]+".mp3"], onload: function(){ thisObj.checkLoaded(); }, onloaderror: function(id, error){ console.log('error: '+id) console.log(error); console.log('sounds/chain'+chain+'/'+srcArr[i]+'.mp3'); $("#error_msg").html("There was an error. Please try clearing your browser's cache and reload the page."); } }); } // checks if all of the sounds have loaded // if they have, load the keyboard Keyboard.prototype.checkLoaded = function(){ numSoundsLoaded++; $(".soundPack").html("Loading sounds ("+numSoundsLoaded+"/"+(4*12*numChains)+")"); if(numSoundsLoaded == 4*12*numChains){ loadingSongs = false; this.keyboardUI.loadKeyboard(this, currentSongData, currentSoundPack); } } Keyboard.prototype.getKeyInd = function(kc){ var keyInd = keyPairs.indexOf(kc); if(keyInd == -1) keyInd = backupPairs.indexOf(kc); return keyInd; } Keyboard.prototype.switchSoundPackCheck = function(kc){ // up if(kc == 39){ this.switchSoundPack(3); return true; } // left else if(kc == 37){ this.switchSoundPack(0); return true; } // down else if(kc == 38){ this.switchSoundPack(1); return true; } // right else if(kc == 40){ this.switchSoundPack(2); return true; } } // switch sound pack and update pressures Keyboard.prototype.switchSoundPack = function(sp){ // release all keys for(var i = 0; i < 4; i++) for(var j = 0; j < 12; j++) if($(".button-"+(i*12+j)+"").attr("released") == "false") this.releaseKey(keyPairs[i*12+j]); // set the new soundpack currentSoundPack = sp; $(".sound_pack_button").css("background-color","white"); $(".sound_pack_button_"+(currentSoundPack+1)).css("background-color","rgb(255,160,0)"); $(".soundPack").html("Sound Pack: "+(currentSoundPack+1)); // set pressures for buttons in new sound pack for(var i = 0; i < 4; i++){ for(var j = 0; j < 12; j++){ var press = false; if(currentSongData["holdToPlay"]["chain"+(currentSoundPack+1)].indexOf((i*12+j)) != -1) press = true; $('.button-'+(i*12+j)+'').attr("pressure", ""+press+""); // holdToPlay coloring, turned off for now //$('.button-'+(i*12+j)+'').css("background-color", $('.button-'+(i*12+j)+'').attr("pressure") == "true" ? "lightgray" : "white"); } } } // key released // stop playing sound if holdToPlay Keyboard.prototype.releaseKey = function(kc){ var keyInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][keyInd] != null){ this.midiKeyUp(kc); // send key code to MIDI editor this.editor.recordKeyUp(kc); } } Keyboard.prototype.midiKeyUp = function(kc){ if(this.switchSoundPackCheck(kc)){ // do nothing } else{ var kcInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][kcInd] != null){ if($(".button-"+(kcInd)+"").attr("pressure") == "true") currentSounds[currentSoundPack][kcInd].stop(); $(".button-"+(kcInd)+"").attr("released","true"); // holdToPlay coloring, turned off for now // Removes Style Attribute to clean up HTML $(".button-"+(kcInd)+"").removeAttr("style"); if($(".button-"+(kcInd)+"").hasClass("pressed") == true) $(".button-"+(kcInd)+"").removeClass("pressed"); //$(".button-"+(kcInd)+"").css("background-color", $(".button-"+(kcInd)+"").attr("pressure") == "true" ? "lightgray" : "white"); } } } // play the key by finding the mapping, // stopping all sounds in key's linkedArea // and then playing sound Keyboard.prototype.playKey = function(kc){ var keyInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][keyInd] != null){ this.midiKeyDown(kc); // send key code to midi editor this.editor.recordKeyDown(kc); } } Keyboard.prototype.midiKeyDown = function(kc){ if(this.switchSoundPackCheck(kc)){ // do nothing } else{ var kcInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][kcInd] != null){ currentSounds[currentSoundPack][kcInd].stop(); currentSounds[currentSoundPack][kcInd].play(); // go through all linked Areas in current chain currentSongData["linkedAreas"]["chain"+(currentSoundPack+1)].forEach(function(el, ind, arr){ // for ever linked area array for(var j = 0; j < el.length; j++){ // if key code is in linked area array if(kcInd == el[j]){ // stop all other sounds in linked area array for(var k = 0; k < el.length; k++){ if(k != j) currentSounds[currentSoundPack][el[k]].stop(); } break; } } }); // set button color and attribute $(".button-"+(kcInd)+"").addClass("pressed"); $(".button-"+(kcInd)+"").attr("released","false"); //$(".button-"+(kcInd)+"").css("background-color","rgb(255,160,0)"); } } } // shows and formats all of the UI elements Keyboard.prototype.initUI = function(){ // create new editor and append it to the body element if(testmode) BasicMIDI.init("#editor_container_div", this, 170); else MIDI_Editor.init("#editor_container_div", this, 170); // info and links buttons // $(".click_button").css("display", "inline-block"); for(var s in songDatas) $("#songs_container").append("<div class='song_selection' songInd='"+s+"'>"+songDatas[s].song_name+"</div>"); $("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)"); var mainObj = this; $(".song_selection").click(function() { var tempS = parseInt($(this).attr("songInd")); if(tempS != currentSongInd && !loadingSongs){ loadingSongs = true; currentSongInd = tempS currentSongData = songDatas[currentSongInd]; $(".song_selection").css("background-color","white"); $("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)"); $(".button-row").remove(); for(var i = 0; i < currentSounds.length; i++){ for(var k = 0; k < currentSounds[i].length; k++){ if(currentSounds[i][k] != null) currentSounds[i][k].unload(); } } currentSounds = []; for(var i = 0; i < numChains; i++) currentSounds.push([]); mainObj.editor.notesLoaded([],-1); mainObj.editor.setBPM(currentSongData.bpm) numSoundsLoaded = 0; Zip_Space.loadZip(currentSongData["filename"], function() { mainObj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1); mainObj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2); mainObj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3); mainObj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4); }) } }); } // send request to server to save the notes to the corresponding projectId (pid) Keyboard.prototype.saveNotes = function(notes, pid){ var saveNote = []; for(var n in notes) saveNote.push({"note":notes[n].note, "beat":notes[n].beat, "length":notes[n].length}); //console.log(saveNote); this.backend.saveSong(JSON.stringify(saveNote), pid, this.editor, currentSongData.song_number); } // ask the user for the project they would like to load and then load that project from the server // send back a notes array of the loaded project with note,beat,and length and the project id Keyboard.prototype.loadNotes = function(){ this.backend.loadSongs(this.editor, currentSongData.song_number); } // current soundpack (0-3) var currentSoundPack = 0; // number of sounds loaded var numSoundsLoaded = 0; // howl objects for current song var currentSounds = []; // reference to current song data var songDatas = [equinoxData, animalsData, electroData, ghetData, kyotoData, aeroData]; var currentSongInd = 0; var currentSongData = equinoxData; // number of chains var numChains = 4; var testmode = false; var loadingSongs = true; } // Global Variables // ascii key mappings to array index var keyPairs = [49,50,51,52,53,54,55,56,57,48,189,187, 81,87,69,82,84,89,85,73,79,80,219,221, 65,83,68,70,71,72,74,75,76,186,222,13, 90,88,67,86,66,78,77,188,190,191,16,-1]; // alternate keys for firefox var backupPairs = [49,50,51,52,53,54,55,56,57,48,173,61, 81,87,69,82,84,89,85,73,79,80,219,221, 65,83,68,70,71,72,74,75,76,59,222,13, 90,88,67,86,66,78,77,188,190,191,16,-1]; // letter to show in each button var letterPairs = ["1","2","3","4","5","6","7","8","9","0","-","=", "Q","W","E","R","T","Y","U","I","O","P","[","]", "A","S","D","F","G","H","J","K","L",";","'","\\n", "Z","X","C","V","B","N","M",",",".","/","\\s","NA"];
Dan12/Launchpad
app/assets/javascripts/keyboard.js
JavaScript
mit
13,120
angular.module('booksAR') .directive('userNavbar', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-navbar.html' }; }) .directive('userBooksTable', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-books-table.html' }; }) .directive('userTable', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-table.html' }; }) .directive('userProfileInfo', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-profile-info.html' }; }) .directive('ngConfirmClick', [ function(){ return { link: function (scope, element, attr) { var msg = attr.ngConfirmClick || "Are you sure?"; var clickAction = attr.confirmedClick; element.bind('click',function (event) { if ( window.confirm(msg) ) { scope.$eval(clickAction) } }); } }; }]);
AlejandroAcostaT/TypewriterAR
frontend/app/components/directives/user/user.js
JavaScript
mit
1,158
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all helper_method :current_user_session, :current_user filter_parameter_logging :password, :password_confirmation layout 'application' protected def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.record end def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to login_url return false end end def require_no_user if current_user store_location flash[:notice] = "You must be logged out to access this page" redirect_to account_url return false end end def store_location session[:return_to] = request.request_uri end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end end
markbates/warp_drive
test_apps/enterprise/app/controllers/application_controller.rb
Ruby
mit
1,267
<?php namespace App\AAS_Bundle\Entity; use Doctrine\ORM\Mapping as ORM; use App\AAS_Bundle\Utils\AAS as AAS; /** * Person */ class Person { /** * @var integer */ private $id; /** * @var string */ private $surname; /** * @var string */ private $name; /** * @var string */ private $patronymic; /** * @var string */ private $position; /** * @var \App\AAS_Bundle\Entity\Witness */ private $witness; /** * @var \Doctrine\Common\Collections\Collection */ private $phone_numbers; /** * @var \App\AAS_Bundle\Entity\Team */ private $team; /** * @var \DateTime */ private $created_at; /** * @var \DateTime */ private $updated_at; /** * Constructor */ public function __construct() { $this->phone_numbers = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set surname * * @param string $surname * @return Person */ public function setSurname($surname) { $this->surname = $surname; return $this; } /** * Get surname * * @return string */ public function getSurname() { return $this->surname; } public function getSurnameSlug() { return AAS::slugify($this->getSurname()); } /** * Set name * * @param string $name * @return Person */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } public function getNameSlug() { return AAS::slugify($this->getName()); } /** * Set patronymic * * @param string $patronymic * @return Person */ public function setPatronymic($patronymic) { $this->patronymic = $patronymic; return $this; } /** * Get patronymic * * @return string */ public function getPatronymic() { return $this->patronymic; } public function getPatronymicSlug() { return AAS::slugify($this->getPatronymic()); } /** * Set created_at * * @param \DateTime $createdAt * @return Person */ public function setCreatedAt($createdAt) { $this->created_at = $createdAt; return $this; } /** * Get created_at * * @return \DateTime */ public function getCreatedAt() { return $this->created_at; } /** * Set updated_at * * @param \DateTime $updatedAt * @return Person */ public function setUpdatedAt($updatedAt) { $this->updated_at = $updatedAt; return $this; } /** * Get updated_at * * @return \DateTime */ public function getUpdatedAt() { return $this->updated_at; } /** * @ORM\PrePersist */ public function setCreatedAtValue() { if(!$this->getCreatedAt()) { $this->created_at = new \DateTime(); } } /** * @ORM\PreUpdate */ public function setUpdatedAtValue() { $this->updated_at = new \DateTime(); } /** * @var \App\AAS_Bundle\Entity\SecurityPerson */ private $security_person; /** * Set security_person * * @param \App\AAS_Bundle\Entity\SecurityPerson $securityPerson * @return Person */ public function setSecurityPerson(\App\AAS_Bundle\Entity\SecurityPerson $securityPerson = null) { $this->security_person = $securityPerson; return $this; } /** * Get security_person * * @return \App\AAS_Bundle\Entity\SecurityPerson */ public function getSecurityPerson() { return $this->security_person; } /** * Set position * * @param string $position * @return Person */ public function setPosition($position) { $this->position = $position; return $this; } /** * Get position * * @return string */ public function getPosition() { return $this->position; } /** * Set witness * * @param \App\AAS_Bundle\Entity\Witness $witness * @return Person */ public function setWitness(\App\AAS_Bundle\Entity\Witness $witness = null) { $this->witness = $witness; return $this; } /** * Get witness * * @return \App\AAS_Bundle\Entity\Witness */ public function getWitness() { return $this->witness; } /** * Add phone_numbers * * @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers * @return Person */ public function addPhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers) { $this->phone_numbers[] = $phoneNumbers; return $this; } /** * Remove phone_numbers * * @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers */ public function removePhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers) { $this->phone_numbers->removeElement($phoneNumbers); } /** * Get phone_numbers * * @return \Doctrine\Common\Collections\Collection */ public function getPhoneNumbers() { return $this->phone_numbers; } /** * Set team * * @param \App\AAS_Bundle\Entity\Team $team * @return Person */ public function setTeam(\App\AAS_Bundle\Entity\Team $team = null) { $this->team = $team; return $this; } /** * Get team * * @return \App\AAS_Bundle\Entity\Team */ public function getTeam() { return $this->team; } /** * @var \App\AAS_Bundle\Entity\MedicalCommission */ private $medical_commission; /** * Set medical_commission * * @param \App\AAS_Bundle\Entity\MedicalCommission $medicalCommission * @return Person */ public function setMedicalCommission(\App\AAS_Bundle\Entity\MedicalCommission $medicalCommission = null) { $this->medical_commission = $medicalCommission; return $this; } /** * Get medical_commission * * @return \App\AAS_Bundle\Entity\MedicalCommission */ public function getMedicalCommission() { return $this->medical_commission; } /** * @var \Doctrine\Common\Collections\Collection */ private $admissions; /** * Add admissions * * @param \App\AAS_Bundle\Entity\Admission $admissions * @return Person */ public function addAdmission(\App\AAS_Bundle\Entity\Admission $admissions) { $this->admissions[] = $admissions; return $this; } /** * Remove admissions * * @param \App\AAS_Bundle\Entity\Admission $admissions */ public function removeAdmission(\App\AAS_Bundle\Entity\Admission $admissions) { $this->admissions->removeElement($admissions); } /** * Get admissions * * @return \Doctrine\Common\Collections\Collection */ public function getAdmissions() { return $this->admissions; } /** * @var \App\AAS_Bundle\Entity\BusinessTripGroup */ private $business_trip_group; /** * Set business_trip_group * * @param \App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup * @return Person */ public function setBusinessTripGroup(\App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup = null) { $this->business_trip_group = $businessTripGroup; return $this; } /** * Get business_trip_group * * @return \App\AAS_Bundle\Entity\BusinessTripGroup */ public function getBusinessTripGroup() { return $this->business_trip_group; } }
mrkonovalov/AAS
src/App/AAS_Bundle/Entity/Person.php
PHP
mit
8,735
import chalk = require("chalk"); import { take, select } from "redux-saga/effects"; import path = require("path"); import moment = require("moment"); import { titleize } from "inflection"; import { parallel } from "mesh"; import { weakMemo } from "../memo"; import AnsiUp from "ansi_up"; import { reader } from "../monad"; import { noop } from "lodash"; import { ImmutableObject, createImmutableObject } from "../immutable"; import { LogLevel, LogAction, LogActionTypes, Logger } from "./base"; // beat TS type checking chalk.enabled = true; function createLogColorizer(tester: RegExp, replaceValue: any) { return function(input: string) { if (!tester.test(input)) return input; return input.replace(tester, replaceValue); } } export type ConsoleLogState = { argv?: { color?: boolean, hlog?: boolean }, log?: { level: LogLevel, prefix?: string } } const cwd = process.cwd(); const highlighters = [ createLogColorizer(/^INF/, (match) => chalk.bgCyan(match)), createLogColorizer(/^ERR/, (match) => chalk.bgRed(match)), createLogColorizer(/^DBG/, (match) => chalk.grey.bgBlack(match)), createLogColorizer(/^WRN/, (match) => chalk.bgYellow(match)), // timestamp createLogColorizer(/\[\d+\.\d+\.\d+\]/, (match, inner) => `[${chalk.grey(inner)}]`), // URL createLogColorizer(/((\w{3,}\:\/\/)|([^\/\s\("':]+)?\/)([^\/\)\s"':]+\/?)+/g, (match) => { return chalk.yellow(/\w+:\/\//.test(match) ? match : match.replace(cwd + "/", "")) }), // duration createLogColorizer(/\s\d+(\.\d+)?(s|ms|m|h|d)(\s|$)/g, (match) => chalk.bold.cyan(match)), // numbers createLogColorizer(/\b\d+(\.\d+)?\b/g, (match, inner) => `${chalk.cyan(match)}`), // strings createLogColorizer(/"(.*?)"/g, (match, inner) => `"${chalk.blue(inner)}"`), // tokens createLogColorizer(/([\:\{\}",\(\)]|->|null|undefined|Infinity)/g, (match) => chalk.grey(match)), // <<output - green (from audio again) createLogColorizer(/<<(.*)/g, (match, word) => chalk.green(word)), // >>input - magenta (from audio) createLogColorizer(/>>(.*)/g, (match, word) => chalk.magenta(word)), // **BIG EMPHASIS** createLogColorizer(/\*\*(.*?)\*\*/, (match, word) => chalk.bgBlue(word)), // *emphasis* createLogColorizer(/\*(.*?)\*/g, (match, word) => chalk.bold(word)), // ___underline___ createLogColorizer(/___(.*?)___/g, (match, word) => chalk.underline(word)), // ~de emphasis~ createLogColorizer(/~(.*?)~/g, (match, word) => chalk.grey(word)), ]; function colorize(input: string) { let output = input; for (let i = 0, n = highlighters.length; i < n; i++) output = highlighters[i](output); return output; } function styledConsoleLog(...args: any[]) { var argArray = []; if (args.length) { var startTagRe = /<span\s+style=(['"])([^'"]*)\1\s*>/gi; var endTagRe = /<\/span>/gi; var reResultArray; argArray.push(arguments[0].replace(startTagRe, '%c').replace(endTagRe, '%c')); while (reResultArray = startTagRe.exec(arguments[0])) { argArray.push(reResultArray[2]); argArray.push(''); } // pass through subsequent args since chrome dev tools does not (yet) support console.log styling of the following form: console.log('%cBlue!', 'color: blue;', '%cRed!', 'color: red;'); for (var j = 1; j < arguments.length; j++) { argArray.push(arguments[j]); } } console.log.apply(console, argArray); } // I'm against abbreviations, but it's happening here // since all of these are the same length -- saves space in stdout, and makes // logs easier to read. const PREFIXES = { [LogLevel.DEBUG]: "DBG ", [LogLevel.INFO]: "INF ", [LogLevel.WARNING]: "WRN ", [LogLevel.ERROR]: "ERR ", }; const defaultState = { level: LogLevel.ALL, prefix: "" }; export function* consoleLogSaga() { while(true) { const { log: { level: acceptedLevel, prefix }}: ConsoleLogState = (yield select()) || defaultState; let { text, level }: LogAction = (yield take(LogActionTypes.LOG)); if (!(acceptedLevel & level)) continue; const log = { [LogLevel.DEBUG]: console.log.bind(console), [LogLevel.LOG]: console.log.bind(console), [LogLevel.INFO]: console.info.bind(console), [LogLevel.WARNING]: console.warn.bind(console), [LogLevel.ERROR]: console.error.bind(console) }[level]; text = PREFIXES[level] + (prefix || "") + text; text = colorize(text); if (typeof window !== "undefined" && !window["$synthetic"]) { return styledConsoleLog(new AnsiUp().ansi_to_html(text)); } log(text); } }
crcn/aerial
packages/aerial-common2/src/log/console.ts
TypeScript
mit
4,631
<?php namespace Payname\Security; use Payname\Exception\ApiCryptoException; /** * Class Crypto * Extract from https://github.com/illuminate/encryption */ class Crypto { /** * The algorithm used for encryption. * * @var string */ private static $cipher = 'AES-128-CBC'; /** * Encrypt the given value. * * @param string $value * @param string $key * @return string */ public static function encrypt($value, $key) { $iv = openssl_random_pseudo_bytes(self::getIvSize()); $value = openssl_encrypt(serialize($value), self::$cipher, $key, 0, $iv); if ($value === false) { throw new ApiCryptoException('Could not encrypt the data.'); } $mac = self::hash($iv = base64_encode($iv), $value, $key); return base64_encode(json_encode(compact('iv', 'value', 'mac'))); } /** * Decrypt the given value. * * @param string $payload * @param string $key * @return string */ public static function decrypt($value, $key) { $payload = self::getJsonPayload($value, $key); $iv = base64_decode($payload['iv']); $decrypted = openssl_decrypt($payload['value'], self::$cipher, $key, 0, $iv); if ($decrypted === false) { throw new ApiCryptoException('Could not decrypt the data.'); } return unserialize($decrypted); } /** * Get the JSON array from the given payload. * * @param string $payload * @param string $key * @return array */ private static function getJsonPayload($payload, $key) { $payload = json_decode(base64_decode($payload), true); if (!$payload || (!is_array($payload) || !isset($payload['iv']) || !isset($payload['value']) || !isset($payload['mac']))) { throw new ApiCryptoException('The payload is invalid.'); } if (!self::validMac($payload, $key)) { throw new ApiCryptoException('The MAC is invalid.'); } return $payload; } /** * Determine if the MAC for the given payload is valid. * * @param array $payload * @param string $key * @return bool */ private static function validMac(array $payload, $key) { $bytes = null; if (function_exists('random_bytes')) { $bytes = random_bytes(16); } elseif (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes(16, $strong); if ($bytes === false || $strong === false) { throw new ApiCryptoException('Unable to generate random string.'); } } else { throw new ApiCryptoException('OpenSSL extension is required for PHP 5 users.'); } $calcMac = hash_hmac('sha256', self::hash($payload['iv'], $payload['value'], $key), $bytes, true); return hash_hmac('sha256', $payload['mac'], $bytes, true) === $calcMac; } /** * Create a MAC for the given value. * * @param string $iv * @param string $value * @return string */ private static function hash($iv, $value, $key) { return hash_hmac('sha256', $iv.$value, $key); } /** * Get the IV size for the cipher. * * @return int */ private static function getIvSize() { return 16; } }
tplessis/Payname-php-sdk
src/Payname/Security/Crypto.php
PHP
mit
3,450
""" Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols)
tmetsch/graph_stitcher
stitcher/vis.py
Python
mit
5,618
package de.verygame.surface.screen.base; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; import com.badlogic.gdx.utils.viewport.Viewport; import java.util.Map; /** * @author Rico Schrage * * Context which can contain several subscreens. */ public class SubScreenContext implements ScreenContext { /** List of subScreen's plus visibility flag */ protected final ScreenSwitch screenSwitch; /** viewport of the screen (manages the glViewport) */ protected final Viewport viewport; /** True if a subScreen is visible */ protected boolean showSubScreen = false; /** * Constructs a context with the given viewport. * * @param viewport viewport viewport of the screen */ public SubScreenContext(Viewport viewport) { super(); this.viewport = viewport; this.screenSwitch = new ScreenSwitch(); } /** * Sets the dependency map of the screen switch. * * @param dependencies map of dependencies */ public void setDependencies(Map<String, Object> dependencies) { screenSwitch.setDependencyMap(dependencies); } /** * Sets the batch of the context. * * @param polygonSpriteBatch batch */ public void setBatch(PolygonSpriteBatch polygonSpriteBatch) { screenSwitch.setBatch(polygonSpriteBatch); } /** * Sets the inputHandler of the context. * * @param inputHandler inputHandler */ public void setInputHandler(InputMultiplexer inputHandler) { screenSwitch.setInputHandler(inputHandler); } public InputMultiplexer getInputHandler() { return screenSwitch.getInputHandler(); } public void onActivate(ScreenId screenKey) { if (screenSwitch.getActiveScreen() != null) { screenSwitch.getActiveScreen().onActivate(screenKey); } } public float onDeactivate(ScreenId screenKey) { if (screenSwitch.getActiveScreen() != null) { return screenSwitch.getActiveScreen().onDeactivate(screenKey); } return 0; } /** * Applies the viewport of the context. Calls {@link Viewport#apply(boolean)}. */ public void applyViewport() { viewport.apply(true); } /** * Updates the viewport of the context. Calls {@link Viewport#update(int, int, boolean)}. * * @param width width of the frame * @param height height of the frame */ public void updateViewport(int width, int height) { viewport.update(width, height, true); } public void update() { screenSwitch.updateSwitch(); screenSwitch.updateScreen(); } public void renderScreen() { if (showSubScreen) { screenSwitch.renderScreen(); } } public void resizeSubScreen(int width, int height) { screenSwitch.resize(width, height); } public void pauseSubScreen() { screenSwitch.pause(); } public void resumeSubScreen() { screenSwitch.resume(); } public void dispose() { screenSwitch.dispose(); } @Override public Viewport getViewport() { return viewport; } @Override public PolygonSpriteBatch getBatch() { return screenSwitch.getBatch(); } @Override public void addSubScreen(SubScreenId id, SubScreen subScreen) { if (screenSwitch.getBatch() == null) { throw new IllegalStateException("Parent screen have to be attached to a screen switch!"); } this.screenSwitch.addScreen(id, subScreen); } @Override public SubScreen getActiveSubScreen() { return (SubScreen) screenSwitch.getActiveScreen(); } @Override public void showScreen(SubScreenId id) { showSubScreen = true; screenSwitch.setActive(id); } @Override public void initialize(SubScreenId id) { showSubScreen = true; screenSwitch.setScreenSimple(id); } @Override public void hideScreen() { showSubScreen = false; } }
VeryGame/gdx-surface
gdx-surface/src/main/java/de/verygame/surface/screen/base/SubScreenContext.java
Java
mit
4,133
const { InventoryError, NotFoundError } = require('../../errors') const checkExists = (data) => { return (entity) => { if (!entity) throw new NotFoundError(`${data} not found`) return entity } } module.exports = (sequelize, DataTypes) => { const Pokemon = sequelize.define('Pokemon', { name: DataTypes.STRING, price: DataTypes.FLOAT, stock: DataTypes.INTEGER }, { tableName: 'pokemons' }) Pokemon.getByIdWithLock = function (pokemonId, transaction) { return Pokemon.findOne({ where: { id: pokemonId }, lock: { level: transaction.LOCK.UPDATE } }) } Pokemon.getByName = function (name) { return Pokemon.findOne({ where: { name } }).then(checkExists(name)) } Pokemon.prototype.decreaseStock = function (quantity) { if (this.stock < quantity) { return Promise.reject(new InventoryError(this.name, this.stock)) } this.stock -= quantity return this.save() } Pokemon.prototype.increaseStock = function (quantity) { this.stock += quantity return this.save() } return Pokemon }
gcaraciolo/pokemon-challenge
src/database/models/Pokemon.js
JavaScript
mit
1,131
// File auto generated by STUHashTool using static STULib.Types.Generic.Common; namespace STULib.Types.Dump { [STU(0x6250465B)] public class STU_6250465B : STUInstance { [STUField(0x6674CA34)] public string m_6674CA34; [STUField(0xDC05EA3B)] public ulong m_DC05EA3B; [STUField(0x781349E1)] public byte m_781349E1; } }
kerzyte/OWLib
STULib/Types/Dump/STU_6250465B.cs
C#
mit
381
class DeluxePublisher::Settings < ActiveRecord::Base set_table_name 'deluxe_publisher_settings' end
PaulRaye/Deluxe-Publisher
app/models/deluxe_publisher/settings.rb
Ruby
mit
101
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.http.policy; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.logging.LogLevel; import reactor.core.publisher.Mono; /** * Manages logging HTTP requests in {@link HttpLoggingPolicy}. */ @FunctionalInterface public interface HttpRequestLogger { /** * Gets the {@link LogLevel} used to log the HTTP request. * <p> * By default this will return {@link LogLevel#INFORMATIONAL}. * * @param loggingOptions The information available during request logging. * @return The {@link LogLevel} used to log the HTTP request. */ default LogLevel getLogLevel(HttpRequestLoggingContext loggingOptions) { return LogLevel.INFORMATIONAL; } /** * Logs the HTTP request. * <p> * To get the {@link LogLevel} used to log the HTTP request use {@link #getLogLevel(HttpRequestLoggingContext)}. * * @param logger The {@link ClientLogger} used to log the HTTP request. * @param loggingOptions The information available during request logging. * @return A reactive response that indicates that the HTTP request has been logged. */ Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions); }
Azure/azure-sdk-for-java
sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpRequestLogger.java
Java
mit
1,343
import React from 'react' import { Hero } from '../../components' const HeroContainer = () => ( <Hero /> ) export default HeroContainer
saelili/F3C_Website
app/containers/Hero/HeroContainer.js
JavaScript
mit
140
/* * 2007-2016 [PagSeguro Internet Ltda.] * * NOTICE OF LICENSE * * 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. * * Copyright: 2007-2016 PagSeguro Internet Ltda. * Licence: http://www.apache.org/licenses/LICENSE-2.0 */ package br.com.uol.pagseguro.api.common.domain; import br.com.uol.pagseguro.api.common.domain.enums.DocumentType; /** * Interface for documents. * * @author PagSeguro Internet Ltda. */ public interface Document { /** * Get Document Type * * @return Document Type * @see DocumentType */ DocumentType getType(); /** * Get Value of document * * @return Value of document */ String getValue(); }
girinoboy/lojacasamento
pagseguro-api/src/main/java/br/com/uol/pagseguro/api/common/domain/Document.java
Java
mit
1,173
# -*- coding: utf-8 -*- # django-simple-help # simple_help/admin.py from __future__ import unicode_literals from django.contrib import admin try: # add modeltranslation from modeltranslation.translator import translator from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin except ImportError: pass from simple_help.models import PageHelp from simple_help.forms import PageHelpAdminForm from simple_help.utils import modeltranslation try: from simple_help.translation import PageHelpTranslationOptions except ImportError: pass __all__ = [ "PageHelpAdmin", ] class PageHelpAdmin(TabbedDjangoJqueryTranslationAdmin if modeltranslation() else admin.ModelAdmin): """ Customize PageHelp model for admin area. """ list_display = ["page", "title", ] search_fields = ["title", ] list_filter = ["page", ] form = PageHelpAdminForm if modeltranslation(): # registering translation options translator.register(PageHelp, PageHelpTranslationOptions) # registering admin custom classes admin.site.register(PageHelp, PageHelpAdmin)
DCOD-OpenSource/django-simple-help
simple_help/admin.py
Python
mit
1,108
using UnityEngine; using System.Collections; public class MuteButton : MonoBehaviour { public Sprite MuteSprite; public Sprite PlaySprite; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
incredible-drunk/incredible-drunk
Assets/MuteButton.cs
C#
mit
269
using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { // Transform of the camera to shake. Grabs the gameObject's transform // if null. public Transform camTransform; // How long the object should shake for. public float shakeDuration = 0f; // Amplitude of the shake. A larger value shakes the camera harder. public float shakeAmount = 0.7f; public float decreaseFactor = 1.0f; Vector3 originalPos; void Awake() { if (camTransform == null) { camTransform = GetComponent(typeof(Transform)) as Transform; } } void OnEnable() { originalPos = camTransform.localPosition; } void Update() { if (shakeDuration > 0) { camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount; shakeDuration -= Time.deltaTime * decreaseFactor; } else { shakeDuration = 0f; camTransform.localPosition = originalPos; } } }
hakur/shooter
Assets/Shooter/Scripts/Shooter/CameraShake.cs
C#
mit
924
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MyWebApp { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
Microsoft-Build-2016/CodeLabs-WebDev
Module3-DeploymentAndAzure/Source/MyWebApp/src/MyWebApp/Startup.cs
C#
mit
2,018
# -*- coding: utf-8 -*- import sys from io import BytesIO import argparse from PIL import Image from .api import crop_resize parser = argparse.ArgumentParser( description='crop and resize an image without aspect ratio distortion.') parser.add_argument('image') parser.add_argument('-w', '-W', '--width', metavar='<width>', type=int, help='desired width of image in pixels') parser.add_argument('-H', '--height', metavar='<height>', type=int, help='desired height of image in pixels') parser.add_argument('-f', '--force', action='store_true', help='whether to scale up for smaller images') parser.add_argument('-d', '--display', action='store_true', default=False, help='display the new image (don\'t write to file)') parser.add_argument('-o', '--output', metavar='<file>', help='Write output to <file> instead of stdout.') def main(): parsed_args = parser.parse_args() image = Image.open(parsed_args.image) size = (parsed_args.width, parsed_args.height) new_image = crop_resize(image, size, parsed_args.force) if parsed_args.display: new_image.show() elif parsed_args.output: new_image.save(parsed_args.output) else: f = BytesIO() new_image.save(f, image.format) try: stdout = sys.stdout.buffer except AttributeError: stdout = sys.stdout stdout.write(f.getvalue())
codeif/crimg
crimg/bin.py
Python
mit
1,481
'use strict'; let sounds = new Map(); let playSound = path => { let sound = sounds.get(path); if (sound) { sound.play(); } else { sound = new Audio(path); sound.play(); } }; export default playSound;
attilahorvath/infinitree
src/infinitree/play_sound.js
JavaScript
mit
224
using System; using System.Windows.Input; namespace RFiDGear.ViewModel { /// <summary> /// Description of RelayCommand. /// </summary> public class RelayCommand : ICommand { public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } private Action methodToExecute; private Func<bool> canExecuteEvaluator; public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator) { this.methodToExecute = methodToExecute; this.canExecuteEvaluator = canExecuteEvaluator; } public RelayCommand(Action methodToExecute) : this(methodToExecute, null) { } public bool CanExecute(object parameter) { if (this.canExecuteEvaluator == null) { return true; } else { bool result = this.canExecuteEvaluator.Invoke(); return result; } } public void Execute(object parameter) { this.methodToExecute.Invoke(); } } }
c3rebro/RFiDGear
PluginSystem/DataAccessLayer/RelayCommand.cs
C#
mit
985
package com.etop.service; import com.etop.dao.UserDAO; import com.etop.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户服务,与dao进行对接 * <p/> * Created by Jeremie on 2014/9/30. */ @Service("UserService") public class UserService implements Serializable { @Autowired private UserDAO userDAO; /** * 通过用户名查找用户信息 * * @param username * @return */ public User findByName(String username) { Map<String, Object> params = new HashMap<>(); params.put("name", username); return userDAO.findUniqueResult("from User u where u.username = :name", params); } public List<User> getAllUser() { return userDAO.find("from User u"); } }
brucevsked/vskeddemolist
vskeddemos/projects/shirodemo/SpringMVC_Shiro/src/com/etop/service/UserService.java
Java
mit
930
from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n
MetaPlot/MetaPlot
metaplot/helpers.py
Python
mit
4,900
package states; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.ArrayList; import database.DeleteGame; import database.LoadGame; import game.Game; import graphics.ButtonAction; import graphics.Text; import graphics.UIButton; import graphics.UIList; import graphics.UIScrollScreen; import loader.ImageLoader; public class MenuState extends State { /* Menu screen state it is the initial screen of the game it control the new button and the load button*/ //Main Menu private UIList menuButtons; private BufferedImage menuBackground; //Load Buttons Menu (second Screen) private UIScrollScreen loadScreen; private BufferedImage subMenuBackground; private boolean loadScreenMenu; //Selected Game Menu (Third Screen) private UIList loadSubMenu; private BufferedImage gameSelectedBackground; private boolean gameSelected; public MenuState(Game game) { super(game); State.loadMenuState = true; } @Override public UIList getUIButtons() { /*Control of active buttons*/ if (!gameSelected) { return menuButtons; } else { return loadSubMenu; } } @Override public UIScrollScreen getScreen() { /*control if scroll buttons are active*/ if (loadScreenMenu) return loadScreen; else return null; } @Override public void tick() { // If ESC is clicked on the menu screen then the game closes if(State.loadMenuState) { //loadMenuState is true then init menu screen initMenuScreen(); State.loadMenuState = false; } if (game.getKeyboard().mESC == true) { //If esc was pressed if (loadScreenMenu) { //Release loadScreen memory loadScreenMenu = false; loadScreen.getButtons().clear(); loadScreen = null; subMenuBackground = null; } else if(gameSelected) { //Release memory of the screen after choose a saved game gameSelected = false; loadSubMenu.getButtons().clear(); loadSubMenu = null; gameSelectedBackground = null; } else { // If esc was clicked on menu then close game game.stop(); } game.getKeyboard().mESC = false; } if(State.loadGame || State.newGame) // If load or new game true then it will change to gameState so release menu memory and changes state { menuButtons.getButtons().clear(); menuButtons = null; menuBackground = null; State.setCurrentState(game.getGameState()); } } @Override public void render(Graphics graph) { if(State.loadMenuState) // Make sure that only render after menu was loaded return; // Draw the menu background image and render the UI buttons graph.drawImage(menuBackground, 0, 0, game.getWidth(), game.getHeight(), null); menuButtons.render(graph); if (loadScreenMenu) { //Draw subMenu background and render buttons graph.drawImage(subMenuBackground, 0, 0, game.getWidth(), game.getHeight(), null); loadScreen.render(graph); } else if (gameSelected) { //Draw gameSelected background and render buttons graph.drawImage(gameSelectedBackground, 0, 0, game.getWidth(), game.getHeight(), null); loadSubMenu.render(graph); } } private void initMenuScreen() { /*Initialize the screen and buttons of the first menu screen*/ menuBackground = ImageLoader.loadImage("/background/menu_backgroud.png"); try { initMenuButtons(); } catch (Exception e) { e.printStackTrace(); } } private void initLoadScreen() { /*Initialize the screen and buttons of the second menu screen (list of saved games)*/ subMenuBackground = ImageLoader.loadImage("/background/submenu_background.png"); initLoadScreenButtons(); } private void initGameSelectedScreen() { /*Initialize the screen and of the third menu screen (game selected)*/ gameSelectedBackground = ImageLoader.loadImage("/background/load_submenu_background.png"); initGameSelectedButtons(); } private void initGameSelectedButtons() { /*Init buttons of the selected game load, delete and cancel*/ BufferedImage loadSaveButton[] = new BufferedImage[2]; BufferedImage deleteSaveButton[] = new BufferedImage[2]; BufferedImage cancelButton[] = new BufferedImage[2]; loadSubMenu = new UIList(); loadSaveButton[0] = ImageLoader.loadImage("/button/load_submenu_d.png"); loadSaveButton[1] = ImageLoader.loadImage("/button/load_submenu_s.png"); int buttonWidth = (int) (loadSaveButton[0].getWidth() * game.getScale()); int buttonHeight = (int) (loadSaveButton[0].getHeight() * game.getScale()); //Load a saved game loadSubMenu.getButtons().add(new UIButton((int) (50 * game.getScale()), (int)(300 * game.getScale()), buttonWidth, buttonHeight, loadSaveButton, -1, new ButtonAction() { @Override public void action() { State.loadGame = true; // Tells gameState to load a game game.getKeyboard().mESC = true; // Set esc true to release memory from this screen (GameSelected screen) } })); deleteSaveButton[0] = ImageLoader.loadImage("/button/delete_submenu_d.png"); deleteSaveButton[1] = ImageLoader.loadImage("/button/delete_submenu_s.png"); //Delete a saved game loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(430 * game.getScale()), buttonWidth, buttonHeight, deleteSaveButton, -1, new ButtonAction() { @Override public void action() { try { DeleteGame.Delete(State.savedGames.get(lastButtonIndex).split(" ")[0]); //Get the name of the button pressed and removes from database } catch (Exception e) { e.printStackTrace(); } State.savedGames.clear(); //Clear database name loaded State.savedGames = null; game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen) } })); cancelButton[0] = ImageLoader.loadImage("/button/cancel_submenu_d.png"); cancelButton[1] = ImageLoader.loadImage("/button/cancel_submenu_s.png"); //Cancel operation and goes back to the first menu screen loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(550 * game.getScale()), buttonWidth, buttonHeight, cancelButton, -1, new ButtonAction() { @Override public void action() { State.savedGames.clear(); //Clear database name loaded State.savedGames = null; game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen) } })); } private void initLoadScreenButtons() { /*Initialize all load screen buttons*/ BufferedImage loadScreenImage = ImageLoader.loadImage("/background/scrollScreen.png"); BufferedImage loadButton[] = new BufferedImage[2]; int scrollSpeed = 10; //Init load screen loadScreen = new UIScrollScreen(loadScreenImage, (int)(31 * game.getScale()), (int)(132 * game.getScale()), (int)(loadScreenImage.getWidth() * game.getScale()), (int)(loadScreenImage.getHeight() * game.getScale()), scrollSpeed); loadButton[0] = ImageLoader.loadImage("/button/submenu_button_d.png"); loadButton[1] = ImageLoader.loadImage("/button/submenu_button_s.png"); float buttonWidth = loadButton[0].getWidth() * game.getScale(); float buttonHeight = loadButton[0].getHeight() * game.getScale(); Font font = new Font("Castellar", Font.PLAIN, (int)(25 * game.getScale())); for (int i = 0, accumulator = (int) loadScreen.getScreen().getY(); (int) i < savedGames.size(); i++) { //Accumulator controls the button position on the screen String split[] = savedGames.get(i).split(" "); //split the name that came from the database float buttonX = (float) (loadScreen.getScreen().getX() + 3); Text text[] = new Text[2]; //Initialize both colors of the text and create the visible buttons text[0] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.black, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2)); text[1] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.white, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2)); loadScreen.getButtons().add(new UIButton((int) buttonX, accumulator, (int) (buttonWidth), (int) buttonHeight, loadButton, i, text, new ButtonAction() { public void action() { initGameSelectedScreen(); //Initialize gameSelect screen and buttons gameSelected = true; game.getKeyboard().mESC = true; // Select true to free memory used by the loadScreen } })); accumulator += (buttonHeight); } } private void initMenuButtons() throws Exception{ // Resize the button depending of the scale attribute of the game class BufferedImage[] buttonNewGame = new BufferedImage[2]; BufferedImage[] buttonLoadGame = new BufferedImage[2]; buttonNewGame[0] = ImageLoader.loadImage("/button/new_game.png"); buttonNewGame[1] = ImageLoader.loadImage("/button/new_game_b.png"); buttonLoadGame[0] = ImageLoader.loadImage("/button/load_game.png"); buttonLoadGame[1] = ImageLoader.loadImage("/button/load_game_b.png"); menuButtons = new UIList(); /* * Creates the load button and add to the UI button list, the first two * parameters has the position of the button on the screen it uses the * game.width to centralize the button and the game.height to control * the y position on the screen for every button a Button action is * defined when passing the argument, this way is possible to program * the button when creating it */ float buttonWidth = buttonLoadGame[0].getWidth() * game.getScale(); float buttonHeight = buttonLoadGame[0].getHeight() * game.getScale(); menuButtons.getButtons().add(new UIButton((int) ((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3) + buttonHeight), (int) (buttonWidth), (int) buttonHeight, buttonLoadGame, -1, new ButtonAction() { public void action() { savedGames = new ArrayList<>(); try { savedGames = LoadGame.loadNames(); } catch (Exception e) { e.printStackTrace(); } initLoadScreen(); loadScreenMenu = true; } })); /* * Creates the game button and add to the UI button list, the first two * parameters has the position of the button on the screen it uses the * game.width to centralize the button and the game.height to control * the y position on the screen for every button a Button action is * defined when passing the argument, this way is possible to program * the button when creating it */ // Resize the button depending of the scale attribute of the game class buttonWidth = buttonNewGame[0].getWidth() * game.getScale(); buttonHeight = buttonNewGame[0].getHeight() * game.getScale(); menuButtons.getButtons() .add(new UIButton((int) ((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3)), (int) (buttonWidth), (int) (buttonHeight), buttonNewGame, -1, new ButtonAction() { public void action() { State.newGame = true; } })); } }
BrunoMarchi/Chess_Game-LCP_2017
ChessGame/src/states/MenuState.java
Java
mit
11,128
# frozen_string_literal: true module HelperFunctions def log_in email = 'test@sumofus.org' password = 'password' User.create! email: email, password: password visit '/users/sign_in' fill_in 'user_email', with: email fill_in 'user_password', with: password click_button 'Log in' end def create_tags Tag.create!([ { tag_name: '*Welcome_Sequence', actionkit_uri: '/rest/v1/tag/1000/' }, { tag_name: '#Animal_Rights', actionkit_uri: '/rest/v1/tag/944/' }, { tag_name: '#Net_Neutrality', actionkit_uri: '/rest/v1/tag/1078/' }, { tag_name: '*FYI_and_VIP', actionkit_uri: '/rest/v1/tag/980/' }, { tag_name: '@Germany', actionkit_uri: '/rest/v1/tag/1036/' }, { tag_name: '@NewZealand', actionkit_uri: '/rest/v1/tag/1140/' }, { tag_name: '@France', actionkit_uri: '/rest/v1/tag/1128/' }, { tag_name: '#Sexism', actionkit_uri: '/rest/v1/tag/1208/' }, { tag_name: '#Disability_Rights', actionkit_uri: '/rest/v1/tag/1040/' }, { tag_name: '@Austria', actionkit_uri: '/rest/v1/tag/1042/' } ]) end def error_messages_from_response(response) JSON.parse(response.body)['errors'].inject([]) { |memo, error| memo << error['message'] }.uniq end end
SumOfUs/Champaign
spec/support/helper_functions.rb
Ruby
mit
1,244
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms'; export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { const name = control.value; const no = nameRe.test(name); return no ? {forbiddenName: {name}} : null; }; } @Directive({ selector: '[forbiddenName]', providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}] }) export class ForbiddenValidatorDirective implements Validator, OnChanges { @Input() public forbiddenName: string; private valFn = Validators.nullValidator; public ngOnChanges(changes: SimpleChanges): void { // const change = changes['forbiddenName']; // if (change) { // const val: string | RegExp = change.currentValue; // const re = val instanceof RegExp ? val : new RegExp(val, 'i'); // this.valFn = forbiddenNameValidator(re); // } else { // this.valFn = Validators.nullValidator; // } } public validate(control: AbstractControl): {[key: string]: any} { return this.valFn(control); } }
TaylorPzreal/curriculum-vitae
src/app/func/sign-up/forbidden-name.directive.ts
TypeScript
mit
1,223
namespace TransferCavityLock2012 { partial class LockControlPanel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lockParams = new System.Windows.Forms.GroupBox(); this.lockedLED = new NationalInstruments.UI.WindowsForms.Led(); this.label10 = new System.Windows.Forms.Label(); this.setPointIncrementBox = new System.Windows.Forms.TextBox(); this.GainTextbox = new System.Windows.Forms.TextBox(); this.VoltageToLaserTextBox = new System.Windows.Forms.TextBox(); this.setPointAdjustMinusButton = new System.Windows.Forms.Button(); this.setPointAdjustPlusButton = new System.Windows.Forms.Button(); this.LaserSetPointTextBox = new System.Windows.Forms.TextBox(); this.lockEnableCheck = new System.Windows.Forms.CheckBox(); this.label4 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.SlaveLaserIntensityScatterGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.SlaveDataPlot = new NationalInstruments.UI.ScatterPlot(); this.xAxis1 = new NationalInstruments.UI.XAxis(); this.yAxis1 = new NationalInstruments.UI.YAxis(); this.SlaveFitPlot = new NationalInstruments.UI.ScatterPlot(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.ErrorScatterGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.ErrorPlot = new NationalInstruments.UI.ScatterPlot(); this.xAxis2 = new NationalInstruments.UI.XAxis(); this.yAxis2 = new NationalInstruments.UI.YAxis(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.slErrorResetButton = new System.Windows.Forms.Button(); this.VoltageTrackBar = new System.Windows.Forms.TrackBar(); this.lockParams.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.lockedLED)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SlaveLaserIntensityScatterGraph)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).BeginInit(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).BeginInit(); this.SuspendLayout(); // // lockParams // this.lockParams.Controls.Add(this.lockedLED); this.lockParams.Controls.Add(this.label10); this.lockParams.Controls.Add(this.setPointIncrementBox); this.lockParams.Controls.Add(this.GainTextbox); this.lockParams.Controls.Add(this.VoltageToLaserTextBox); this.lockParams.Controls.Add(this.setPointAdjustMinusButton); this.lockParams.Controls.Add(this.setPointAdjustPlusButton); this.lockParams.Controls.Add(this.LaserSetPointTextBox); this.lockParams.Controls.Add(this.lockEnableCheck); this.lockParams.Controls.Add(this.label4); this.lockParams.Controls.Add(this.label2); this.lockParams.Controls.Add(this.label3); this.lockParams.Controls.Add(this.VoltageTrackBar); this.lockParams.Location = new System.Drawing.Point(589, 3); this.lockParams.Name = "lockParams"; this.lockParams.Size = new System.Drawing.Size(355, 162); this.lockParams.TabIndex = 13; this.lockParams.TabStop = false; this.lockParams.Text = "Lock Parameters"; // // lockedLED // this.lockedLED.LedStyle = NationalInstruments.UI.LedStyle.Round3D; this.lockedLED.Location = new System.Drawing.Point(310, 6); this.lockedLED.Name = "lockedLED"; this.lockedLED.Size = new System.Drawing.Size(32, 30); this.lockedLED.TabIndex = 34; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(6, 66); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(123, 13); this.label10.TabIndex = 33; this.label10.Text = "Set Point Increment Size"; // // setPointIncrementBox // this.setPointIncrementBox.Location = new System.Drawing.Point(168, 63); this.setPointIncrementBox.Name = "setPointIncrementBox"; this.setPointIncrementBox.Size = new System.Drawing.Size(55, 20); this.setPointIncrementBox.TabIndex = 32; this.setPointIncrementBox.Text = "0.01"; this.setPointIncrementBox.TextChanged += new System.EventHandler(this.setPointIncrementBox_TextChanged); // // GainTextbox // this.GainTextbox.Location = new System.Drawing.Point(167, 15); this.GainTextbox.Name = "GainTextbox"; this.GainTextbox.Size = new System.Drawing.Size(81, 20); this.GainTextbox.TabIndex = 31; this.GainTextbox.Text = "0.5"; this.GainTextbox.TextChanged += new System.EventHandler(this.GainChanged); // // VoltageToLaserTextBox // this.VoltageToLaserTextBox.Location = new System.Drawing.Point(167, 89); this.VoltageToLaserTextBox.Name = "VoltageToLaserTextBox"; this.VoltageToLaserTextBox.Size = new System.Drawing.Size(100, 20); this.VoltageToLaserTextBox.TabIndex = 30; this.VoltageToLaserTextBox.Text = "0"; this.VoltageToLaserTextBox.TextChanged += new System.EventHandler(this.VoltageToLaserChanged); // // setPointAdjustMinusButton // this.setPointAdjustMinusButton.Location = new System.Drawing.Point(124, 37); this.setPointAdjustMinusButton.Name = "setPointAdjustMinusButton"; this.setPointAdjustMinusButton.Size = new System.Drawing.Size(37, 23); this.setPointAdjustMinusButton.TabIndex = 29; this.setPointAdjustMinusButton.Text = "-"; this.setPointAdjustMinusButton.UseVisualStyleBackColor = true; this.setPointAdjustMinusButton.Click += new System.EventHandler(this.setPointAdjustMinusButton_Click); // // setPointAdjustPlusButton // this.setPointAdjustPlusButton.Location = new System.Drawing.Point(81, 37); this.setPointAdjustPlusButton.Name = "setPointAdjustPlusButton"; this.setPointAdjustPlusButton.Size = new System.Drawing.Size(37, 23); this.setPointAdjustPlusButton.TabIndex = 28; this.setPointAdjustPlusButton.Text = "+"; this.setPointAdjustPlusButton.UseVisualStyleBackColor = true; this.setPointAdjustPlusButton.Click += new System.EventHandler(this.setPointAdjustPlusButton_Click); // // LaserSetPointTextBox // this.LaserSetPointTextBox.AcceptsReturn = true; this.LaserSetPointTextBox.Location = new System.Drawing.Point(167, 39); this.LaserSetPointTextBox.Name = "LaserSetPointTextBox"; this.LaserSetPointTextBox.Size = new System.Drawing.Size(57, 20); this.LaserSetPointTextBox.TabIndex = 27; this.LaserSetPointTextBox.Text = "0"; // // lockEnableCheck // this.lockEnableCheck.AutoSize = true; this.lockEnableCheck.Location = new System.Drawing.Point(254, 17); this.lockEnableCheck.Name = "lockEnableCheck"; this.lockEnableCheck.Size = new System.Drawing.Size(50, 17); this.lockEnableCheck.TabIndex = 9; this.lockEnableCheck.Text = "Lock"; this.lockEnableCheck.UseVisualStyleBackColor = true; this.lockEnableCheck.CheckedChanged += new System.EventHandler(this.lockEnableCheck_CheckedChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 18); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(29, 13); this.label4.TabIndex = 20; this.label4.Text = "Gain"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 92); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(122, 13); this.label2.TabIndex = 17; this.label2.Text = "Voltage sent to laser (V):"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 42); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(69, 13); this.label3.TabIndex = 13; this.label3.Text = "Set Point (V):"; // // SlaveLaserIntensityScatterGraph // this.SlaveLaserIntensityScatterGraph.Location = new System.Drawing.Point(9, 17); this.SlaveLaserIntensityScatterGraph.Name = "SlaveLaserIntensityScatterGraph"; this.SlaveLaserIntensityScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.SlaveDataPlot, this.SlaveFitPlot}); this.SlaveLaserIntensityScatterGraph.Size = new System.Drawing.Size(567, 132); this.SlaveLaserIntensityScatterGraph.TabIndex = 12; this.SlaveLaserIntensityScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis1}); this.SlaveLaserIntensityScatterGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis1}); // // SlaveDataPlot // this.SlaveDataPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.SlaveDataPlot.PointSize = new System.Drawing.Size(3, 3); this.SlaveDataPlot.PointStyle = NationalInstruments.UI.PointStyle.SolidCircle; this.SlaveDataPlot.XAxis = this.xAxis1; this.SlaveDataPlot.YAxis = this.yAxis1; // // SlaveFitPlot // this.SlaveFitPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.SlaveFitPlot.PointColor = System.Drawing.Color.LawnGreen; this.SlaveFitPlot.PointStyle = NationalInstruments.UI.PointStyle.EmptyTriangleUp; this.SlaveFitPlot.XAxis = this.xAxis1; this.SlaveFitPlot.YAxis = this.yAxis1; // // groupBox1 // this.groupBox1.Controls.Add(this.ErrorScatterGraph); this.groupBox1.Controls.Add(this.SlaveLaserIntensityScatterGraph); this.groupBox1.Location = new System.Drawing.Point(4, 3); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(582, 286); this.groupBox1.TabIndex = 15; this.groupBox1.TabStop = false; this.groupBox1.Text = "Slave laser"; // // ErrorScatterGraph // this.ErrorScatterGraph.Location = new System.Drawing.Point(6, 155); this.ErrorScatterGraph.Name = "ErrorScatterGraph"; this.ErrorScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.ErrorPlot}); this.ErrorScatterGraph.Size = new System.Drawing.Size(570, 125); this.ErrorScatterGraph.TabIndex = 13; this.ErrorScatterGraph.UseColorGenerator = true; this.ErrorScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis2}); this.ErrorScatterGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis2}); // // ErrorPlot // this.ErrorPlot.LineColor = System.Drawing.Color.Red; this.ErrorPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.ErrorPlot.XAxis = this.xAxis2; this.ErrorPlot.YAxis = this.yAxis2; // // xAxis2 // this.xAxis2.Mode = NationalInstruments.UI.AxisMode.StripChart; this.xAxis2.Range = new NationalInstruments.UI.Range(0D, 500D); // // groupBox2 // this.groupBox2.Controls.Add(this.slErrorResetButton); this.groupBox2.Location = new System.Drawing.Point(589, 171); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(355, 118); this.groupBox2.TabIndex = 16; this.groupBox2.TabStop = false; this.groupBox2.Text = "Error Signal Parameters"; // // slErrorResetButton // this.slErrorResetButton.Location = new System.Drawing.Point(9, 19); this.slErrorResetButton.Name = "slErrorResetButton"; this.slErrorResetButton.Size = new System.Drawing.Size(109, 23); this.slErrorResetButton.TabIndex = 29; this.slErrorResetButton.Text = "Reset Graph"; this.slErrorResetButton.UseVisualStyleBackColor = true; this.slErrorResetButton.Click += new System.EventHandler(this.slErrorResetButton_Click); // // VoltageTrackBar // this.VoltageTrackBar.BackColor = System.Drawing.SystemColors.ButtonFace; this.VoltageTrackBar.Location = new System.Drawing.Point(6, 114); this.VoltageTrackBar.Maximum = 1000; this.VoltageTrackBar.Name = "VoltageTrackBar"; this.VoltageTrackBar.RightToLeft = System.Windows.Forms.RightToLeft.No; this.VoltageTrackBar.Size = new System.Drawing.Size(343, 45); this.VoltageTrackBar.TabIndex = 53; this.VoltageTrackBar.Value = 100; this.VoltageTrackBar.Scroll += new System.EventHandler(this.VoltageTrackBar_Scroll); // // LockControlPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add(this.lockParams); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Name = "LockControlPanel"; this.Size = new System.Drawing.Size(952, 294); this.lockParams.ResumeLayout(false); this.lockParams.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.lockedLED)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SlaveLaserIntensityScatterGraph)).EndInit(); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).EndInit(); this.groupBox2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox lockParams; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox setPointIncrementBox; private System.Windows.Forms.TextBox GainTextbox; private System.Windows.Forms.TextBox VoltageToLaserTextBox; private System.Windows.Forms.Button setPointAdjustMinusButton; private System.Windows.Forms.Button setPointAdjustPlusButton; private System.Windows.Forms.TextBox LaserSetPointTextBox; private System.Windows.Forms.CheckBox lockEnableCheck; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; public NationalInstruments.UI.WindowsForms.ScatterGraph SlaveLaserIntensityScatterGraph; public NationalInstruments.UI.ScatterPlot SlaveDataPlot; private NationalInstruments.UI.XAxis xAxis1; private NationalInstruments.UI.YAxis yAxis1; public NationalInstruments.UI.ScatterPlot SlaveFitPlot; private System.Windows.Forms.GroupBox groupBox1; private NationalInstruments.UI.WindowsForms.Led lockedLED; private NationalInstruments.UI.WindowsForms.ScatterGraph ErrorScatterGraph; private NationalInstruments.UI.ScatterPlot ErrorPlot; private NationalInstruments.UI.XAxis xAxis2; private NationalInstruments.UI.YAxis yAxis2; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button slErrorResetButton; public System.Windows.Forms.TrackBar VoltageTrackBar; } }
jstammers/EDMSuite
TransferCavityLock2012/LockControlPanel.Designer.cs
C#
mit
18,415
from django.db import models from .workflow import TestStateMachine class TestModel(models.Model): name = models.CharField(max_length=100) state = models.CharField(max_length=20, null=True, blank=True) state_num = models.IntegerField(null=True, blank=True) other_state = models.CharField(max_length=20, null=True, blank=True) message = models.CharField(max_length=250, null=True, blank=True) class Meta: permissions = TestStateMachine.get_permissions('testmodel', 'Test')
andrewebdev/django-ostinato
ostinato/tests/statemachine/models.py
Python
mit
509
<?php namespace Fisharebest\Localization\Locale; use Fisharebest\Localization\Territory\TerritoryNi; /** * Class LocaleEsNi * * @author Greg Roach <fisharebest@gmail.com> * @copyright (c) 2015 Greg Roach * @license GPLv3+ */ class LocaleEsNi extends LocaleEs { public function territory() { return new TerritoryNi; } }
fweber1/Annies-Ancestors
webtrees/vendor/fisharebest/localization/src/Locale/LocaleEsNi.php
PHP
mit
344
require 'builder' module MWS module API class Fulfillment < Base include Feeds ## Takes an array of hash AmazonOrderID,FulfillmentDate,CarrierName,ShipperTrackingNumber,sku,quantity ## Returns true if all the orders were updated successfully ## Otherwise raises an exception def post_ship_confirmation(merchant_id, ship_info) # Shipping Confirmation is done by sending an XML "feed" to Amazon xml = "" builder = Builder::XmlMarkup.new(:indent => 2, :target => xml) builder.instruct! # <?xml version="1.0" encoding="UTF-8"?> builder.AmazonEnvelope(:"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", :"xsi:noNamespaceSchemaLocation" => "amzn-envelope.xsd") do |env| env.Header do |head| head.DocumentVersion('1.01') head.MerchantIdentifier(merchant_id) end env.MessageType('OrderFulfillment') i = 0 ship_info.each do |shp| env.Message do |msg| msg.MessageID(i += 1) msg.OrderFulfillment do |orf| orf.AmazonOrderID(shp.AmazonOrderID) orf.FulfillmentDate(shp.FulfillmentDate.to_time.iso8601) orf.FulfillmentData do |fd| fd.CarrierCode(shp.CarrierCode) fd.ShippingMethod() fd.ShipperTrackingNumber(shp.ShipperTrackingNumber) end if shp.sku != '' orf.Item do |itm| itm.MerchantOrderItemID(shp.sku) itm.MerchantFulfillmentItemID(shp.sku) itm.Quantity(shp.quantity) end end end end end end submit_feed('_POST_ORDER_FULFILLMENT_DATA_', xml) end end end end
tinabme/ruby-mws
lib/ruby-mws/api/fulfillment.rb
Ruby
mit
1,850
import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { HelloRoutingModule } from './hello-routing.module'; import { HelloComponent } from './hello.component'; @NgModule({ imports: [ SharedModule, HelloRoutingModule, ], declarations: [ HelloComponent, ], }) export class HelloModule { }
rangle/angular2-starter
src/app/hello/hello.module.ts
TypeScript
mit
361
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('geokey_sapelli', '0005_sapellifield_truefalse'), ] operations = [ migrations.AddField( model_name='sapelliproject', name='sapelli_fingerprint', field=models.IntegerField(default=-1), preserve_default=False, ), ]
ExCiteS/geokey-sapelli
geokey_sapelli/migrations/0006_sapelliproject_sapelli_fingerprint.py
Python
mit
468
using UnityEngine; using System.Collections; public class HurtSusukeOnContact : MonoBehaviour { public int damageToGive; public float bounceOnEnemy; private Rigidbody2D myRigidbody2D; // Use this for initialization void Start () { myRigidbody2D = transform.parent.GetComponent<Rigidbody2D> (); } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Susuke") { other.GetComponent<EnemyHealthManager>().giveDamage(damageToGive); myRigidbody2D.velocity = new Vector2 (myRigidbody2D.velocity.x, bounceOnEnemy); } } }
SafeRamen/Nerd-Quest
Nerd Quest/Assets/Scripts/HurtSusukeOnContact.cs
C#
mit
611
 #include "Internal.hpp" #include <LuminoEngine/Graphics/Texture.hpp> #include <LuminoEngine/Rendering/Material.hpp> #include <LuminoEngine/Mesh/Mesh.hpp> #include <LuminoEngine/Visual/StaticMeshComponent.hpp> namespace ln { //============================================================================= // StaticMeshComponent StaticMeshComponent::StaticMeshComponent() : m_model(nullptr) { } StaticMeshComponent::~StaticMeshComponent() { } void StaticMeshComponent::init() { VisualComponent::init(); } void StaticMeshComponent::setModel(StaticMeshModel* model) { m_model = model; } StaticMeshModel* StaticMeshComponent::model() const { return m_model; } void StaticMeshComponent::onRender(RenderingContext* context) { const auto& containers = m_model->meshContainers(); for (int iContainer = 0; iContainer < containers.size(); iContainer++) { const auto& meshContainer = containers[iContainer]; MeshResource* meshResource = meshContainer->meshResource(); if (meshResource) { for (int iSection = 0; iSection < meshResource->sections().size(); iSection++) { context->setMaterial(m_model->materials()[meshResource->sections()[iSection].materialIndex]); context->drawMesh(meshResource, iSection); } } //Mesh* mesh = meshContainer->mesh(); //if (mesh) { // for (int iSection = 0; iSection < mesh->sections().size(); iSection++) { // context->setMaterial(m_model->materials()[mesh->sections()[iSection].materialIndex]); // context->drawMesh(mesh, iSection); // } //} } for (const auto& node : m_model->meshNodes()) { if (node->meshContainerIndex() >= 0) { context->setTransfrom(m_model->nodeGlobalTransform(node->index())); const auto& meshContainer = m_model->meshContainers()[node->meshContainerIndex()]; Mesh* mesh = meshContainer->mesh(); if (mesh) { for (int iSection = 0; iSection < mesh->sections().size(); iSection++) { context->setMaterial(m_model->materials()[mesh->sections()[iSection].materialIndex]); context->drawMesh(mesh, iSection); } } } } } } // namespace ln
lriki/Lumino
src/LuminoEngine/src/Visual/StaticMeshComponent.cpp
C++
mit
2,432
<?php namespace App\Controllers\Admin; use BaseController; use DB, View, Datatables, Input, Redirect, Str, Validator, Image, File; use App\Models\Music; class MusicController extends BaseController { private $upload_path = "uploads/music/"; public function getList() { $music_count = Music::count(); $data = array(); if($music_count > 0){ $data['formProcess'] = "editProcess"; $musicRecord = Music::orderBy('id', 'DESC')->first(); $id = $musicRecord->id; $data['input'] = Music::find($id); } return View::make('admin.site.music',$data); } public function postSubmit(){ if(Input::get('_action') == 'addProcess'){ $validator = Validator::make( array( 'Title' => Input::get('title'), 'MP3 File' => Input::file('file_name') ), array( 'Title' => 'required', 'MP3 File' => 'required' ) ); $mime = Input::file('file_name')->getMimeType(); if ($validator->fails()){ return Redirect::route('admin.music')->withErrors($validator)->withInput(); } // if($mime !== 'audio/mpeg'){ // $error = "You have to input audio MP3 file"; // return Redirect::route('admin.music')->withErrors($error)->withInput(); // } $music = new Music; $music->title = Input::get('title'); if(!file_exists($this->upload_path)) { mkdir($this->upload_path, 0777, true); } if(!is_null(Input::file('file_name'))){ $file = Input::file('file_name'); if($file->isValid()){ $filename = "subud_".str_random(10); $extension = $file->getClientOriginalExtension(); $upload_name = $filename.".".$extension; $upload_success = $file->move($this->upload_path, $upload_name); if( $upload_success ) { $music->file_name = $this->upload_path.$upload_name; } else { $error = "Failed uploading file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } $music->save(); } else { $error = "Invalid file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } } else { $error = "Null file input"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } } elseif(Input::get('_action') == 'editProcess'){ if(Input::has('id')){ $validator = Validator::make( array( 'Title' => Input::get('title') ), array( 'Title' => 'required' ) ); if ($validator->fails()){ return Redirect::route('admin.music')->withErrors($validator)->withInput(); } $music = Music::find(Input::get('id')); $music->title = Input::get('title'); if(!is_null(Input::file('file_name'))){ $mime = Input::file('file_name')->getMimeType(); if($mime !== 'audio/mpeg'){ $error = "You have to input audio MP3 file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } if(!file_exists($this->upload_path)) { mkdir($this->upload_path, 0777, true); } $file = Input::file('file_name'); if($file->isValid()){ $filename = "subud_".str_random(10); $extension = $file->getClientOriginalExtension(); $upload_name = $filename.".".$extension; $upload_success = $file->move($this->upload_path, $upload_name); if( $upload_success ) { $music->file_name = $this->upload_path.$upload_name; } else { $error = "Failed uploading file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } $music->save(); } else { $error = "Invalid file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } } $music->save(); } } return Redirect::route('admin.music'); } }
benhanks040888/subud
app/controllers/admin/MusicController.php
PHP
mit
3,793
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.formatter.bibtexfields.ClearFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import org.jabref.logic.help.HelpFile; import org.jabref.logic.importer.EntryBasedFetcher; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.IdBasedFetcher; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.URLDownload; import org.jabref.model.cleanup.FieldFormatterCleanup; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.OptionalUtil; public class DoiFetcher implements IdBasedFetcher, EntryBasedFetcher { public static final String NAME = "DOI"; private final ImportFormatPreferences preferences; public DoiFetcher(ImportFormatPreferences preferences) { this.preferences = preferences; } @Override public String getName() { return DoiFetcher.NAME; } @Override public Optional<HelpFile> getHelpPage() { return Optional.of(HelpFile.FETCHER_DOI); } @Override public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { Optional<DOI> doi = DOI.parse(identifier); try { if (doi.isPresent()) { URL doiURL = new URL(doi.get().getURIAsASCIIString()); // BibTeX data URLDownload download = new URLDownload(doiURL); download.addHeader("Accept", "application/x-bibtex"); String bibtexString = download.asString(); // BibTeX entry Optional<BibEntry> fetchedEntry = BibtexParser.singleFromString(bibtexString, preferences, new DummyFileUpdateMonitor()); fetchedEntry.ifPresent(this::doPostCleanup); return fetchedEntry; } else { throw new FetcherException(Localization.lang("Invalid DOI: '%0'.", identifier)); } } catch (IOException e) { throw new FetcherException(Localization.lang("Connection error"), e); } catch (ParseException e) { throw new FetcherException("Could not parse BibTeX entry", e); } } private void doPostCleanup(BibEntry entry) { new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry); new FieldFormatterCleanup(StandardField.URL, new ClearFormatter()).cleanup(entry); } @Override public List<BibEntry> performSearch(BibEntry entry) throws FetcherException { Optional<String> doi = entry.getField(StandardField.DOI); if (doi.isPresent()) { return OptionalUtil.toList(performSearchById(doi.get())); } else { return Collections.emptyList(); } } }
zellerdev/jabref
src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java
Java
mit
3,259
from __future__ import division, print_function #, unicode_literals """ Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ import numpy as np # Setup. num_max = 1000 basis = [3, 5] factors = [] for i in range(num_max): for k in basis: if not i % k: factors.append(i) break print('\nRange: {:d}'.format(num_max)) print('Number of factors: {:d}'.format(len(factors))) print('The answer: {:d}'.format(np.sum(factors))) # Done.
Who8MyLunch/euler
problem_001.py
Python
mit
632
s="the quick brown fox jumped over the lazy dog" t = s.split(" ") for v in t: print(v) r = s.split("e") for v in r: print(v) x = s.split() for v in x: print(v) # 2-arg version of split not supported # y = s.split(" ",7) # for v in y: # print v
naitoh/py2rb
tests/strings/split.py
Python
mit
266
module Xronor class DSL module Checker class ValidationError < StandardError end def required(name, value) invalid = false if value case value when String invalid = value.strip.empty? when Array, Hash invalid = value.empty? end else invalid = true end raise ValidationError.new("'#{name}' is required") if invalid end end end end
dtan4/xronor
lib/xronor/dsl/checker.rb
Ruby
mit
483
var mongoose = require('mongoose'); var statuses = ['open', 'closed', 'as_expected']; var priorities = ['major','regular','minor','enhancement']; var Comment = new mongoose.Schema( { comment: String, username: String, name: String, dca: {type: Date, default: Date.now} } ); var Bug = new mongoose.Schema( { id: {type: String}, name: {type: String, required: true}, desc: String, status: {type: String, default: 'open'}, priority: {type: String, default: 'regular'}, username: { type: String, required: true}, reported_by: {type: String}, company: {type: String, required: true}, comments: [Comment], dca: {type: Date, default: Date.now}, dua: Date } ); Bug.pre('save', function(next) { if (this.id === undefined) { this.id = (new Date()).getTime().toString(); } now = new Date(); this.dua = now; next(); }); module.exports = mongoose.model('Bug', Bug);
baliganikhil/Storm
models/bug.js
JavaScript
mit
1,110
#include "EngineImplDefine.h" void BlendColor::Init(D3DCOLOR defaultColor, D3DCOLOR disabledColor, D3DCOLOR hiddenColor) { for (decltype(States.size()) i = 0; i != States.size(); ++i) { States[i] = defaultColor; } States[STATE_DISABLED] = disabledColor; States[STATE_HIDDEN] = hiddenColor; Current = hiddenColor; } void BlendColor::Blend(CONTROL_STATE iState, float fElapsedTime, float fRate) { D3DXCOLOR destColor = States[iState]; D3DXColorLerp(&Current, &Current, &destColor, 1.0f - powf(fRate, 30 * fElapsedTime)); } void FontTexElement::SetTexture(UINT iTexture, RECT * prcTexture, D3DCOLOR defaultTextureColor) { this->iTexture = iTexture; if (prcTexture) rcTexture = *prcTexture; else SetRectEmpty(&rcTexture); TextureColor.Init(defaultTextureColor); } void FontTexElement::SetFont(UINT iFont, D3DCOLOR defaultFontColor, DWORD dwTextFormat) { this->iFont = iFont; this->dwTextFormat = dwTextFormat; FontColor.Init(defaultFontColor); } void FontTexElement::Refresh() { TextureColor.Current = TextureColor.States[STATE_HIDDEN]; FontColor.Current = FontColor.States[STATE_HIDDEN]; }
ss-torres/UI-Editor
UI Editor/DrawEngine/EngineImplDefine.cpp
C++
mit
1,118
class AddColumnToRequestSchema < ActiveRecord::Migration def change add_column :request_schemata, :name, :string, null: false, default: "" end end
opentie/opentie-app
db/migrate/20150502043108_add_column_to_request_schema.rb
Ruby
mit
155
ActionController::Routing::Routes.draw do |map| map.resources :companies, :member => { :filter_available_members => :get, :delete_member => :post, :add_members => :post, :filter_available_projects => :get, :delete_project => :post, :add_projects => :post } end
splendeo/chiliproject_companies
config/routes.rb
Ruby
mit
283
class AddVersionToComponents < ActiveRecord::Migration def change add_column :components, :version, :float end end
e-nable/LimbForge
db/migrate/20160829013357_add_version_to_components.rb
Ruby
mit
123
using GalaSoft.MvvmLight; namespace Operation.WPF.ViewModels { public interface IViewModelFactory { T ResolveViewModel<T>() where T : ViewModelBase; } }
ElijahReva/operations-research-wpf
Operation.WPF/ViewModels/IViewModelFactory.cs
C#
mit
181
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class MageTurret : Turret { [SerializeField] float range; [SerializeField] float baseDamage = 0.00f; float currentDamage = 0.00f; [SerializeField] float damageIncrease; [SerializeField] float attackCooldown; float currentCooldown; [SerializeField] float damageMultiplier; float currentMultiplier; bool isAttacking; [SerializeField] List<Enemy> enemiesCanAttack; Enemy oldClosestEnemy; Enemy closestEnemy; Enemy target; [Header("AttackRay")] [SerializeField] Transform raySpawnPoint; [SerializeField] LineRenderer lr; [SerializeField] ParticleSystem partSystemTurret; [SerializeField] ParticleSystem finalRaySystem; void Start() { enemiesCanAttack = new List<Enemy>(); currentDamage = baseDamage; currentMultiplier = damageMultiplier; } public override void PooledStart() { enemiesCanAttack = new List<Enemy>(); currentDamage = baseDamage; currentMultiplier = damageMultiplier; } void Update() { if (enemiesCanAttack.Count > 0) { if (isAttacking) { Attack(); return; } finalRaySystem.Stop(); currentCooldown -= Time.deltaTime; if (currentCooldown <= 0) { FindClosestTarget(); currentCooldown = attackCooldown; } } else { lr.enabled = false; } } void Attack() { if (currentDamage <= 200) { currentDamage += damageIncrease * currentMultiplier; } target.TakeDamage(currentDamage); if (target.isDead) { ClearDeadTarget(); return; } currentMultiplier += damageIncrease; lr.enabled = true; lr.SetPosition(0, raySpawnPoint.position); lr.SetPosition(1, target.transform.position); finalRaySystem.Play(); finalRaySystem.transform.position = lr.GetPosition(1); } void ClearDeadTarget() { lr.enabled = false; enemiesCanAttack.Remove(target); target = null; currentDamage = baseDamage; currentMultiplier = damageMultiplier; isAttacking = false; finalRaySystem.Stop(); } void ClearTarget() { target.ClearDamage(); lr.enabled = false; enemiesCanAttack.Remove(target); target = null; currentDamage = baseDamage; currentMultiplier = damageMultiplier; isAttacking = false; finalRaySystem.Stop(); } void OnTriggerEnter(Collider other) { if (other.CompareTag("Enemy")) { enemiesCanAttack.Add(other.GetComponent<Enemy>()); if (target == null) { FindClosestTarget(); } } } void OnTriggerExit(Collider other) { if (other.CompareTag("Enemy")) { if (target != null && Vector3.Distance(target.transform. position, transform.position) > range) { ClearTarget(); } enemiesCanAttack.Remove(other.GetComponent<Enemy>()); } } public override void Sell() { base.Sell(); EndSell(); } protected virtual void FindClosestTarget() { for (int i = 0; i < enemiesCanAttack.Count; i++) { if (closestEnemy != null) { if (Vector3.Distance(transform.position, enemiesCanAttack[i].transform.position) <= Vector3.Distance(transform.position, closestEnemy.transform.position)) { closestEnemy = enemiesCanAttack[i]; } } else closestEnemy = enemiesCanAttack[i]; target = closestEnemy.GetComponent<Enemy>(); oldClosestEnemy = closestEnemy; isAttacking = true; } } void OnDrawGizmos() { Color color = Color.blue; Gizmos.color = color; Gizmos.DrawWireSphere(transform.position, range); } }
GoldenArmor/HostileKingdom
Assets/Turrets/MageTower/Scripts/MageTurret.cs
C#
mit
4,399
#include "Namespace_Base.h" #include <co/Coral.h> #include <co/IComponent.h> #include <co/IPort.h> #include <co/IInterface.h> namespace co { //------ co.Namespace has a facet named 'namespace', of type co.INamespace ------// co::IInterface* Namespace_co_INamespace::getInterface() { return co::typeOf<co::INamespace>::get(); } co::IPort* Namespace_co_INamespace::getFacet() { co::IComponent* component = static_cast<co::IComponent*>( co::getType( "co.Namespace" ) ); assert( component ); co::IPort* facet = static_cast<co::IPort*>( component->getMember( "namespace" ) ); assert( facet ); return facet; } //------ Namespace_Base ------// Namespace_Base::Namespace_Base() { // empty } Namespace_Base::~Namespace_Base() { // empty } co::IObject* Namespace_Base::getProvider() { return this; } void Namespace_Base::serviceRetain() { incrementRefCount(); } void Namespace_Base::serviceRelease() { decrementRefCount(); } co::IComponent* Namespace_Base::getComponent() { co::IType* type = co::getType( "co.Namespace" ); assert( type->getKind() == co::TK_COMPONENT ); return static_cast<co::IComponent*>( type ); } co::IService* Namespace_Base::getServiceAt( co::IPort* port ) { checkValidPort( port ); co::IService* res = NULL; switch( port->getIndex() ) { case 0: res = static_cast<co::INamespace*>( this ); break; default: raiseUnexpectedPortIndex(); } return res; } void Namespace_Base::setServiceAt( co::IPort* receptacle, co::IService* service ) { checkValidReceptacle( receptacle ); raiseUnexpectedPortIndex(); CORAL_UNUSED( service ); } } // namespace co
coral-framework/coral
src/core/generated/Namespace_Base.cpp
C++
mit
1,595
/*** AppView ***/ define(function(require, exports, module) { var View = require('famous/core/View'); var Surface = require('famous/core/Surface'); var Transform = require('famous/core/Transform'); var StateModifier = require('famous/modifiers/StateModifier'); var SlideshowView = require('views/SlideshowView'); function ProjectView() { View.apply(this, arguments); } ProjectView.prototype = Object.create(View.prototype); ProjectView.prototype.constructor = ProjectView; ProjectView.DEFAULT_OPTIONS = {}; module.exports = ProjectView; });
M1Reeder/famous-example-server
app/public/sandbox/index/views/ProjectView.js
JavaScript
mit
599
<?php /** * Go! AOP framework * * @copyright Copyright 2013, Lisachenko Alexander <lisachenko.it@gmail.com> * * This source file is subject to the license that is bundled * with this source code in the file LICENSE. */ namespace Demo\Example; /** * Human class example */ class HumanDemo { /** * Eat something */ public function eat() { echo "Eating...", PHP_EOL; } /** * Clean the teeth */ public function cleanTeeth() { echo "Cleaning teeth...", PHP_EOL; } /** * Washing up */ public function washUp() { echo "Washing up...", PHP_EOL; } /** * Working */ public function work() { echo "Working...", PHP_EOL; } /** * Go to sleep */ public function sleep() { echo "Go to sleep...", PHP_EOL; } }
latamautos/goaop
demos/Demo/Example/HumanDemo.php
PHP
mit
880
using Microsoft.AspNet.Http; using Microsoft.AspNet.Routing; using Migrap.AspNet.Multitenant; using System; using System.Collections.Generic; namespace Migrap.AspNet.Routing { public class TenantRouteConstraint : IRouteConstraint { public const string TenantKey = "tenant"; private readonly ISet<string> _tenants = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly ITenantService _tenantService; public TenantRouteConstraint(ITenantService tenantService) { _tenantService = tenantService; } public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection) { var address = httpContext.Request.Headers["Host"][0].Split('.'); if(address.Length < 2) { return false; } var tenant = address[0]; if(!values.ContainsKey("tenant")) { values.Add("tenant", tenant); } return true; } } }
migrap/Migrap.AspNet.Multitenant
src/Migrap.AspNet.Multitenant/Routing/TenantRouteConstraint.cs
C#
mit
1,080
import numpy as np __author__ = 'David John Gagne <djgagne@ou.edu>' def main(): # Contingency Table from Wilks (2011) Table 8.3 table = np.array([[50, 91, 71], [47, 2364, 170], [54, 205, 3288]]) mct = MulticlassContingencyTable(table, n_classes=table.shape[0], class_names=np.arange(table.shape[0]).astype(str)) print(mct.peirce_skill_score()) print(mct.gerrity_score()) class MulticlassContingencyTable(object): """ This class is a container for a contingency table containing more than 2 classes. The contingency table is stored in table as a numpy array with the rows corresponding to forecast categories, and the columns corresponding to observation categories. """ def __init__(self, table=None, n_classes=2, class_names=("1", "0")): self.table = table self.n_classes = n_classes self.class_names = class_names if table is None: self.table = np.zeros((self.n_classes, self.n_classes), dtype=int) def __add__(self, other): assert self.n_classes == other.n_classes, "Number of classes does not match" return MulticlassContingencyTable(self.table + other.table, n_classes=self.n_classes, class_names=self.class_names) def peirce_skill_score(self): """ Multiclass Peirce Skill Score (also Hanssen and Kuipers score, True Skill Score) """ n = float(self.table.sum()) nf = self.table.sum(axis=1) no = self.table.sum(axis=0) correct = float(self.table.trace()) return (correct / n - (nf * no).sum() / n ** 2) / (1 - (no * no).sum() / n ** 2) def gerrity_score(self): """ Gerrity Score, which weights each cell in the contingency table by its observed relative frequency. :return: """ k = self.table.shape[0] n = float(self.table.sum()) p_o = self.table.sum(axis=0) / n p_sum = np.cumsum(p_o)[:-1] a = (1.0 - p_sum) / p_sum s = np.zeros(self.table.shape, dtype=float) for (i, j) in np.ndindex(*s.shape): if i == j: s[i, j] = 1.0 / (k - 1.0) * (np.sum(1.0 / a[0:j]) + np.sum(a[j:k - 1])) elif i < j: s[i, j] = 1.0 / (k - 1.0) * (np.sum(1.0 / a[0:i]) - (j - i) + np.sum(a[j:k - 1])) else: s[i, j] = s[j, i] return np.sum(self.table / float(self.table.sum()) * s) def heidke_skill_score(self): n = float(self.table.sum()) nf = self.table.sum(axis=1) no = self.table.sum(axis=0) correct = float(self.table.trace()) return (correct / n - (nf * no).sum() / n ** 2) / (1 - (nf * no).sum() / n ** 2) if __name__ == "__main__": main()
djgagne/hagelslag
hagelslag/evaluation/MulticlassContingencyTable.py
Python
mit
2,908
"use strict"; var ArrayCollection_1 = require('./ArrayCollection'); exports.ArrayCollection = ArrayCollection_1.ArrayCollection; var ArrayList_1 = require('./ArrayList'); exports.ArrayList = ArrayList_1.ArrayList; var SequenceBase_1 = require('./SequenceBase'); exports.SequenceBase = SequenceBase_1.SequenceBase; var Buckets_1 = require('./Buckets'); exports.Buckets = Buckets_1.Buckets; var Collection_1 = require('./Collection'); exports.Collection = Collection_1.Collection; var Dictionary_1 = require('./Dictionary'); exports.Dictionary = Dictionary_1.Dictionary; exports.Pair = Dictionary_1.Pair; var Hash_1 = require('./Hash'); exports.HashFunc = Hash_1.HashFunc; exports.DefaultHashFunc = Hash_1.DefaultHashFunc; var HashSet_1 = require('./HashSet'); exports.HashSet = HashSet_1.HashSet; var Iterable_1 = require('./Iterable'); exports.Iterable = Iterable_1.Iterable; var LinkedList_1 = require('./LinkedList'); exports.LinkedList = LinkedList_1.LinkedList; var Native_1 = require('./Native'); exports.NativeIndex = Native_1.NativeIndex; exports.NativeMap = Native_1.NativeMap; var Sequence_1 = require('./Sequence'); exports.Sequence = Sequence_1.Sequence; var Stack_1 = require('./Stack'); exports.Stack = Stack_1.Stack; var Util_1 = require('./Util'); exports.Util = Util_1.Util; //# sourceMappingURL=index.js.map
swhitf/paladin-core
dist/collections/internal/index.js
JavaScript
mit
1,324
<?php /** * Provides low-level debugging, error and exception functionality * * @copyright Copyright (c) 2007-2011 Will Bond, others * @author Will Bond [wb] <will@flourishlib.com> * @author Will Bond, iMarc LLC [wb-imarc] <will@imarc.net> * @author Nick Trew [nt] * @license http://flourishlib.com/license * * @package Flourish * @link http://flourishlib.com/fCore * * @version 1.0.0b20 * @changes 1.0.0b20 Backwards Compatibility Break - Updated ::expose() to not wrap the data in HTML when running via CLI, and instead just append a newline [wb, 2011-02-24] * @changes 1.0.0b19 Added detection of AIX to ::checkOS() [wb, 2011-01-19] * @changes 1.0.0b18 Updated ::expose() to be able to accept multiple parameters [wb, 2011-01-10] * @changes 1.0.0b17 Fixed a bug with ::backtrace() triggering notices when an argument is not UTF-8 [wb, 2010-08-17] * @changes 1.0.0b16 Added the `$types` and `$regex` parameters to ::startErrorCapture() and the `$regex` parameter to ::stopErrorCapture() [wb, 2010-08-09] * @changes 1.0.0b15 Added ::startErrorCapture() and ::stopErrorCapture() [wb, 2010-07-05] * @changes 1.0.0b14 Changed ::enableExceptionHandling() to only call fException::printMessage() when the destination is not `html` and no callback has been defined, added ::configureSMTP() to allow using fSMTP for error and exception emails [wb, 2010-06-04] * @changes 1.0.0b13 Added the `$backtrace` parameter to ::backtrace() [wb, 2010-03-05] * @changes 1.0.0b12 Added ::getDebug() to check for the global debugging flag, added more specific BSD checks to ::checkOS() [wb, 2010-03-02] * @changes 1.0.0b11 Added ::detectOpcodeCache() [nt+wb, 2009-10-06] * @changes 1.0.0b10 Fixed ::expose() to properly display when output includes non-UTF-8 binary data [wb, 2009-06-29] * @changes 1.0.0b9 Added ::disableContext() to remove context info for exception/error handling, tweaked output for exceptions/errors [wb, 2009-06-28] * @changes 1.0.0b8 ::enableErrorHandling() and ::enableExceptionHandling() now accept multiple email addresses, and a much wider range of emails [wb-imarc, 2009-06-01] * @changes 1.0.0b7 ::backtrace() now properly replaces document root with {doc_root} on Windows [wb, 2009-05-02] * @changes 1.0.0b6 Fixed a bug with getting the server name for error messages when running on the command line [wb, 2009-03-11] * @changes 1.0.0b5 Fixed a bug with checking the error/exception destination when a log file is specified [wb, 2009-03-07] * @changes 1.0.0b4 Backwards compatibility break - ::getOS() and ::getPHPVersion() removed, replaced with ::checkOS() and ::checkVersion() [wb, 2009-02-16] * @changes 1.0.0b3 ::handleError() now displays what kind of error occured as the heading [wb, 2009-02-15] * @changes 1.0.0b2 Added ::registerDebugCallback() [wb, 2009-02-07] * @changes 1.0.0b The initial implementation [wb, 2007-09-25] */ class fCore { // The following constants allow for nice looking callbacks to static methods const backtrace = 'fCore::backtrace'; const call = 'fCore::call'; const callback = 'fCore::callback'; const checkOS = 'fCore::checkOS'; const checkVersion = 'fCore::checkVersion'; const configureSMTP = 'fCore::configureSMTP'; const debug = 'fCore::debug'; const detectOpcodeCache = 'fCore::detectOpcodeCache'; const disableContext = 'fCore::disableContext'; const dump = 'fCore::dump'; const enableDebugging = 'fCore::enableDebugging'; const enableDynamicConstants = 'fCore::enableDynamicConstants'; const enableErrorHandling = 'fCore::enableErrorHandling'; const enableExceptionHandling = 'fCore::enableExceptionHandling'; const expose = 'fCore::expose'; const getDebug = 'fCore::getDebug'; const handleError = 'fCore::handleError'; const handleException = 'fCore::handleException'; const registerDebugCallback = 'fCore::registerDebugCallback'; const reset = 'fCore::reset'; const sendMessagesOnShutdown = 'fCore::sendMessagesOnShutdown'; const startErrorCapture = 'fCore::startErrorCapture'; const stopErrorCapture = 'fCore::stopErrorCapture'; /** * A regex to match errors to capture * * @var string */ static private $captured_error_regex = NULL; /** * The previous error handler * * @var callback */ static private $captured_errors_previous_handler = NULL; /** * The types of errors to capture * * @var integer */ static private $captured_error_types = NULL; /** * An array of errors that have been captured * * @var array */ static private $captured_errors = NULL; /** * If the context info has been shown * * @var boolean */ static private $context_shown = FALSE; /** * If global debugging is enabled * * @var boolean */ static private $debug = NULL; /** * A callback to pass debug messages to * * @var callback */ static private $debug_callback = NULL; /** * If dynamic constants should be created * * @var boolean */ static private $dynamic_constants = FALSE; /** * Error destination * * @var string */ static private $error_destination = 'html'; /** * An array of errors to be send to the destination upon page completion * * @var array */ static private $error_message_queue = array(); /** * Exception destination * * @var string */ static private $exception_destination = 'html'; /** * Exception handler callback * * @var mixed */ static private $exception_handler_callback = NULL; /** * Exception handler callback parameters * * @var array */ static private $exception_handler_parameters = array(); /** * The message generated by the uncaught exception * * @var string */ static private $exception_message = NULL; /** * If this class is handling errors * * @var boolean */ static private $handles_errors = FALSE; /** * If this class is handling exceptions * * @var boolean */ static private $handles_exceptions = FALSE; /** * If the context info should be shown with errors/exceptions * * @var boolean */ static private $show_context = TRUE; /** * An SMTP connection for sending error and exception emails * * @var fSMTP */ static private $smtp_connection = NULL; /** * The email address to send error emails from * * @var string */ static private $smtp_from_email = NULL; /** * Creates a nicely formatted backtrace to the the point where this method is called * * @param integer $remove_lines The number of trailing lines to remove from the backtrace * @param array $backtrace A backtrace from [http://php.net/backtrace `debug_backtrace()`] to format - this is not usually required or desired * @return string The formatted backtrace */ static public function backtrace($remove_lines=0, $backtrace=NULL) { if ($remove_lines !== NULL && !is_numeric($remove_lines)) { $remove_lines = 0; } settype($remove_lines, 'integer'); $doc_root = realpath($_SERVER['DOCUMENT_ROOT']); $doc_root .= (substr($doc_root, -1) != DIRECTORY_SEPARATOR) ? DIRECTORY_SEPARATOR : ''; if ($backtrace === NULL) { $backtrace = debug_backtrace(); } while ($remove_lines > 0) { array_shift($backtrace); $remove_lines--; } $backtrace = array_reverse($backtrace); $bt_string = ''; $i = 0; foreach ($backtrace as $call) { if ($i) { $bt_string .= "\n"; } if (isset($call['file'])) { $bt_string .= str_replace($doc_root, '{doc_root}' . DIRECTORY_SEPARATOR, $call['file']) . '(' . $call['line'] . '): '; } else { $bt_string .= '[internal function]: '; } if (isset($call['class'])) { $bt_string .= $call['class'] . $call['type']; } if (isset($call['class']) || isset($call['function'])) { $bt_string .= $call['function'] . '('; $j = 0; if (!isset($call['args'])) { $call['args'] = array(); } foreach ($call['args'] as $arg) { if ($j) { $bt_string .= ', '; } if (is_bool($arg)) { $bt_string .= ($arg) ? 'true' : 'false'; } elseif (is_null($arg)) { $bt_string .= 'NULL'; } elseif (is_array($arg)) { $bt_string .= 'Array'; } elseif (is_object($arg)) { $bt_string .= 'Object(' . get_class($arg) . ')'; } elseif (is_string($arg)) { // Shorten the UTF-8 string if it is too long if (strlen(utf8_decode($arg)) > 18) { // If we can't match as unicode, try single byte if (!preg_match('#^(.{0,15})#us', $arg, $short_arg)) { preg_match('#^(.{0,15})#s', $arg, $short_arg); } $arg = $short_arg[0] . '...'; } $bt_string .= "'" . $arg . "'"; } else { $bt_string .= (string) $arg; } $j++; } $bt_string .= ')'; } $i++; } return $bt_string; } /** * Performs a [http://php.net/call_user_func call_user_func()], while translating PHP 5.2 static callback syntax for PHP 5.1 and 5.0 * * Parameters can be passed either as a single array of parameters or as * multiple parameters. * * {{{ * #!php * // Passing multiple parameters in a normal fashion * fCore::call('Class::method', TRUE, 0, 'test'); * * // Passing multiple parameters in a parameters array * fCore::call('Class::method', array(TRUE, 0, 'test')); * }}} * * To pass parameters by reference they must be assigned to an * array by reference and the function/method being called must accept those * parameters by reference. If either condition is not met, the parameter * will be passed by value. * * {{{ * #!php * // Passing parameters by reference * fCore::call('Class::method', array(&$var1, &$var2)); * }}} * * @param callback $callback The function or method to call * @param array $parameters The parameters to pass to the function/method * @return mixed The return value of the called function/method */ static public function call($callback, $parameters=array()) { // Fix PHP 5.0 and 5.1 static callback syntax if (is_string($callback) && strpos($callback, '::') !== FALSE) { $callback = explode('::', $callback); } $parameters = array_slice(func_get_args(), 1); if (sizeof($parameters) == 1 && is_array($parameters[0])) { $parameters = $parameters[0]; } return call_user_func_array($callback, $parameters); } /** * Translates a Class::method style static method callback to array style for compatibility with PHP 5.0 and 5.1 and built-in PHP functions * * @param callback $callback The callback to translate * @return array The translated callback */ static public function callback($callback) { if (is_string($callback) && strpos($callback, '::') !== FALSE) { return explode('::', $callback); } return $callback; } /** * Checks an error/exception destination to make sure it is valid * * @param string $destination The destination for the exception. An email, file or the string `'html'`. * @return string|boolean `'email'`, `'file'`, `'html'` or `FALSE` */ static private function checkDestination($destination) { if ($destination == 'html') { return 'html'; } if (preg_match('~^(?: # Allow leading whitespace (?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+") # An "atom" or a quoted string (?:\.[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))* # A . plus another "atom" or a quoted string, any number of times )@(?: # The @ symbol (?:[a-z0-9\\-]+\.)+[a-z]{2,}| # Domain name (?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5]) # (or) IP addresses ) (?:\s*,\s* # Any number of other emails separated by a comma with surrounding spaces (?: (?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+") (?:\.[ \t]*(?:[^\x00-\x20\(\)<>@,;:\\\\"\.\[\]]+|"[^"\\\\\n\r]+"[ \t]*))* )@(?: (?:[a-z0-9\\-]+\.)+[a-z]{2,}| (?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5]) ) )*$~xiD', $destination)) { return 'email'; } $path_info = pathinfo($destination); $dir_exists = file_exists($path_info['dirname']); $dir_writable = ($dir_exists) ? is_writable($path_info['dirname']) : FALSE; $file_exists = file_exists($destination); $file_writable = ($file_exists) ? is_writable($destination) : FALSE; if (!$dir_exists || ($dir_exists && ((!$file_exists && !$dir_writable) || ($file_exists && !$file_writable)))) { return FALSE; } return 'file'; } /** * Returns is the current OS is one of the OSes passed as a parameter * * Valid OS strings are: * - `'linux'` * - `'aix'` * - `'bsd'` * - `'freebsd'` * - `'netbsd'` * - `'openbsd'` * - `'osx'` * - `'solaris'` * - `'windows'` * * @param string $os The operating system to check - see method description for valid OSes * @param string ... * @return boolean If the current OS is included in the list of OSes passed as parameters */ static public function checkOS($os) { $oses = func_get_args(); $valid_oses = array('linux', 'aix', 'bsd', 'freebsd', 'openbsd', 'netbsd', 'osx', 'solaris', 'windows'); if ($invalid_oses = array_diff($oses, $valid_oses)) { throw new fProgrammerException( 'One or more of the OSes specified, %$1s, is invalid. Must be one of: %2$s.', join(' ', $invalid_oses), join(', ', $valid_oses) ); } $uname = php_uname('s'); if (stripos($uname, 'linux') !== FALSE) { return in_array('linux', $oses); } elseif (stripos($uname, 'aix') !== FALSE) { return in_array('aix', $oses); } elseif (stripos($uname, 'netbsd') !== FALSE) { return in_array('netbsd', $oses) || in_array('bsd', $oses); } elseif (stripos($uname, 'openbsd') !== FALSE) { return in_array('openbsd', $oses) || in_array('bsd', $oses); } elseif (stripos($uname, 'freebsd') !== FALSE) { return in_array('freebsd', $oses) || in_array('bsd', $oses); } elseif (stripos($uname, 'solaris') !== FALSE || stripos($uname, 'sunos') !== FALSE) { return in_array('solaris', $oses); } elseif (stripos($uname, 'windows') !== FALSE) { return in_array('windows', $oses); } elseif (stripos($uname, 'darwin') !== FALSE) { return in_array('osx', $oses); } throw new fEnvironmentException('Unable to determine the current OS'); } /** * Checks to see if the running version of PHP is greater or equal to the version passed * * @return boolean If the running version of PHP is greater or equal to the version passed */ static public function checkVersion($version) { static $running_version = NULL; if ($running_version === NULL) { $running_version = preg_replace( '#^(\d+\.\d+\.\d+).*$#D', '\1', PHP_VERSION ); } return version_compare($running_version, $version, '>='); } /** * Composes text using fText if loaded * * @param string $message The message to compose * @param mixed $component A string or number to insert into the message * @param mixed ... * @return string The composed and possible translated message */ static private function compose($message) { $args = array_slice(func_get_args(), 1); if (class_exists('fText', FALSE)) { return call_user_func_array( array('fText', 'compose'), array($message, $args) ); } else { return vsprintf($message, $args); } } /** * Sets an fSMTP object to be used for sending error and exception emails * * @param fSMTP $smtp The SMTP connection to send emails over * @param string $from_email The email address to use in the `From:` header * @return void */ static public function configureSMTP($smtp, $from_email) { self::$smtp_connection = $smtp; self::$smtp_from_email = $from_email; } /** * Prints a debugging message if global or code-specific debugging is enabled * * @param string $message The debug message * @param boolean $force If debugging should be forced even when global debugging is off * @return void */ static public function debug($message, $force=FALSE) { if ($force || self::$debug) { if (self::$debug_callback) { call_user_func(self::$debug_callback, $message); } else { self::expose($message); } } } /** * Detects if a PHP opcode cache is installed * * The following opcode caches are currently detected: * * - [http://pecl.php.net/package/APC APC] * - [http://eaccelerator.net eAccelerator] * - [http://www.nusphere.com/products/phpexpress.htm Nusphere PhpExpress] * - [http://turck-mmcache.sourceforge.net/index_old.html Turck MMCache] * - [http://xcache.lighttpd.net XCache] * - [http://www.zend.com/en/products/server/ Zend Server (Optimizer+)] * - [http://www.zend.com/en/products/platform/ Zend Platform (Code Acceleration)] * * @return boolean If a PHP opcode cache is loaded */ static public function detectOpcodeCache() { $apc = ini_get('apc.enabled'); $eaccelerator = ini_get('eaccelerator.enable'); $mmcache = ini_get('mmcache.enable'); $phpexpress = function_exists('phpexpress'); $xcache = ini_get('xcache.size') > 0 && ini_get('xcache.cacher'); $zend_accelerator = ini_get('zend_accelerator.enabled'); $zend_plus = ini_get('zend_optimizerplus.enable'); return $apc || $eaccelerator || $mmcache || $phpexpress || $xcache || $zend_accelerator || $zend_plus; } /** * Creates a string representation of any variable using predefined strings for booleans, `NULL` and empty strings * * The string output format of this method is very similar to the output of * [http://php.net/print_r print_r()] except that the following values * are represented as special strings: * * - `TRUE`: `'{true}'` * - `FALSE`: `'{false}'` * - `NULL`: `'{null}'` * - `''`: `'{empty_string}'` * * @param mixed $data The value to dump * @return string The string representation of the value */ static public function dump($data) { if (is_bool($data)) { return ($data) ? '{true}' : '{false}'; } elseif (is_null($data)) { return '{null}'; } elseif ($data === '') { return '{empty_string}'; } elseif (is_array($data) || is_object($data)) { ob_start(); var_dump($data); $output = ob_get_contents(); ob_end_clean(); // Make the var dump more like a print_r $output = preg_replace('#=>\n( )+(?=[a-zA-Z]|&)#m', ' => ', $output); $output = str_replace('string(0) ""', '{empty_string}', $output); $output = preg_replace('#=> (&)?NULL#', '=> \1{null}', $output); $output = preg_replace('#=> (&)?bool\((false|true)\)#', '=> \1{\2}', $output); $output = preg_replace('#string\(\d+\) "#', '', $output); $output = preg_replace('#"(\n( )*)(?=\[|\})#', '\1', $output); $output = preg_replace('#(?:float|int)\((-?\d+(?:.\d+)?)\)#', '\1', $output); $output = preg_replace('#((?: )+)\["(.*?)"\]#', '\1[\2]', $output); $output = preg_replace('#(?:&)?array\(\d+\) \{\n((?: )*)((?: )(?=\[)|(?=\}))#', "Array\n\\1(\n\\1\\2", $output); $output = preg_replace('/object\((\w+)\)#\d+ \(\d+\) {\n((?: )*)((?: )(?=\[)|(?=\}))/', "\\1 Object\n\\2(\n\\2\\3", $output); $output = preg_replace('#^((?: )+)}(?=\n|$)#m', "\\1)\n", $output); $output = substr($output, 0, -2) . ')'; // Fix indenting issues with the var dump output $output_lines = explode("\n", $output); $new_output = array(); $stack = 0; foreach ($output_lines as $line) { if (preg_match('#^((?: )*)([^ ])#', $line, $match)) { $spaces = strlen($match[1]); if ($spaces && $match[2] == '(') { $stack += 1; } $new_output[] = str_pad('', ($spaces)+(4*$stack)) . $line; if ($spaces && $match[2] == ')') { $stack -= 1; } } else { $new_output[] = str_pad('', ($spaces)+(4*$stack)) . $line; } } return join("\n", $new_output); } else { return (string) $data; } } /** * Disables including the context information with exception and error messages * * The context information includes the following superglobals: * * - `$_SERVER` * - `$_POST` * - `$_GET` * - `$_SESSION` * - `$_FILES` * - `$_COOKIE` * * @return void */ static public function disableContext() { self::$show_context = FALSE; } /** * Enables debug messages globally, i.e. they will be shown for any call to ::debug() * * @param boolean $flag If debugging messages should be shown * @return void */ static public function enableDebugging($flag) { self::$debug = (boolean) $flag; } /** * Turns on a feature where undefined constants are automatically created with the string value equivalent to the name * * This functionality only works if ::enableErrorHandling() has been * called first. This functionality may have a very slight performance * impact since a `E_STRICT` error message must be captured and then a * call to [http://php.net/define define()] is made. * * @return void */ static public function enableDynamicConstants() { if (!self::$handles_errors) { throw new fProgrammerException( 'Dynamic constants can not be enabled unless error handling has been enabled via %s', __CLASS__ . '::enableErrorHandling()' ); } self::$dynamic_constants = TRUE; } /** * Turns on developer-friendly error handling that includes context information including a backtrace and superglobal dumps * * All errors that match the current * [http://php.net/error_reporting error_reporting()] level will be * redirected to the destination and will include a full backtrace. In * addition, dumps of the following superglobals will be made to aid in * debugging: * * - `$_SERVER` * - `$_POST` * - `$_GET` * - `$_SESSION` * - `$_FILES` * - `$_COOKIE` * * The superglobal dumps are only done once per page, however a backtrace * in included for each error. * * If an email address is specified for the destination, only one email * will be sent per script execution. If both error and * [enableExceptionHandling() exception handling] are set to the same * email address, the email will contain both errors and exceptions. * * @param string $destination The destination for the errors and context information - an email address, a file path or the string `'html'` * @return void */ static public function enableErrorHandling($destination) { if (!self::checkDestination($destination)) { return; } self::$error_destination = $destination; self::$handles_errors = TRUE; set_error_handler(self::callback(self::handleError)); } /** * Turns on developer-friendly uncaught exception handling that includes context information including a backtrace and superglobal dumps * * Any uncaught exception will be redirected to the destination specified, * and the page will execute the `$closing_code` callback before exiting. * The destination will receive a message with the exception messaage, a * full backtrace and dumps of the following superglobals to aid in * debugging: * * - `$_SERVER` * - `$_POST` * - `$_GET` * - `$_SESSION` * - `$_FILES` * - `$_COOKIE` * * The superglobal dumps are only done once per page, however a backtrace * in included for each error. * * If an email address is specified for the destination, only one email * will be sent per script execution. * * If an email address is specified for the destination, only one email * will be sent per script execution. If both exception and * [enableErrorHandling() error handling] are set to the same * email address, the email will contain both exceptions and errors. * * @param string $destination The destination for the exception and context information - an email address, a file path or the string `'html'` * @param callback $closing_code This callback will happen after the exception is handled and before page execution stops. Good for printing a footer. If no callback is provided and the exception extends fException, fException::printMessage() will be called. * @param array $parameters The parameters to send to `$closing_code` * @return void */ static public function enableExceptionHandling($destination, $closing_code=NULL, $parameters=array()) { if (!self::checkDestination($destination)) { return; } self::$handles_exceptions = TRUE; self::$exception_destination = $destination; self::$exception_handler_callback = $closing_code; if (!is_object($parameters)) { settype($parameters, 'array'); } else { $parameters = array($parameters); } self::$exception_handler_parameters = $parameters; set_exception_handler(self::callback(self::handleException)); } /** * Prints the ::dump() of a value * * The dump will be printed in a `<pre>` tag with the class `exposed` if * PHP is running anywhere but via the command line (cli). If PHP is * running via the cli, the data will be printed, followed by a single * line break (`\n`). * * If multiple parameters are passed, they are exposed as an array. * * @param mixed $data The value to show * @param mixed ... * @return void */ static public function expose($data) { $args = func_get_args(); if (count($args) > 1) { $data = $args; } if (PHP_SAPI != 'cli') { echo '<pre class="exposed">' . htmlspecialchars((string) self::dump($data), ENT_QUOTES) . '</pre>'; } else { echo self::dump($data) . "\n"; } } /** * Generates some information about the context of an error or exception * * @return string A string containing `$_SERVER`, `$_GET`, `$_POST`, `$_FILES`, `$_SESSION` and `$_COOKIE` */ static private function generateContext() { return self::compose('Context') . "\n-------" . "\n\n\$_SERVER: " . self::dump($_SERVER) . "\n\n\$_POST: " . self::dump($_POST) . "\n\n\$_GET: " . self::dump($_GET) . "\n\n\$_FILES: " . self::dump($_FILES) . "\n\n\$_SESSION: " . self::dump((isset($_SESSION)) ? $_SESSION : NULL) . "\n\n\$_COOKIE: " . self::dump($_COOKIE); } /** * If debugging is enabled * * @param boolean $force If debugging is forced * @return boolean If debugging is enabled */ static public function getDebug($force=FALSE) { return self::$debug || $force; } /** * Handles an error, creating the necessary context information and sending it to the specified destination * * @internal * * @param integer $error_number The error type * @param string $error_string The message for the error * @param string $error_file The file the error occured in * @param integer $error_line The line the error occured on * @param array $error_context A references to all variables in scope at the occurence of the error * @return void */ static public function handleError($error_number, $error_string, $error_file=NULL, $error_line=NULL, $error_context=NULL) { if (self::$dynamic_constants && $error_number == E_NOTICE) { if (preg_match("#^Use of undefined constant (\w+) - assumed '\w+'\$#D", $error_string, $matches)) { define($matches[1], $matches[1]); return; } } $capturing = is_array(self::$captured_errors); $level_match = (bool) (error_reporting() & $error_number); if (!$capturing && !$level_match) { return; } $doc_root = realpath($_SERVER['DOCUMENT_ROOT']); $doc_root .= (substr($doc_root, -1) != '/' && substr($doc_root, -1) != '\\') ? '/' : ''; $backtrace = self::backtrace(1); // Remove the reference to handleError $backtrace = preg_replace('#: fCore::handleError\(.*?\)$#', '', $backtrace); $error_string = preg_replace('# \[<a href=\'.*?</a>\]: #', ': ', $error_string); // This was added in 5.2 if (!defined('E_RECOVERABLE_ERROR')) { define('E_RECOVERABLE_ERROR', 4096); } // These were added in 5.3 if (!defined('E_DEPRECATED')) { define('E_DEPRECATED', 8192); } if (!defined('E_USER_DEPRECATED')) { define('E_USER_DEPRECATED', 16384); } switch ($error_number) { case E_WARNING: $type = self::compose('Warning'); break; case E_NOTICE: $type = self::compose('Notice'); break; case E_USER_ERROR: $type = self::compose('User Error'); break; case E_USER_WARNING: $type = self::compose('User Warning'); break; case E_USER_NOTICE: $type = self::compose('User Notice'); break; case E_STRICT: $type = self::compose('Strict'); break; case E_RECOVERABLE_ERROR: $type = self::compose('Recoverable Error'); break; case E_DEPRECATED: $type = self::compose('Deprecated'); break; case E_USER_DEPRECATED: $type = self::compose('User Deprecated'); break; } if ($capturing) { $type_to_capture = (bool) (self::$captured_error_types & $error_number); $string_to_capture = !self::$captured_error_regex || (self::$captured_error_regex && preg_match(self::$captured_error_regex, $error_string)); if ($type_to_capture && $string_to_capture) { self::$captured_errors[] = array( 'number' => $error_number, 'type' => $type, 'string' => $error_string, 'file' => str_replace($doc_root, '{doc_root}/', $error_file), 'line' => $error_line, 'backtrace' => $backtrace, 'context' => $error_context ); return; } // If the old handler is not this method, then we must have been trying to match a regex and failed // so we pass the error on to the original handler to do its thing if (self::$captured_errors_previous_handler != array('fCore', 'handleError')) { if (self::$captured_errors_previous_handler === NULL) { return FALSE; } return call_user_func(self::$captured_errors_previous_handler, $error_number, $error_string, $error_file, $error_line, $error_context); // If we get here, this method is the error handler, but we don't want to actually report the error so we return } elseif (!$level_match) { return; } } $error = $type . "\n" . str_pad('', strlen($type), '-') . "\n" . $backtrace . "\n" . $error_string; self::sendMessageToDestination('error', $error); } /** * Handles an uncaught exception, creating the necessary context information, sending it to the specified destination and finally executing the closing callback * * @internal * * @param object $exception The uncaught exception to handle * @return void */ static public function handleException($exception) { $message = ($exception->getMessage()) ? $exception->getMessage() : '{no message}'; if ($exception instanceof fException) { $trace = $exception->formatTrace(); } else { $trace = $exception->getTraceAsString(); } $code = ($exception->getCode()) ? ' (code ' . $exception->getCode() . ')' : ''; $info = $trace . "\n" . $message . $code; $headline = self::compose("Uncaught") . " " . get_class($exception); $info_block = $headline . "\n" . str_pad('', strlen($headline), '-') . "\n" . trim($info); self::sendMessageToDestination('exception', $info_block); if (self::$exception_handler_callback === NULL) { if (self::$exception_destination != 'html' && $exception instanceof fException) { $exception->printMessage(); } return; } try { self::call(self::$exception_handler_callback, self::$exception_handler_parameters); } catch (Exception $e) { trigger_error( self::compose( 'An exception was thrown in the %s closing code callback', 'setExceptionHandling()' ), E_USER_ERROR ); } } /** * Registers a callback to handle debug messages instead of the default action of calling ::expose() on the message * * @param callback $callback A callback that accepts a single parameter, the string debug message to handle * @return void */ static public function registerDebugCallback($callback) { self::$debug_callback = self::callback($callback); } /** * Resets the configuration of the class * * @internal * * @return void */ static public function reset() { if (self::$handles_errors) { restore_error_handler(); } if (self::$handles_exceptions) { restore_exception_handler(); } if (is_array(self::$captured_errors)) { restore_error_handler(); } self::$captured_error_regex = NULL; self::$captured_errors_previous_handler = NULL; self::$captured_error_types = NULL; self::$captured_errors = NULL; self::$context_shown = FALSE; self::$debug = NULL; self::$debug_callback = NULL; self::$dynamic_constants = FALSE; self::$error_destination = 'html'; self::$error_message_queue = array(); self::$exception_destination = 'html'; self::$exception_handler_callback = NULL; self::$exception_handler_parameters = array(); self::$exception_message = NULL; self::$handles_errors = FALSE; self::$handles_exceptions = FALSE; self::$show_context = TRUE; } /** * Sends an email or writes a file with messages generated during the page execution * * This method prevents multiple emails from being sent or a log file from * being written multiple times for one script execution. * * @internal * * @return void */ static public function sendMessagesOnShutdown() { $subject = self::compose( '[%1$s] One or more errors or exceptions occured at %2$s', isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : php_uname('n'), date('Y-m-d H:i:s') ); $messages = array(); if (self::$error_message_queue) { $message = join("\n\n", self::$error_message_queue); $messages[self::$error_destination] = $message; } if (self::$exception_message) { if (isset($messages[self::$exception_destination])) { $messages[self::$exception_destination] .= "\n\n"; } else { $messages[self::$exception_destination] = ''; } $messages[self::$exception_destination] .= self::$exception_message; } foreach ($messages as $destination => $message) { if (self::$show_context) { $message .= "\n\n" . self::generateContext(); } if (self::checkDestination($destination) == 'email') { if (self::$smtp_connection) { $email = new fEmail(); foreach (explode(',', $destination) as $recipient) { $email->addRecipient($recipient); } $email->setFromEmail(self::$smtp_from_email); $email->setSubject($subject); $email->setBody($message); $email->send(self::$smtp_connection); } else { mail($destination, $subject, $message); } } else { $handle = fopen($destination, 'a'); fwrite($handle, $subject . "\n\n"); fwrite($handle, $message . "\n\n"); fclose($handle); } } } /** * Handles sending a message to a destination * * If the destination is an email address or file, the messages will be * spooled up until the end of the script execution to prevent multiple * emails from being sent or a log file being written to multiple times. * * @param string $type If the message is an error or an exception * @param string $message The message to send to the destination * @return void */ static private function sendMessageToDestination($type, $message) { $destination = ($type == 'exception') ? self::$exception_destination : self::$error_destination; if ($destination == 'html') { if (self::$show_context && !self::$context_shown) { self::expose(self::generateContext()); self::$context_shown = TRUE; } self::expose($message); return; } static $registered_function = FALSE; if (!$registered_function) { register_shutdown_function(self::callback(self::sendMessagesOnShutdown)); $registered_function = TRUE; } if ($type == 'error') { self::$error_message_queue[] = $message; } else { self::$exception_message = $message; } } /** * Temporarily enables capturing error messages * * @param integer $types The error types to capture - this should be as specific as possible - defaults to all (E_ALL | E_STRICT) * @param string $regex A PCRE regex to match against the error message * @return void */ static public function startErrorCapture($types=NULL, $regex=NULL) { if ($types === NULL) { $types = E_ALL | E_STRICT; } self::$captured_error_types = $types; self::$captured_errors = array(); self::$captured_errors_previous_handler = set_error_handler(self::callback(self::handleError)); self::$captured_error_regex = $regex; } /** * Stops capturing error messages, returning all that have been captured * * @param string $regex A PCRE regex to filter messages by * @return array The captured error messages */ static public function stopErrorCapture($regex=NULL) { $captures = self::$captured_errors; self::$captured_error_regex = NULL; self::$captured_errors_previous_handler = NULL; self::$captured_error_types = NULL; self::$captured_errors = NULL; restore_error_handler(); if ($regex) { $new_captures = array(); foreach ($captures as $capture) { if (!preg_match($regex, $capture['string'])) { continue; } $new_captures[] = $capture; } $captures = $new_captures; } return $captures; } /** * Forces use as a static class * * @return fCore */ private function __construct() { } } /** * Copyright (c) 2007-2011 Will Bond <will@flourishlib.com>, others * * 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. */
mkrause/roy
_example/thirdparty/flourish/fCore.php
PHP
mit
39,704
// Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved. package com.blinkboxbooks.android.list; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.database.MergeCursor; import android.support.v4.content.AsyncTaskLoader; import android.util.SparseArray; import com.blinkboxbooks.android.model.Book; import com.blinkboxbooks.android.model.BookItem; import com.blinkboxbooks.android.model.Bookmark; import com.blinkboxbooks.android.model.Query; import com.blinkboxbooks.android.model.helper.BookHelper; import com.blinkboxbooks.android.model.helper.BookmarkHelper; import com.blinkboxbooks.android.util.LogUtils; import com.crashlytics.android.Crashlytics; import java.util.ArrayList; import java.util.List; /* * A loader that queries the {@link ContentResolver} and returns a {@link Cursor}. * This class implements the {@link Loader} protocol in a standard way for * querying cursors, building on {@link AsyncTaskLoader} to perform the cursor * query on a background thread so that it does not block the application's UI. * * <p>A LibraryLoader must be built with the full information for the query to * perform. */ public class LibraryLoader extends AsyncTaskLoader<List<BookItem>> { final ForceLoadContentObserver mObserver; List<BookItem> mBookItems; private List<Query> mQueryList; /** * Creates an empty unspecified CursorLoader. You must follow this with * calls to {@link #setQueryList(List<Query>)} to specify the query to * perform. */ public LibraryLoader(Context context) { super(context); mObserver = new ForceLoadContentObserver(); } /** * Creates a fully-specified LibraryLoader. */ public LibraryLoader(Context context, List<Query> queryList) { super(context); mObserver = new ForceLoadContentObserver(); mQueryList = queryList; } public void setQueryList(List<Query> queryList) { mQueryList = queryList; } /* Runs on a worker thread */ @Override public List<BookItem> loadInBackground() { Cursor cursor = null; List<Cursor> cursorList = new ArrayList<Cursor>(); for (Query query : mQueryList) { cursor = getContext().getContentResolver().query(query.uri, query.projection, query.selection, query.selectionArgs, query.sortOrder); if (cursor != null) { // Ensure the cursor window is filled cursor.getCount(); // registerContentObserver(cursor, mObserver); cursorList.add(cursor); } } Cursor[] cursorArray = new Cursor[cursorList.size()]; List<BookItem> bookItemList; if (cursorList.size() > 0) { bookItemList = createBookItems(new MergeCursor(cursorList.toArray(cursorArray))); for (Cursor c : cursorList) { c.close(); } } else { // Return an empty book list bookItemList = new ArrayList<BookItem>(); } return bookItemList; } /** * Registers an observer to get notifications from the content provider * when the cursor needs to be refreshed. */ void registerContentObserver(Cursor cursor, ContentObserver observer) { cursor.registerContentObserver(mObserver); } /* Runs on the UI thread */ @Override public void deliverResult(List<BookItem> bookItems) { if (isReset()) { // An async query came in while the loader is stopped return; } mBookItems = bookItems; if (isStarted()) { super.deliverResult(bookItems); } } /** * Starts an asynchronous load of the book list data. When the result is ready the callbacks * will be called on the UI thread. If a previous load has been completed and is still valid * the result may be passed to the callbacks immediately. * <p/> * Must be called from the UI thread */ @Override protected void onStartLoading() { if (mBookItems != null) { deliverResult(mBookItems); } if (takeContentChanged() || mBookItems == null) { forceLoad(); } } /** * Must be called from the UI thread */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); } /** * Takes a list of books from the Cursor and arranges them into a list of BookItem objects */ private List<BookItem> createBookItems(Cursor cursor) { // Check for error cases if (cursor == null || cursor.isClosed()) { String error = String.format("Trying to create a new library item list with %s cursor.", cursor == null ? "null" : "closed"); Crashlytics.logException(new Exception(error)); LogUtils.stack(); List<BookItem> bookItems = new ArrayList<BookItem>(); return bookItems; } cursor.moveToFirst(); Book book; Bookmark bookmark; BookItem bookItem; List<BookItem> booksList = new ArrayList<BookItem>(); while (!cursor.isAfterLast()) { book = BookHelper.createBook(cursor); bookmark = BookmarkHelper.createBookmark(cursor); bookItem = new BookItem(book, bookmark, "", "", null); booksList.add(bookItem); cursor.moveToNext(); } return booksList; } }
blinkboxbooks/android-app
app/src/main/java/com/blinkboxbooks/android/list/LibraryLoader.java
Java
mit
5,766
<?php return array ( 'id' => 'samsung_d500_ver1_sub6226', 'fallback' => 'samsung_d500_ver1', 'capabilities' => array ( 'max_data_rate' => '40', ), );
cuckata23/wurfl-data
data/samsung_d500_ver1_sub6226.php
PHP
mit
165
using System; using System.Net.Http; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Castle.Core; using DotJEM.Json.Storage.Adapter; using DotJEM.Pipelines; using DotJEM.Web.Host.Diagnostics.Performance; using DotJEM.Web.Host.Providers.Concurrency; using DotJEM.Web.Host.Providers.Services.DiffMerge; using Newtonsoft.Json.Linq; namespace DotJEM.Web.Host.Providers.Services { public interface IContentService { IStorageArea StorageArea { get; } Task<JObject> GetAsync(Guid id, string contentType); Task<JObject> PostAsync(string contentType, JObject entity); Task<JObject> PutAsync(Guid id, string contentType, JObject entity); Task<JObject> PatchAsync(Guid id, string contentType, JObject entity); Task<JObject> DeleteAsync(Guid id, string contentType); } //TODO: Apply Pipeline for all requests. [Interceptor(typeof(PerformanceLogAspect))] public class ContentService : IContentService { private readonly IStorageArea area; private readonly IStorageIndexManager manager; private readonly IPipelines pipelines; private readonly IContentMergeService merger; public IStorageArea StorageArea => area; public ContentService(IStorageArea area, IStorageIndexManager manager, IPipelines pipelines, IJsonMergeVisitor merger) { this.area = area; this.manager = manager; this.pipelines = pipelines; this.merger = new ContentMergeService(merger, area); } public Task<JObject> GetAsync(Guid id, string contentType) { HttpGetContext context = new (contentType, id); ICompiledPipeline<JObject> pipeline = pipelines .For(context, ctx => Task.Run(() => area.Get(ctx.Id))); return pipeline.Invoke(); } public async Task<JObject> PostAsync(string contentType, JObject entity) { HttpPostContext context = new (contentType, entity); ICompiledPipeline<JObject> pipeline = pipelines .For(context, ctx => Task.Run(() => area.Insert(ctx.ContentType, ctx.Entity))); entity = await pipeline.Invoke().ConfigureAwait(false); manager.QueueUpdate(entity); return entity; } public async Task<JObject> PutAsync(Guid id, string contentType, JObject entity) { JObject prev = area.Get(id); entity = merger.EnsureMerge(id, entity, prev); HttpPutContext context = new (contentType, id, entity, prev); ICompiledPipeline<JObject> pipeline = pipelines .For(context, ctx => Task.Run(() => area.Update(ctx.Id, ctx.Entity))); entity = await pipeline.Invoke().ConfigureAwait(false); manager.QueueUpdate(entity); return entity; } public async Task<JObject> PatchAsync(Guid id, string contentType, JObject entity) { JObject prev = area.Get(id); //TODO: This can be done better by simply merging the prev into the entity but skipping // values that are present in the entity. However, we might wan't to inclide the raw patch // content in the pipeline as well, so we need to consider pro/cons JObject clone = (JObject)prev.DeepClone(); clone.Merge(entity); entity = clone; entity = merger.EnsureMerge(id, entity, prev); HttpPatchContext context = new (contentType, id, entity, prev); ICompiledPipeline<JObject> pipeline = pipelines .For(context, ctx => Task.Run(() => area.Update(ctx.Id, ctx.Entity))); entity = await pipeline.Invoke().ConfigureAwait(false); manager.QueueUpdate(entity); return entity; } public async Task<JObject> DeleteAsync(Guid id, string contentType) { JObject prev = area.Get(id); if (prev == null) return null; HttpDeleteContext context = new (contentType, id, prev); ICompiledPipeline<JObject> pipeline = pipelines .For(context, ctx => Task.Run(() => area.Delete(ctx.Id))); JObject deleted = await pipeline.Invoke().ConfigureAwait(false); //Note: This may pose a bit of a problem, because we don't lock so far out (performance), // this can theoretically happen if two threads or two nodes are trying to delete the // same object at the same time. if (deleted == null) return null; manager.QueueDelete(deleted); return deleted; } } public class HttpPipelineContext : PipelineContext { public HttpPipelineContext(string method, string contentType) { this.Set(nameof(method), method); this.Set(nameof(contentType), contentType); } } public class HttpGetContext : HttpPipelineContext { public string ContentType => (string)Get("contentType"); public Guid Id => (Guid) Get("id"); public HttpGetContext(string contentType, Guid id) : base("GET", contentType) { Set(nameof(id), id); } } public class HttpPostContext : HttpPipelineContext { public string ContentType => (string)Get("contentType"); public JObject Entity => (JObject)Get("entity"); public HttpPostContext( string contentType, JObject entity) : base("POST", contentType) { Set(nameof(entity), entity); } } public class HttpPutContext : HttpPipelineContext { public string ContentType => (string)Get("contentType"); public Guid Id => (Guid) Get("id"); public JObject Entity => (JObject)Get("entity"); public JObject Previous => (JObject)Get("previous"); public HttpPutContext(string contentType, Guid id, JObject entity, JObject previous) : base("PUT", contentType) { Set(nameof(id), id); Set(nameof(entity), entity); Set(nameof(previous), previous); } } public class HttpPatchContext : HttpPipelineContext { public string ContentType => (string)Get("contentType"); public Guid Id => (Guid)Get("id"); public JObject Entity => (JObject)Get("entity"); public JObject Previous => (JObject)Get("previous"); public HttpPatchContext(string contentType, Guid id, JObject entity, JObject previous) : base("PATCH", contentType) { Set(nameof(id), id); Set(nameof(entity), entity); Set(nameof(previous), previous); } } public class HttpDeleteContext : HttpPipelineContext { public string ContentType => (string)Get("contentType"); public Guid Id => (Guid)Get("id"); public HttpDeleteContext(string contentType, Guid id, JObject previous) : base("DELETE", contentType) { Set(nameof(id), id); Set(nameof(previous), previous); } } }
dotJEM/web-host
src/DotJEM.Web.Host/Providers/Services/ContentService.cs
C#
mit
7,585
package com.gdgand.rxjava.rxjavasample.hotandcold; import android.app.Application; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.ApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.component.DaggerApplicationComponent; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.ApplicationModule; import com.gdgand.rxjava.rxjavasample.hotandcold.di.module.DataModule; public class SampleApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); applicationComponent = createComponent(); } private ApplicationComponent createComponent() { return DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .dataModule(new DataModule()) .build(); } public ApplicationComponent getApplicationComponent() { return applicationComponent; } }
gdgand/android-rxjava
2016-06-15_hot_and_cold/app/src/main/java/com/gdgand/rxjava/rxjavasample/hotandcold/SampleApplication.java
Java
mit
911
'use strict' var solc = require('solc/wrapper') var compileJSON = function () { return '' } var missingInputs = [] module.exports = function (self) { self.addEventListener('message', function (e) { var data = e.data switch (data.cmd) { case 'loadVersion': delete self.Module // NOTE: workaround some browsers? self.Module = undefined compileJSON = null self.importScripts(data.data) var compiler = solc(self.Module) compileJSON = function (input) { try { return compiler.compileStandardWrapper(input, function (path) { missingInputs.push(path) return { 'error': 'Deferred import' } }) } catch (exception) { return JSON.stringify({ error: 'Uncaught JavaScript exception:\n' + exception }) } } self.postMessage({ cmd: 'versionLoaded', data: compiler.version() }) break case 'compile': missingInputs.length = 0 self.postMessage({cmd: 'compiled', job: data.job, data: compileJSON(data.input), missingInputs: missingInputs}) break } }, false) }
Yann-Liang/browser-solidity
src/app/compiler/compiler-worker.js
JavaScript
mit
1,202
//Express, Mongo & Environment specific imports var express = require('express'); var morgan = require('morgan'); var serveStatic = require('serve-static'); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var compression = require('compression'); var errorHandler = require('errorhandler'); var mongo = require('./api/config/db'); var env = require('./api/config/env'); // Controllers/Routes import var BookController = require('./api/controller/BookController'); //MongoDB setup mongo.createConnection(env.mongoUrl); //Express setup var app = express(); //Express middleware app.use(morgan('short')); app.use(serveStatic(__dirname + '/app')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(compression()); var environment = process.env.NODE_ENV || 'development'; if ('development' == environment) { app.use(errorHandler({ dumpExceptions: true, showStack: true })); var ImportController = require('./api/controller/ImportController'); app.get('/import', ImportController.import); app.get('/import/reset', ImportController.reset); } // Route definitions app.get('/api/books', BookController.list); app.get('/api/books/:id', BookController.show); app.post('api/books', BookController.create); app.put('/api/books/:id', BookController.update); app.delete('/api/books/:id', BookController.remove); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Books app listening at http://%s:%s', host, port); console.log("Configured MongoDB URL: " + env.mongoUrl); });
rpelger/books-app-mean
app.js
JavaScript
mit
1,664
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require("@angular/core"); var ConversationHeaderComponent = (function () { function ConversationHeaderComponent() { } ConversationHeaderComponent.prototype.ngOnInit = function () { }; __decorate([ core_1.Input(), __metadata('design:type', Object) ], ConversationHeaderComponent.prototype, "conversationDetailItem", void 0); ConversationHeaderComponent = __decorate([ core_1.Component({ selector: 'ngm-conversation-header', styleUrls: ['./conversation-header.component.scss'], templateUrl: './conversation-header.component.html' }), __metadata('design:paramtypes', []) ], ConversationHeaderComponent); return ConversationHeaderComponent; }()); exports.ConversationHeaderComponent = ConversationHeaderComponent; //# sourceMappingURL=conversation-header.component.js.map
DREEBIT/ng-messenger
src/components/conversation-header/conversation-header.component.js
JavaScript
mit
1,657
const describe = require("mocha").describe; const it = require("mocha").it; const assert = require("chai").assert; const HttpError = require("./HttpError"); describe("HttpError", function () { it("should be instance of Error", function () { const testSubject = new HttpError(); assert.isOk(testSubject instanceof Error); }); });
danielireson/formplug-serverless
src/error/HttpError.spec.js
JavaScript
mit
343
import { inject, injectable } from 'inversify'; import TYPES from '../../di/types'; import * as i from '../../i'; import { RunOptions } from '../../models'; import { IInputConfig } from '../../user-extensibility'; import { BaseInputManager } from '../base-input-manager'; var NestedError = require('nested-error-stacks'); @injectable() export class CustomInputManager extends BaseInputManager { constructor( @inject(TYPES.HandlerService) private handlerService: i.IHandlerService ) { super(); } async ask(config: IInputConfig, options: RunOptions): Promise<{ [key: string]: any }> { try { const handler: Function = await this.handlerService .resolveAndLoad(this.tmplRootPath, config.handler); return handler(config); } catch (ex) { throw new NestedError("Error running handler for input configuration", ex); } } }
yosplz/neoman
src/lib/input-managers/custom/custom-input-manager.ts
TypeScript
mit
928
<?php if (!file_exists('./../include/config.php')){ header('Location:install.php'); } include('./../include/config.php'); include('./../include/functions.php'); if (isset($_POST['step'])) $step = intval($_POST['step']); else{ $step = 0; } ?> <!DOCTYPE html> <html> <head> <title>SPC - DB Upgrade</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./../css/spc.css" type="text/css" media="screen" /> <link rel="icon" type="image/png" href="./../favicon.png" /> <style type="text/css"> body{ font-size: 16px; } h1, h2{ color: #ff0056; margin: 6px; } h1{ font-size: 60px; } dt{ color: #999; } dd, dl{ margin-left: 10px; } p{ margin-left: 10px; margin-bottom: 10px; } .code{ border: 1px solid #ff0056; padding: 6px; } </style> </head> <body> <div id="wrap"> <h1>Welcome to Simple Photos Contest DataBase Upgrader</h1> <?php switch($step){ case 0: ?> <form class="large" method="POST" action="upgrade.php"> <p><em>This installer will be displayed in english only</em>.</p> <p>It's <b>highly recommended</b> to do an SQL backup before upgrading.</p> <div class="form_buttons"> <input type="submit" value="Upgrade" name="submit"/> <input type="hidden" name="step" value="1"/> </div> <?php break; case 1 :?> <form class="large" method="POST" action="../index.php"> <p>Upgrade from <a href="#"><?php if(!isset($settings->spc_version) or $settings->spc_version=="") echo "Unknown(2.0?)"; else echo $settings->spc_version; ?></a> to <a href="#" title="<?php echo SPC_VERSION; ?>"><?php echo SPC_VERSION_DB; ?></a></p> <?php if(!isset($settings->spc_version) or $settings->spc_version=="") $ver = 0; else $ver = $settings->spc_version; function sqlalter($command){ global $bd; if (!mysqli_query($bd,"ALTER TABLE ".$command)) { die("Error : ". mysqli_error($bd)); } } switch($ver) { case SPC_VERSION_DB: echo " <p>No upgraded needed</p>"; break; case 0: sqlalter("`contests` ADD `icon` VARCHAR(200) NOT NULL"); sqlalter("`settings` ADD `language_auto` BOOLEAN NOT NULL") ; sqlalter("`settings` ADD `homepage` BOOLEAN NOT NULL") ; sqlalter("`settings` ADD `auth_method` INT(2) NOT NULL , ADD `spc_version` VARCHAR(8) NOT NULL") ; sqlalter("`image_ip` CHANGE `ip_add` `ip_add` BIGINT NULL DEFAULT NULL;"); //case "3.0 A2": if (!mysqli_query($bd, "UPDATE `settings` SET `spc_version`='".SPC_VERSION_DB."' WHERE 1")) { die("Error : ". mysqli_error($bd)); } echo " <p>Done!</a></p>"; break; default: echo " <p>Your version were not found. </p>"; break; } ?> <div class="form_buttons"> <input type="submit" value="Home" name="submit"/> <input type="hidden" name="step" value="1"/> </div> </form> <?php break; } ?> </form> </div> <script> var noTiling = true; </script> <script type="text/javascript" src="./../js/jquery-1.8.2.min.js"></script> <script type="text/javascript" src="./../js/jquery.freetile.min.js"></script> <script type="text/javascript" src="./../js/contest.js"></script> </body> </html>
50thomatoes50/simple-photos-contest
install/upgrade.php
PHP
mit
3,262
package io.blitz.curl.exception; /** * Exceptions thrown when a validation error occur during a test execution * @author ghermeto */ public class ValidationException extends BlitzException { /** * Constructs an instance of <code>ValidationException</code> with the * specified error and reason message. * @param reason the detailed error message. */ public ValidationException(String reason) { super("validation", reason); } }
blitz-io/blitz-java
src/main/java/io/blitz/curl/exception/ValidationException.java
Java
mit
473
/** * jQuery object. * @external jQuery * @see {@link http://api.jquery.com/jQuery/} */ /** * The jQuery plugin namespace. * @external "jQuery.fn" * @see {@link http://docs.jquery.com/Plugins/Authoring The jQuery Plugin Guide} */ /** * The plugin global configuration object. * @external "jQuery.vulcanup" * @property {String} version - The plugin version. * @property {settings} defaults - The default configuration. * @property {Object} templates - The default templates. */ require('./jup-validation'); const templates = require('./templates'); const constants = require('./constants'); const defaults = require('./defaults'); const methods = require('./methods'); const utils = require('./utils'); const version = '1.0.0-beta'; $(document).on('drop dragover', function (e) { e.preventDefault(); }); /** * Invoke on a `<input type="file">` to set it as a file uploader. * * By default the configuration is {@link settings} but you can pass an object * to configure it as you want. * * Listen to event changes on the same input, review demo to see how to implement them * and what parameters they receive: * * **`vulcanup-val`** - On validation error. Receives as parameter an object with the error message. * * **`vulcanup-upload`** - On file started to being uploaded. * * **`vulcanup-progress`** - On upload progress update. Receives as parameter the progress number. * * **`vulcanup-error`** - On server error. Receives as parameter an object with details. * * **`vulcanup-change`** - On file change. This is triggered when the user uploads * a file in the server, when it is deleted or when it is changed programmatically. * Receives as parameter an object with the new file details. * * **`vulcanup-delete`** - On file deleted. Receives as parameter the deleted file details. * * **`vulcanup-uploaded`** - On file uploaded in the server. * * **`vulcanup-complete`** - On upload process completed. This is fired when the * XHR is finished, regardless of fail or success. * * @function external:"jQuery.fn".vulcanup * * @param {settings} [settings] - Optional configuration. * * @example * $('input[type=file]').vulcanup({ * url: '/initial/file/url.ext' * }); */ jQuery.fn.vulcanup = function (settings) { 'use strict'; const $input = $(this).first(); if (typeof settings === 'string') { if (methods[settings]) { if (!$input.data(`vulcanup-config`)) { throw new Error(`vulcanup element is not instantiated, cannot invoke methods`); } const args = Array.prototype.slice.call(arguments, 1); return methods[settings].apply($input, args); } else { throw new Error(`vulcanup method unrecognized "${settings}".`); } } if ($input.data(`vulcanup-config`)) return this; // // CONFIGURATION // let id = $input.attr('id'); if (!id) { id = 'vulcanup-'+ (new Date()).getTime(); $input.attr('id', id); } if ($input.attr('multiple') !== undefined) { throw new Error('Input type file cannot be multiple'); } const conf = $.extend(true, {}, defaults, settings, { _id: id, fileupload: { fileInput: $input } }); // File type validation. if (conf.types[conf.type]) { conf._type = conf.types[conf.type]; conf.fileupload.acceptFileTypes = conf._type.formats; } else { throw new Error('A valid type of file is required'); } $input.data(`vulcanup-config`, conf); // // DOM // const $container = $(utils.format(templates.main, conf)); const $validations = $(utils.format(templates.validations, conf)); const $remove = $container.find('.vulcanup__remove'); const $dropzone = $container.find('.vulcanup__dropzone'); const $msg = $container.find('.vulcanup__msg'); $remove.attr('title', utils.format(conf.messages.REMOVE, conf._type)); $input.addClass('vulcanup-input vulcanup-input__hidden'); $input.after($container); $container.after($validations); conf.fileupload.dropZone = $container; conf._$validations = $validations; conf._$container = $container; conf._$dropzone = $dropzone; conf._$msg = $msg; if (conf.type === 'image') { $container.addClass('vulcanup_isimage'); } if (conf.imageContain) { $container.addClass('vulcanup_isimagecontain'); } if (!conf.enableReupload) { $container.addClass('vulcanup_noreupload'); } if (conf.canRemove) { $container.addClass('vulcanup_canremove'); } // // EVENTS // $input. // On click. on('click', function (e) { if (conf._uploading || (conf._url && !conf.enableReupload)) { e.preventDefault(); return false; } }). // On user error. on('fileuploadprocessfail', function (e, info) { const err = info.files[0].error; methods.setValidation.call($input, err); }). // On send. on('fileuploadsend', function (e, data) { methods.setUploading.call($input); }). // On server progress. on('fileuploadprogressall', function (e, data) { const progress = parseInt(data.loaded / data.total * 100, 10); methods.updateProgress.call($input, progress); }). // On server success. on('fileuploaddone', function (e, data) { const files = data.files; const result = data.result; if (conf.handler) { const info = conf.handler(result); if (typeof info !== 'object') { methods.setError.call($input); throw new Error('handler should return file object info'); } if (typeof info.url !== 'string') { methods.setError.call($input); throw new Error('handler should return file url property'); } methods.setUploaded.call($input, { url: info.url, file: files[0] }); } else if (result && result.files && result.files.length) { methods.setUploaded.call($input, { url: result.files[0].url, file: files[0] }); } else { methods.setError.call($input); } }). // On server error. on('fileuploadfail', function (e, data) { methods.setError.call($input); }); $dropzone. on('dragenter dragover', e => { $container.addClass('vulcanup_dragover'); }). on('dragleave drop', e => { $container.removeClass('vulcanup_dragover'); }); $container.find('.vulcanup__remove').on('click', function (e) { e.preventDefault(); $input.trigger(`vulcanup-delete`, { url: conf._url, name: conf._name }); $input.trigger(`vulcanup-change`, { url: null, name: null }); methods.updateProgress.call($input, 0, {silent: true}); methods.setUpload.call($input); return false; }); // // CREATING AND SETTING // $input.fileupload(conf.fileupload); if (conf.url) { methods.setUploaded.call(this, { url: conf.url, name: conf.name, initial: true }); } else { methods.setUpload.call(this); } return this; }; module.exports = jQuery.vulcanup = { version, defaults, templates };
vulcan-estudios/vulcanup
src/js/vulcanup.js
JavaScript
mit
7,069
const test = require('tape') const nlp = require('../_lib') test('match min-max', function(t) { let doc = nlp('hello1 one hello2').match('#Value{7,9}') t.equal(doc.out(), '', 'match was too short') doc = nlp('hello1 one two three four five hello2').match('#Value{3}') t.equal(doc.out(), 'one two three', 'exactly three') doc = nlp('hello1 one two three four five hello2').match('#Value{3,3}') t.equal(doc.out(), 'one two three', 'still exactly three') doc = nlp('hello1 one two three four five hello2').match('#Value{3,}') t.equal(doc.out(), 'one two three four five', 'minimum three') doc = nlp('hello1 one two three four five hello2').match('hello1 .{3}') t.equal(doc.out(), 'hello1 one two three', 'unspecific greedy exact length') doc = nlp('hello1 one two').match('hello1 .{3}') t.equal(doc.out(), '', 'unspecific greedy not long enough') t.end() })
nlp-compromise/compromise
tests/match/min-max.test.js
JavaScript
mit
888
# encoding: utf-8 require 'webmock/rspec' require 'vcr' require_relative '../lib/spotifiery' VCR.configure do |config| config.cassette_library_dir = 'spec/fixtures/vcr_cassettes' config.hook_into :webmock end
cicloon/spotifiery
spec/spec_helper.rb
Ruby
mit
218
class Tweet < ActiveRecord::Base # Remember to create a migration! belongs_to :user end
WoodhamsBD/lil_twitter
app/models/tweet.rb
Ruby
mit
93
using System.IO; using System.Runtime.InteropServices; internal static class Example { [STAThread()] public static void Main() { SolidEdgeFramework.Application objApplication = null; SolidEdgeAssembly.AssemblyDocument objAssemblyDocument = null; SolidEdgeAssembly.StructuralFrames objStructuralFrames = null; // SolidEdgeAssembly.StructuralFrame objStructuralFrame = null; try { OleMessageFilter.Register(); objApplication = (SolidEdgeFramework.Application)Marshal.GetActiveObject("SolidEdge.Application"); objAssemblyDocument = objApplication.ActiveDocument; objStructuralFrames = objAssemblyDocument.StructuralFrames; // Loop through all of the structural frames. foreach (SolidEdgeAssembly.StructuralFrame objStructuralFrame in objStructuralFrames) { objStructuralFrame.RetrieveHoleLocation(); objStructuralFrame.DeleteHoleLocation(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { OleMessageFilter.Revoke(); } } }
SolidEdgeCommunity/docs
docfx_project/snippets/SolidEdgeAssembly.StructuralFrame.DeleteHoleLocation.cs
C#
mit
1,219
#!/usr/bin/env ruby require 'json' SRC_RANDOM = Random.new(1984) MAX_VALUES = Hash.new(1).update "rcat" => 50, "vcat" => 50, "infq" => 5, "kws" => 10 MRG_VALUES = { "dev" => ["oth","oth","oth","oth","oth","oth"], "bwsm" => ["ff", "sf", "op", "ng", "kq", "an", "ms", "kk", "mo"], "pos" => [2, 4, 5, 6, 7], "mob" => [0] * 8, "loc" => ["en","en","en","en","en","en","en","en","en","en","en","en","es","es","es","es"], } targets = [] attrs = {} File.open(File.expand_path("../targets.json", __FILE__)) do |file| targets = JSON.load(file) end targets.each do |target| target['rules'].each do |rule| attrs[rule['attr']] ||= [] attrs[rule['attr']].concat rule['values'] end end attrs.keys.each do |name| attrs[name] = attrs[name].sort.uniq attrs[name].concat(MRG_VALUES[name] || []) end File.open(File.expand_path("../facts.json", __FILE__), "w") do |file| 10000.times do |_| fact = {} attrs.each do |name, values| vals = if MAX_VALUES[name] == 1 values.sample else values.sample(SRC_RANDOM.rand(MAX_VALUES[name])+1) end fact[name] = vals end file.puts JSON.dump(fact) end end p attrs.keys
bsm/flood
qfy/testdata/generate.rb
Ruby
mit
1,184
package com.lht.dot.ui.view; import android.content.Context; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.bumptech.glide.Glide; /** * Created by lht-Mac on 2017/7/11. */ public class PhotoShotRecyclerView extends RecyclerView { View mDispatchToView; public PhotoShotRecyclerView(Context context) { super(context); init(); } public PhotoShotRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } private void init() { setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); switch (newState) { case RecyclerView.SCROLL_STATE_SETTLING: Glide.with(getContext()).pauseRequests(); break; case RecyclerView.SCROLL_STATE_DRAGGING: case RecyclerView.SCROLL_STATE_IDLE: Glide.with(getContext()).resumeRequests(); break; } } }); } @Override public boolean dispatchTouchEvent(MotionEvent event) { if(mDispatchToView==null){ return super.dispatchTouchEvent(event); }else{ return mDispatchToView.dispatchTouchEvent(event); } } public View getDispatchToView() { return mDispatchToView; } public void setDispatchToView(View dispatchToView) { this.mDispatchToView = dispatchToView; } public void clearDispatchToView() { setDispatchToView(null); } }
LiuHongtao/Dot
app/src/main/java/com/lht/dot/ui/view/PhotoShotRecyclerView.java
Java
mit
1,901
function ones(rows, columns) { columns = columns || rows; if (typeof rows === 'number' && typeof columns === 'number') { const matrix = []; for (let i = 0; i < rows; i++) { matrix.push([]); for (let j = 0; j < columns; j++) { matrix[i].push(1); } } return matrix; } throw new TypeError('Matrix dimensions should be integers.'); } module.exports = ones;
arnellebalane/matrix.js
source/matrix.ones.js
JavaScript
mit
455
<?php namespace LolApi\Classes\TournamentProvider; /** * TournamentCodeParameters * * @author Javier */ class TournamentCodeParameters { // ~ maptype ~ const MAPTYPE_SUMMONERS_RIFT='SUMMONERS_RIFT'; const MAPTYPE_TWISTED_TREELINE='TWISTED_TREELINE'; const MAPTYPE_HOWLING_ABYSS='HOWLING_ABYSS'; // ~ pickType ~ const PICKTYPE_BLIND_PICK='BLIND_PICK'; const PICKTYPE_DRAFT_MODE='DRAFT_MODE'; const PICKTYPE_ALL_RANDOM='ALL_RANDOM'; const PICKTYPE_TOURNAMENT_DRAFT='TOURNAMENT_DRAFT'; // ~ SPECTATORTYPE ~ const SPECTATORTYPE_NONE='NONE'; const SPECTATORTYPE_LOBBYONLY='LOBBYONLY'; const SPECTATORTYPE_ALL=''; /** * Optional list of participants in order to validate the players eligible * to join the lobby. NOTE: We currently do not enforce participants at the * team level, but rather the aggregate of teamOne and teamTwo. We may add * the ability to enforce at the team level in the future. * @var SummonerIdParams */ public $allowedSummonerIds; /** * The map type of the game. Valid values are SUMMONERS_RIFT, TWISTED_TREELINE, and HOWLING_ABYSS. * @var string */ public $mapType; /** * Optional string that may contain any data in any format, if specified at all. Used to denote any custom information about the game. * @var string */ public $metadata; /** * The pick type of the game. Valid values are BLIND_PICK, DRAFT_MODE, ALL_RANDOM, TOURNAMENT_DRAFT. * @var string */ public $pickType; /** * The spectator type of the game. Valid values are NONE, LOBBYONLY, ALL. * @var string */ public $spectatorType; /** * The team size of the game. Valid values are 1-5. * @var int */ public $teamSize; function __construct($d) { $this->allowedSummonerIds = new SummonerIdParams($d->allowedSummonerIds); $this->mapType = $d->mapType; $this->metadata = $d->metadata; $this->pickType = $d->pickType; $this->spectatorType = $d->spectatorType; $this->teamSize = $d->teamSize; } }
javierglch/HexaniaBlogSymfony
src/LolApi/Classes/TournamentProvider/TournamentCodeParameters.php
PHP
mit
2,170
/* * The MIT License * * Copyright 2015 Adam Kowalewski. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.adamkowalewski.opw.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author Adam Kowalewski */ @Entity @Table(name = "opw_link", catalog = "opw", schema = "") @XmlRootElement @NamedQueries({ @NamedQuery(name = "OpwLink.findAll", query = "SELECT o FROM OpwLink o"), @NamedQuery(name = "OpwLink.findById", query = "SELECT o FROM OpwLink o WHERE o.id = :id"), @NamedQuery(name = "OpwLink.findByLabel", query = "SELECT o FROM OpwLink o WHERE o.label = :label"), @NamedQuery(name = "OpwLink.findByUrl", query = "SELECT o FROM OpwLink o WHERE o.url = :url"), @NamedQuery(name = "OpwLink.findByComment", query = "SELECT o FROM OpwLink o WHERE o.comment = :comment"), @NamedQuery(name = "OpwLink.findByActive", query = "SELECT o FROM OpwLink o WHERE o.active = :active"), @NamedQuery(name = "OpwLink.findByDateCreated", query = "SELECT o FROM OpwLink o WHERE o.dateCreated = :dateCreated")}) public class OpwLink implements Serializable { @Column(name = "dateCreated") @Temporal(TemporalType.TIMESTAMP) private Date dateCreated; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Integer id; @Size(max = 128) @Column(name = "label", length = 128) private String label; @Size(max = 256) @Column(name = "url", length = 256) private String url; @Size(max = 256) @Column(name = "comment", length = 256) private String comment; @Column(name = "active") private Boolean active; @JoinColumn(name = "opw_user_id", referencedColumnName = "id", nullable = false) @ManyToOne(optional = false) private OpwUser opwUserId; @JoinColumn(name = "opw_wynik_id", referencedColumnName = "id", nullable = false) @ManyToOne(optional = false) private OpwWynik opwWynikId; public OpwLink() { } public OpwLink(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public OpwUser getOpwUserId() { return opwUserId; } public void setOpwUserId(OpwUser opwUserId) { this.opwUserId = opwUserId; } public OpwWynik getOpwWynikId() { return opwWynikId; } public void setOpwWynikId(OpwWynik opwWynikId) { this.opwWynikId = opwWynikId; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof OpwLink)) { return false; } OpwLink other = (OpwLink) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.adamkowalewski.opw.entity.OpwLink[ id=" + id + " ]"; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } }
OtwartaPlatformaWyborcza/OPW-backend-JavaEE
opw/src/main/java/com/adamkowalewski/opw/entity/OpwLink.java
Java
mit
5,602