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
define(['leaflet', 'layoutManager'], function(L, layoutManager) { return new (L.Class.extend({ initialize: function(options) { this.el = options.el; }, destroyModal: function() { this.modal = null; this.el.innerHTML = ''; }, setModal: function(modal) { this.destroyModal(); this.modal = modal; this.modal.appendTo(this.el); this.modal.on('destroy', function() { this.destroyModal(); }.bind(this)); } }))({ el: layoutManager.getModalsContainer() }) });
Pihta-Open-Data/TransportNocturnal
src/main/webapp/app/modalsManager.js
JavaScript
mit
631
import { coreUtils } from '../../' import fs from 'fs-extra' import path from 'path' export function editStructure(type, folderPath, oldFolderPath = null) { if (type === 'add') coreUtils.file.addFolder(folderPath) else if (type === 'rename') coreUtils.file.renameFolder(oldFolderPath, folderPath) else coreUtils.file.removeFolder(folderPath) return folderPath } export function list(dir) { const walk = entry => { return new Promise((resolve, reject) => { fs.exists(entry, exists => { if (!exists) { return resolve({}); } return resolve(new Promise((resolve, reject) => { fs.lstat(entry, (err, stats) => { if (err) { return reject(err); } if (!stats.isDirectory()) { return resolve({ title: path.basename(entry), key: path.basename(entry) }); } resolve(new Promise((resolve, reject) => { fs.readdir(entry, (err, files) => { if (err) { return reject(err); } Promise.all(files.map(child => walk(path.join(entry, child)))).then(children => { resolve({ title: path.basename(entry), key: path.basename(entry), folder: true, children: children }); }).catch(err => { reject(err); }); }); })); }); })); }); }); } return walk(dir); }
abecms/abecms
src/cli/cms/structure/structure.js
JavaScript
mit
1,631
class Citizens extend Conformist column :name, 0 column :age, 1 column :gender, 2 end
tatey/conformist
test/schemas/citizens.rb
Ruby
mit
94
/* * hasCommunityRole.js * Drew Nelson * Oct 21 2016 * * @module :: Policy Factory * @description :: Verifies the user has the passed role for the community or is an Admin of community * :: Also allows access if the user has a SuperUser role */ module.exports = function(role) { return function(req, res, next) { var roles = {SuperUser: 1, Admin: 2, Member: 3}; // set the search params to search for desired role or admin for community, or superuser access var criteria = { community: req.params.CommID, user: req.user.id, role: { in: [ roles[role], 1 ]} }; CommunityMember .find(criteria) .populate('role') .then(function(member) { if(member.length > 0) { // check to see if the user is a SU AND an Admin for the community // if so, pass the Admin role so the user doesn't get any SU warnings if(member[0].role.type == 'SuperUser' && (member[1] && member[1].role.type == 'Admin')) res.locals.role = member[1].role; else res.locals.role = member[0].role; return next(); } else return res.forbidden(); }); } }
dnelson23/smashtrack
app/api/policyFactories/hasCommunityRole.js
JavaScript
mit
1,081
package io.avalia.samba; import static org.junit.Assert.assertNotNull; import org.junit.Assert; import org.junit.Test; public class CavacoTest { @Test public void thereShouldBeAnIInstrumentInterfaceAndATrumpetClass() { IInstrument cavaco = new Cavaco(); assertNotNull(cavaco); } @Test public void itShouldBePossibleToPlayAnInstrument() { IInstrument cavaco = new Cavaco(); String sound = cavaco.play(); assertNotNull(sound); } @Test public void aCavacoShouldMakePamPam() { IInstrument cavaco = new Cavaco(); String sound = cavaco.play(); Assert.assertEquals("Mandei meu cavaco chorar", sound); } @Test public void aCavacoShouldBeBrown() { IInstrument cavaco = new Cavaco(); String color = cavaco.getColor(); Assert.assertEquals("brown", color); } }
AvaliaSystems/Samba
Samba-build/Samba-tests/src/test/java/io/avalia/samba/CavacoTest.java
Java
mit
855
package problem3; /** * Created by tom on 2/22/17. */ public final class DistanceCalculator { private static final DistanceCalculator DISTANCE = new DistanceCalculator(); public double measureDistance(PointWritable point1, PointWritable point2) { double xResult = Double.parseDouble(point2.getFirst().toString()) - Double.parseDouble(point1.getFirst().toString()); double yResult = Double.parseDouble(point2.getSecond().toString()) - Double.parseDouble(point1.getSecond().toString()); double sum = (xResult * xResult) + (yResult * yResult); return Math.sqrt(sum); } }
tmm-ms/DS503
homework/02/intellij/src/main/java/problem3/DistanceCalculator.java
Java
mit
617
/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import {Config} from '@jest/types'; import {ChangedFilesPromise, getChangedFilesForRoots} from 'jest-changed-files'; import {formatExecError} from 'jest-message-util'; import chalk from 'chalk'; export default ( globalConfig: Config.GlobalConfig, configs: Array<Config.ProjectConfig>, ): ChangedFilesPromise | undefined => { if (globalConfig.onlyChanged) { const allRootsForAllProjects = configs.reduce<Array<Config.Path>>( (roots, config) => [...roots, ...(config.roots || [])], [], ); return getChangedFilesForRoots(allRootsForAllProjects, { changedSince: globalConfig.changedSince, lastCommit: globalConfig.lastCommit, withAncestor: globalConfig.changedFilesWithAncestor, }).catch(e => { const message = formatExecError(e, configs[0], {noStackTrace: true}) .split('\n') .filter(line => !line.includes('Command failed:')) .join('\n'); console.error(chalk.red(`\n\n${message}`)); process.exit(1); // We do process.exit, so this is dead code return Promise.reject(e); }); } return undefined; };
ide/jest
packages/jest-core/src/getChangedFilesPromise.ts
TypeScript
mit
1,325
namespace SortingExtensions.Tests.Implementation.Sorters { using System; using System.Collections.Generic; using System.Linq; class SorterTestBase { protected IList<int> OrderedList { get { return new List<int>(Enumerable.Range(0, 20)); } } protected IList<int> DescendingOrderedList { get { return OrderedList.Reverse().ToList(); } } protected IList<int> BigOrderedList { get { return new List<int>(Enumerable.Range(0, 10000)); } } protected IList<int> DescendingBigOrderedList { get { return OrderedList.Reverse().ToList(); } } protected IList<int> DuplicatesList { get { var random = new Random(Environment.TickCount); var list = new List<int>(); for (int i = 0; i < 10; i++) { list.AddRange(Enumerable.Repeat(random.Next(), 4)); } return list; } } protected IEnumerable<IList<int>> DifferentLists { get { yield return OrderedList; yield return DescendingOrderedList; yield return BigOrderedList; yield return DescendingBigOrderedList; yield return DuplicatesList; } } protected bool IsSorted<TComparable>(IList<TComparable> list) where TComparable : IComparable<TComparable> { return list.IsSorted(); } } }
iarovyi/SortingExtensions
SortingExtensions.Tests/Implementation/Sorters/SorterTestBase.cs
C#
mit
1,703
#!/usr/bin/python # -*- coding: utf-8 -*- import json import beanstalkc from flask import Blueprint, current_app, jsonify, g, request import config api = Blueprint('api', __name__) @api.before_request def before_request(): g.beanstalk = beanstalkc.Connection( host=config.BEANSTALKD_HOST, port=config.BEANSTALKD_PORT) @api.route('/push', methods=['POST']) def push_jobs(): jobs = request.json for job in jobs: if job['app_name'] not in config.APPS: ret = dict( error='unknown_app_name', detail='Unknown app name %s' % job['app_name']) return jsonify(ret), 400 if len(jobs) < 5: for job in jobs: if job['app_name'] not in config.APPS: continue g.beanstalk.use(config.PUSH_TUBE % job['app_name']) priority = config.PRIORITIES.get(job.get('priority', 'low')) delay = job.get('delay', 0) g.beanstalk.put(json.dumps(job), priority=priority, delay=delay) else: g.beanstalk.use(config.BATCH_PUSH_TUBE) g.beanstalk.put(json.dumps(jobs)) current_app.logger.info(jobs) return jsonify(dict()) @api.route('/push_stats', methods=['GET']) def push_stats(): ret = g.beanstalk.stats() ret['tubes'] = [] for app_name in config.APPS.keys(): try: ret['tubes'].append( g.beanstalk.stats_tube(config.PUSH_TUBE % app_name)) except beanstalkc.CommandFailed: continue return jsonify(ret)
BeanYoung/push-turbo
src/api.py
Python
mit
1,548
/* * Copyright (C) Lightbend Inc. <https://www.lightbend.com> */ package play.libs.typedmap; public final class TypedMap {}
github/codeql
java/ql/test/stubs/playframework-2.6.x/play/libs/typedmap/TypedMap.java
Java
mit
128
''' Created on 1.12.2016 @author: Darren ''' ''' A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. For example, given three people living at (0,0), (0,4), and (2,2): 1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0 The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6. '''
darrencheng0817/AlgorithmLearning
Python/leetcode/BestMeetingPoint.py
Python
mit
610
class Citation include Mongoid::Document field :text, type: String field :pos, type: Integer field :inner_pos, type: Hash belongs_to :document has_and_belongs_to_many :pages validate :must_have_valid_position def to_s text || super end protected def must_have_valid_position return if inner_pos.nil? pages = {} text_lines = {} ["from", "to"].each do |key| # Existential and type validation if not inner_pos[key].is_a?(Hash) errors.add(:inner_pos, "#{key} is not a Hash") next end if not inner_pos[key]["pid"].is_a?(Moped::BSON::ObjectId) errors.add(:inner_pos, "#{key}[pid] is not a Moped::BSON::ObjectId") end if not inner_pos[key]["tlid"].is_a?(Fixnum) errors.add(:inner_pos, "#{key}[tlid] is not a Fixnum") end if not inner_pos[key]["pos"].is_a?(Fixnum) errors.add(:inner_pos, "#{key}[pos] is not a Fixnum") end # ObjectIds validation if not pages[key] = Page.find(inner_pos[key]["pid"]) errors.add(:inner_pos, "#{key}[pid] references to a non-existent Page") next end if not text_lines[key] = pages[key].text_lines.find(inner_pos[key]["tlid"]) errors.add(:inner_pos, "#{key}[tlid] references to a non-existent TextLine") end # Position out-of-range validation if inner_pos[key]["pos"] < 0 or inner_pos[key]["pos"] >= text_lines[key].text.size errors.add(:inner_pos, "#{key}[pos] is out of range") next end end return if not errors[:inner_pos].empty? # Different documents if pages["from"].document_id != pages["to"].document_id errors.add(:inner_pos, "from[pid] and to[pid] reference to Pages of different Documents") end # Range validation (from..to) if pages["from"].num > pages["to"].num or \ (pages["from"].num == pages["to"].num and (text_lines["from"].id > text_lines["to"].id or \ (text_lines["from"].id == text_lines["to"].id and inner_pos["from"]["pos"] > inner_pos["to"]["pos"]))) errors.add(:inner_pos, "invalid range") end end end
hhba/mapa76-core
lib/mapa76/core/model/citation.rb
Ruby
mit
2,152
# -*- coding: utf-8 -*- import math # Constants taken from http://cesiumjs.org/2013/04/25/Horizon-culling/ radiusX = 6378137.0 radiusY = 6378137.0 radiusZ = 6356752.3142451793 # Stolen from https://github.com/bistromath/gr-air-modes/blob/master/python/mlat.py # WGS84 reference ellipsoid constants # http://en.wikipedia.org/wiki/Geodetic_datum#Conversion_calculations # http://en.wikipedia.org/wiki/File%3aECEF.png wgs84_a = radiusX # Semi-major axis wgs84_b = radiusZ # Semi-minor axis wgs84_e2 = 0.0066943799901975848 # First eccentricity squared wgs84_a2 = wgs84_a ** 2 # To speed things up a bit wgs84_b2 = wgs84_b ** 2 def LLH2ECEF(lon, lat, alt): lat *= (math.pi / 180.0) lon *= (math.pi / 180.0) def n(x): return wgs84_a / math.sqrt(1 - wgs84_e2 * (math.sin(x) ** 2)) x = (n(lat) + alt) * math.cos(lat) * math.cos(lon) y = (n(lat) + alt) * math.cos(lat) * math.sin(lon) z = (n(lat) * (1 - wgs84_e2) + alt) * math.sin(lat) return [x, y, z] # alt is in meters def ECEF2LLH(x, y, z): ep = math.sqrt((wgs84_a2 - wgs84_b2) / wgs84_b2) p = math.sqrt(x ** 2 + y ** 2) th = math.atan2(wgs84_a * z, wgs84_b * p) lon = math.atan2(y, x) lat = math.atan2( z + ep ** 2 * wgs84_b * math.sin(th) ** 3, p - wgs84_e2 * wgs84_a * math.cos(th) ** 3 ) N = wgs84_a / math.sqrt(1 - wgs84_e2 * math.sin(lat) ** 2) alt = p / math.cos(lat) - N r = 180 / math.pi lon *= r lat *= r return [lon, lat, alt]
loicgasser/quantized-mesh-tile
quantized_mesh_tile/llh_ecef.py
Python
mit
1,533
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MCMAIP.Models; namespace MCMAIP.Controllers { public class HomeController : Controller { MCMAIPEntities storeDB = new MCMAIPEntities(); // GET: /Index/ public ActionResult Index() { return View(); } public ActionResult Indexs(int count) { // Get most popular news var news = GetTopSellingNews(count); return Json(news); } private List<News> GetTopSellingNews(int count) { // Group the order details by album and return // the albums with the highest count return storeDB.NewsList .OrderByDescending(a => a.Id) .Take(count) .ToList(); } } }
CrystalZYH/amazing-works
works/MR/ASP.NET/MCMAIP/MCMAIP/Controllers/HomeController.cs
C#
mit
942
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.data.schemaregistry.implementation.models; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpRequest; import com.azure.core.http.rest.ResponseBase; /** Contains all response data for the queryIdByContent operation. */ public final class SchemasQueryIdByContentResponse extends ResponseBase<SchemasQueryIdByContentHeaders, SchemaId> { /** * Creates an instance of SchemasQueryIdByContentResponse. * * @param request the request which resulted in this SchemasQueryIdByContentResponse. * @param statusCode the status code of the HTTP response. * @param rawHeaders the raw headers of the HTTP response. * @param value the deserialized value of the HTTP response. * @param headers the deserialized headers of the HTTP response. */ public SchemasQueryIdByContentResponse( HttpRequest request, int statusCode, HttpHeaders rawHeaders, SchemaId value, SchemasQueryIdByContentHeaders headers) { super(request, statusCode, rawHeaders, value, headers); } /** @return the deserialized response body. */ @Override public SchemaId getValue() { return super.getValue(); } }
selvasingh/azure-sdk-for-java
sdk/schemaregistry/azure-data-schemaregistry/src/main/java/com/azure/data/schemaregistry/implementation/models/SchemasQueryIdByContentResponse.java
Java
mit
1,341
/* --------------------------------------------------------------------------- WAIT! - This file depends on instructions from the PUBNUB Cloud. http://www.pubnub.com/account-javascript-api-include --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- PubNub Real-time Cloud-Hosted Push API and Push Notification Client Frameworks Copyright (c) 2011 PubNub Inc. http://www.pubnub.com/ http://www.pubnub.com/terms --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- 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. --------------------------------------------------------------------------- */ /* =-====================================================================-= */ /* =-====================================================================-= */ /* =-========================= JSON =============================-= */ /* =-====================================================================-= */ /* =-====================================================================-= */ (window['JSON'] && window['JSON']['stringify']) || (function () { window['JSON'] || (window['JSON'] = {}); if (typeof String.prototype.toJSON !== 'function') { String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } if (typeof rep === 'function') { value = rep.call(holder, key, value); } switch (typeof value) { case 'string': return quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; } gap += indent; partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { k = rep[i]; if (typeof k === 'string') { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { for (k in value) { if (Object.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } if (typeof JSON['stringify'] !== 'function') { JSON['stringify'] = function (value, replacer, space) { var i; gap = ''; indent = ''; if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } } else if (typeof space === 'string') { indent = space; } rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } return str('', {'': value}); }; } if (typeof JSON['parse'] !== 'function') { // JSON is parsed on the server for security. JSON['parse'] = function (text) {return eval('('+text+')')}; } }()); /* =-====================================================================-= */ /* =-====================================================================-= */ /* =-======================= DOM UTIL ===========================-= */ /* =-====================================================================-= */ /* =-====================================================================-= */ window['PUBNUB'] || (function() { /** * CONSOLE COMPATIBILITY */ window.console||(window.console=window.console||{}); console.log||(console.log=((window.opera||{}).postError||function(){})); /** * UTILITIES */ function unique() { return'x'+ ++NOW+''+(+new Date) } function rnow() { return+new Date } /** * LOCAL STORAGE OR COOKIE */ var db = (function(){ var ls = window['localStorage']; return { 'get' : function(key) { try { if (ls) return ls.getItem(key); if (document.cookie.indexOf(key) == -1) return null; return ((document.cookie||'').match( RegExp(key+'=([^;]+)') )||[])[1] || null; } catch(e) { return } }, 'set' : function( key, value ) { try { if (ls) return ls.setItem( key, value ) && 0; document.cookie = key + '=' + value + '; expires=Thu, 1 Aug 2030 20:00:00 UTC; path=/'; } catch(e) { return } } }; })(); /** * UTIL LOCALS */ var NOW = 1 , SWF = 'https://dh15atwfs066y.cloudfront.net/pubnub.swf' , REPL = /{([\w\-]+)}/g , ASYNC = 'async' , URLBIT = '/' , XHRTME = 310000 , SECOND = 1000 , PRESENCE_SUFFIX = '-pnpres' , UA = navigator.userAgent , XORIGN = UA.indexOf('MSIE 6') == -1; /** * NEXTORIGIN * ========== * var next_origin = nextorigin(); */ var nextorigin = (function() { var ori = Math.floor(Math.random() * 9) + 1; return function(origin) { return origin.indexOf('pubsub') > 0 && origin.replace( 'pubsub', 'ps' + (++ori < 10 ? ori : ori=1) ) || origin; } })(); /** * UPDATER * ====== * var timestamp = unique(); */ function updater( fun, rate ) { var timeout , last = 0 , runnit = function() { if (last + rate > rnow()) { clearTimeout(timeout); timeout = setTimeout( runnit, rate ); } else { last = rnow(); fun(); } }; return runnit; } /** * $ * = * var div = $('divid'); */ function $(id) { return document.getElementById(id) } /** * LOG * === * log('message'); */ function log(message) { console['log'](message) } /** * SEARCH * ====== * var elements = search('a div span'); */ function search( elements, start ) { var list = []; each( elements.split(/\s+/), function(el) { each( (start || document).getElementsByTagName(el), function(node) { list.push(node); } ); } ); return list; } /** * EACH * ==== * each( [1,2,3], function(item) { console.log(item) } ) */ function each( o, f ) { if ( !o || !f ) return; if ( typeof o[0] != 'undefined' ) for ( var i = 0, l = o.length; i < l; ) f.call( o[i], o[i], i++ ); else for ( var i in o ) o.hasOwnProperty && o.hasOwnProperty(i) && f.call( o[i], i, o[i] ); } /** * MAP * === * var list = map( [1,2,3], function(item) { return item + 1 } ) */ function map( list, fun ) { var fin = []; each( list || [], function( k, v ) { fin.push(fun( k, v )) } ); return fin; } /** * GREP * ==== * var list = grep( [1,2,3], function(item) { return item % 2 } ) */ function grep( list, fun ) { var fin = []; each( list || [], function(l) { fun(l) && fin.push(l) } ); return fin } /** * SUPPLANT * ======== * var text = supplant( 'Hello {name}!', { name : 'John' } ) */ function supplant( str, values ) { return str.replace( REPL, function( _, match ) { return values[match] || _ } ); } /** * BIND * ==== * bind( 'keydown', search('a')[0], function(element) { * console.log( element, '1st anchor' ) * } ); */ function bind( type, el, fun ) { each( type.split(','), function(etype) { var rapfun = function(e) { if (!e) e = window.event; if (!fun(e)) { e.cancelBubble = true; e.returnValue = false; e.preventDefault && e.preventDefault(); e.stopPropagation && e.stopPropagation(); } }; if ( el.addEventListener ) el.addEventListener( etype, rapfun, false ); else if ( el.attachEvent ) el.attachEvent( 'on' + etype, rapfun ); else el[ 'on' + etype ] = rapfun; } ); } /** * UNBIND * ====== * unbind( 'keydown', search('a')[0] ); */ function unbind( type, el, fun ) { if ( el.removeEventListener ) el.removeEventListener( type, false ); else if ( el.detachEvent ) el.detachEvent( 'on' + type, false ); else el[ 'on' + type ] = null; } /** * HEAD * ==== * head().appendChild(elm); */ function head() { return search('head')[0] } /** * ATTR * ==== * var attribute = attr( node, 'attribute' ); */ function attr( node, attribute, value ) { if (value) node.setAttribute( attribute, value ); else return node && node.getAttribute && node.getAttribute(attribute); } /** * CSS * === * var obj = create('div'); */ function css( element, styles ) { for (var style in styles) if (styles.hasOwnProperty(style)) try {element.style[style] = styles[style] + ( '|width|height|top|left|'.indexOf(style) > 0 && typeof styles[style] == 'number' ? 'px' : '' )}catch(e){} } /** * CREATE * ====== * var obj = create('div'); */ function create(element) { return document.createElement(element) } /** * timeout * ======= * timeout( function(){}, 100 ); */ function timeout( fun, wait ) { return setTimeout( fun, wait ); } /** * jsonp_cb * ======== * var callback = jsonp_cb(); */ function jsonp_cb() { return XORIGN || FDomainRequest() ? 0 : unique() } /** * ENCODE * ====== * var encoded_path = encode('path'); */ function encode(path) { return map( (encodeURIComponent(path)).split(''), function(chr) { return "-_.!~*'()".indexOf(chr) < 0 ? chr : "%"+chr.charCodeAt(0).toString(16).toUpperCase() } ).join(''); } /** * EVENTS * ====== * PUBNUB.events.bind( 'you-stepped-on-flower', function(message) { * // Do Stuff with message * } ); * * PUBNUB.events.fire( 'you-stepped-on-flower', "message-data" ); * PUBNUB.events.fire( 'you-stepped-on-flower', {message:"data"} ); * PUBNUB.events.fire( 'you-stepped-on-flower', [1,2,3] ); * */ var events = { 'list' : {}, 'unbind' : function( name ) { events.list[name] = [] }, 'bind' : function( name, fun ) { (events.list[name] = events.list[name] || []).push(fun); }, 'fire' : function( name, data ) { each( events.list[name] || [], function(fun) { fun(data) } ); } }; /** * XDR Cross Domain Request * ======================== * xdr({ * url : ['http://www.blah.com/url'], * success : function(response) {}, * fail : function() {} * }); */ function xdr( setup ) { if (XORIGN || FDomainRequest()) return ajax(setup); var script = create('script') , callback = setup.callback , id = unique() , finished = 0 , timer = timeout( function(){done(1)}, XHRTME ) , fail = setup.fail || function(){} , success = setup.success || function(){} , append = function() { head().appendChild(script); } , done = function( failed, response ) { if (finished) return; finished = 1; failed || success(response); script.onerror = null; clearTimeout(timer); timeout( function() { failed && fail(); var s = $(id) , p = s && s.parentNode; p && p.removeChild(s); }, SECOND ); }; window[callback] = function(response) { done( 0, response ); }; script[ASYNC] = ASYNC; script.onerror = function() { done(1) }; script.src = setup.url.join(URLBIT); if (setup.data) { script.src += "?"; for (key in setup.data) { script.src += key+"="+setup.data[key]+"&"; } } attr( script, 'id', id ); append(); return done; } /** * CORS XHR Request * ================ * xdr({ * url : ['http://www.blah.com/url'], * success : function(response) {}, * fail : function() {} * }); */ function ajax( setup ) { var xhr, response , finished = function() { if (loaded) return; loaded = 1; clearTimeout(timer); try { response = JSON['parse'](xhr.responseText); } catch (r) { return done(1); } success(response); } , complete = 0 , loaded = 0 , timer = timeout( function(){done(1)}, XHRTME ) , fail = setup.fail || function(){} , success = setup.success || function(){} , done = function(failed) { if (complete) return; complete = 1; clearTimeout(timer); if (xhr) { xhr.onerror = xhr.onload = null; xhr.abort && xhr.abort(); xhr = null; } failed && fail(); }; // Send try { xhr = FDomainRequest() || window.XDomainRequest && new XDomainRequest() || new XMLHttpRequest(); xhr.onerror = xhr.onabort = function(){ done(1) }; xhr.onload = xhr.onloadend = finished; xhr.timeout = XHRTME; url = setup.url.join(URLBIT); if (setup.data) { url += "?"; for (key in setup.data) { url += key+"="+setup.data[key]+"&"; } } xhr.open( 'GET', url, true ); xhr.send(); } catch(eee) { done(0); XORIGN = 0; return xdr(setup); } // Return 'done' return done; } /* =-====================================================================-= */ /* =-====================================================================-= */ /* =-========================= PUBNUB ===========================-= */ /* =-====================================================================-= */ /* =-====================================================================-= */ var PDIV = $('pubnub') || {} , READY = 0 , READY_BUFFER = [] , CREATE_PUBNUB = function(setup) { var CHANNELS = {} , PUBLISH_KEY = setup['publish_key'] || '' , SUBSCRIBE_KEY = setup['subscribe_key'] || '' , SSL = setup['ssl'] ? 's' : '' , UUID = setup['uuid'] || db.get(SUBSCRIBE_KEY+'uuid') || '' , ORIGIN = 'http'+SSL+'://'+(setup['origin']||'pubsub.pubnub.com') , SELF = { /* PUBNUB.history({ channel : 'my_chat_channel', limit : 100, callback : function(messages) { console.log(messages) } }); */ 'history' : function( args, callback ) { var callback = args['callback'] || callback , limit = args['limit'] || 100 , channel = args['channel'] , jsonp = jsonp_cb(); // Make sure we have a Channel if (!channel) return log('Missing Channel'); if (!callback) return log('Missing Callback'); // Send Message xdr({ callback : jsonp, url : [ ORIGIN, 'history', SUBSCRIBE_KEY, encode(channel), jsonp, limit ], success : function(response) { callback(response) }, fail : function(response) { log(response) } }); }, /* PUBNUB.time(function(time){ console.log(time) }); */ 'time' : function(callback) { var jsonp = jsonp_cb(); xdr({ callback : jsonp, url : [ORIGIN, 'time', jsonp], success : function(response) { callback(response[0]) }, fail : function() { callback(0) } }); }, /* PUBNUB.uuid(function(uuid) { console.log(uuid) }); */ 'uuid' : function(callback) { var u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); if (callback) callback(u); return u; }, /* PUBNUB.publish({ channel : 'my_chat_channel', message : 'hello!' }); */ 'publish' : function( args, callback ) { var callback = callback || args['callback'] || function(){} , message = args['message'] , channel = args['channel'] , jsonp = jsonp_cb() , url; if (!message) return log('Missing Message'); if (!channel) return log('Missing Channel'); if (!PUBLISH_KEY) return log('Missing Publish Key'); // If trying to send Object message = JSON['stringify'](message); // Create URL url = [ ORIGIN, 'publish', PUBLISH_KEY, SUBSCRIBE_KEY, 0, encode(channel), jsonp, encode(message) ]; // Send Message xdr({ callback : jsonp, success : function(response) { callback(response) }, fail : function() { callback([ 0, 'Disconnected' ]) }, url : url, data : { uuid: UUID } }); }, /* PUBNUB.unsubscribe({ channel : 'my_chat' }); */ 'unsubscribe' : function(args) { // Unsubscribe from both the Channel and the Presence Channel _unsubscribe(args['channel']); _unsubscribe(args['channel'] + PRESENCE_SUFFIX); function _unsubscribe(channel) { // Leave if there never was a channel. if (!(channel in CHANNELS)) return; // Disable Channel CHANNELS[channel].connected = 0; // Abort and Remove Script CHANNELS[channel].done && CHANNELS[channel].done(0); } }, /* PUBNUB.subscribe({ channel : 'my_chat' callback : function(message) { console.log(message) } }); */ 'subscribe' : function( args, callback ) { var channel = args['channel'] , callback = callback || args['callback'] , subscribe_key= args['subscribe_key'] || SUBSCRIBE_KEY , restore = args['restore'] , timetoken = 0 , error = args['error'] || function(){} , connect = args['connect'] || function(){} , reconnect = args['reconnect'] || function(){} , disconnect = args['disconnect'] || function(){} , presence = args['presence'] || function(){} , disconnected = 0 , connected = 0 , origin = nextorigin(ORIGIN); // Reduce Status Flicker if (!READY) return READY_BUFFER.push([ args, callback, SELF ]); // Make sure we have a Channel if (!channel) return log('Missing Channel'); if (!callback) return log('Missing Callback'); if (!SUBSCRIBE_KEY) return log('Missing Subscribe Key'); if (!(channel in CHANNELS)) CHANNELS[channel] = {}; // Make sure we have a Channel if (CHANNELS[channel].connected) return log('Already Connected'); CHANNELS[channel].connected = 1; // Recurse Subscribe function _connect() { var jsonp = jsonp_cb(); // Stop Connection if (!CHANNELS[channel].connected) return; // Connect to PubNub Subscribe Servers CHANNELS[channel].done = xdr({ callback : jsonp, url : [ origin, 'subscribe', subscribe_key, encode(channel), jsonp, timetoken ], data : { uuid: UUID }, fail : function() { // Disconnect if (!disconnected) { disconnected = 1; disconnect(); } timeout( _connect, SECOND ); SELF['time'](function(success){ // Reconnect if (success && disconnected) { disconnected = 0; reconnect(); } else { error(); } }); }, success : function(messages) { if (!CHANNELS[channel].connected) return; // Connect if (!connected) { connected = 1; connect(); } // Reconnect if (disconnected) { disconnected = 0; reconnect(); } // Restore Previous Connection Point if Needed // Also Update Timetoken restore = db.set( SUBSCRIBE_KEY + channel, timetoken = restore && db.get( subscribe_key + channel ) || messages[1] ); each( messages[0], function(msg) { callback( msg, messages ); } ); timeout( _connect, 10 ); } }); } // Presence Subscribe if (args['presence']) SELF.subscribe({ channel : args['channel'] + PRESENCE_SUFFIX, callback : presence, restore : args['restore'] }); // Begin Recursive Subscribe _connect(); }, 'here_now' : function( args, callback ) { var callback = args['callback'] || callback , channel = args['channel'] , jsonp = jsonp_cb() , origin = nextorigin(ORIGIN); // Make sure we have a Channel if (!channel) return log('Missing Channel'); if (!callback) return log('Missing Callback'); data = null; if (jsonp != '0') { data['callback']=jsonp; } // Send Message xdr({ callback : jsonp, url : [ origin, 'v2', 'presence', 'sub_key', SUBSCRIBE_KEY, 'channel', encode(channel) ], data: data, success : function(response) { callback(response) }, fail : function(response) { log(response) } }); }, // Expose PUBNUB Functions 'xdr' : xdr, 'ready' : ready, 'db' : db, 'each' : each, 'map' : map, 'css' : css, '$' : $, 'create' : create, 'bind' : bind, 'supplant' : supplant, 'head' : head, 'search' : search, 'attr' : attr, 'now' : rnow, 'unique' : unique, 'events' : events, 'updater' : updater, 'init' : CREATE_PUBNUB }; if (UUID == '') UUID = SELF.uuid(); db.set(SUBSCRIBE_KEY+'uuid', UUID); return SELF; }; // CREATE A PUBNUB GLOBAL OBJECT PUBNUB = CREATE_PUBNUB({ 'publish_key' : attr( PDIV, 'pub-key' ), 'subscribe_key' : attr( PDIV, 'sub-key' ), 'ssl' : attr( PDIV, 'ssl' ) == 'on', 'origin' : attr( PDIV, 'origin' ), 'uuid' : attr( PDIV, 'uuid' ) }); // PUBNUB Flash Socket css( PDIV, { 'position' : 'absolute', 'top' : -SECOND } ); if ('opera' in window || attr( PDIV, 'flash' )) PDIV['innerHTML'] = '<object id=pubnubs data=' + SWF + '><param name=movie value=' + SWF + '><param name=allowscriptaccess value=always></object>'; var pubnubs = $('pubnubs') || {}; // PUBNUB READY TO CONNECT function ready() { PUBNUB['time'](rnow); PUBNUB['time'](function(t){ timeout( function() { if (READY) return; READY = 1; each( READY_BUFFER, function(sub) { sub[2]['subscribe']( sub[0], sub[1] ) } ); }, SECOND ); }); } // Bind for PUBNUB Readiness to Subscribe bind( 'load', window, function(){ timeout( ready, 0 ) } ); // Create Interface for Opera Flash PUBNUB['rdx'] = function( id, data ) { if (!data) return FDomainRequest[id]['onerror'](); FDomainRequest[id]['responseText'] = unescape(data); FDomainRequest[id]['onload'](); }; function FDomainRequest() { if (!pubnubs['get']) return 0; var fdomainrequest = { 'id' : FDomainRequest['id']++, 'send' : function() {}, 'abort' : function() { fdomainrequest['id'] = {} }, 'open' : function( method, url ) { FDomainRequest[fdomainrequest['id']] = fdomainrequest; pubnubs['get']( fdomainrequest['id'], url ); } }; return fdomainrequest; } FDomainRequest['id'] = SECOND; // jQuery Interface window['jQuery'] && (window['jQuery']['PUBNUB'] = PUBNUB); // For Testling.js - http://testling.com/ typeof module !== 'undefined' && (module.exports = PUBNUB) && ready(); })();
cozza13/tipochat
core/3.2/pubnub-3.2.js
JavaScript
mit
29,957
import { Undefinable } from './Undefinable'; /** * Return _a_ if _a_ is not `undefined`. * Otherwise, return _b_. */ export function orForUndefinable<T>(a: Undefinable<T>, b: Undefinable<T>): Undefinable<T> { return a !== undefined ? a : b; }
saneyuki/option-t.js
src/Undefinable/or.ts
TypeScript
mit
253
using System; using System.Threading.Tasks; namespace Binky { public static class CacheBuilder { public static IBuilder<TKey, TValue> WithFactory<TKey, TValue>(Func<IUpdateValue<TKey, TValue>> getValueUpdater) => new Builder<TKey, TValue>(getValueUpdater().Get); public static IBuilder<TKey, TValue> With<TKey, TValue>(Func<TKey, TValue> getUpdateValue) => new Builder<TKey, TValue>((key,_) => Task.FromResult(getUpdateValue(key))); public static IBuilder<TKey, TValue> WithAsync<TKey, TValue>(Cache<TKey, TValue>.UpdateValueDelegate getUpdateValue) => new Builder<TKey, TValue>(getUpdateValue); class Builder<TKey, TValue> : IBuilder<TKey, TValue> { Cache<TKey, TValue>.UpdateValueDelegate _getUpdateValue; TKey[] _keys; TimeSpan _every; TimeSpan _begin; TimeSpan _rampUp; bool _evictUnused; public Builder(Cache<TKey, TValue>.UpdateValueDelegate getUpdateValue) { _getUpdateValue = getUpdateValue; } public Cache<TKey, TValue> Build() { return new Cache<TKey, TValue>(_getUpdateValue, _every, _begin, _keys ?? new TKey[0], _rampUp, _evictUnused); } public IBuilder<TKey, TValue> Preload(params TKey[] values) { _keys = values; return this; } public IBuilder<TKey, TValue> RefreshEvery(TimeSpan every) { _every = every; return this; } public IBuilder<TKey, TValue> BeginAfter(TimeSpan begin) { _begin = begin; return this; } public IBuilder<TKey, TValue> WithRampUpDuration(TimeSpan rampUp) { _rampUp = rampUp; return this; } public IBuilder<TKey, TValue> EvictUnused() { _evictUnused = true; return this; } } } }
quezlatch/Binky
Binky/CacheBuilder.cs
C#
mit
1,708
class CreateArtistSections < ActiveRecord::Migration def change create_table :artist_sections do |t| t.integer :artist_id t.integer :section_id t.timestamps null: false end end end
markjanzer/rap-analysis
db/migrate/20160219205158_create_artist_sections.rb
Ruby
mit
212
module Hashrocket class UiController < ::ApplicationController extend Wireframe::Excludes exclude 'index', ->(w) { w.starts_with? '_' } expose(:wireframes) do Wireframe.cleaned end end end
hashrocket/hashrocket-rails
app/controllers/hashrocket/ui_controller.rb
Ruby
mit
218
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved. * */ package com.sleepycat.je.tree.dupConvert; import java.util.ArrayList; import com.sleepycat.je.CacheMode; import com.sleepycat.je.EnvironmentFailureException; import com.sleepycat.je.PreloadConfig; import com.sleepycat.je.cleaner.LocalUtilizationTracker; import com.sleepycat.je.config.EnvironmentParams; import com.sleepycat.je.dbi.DatabaseId; import com.sleepycat.je.dbi.DatabaseImpl; import com.sleepycat.je.dbi.DbTree; import com.sleepycat.je.dbi.DupKeyData; import com.sleepycat.je.dbi.EnvironmentImpl; import com.sleepycat.je.log.LogEntryType; import com.sleepycat.je.tree.BIN; import com.sleepycat.je.tree.ChildReference; import com.sleepycat.je.tree.IN; import com.sleepycat.je.tree.Key; import com.sleepycat.je.tree.LN; import com.sleepycat.je.tree.Node; import com.sleepycat.je.txn.BasicLocker; import com.sleepycat.je.txn.LockGrantType; import com.sleepycat.je.txn.LockResult; import com.sleepycat.je.txn.LockType; import com.sleepycat.je.utilint.DbLsn; /** * Performs post-recovery conversion of all dup DBs during Environment * construction, when upgrading from JE 4.1 and earlier. In JE 5.0, duplicates * are represented by a two-part (key + data) key, and empty data. In JE 4.1 * and earlier, the key and data were separate as with non-dup DBs. * * Uses the DbTree.DUPS_CONVERTED_BIT to determine whether conversion of the * environment is necessary. When all databases are successfully converted, * this bit is set and the mapping tree is flushed. See * EnvironmentImpl.convertDupDatabases. * * Uses DatabaseImpl.DUPS_CONVERTED to determine whether an individual database * has been converted, to handle the case where the conversion crashes and is * restarted later. When a database is successfully converted, this bit is set * and the entire database is flushed using Database.sync. * * The conversion of each database is atomic -- either all INs or none are * converted and made durable. This is accomplished by putting the database * into Deferred Write mode so that splits won't log and eviction will be * provisional (eviction will not flush the root IN if it is dirty). The * Deferred Write mode is cleared after conversion is complete and * Database.sync has been called. * * The memory budget is updated during conversion and daemon eviction is * invoked periodically. This provides support for arbitrarily large DBs. * * Uses preload to load all dup trees (DINs/DBINs) prior to conversion, to * minimize random I/O. See EnvironmentConfig.ENV_DUP_CONVERT_PRELOAD_ALL. * * The preload config does not specify loading of LNs, because we do not need * to load LNs from DBINs. The fact that DBIN LNs are not loaded is the main * reason that conversion is quick. LNs are converted lazily instead; see * LNLogEntry.postFetchInit. The DBIN LNs do not need to be loaded because the * DBIN slot key contains the LN 'data' that is needed to create the two-part * key. * * Even when LN loading is not configured, it turns out that preload does load * BIN (not DBIN) LNs in a dup DB, which is what we want. The singleton LNs * must be loaded in order to get the LN data to create the two-part key. When * preload has not loaded a singleton LN, it will be fetched during conversion. * * The DIN, DBIN and DupCount LSN are counted obsolete during conversion using * a local utilization tracker. The tracker must not be flushed until the * conversion of a database is complete. Inexact counting can be used, because * DIN/DBIN/DupCountLN entries are automatically considered obsolete by the * cleaner. Since only totals are tracked, the memory overhead of the local * tracker is not substantial. * * Database Conversion Algorithm * ----------------------------- * 1. Set Deferred Write mode for the database. Preload the database, including * INs/BINs/DINs/DBINs, but not LNs except for singleton LNs (LNs with a BIN * parent). * * 2. Convert all IN/BIN keys to "prefix keys", which are defined by the * DupKeyData class. This allows tree searches and slot insertions to work * correctly as the conversion is performed. * * 3. Traverse through the BIN slots in forward order. * * 4. If a singleton LN is encountered, ensure it is loaded. IN.fetchTarget * automatically updates the slot key if the LNLogEntry's key is different * from the one already in the slot. Because LNLogEntry's key is converted * on the fly, a two-part key is set in the slot as a side effect of * fetching the LN. * * 5. If a DIN is encountered, first delete the BIN slot containing the DIN. * Then iterate through all LNs in the DBINs of this dup tree, assign each * a two-part key, and insert the slot into a BIN. The LSN and state flags * of the DBIN slot are copied to the new BIN slot. * * 6. If a deleted singleton (BIN) LN is encountered, delete the slot rather * than converting the key. If a deleted DBIN LN is encountered, simply * discard it. * * 7. Count the DIN and DupCount LSN obsolete for each DIN encountered, using * a local utilization tracker. * * 8. When all BIN slots have been processed, set the * DatabaseImpl.DUPS_CONVERTED flag, call Database.sync to flush all INs and * the MapLN, clear Deferred Write mode, and flush the local utilization * tracker. */ public class DupConvert { private final static boolean DEBUG = false; private final EnvironmentImpl envImpl; private final DbTree dbTree; private final boolean preloadAll; private final PreloadConfig preloadConfig; private LocalUtilizationTracker localTracker; private long nConverted; // for debugging /* Current working tree position. */ private BIN bin; private int index; /** * Creates a conversion object. */ public DupConvert(final EnvironmentImpl envImpl, final DbTree dbTree) { this.envImpl = envImpl; this.dbTree = dbTree; this.preloadAll = envImpl.getConfigManager().getBoolean (EnvironmentParams.ENV_DUP_CONVERT_PRELOAD_ALL); this.preloadConfig = (envImpl.getDupConvertPreloadConfig() != null) ? envImpl.getDupConvertPreloadConfig() : (new PreloadConfig()); } /** * Converts all dup DBs that need conversion. */ public void convertDatabases() { if (DEBUG) { System.out.println("DupConvert.convertDatabases"); } if (preloadAll) { preloadAllDatabases(); } for (DatabaseId dbId : dbTree.getDbNamesAndIds().keySet()) { final DatabaseImpl dbImpl = dbTree.getDb(dbId); try { if (!needsConversion(dbImpl)) { continue; } convertDatabase(dbImpl); } finally { dbTree.releaseDb(dbImpl); } } assert noDupNodesPresent(); } private boolean noDupNodesPresent() { for (IN in : envImpl.getInMemoryINs()) { if (in instanceof DIN || in instanceof DBIN) { System.out.println(in.toString()); return false; } } return true; } /** * Preload all dup DBs to be converted. */ private void preloadAllDatabases() { final ArrayList<DatabaseImpl> dbsToConvert = new ArrayList<DatabaseImpl>(); try { for (DatabaseId dbId : dbTree.getDbNamesAndIds().keySet()) { final DatabaseImpl dbImpl = dbTree.getDb(dbId); boolean releaseDbImpl = true; try { if (!needsConversion(dbImpl)) { continue; } dbsToConvert.add(dbImpl); releaseDbImpl = false; } finally { if (releaseDbImpl) { dbTree.releaseDb(dbImpl); } } } if (dbsToConvert.size() == 0) { return; } final DatabaseImpl[] dbArray = new DatabaseImpl[dbsToConvert.size()]; dbsToConvert.toArray(dbArray); envImpl.preload(dbArray, preloadConfig); } finally { for (DatabaseImpl dbImpl : dbsToConvert) { dbTree.releaseDb(dbImpl); } } } /** * Returns whether the given DB needs conversion. */ private boolean needsConversion(final DatabaseImpl dbImpl) { return (dbImpl.getSortedDuplicates() && !dbImpl.getDupsConverted() && !dbImpl.isDeleted()); } /** * Converts a single database. */ private void convertDatabase(final DatabaseImpl dbImpl) { if (DEBUG) { System.out.println("DupConvert.convertDatabase " + dbImpl.getId()); } final boolean saveDeferredWrite = dbImpl.isDurableDeferredWrite(); try { localTracker = new LocalUtilizationTracker(envImpl); dbImpl.setDeferredWrite(true); dbImpl.setKeyPrefixing(); if (!preloadAll) { dbImpl.preload(preloadConfig); } bin = (BIN) dbImpl.getTree().getFirstNode(CacheMode.UNCHANGED); if (bin == null) { return; } index = -1; while (getNextBinSlot()) { convertBinSlot(); } dbImpl.setDupsConverted(); dbImpl.sync(false /*flushLog*/); envImpl.getUtilizationProfile().flushLocalTracker(localTracker); } finally { dbImpl.setDeferredWrite(saveDeferredWrite); } } /** * Advances the bin/index fields to the next BIN slot. When moving past * the last BIN slot, the bin field is set to null and false is returned. * * Enter/leave with bin field latched. */ private boolean getNextBinSlot() { index += 1; if (index < bin.getNEntries()) { return true; } /* Compact keys after finishing with a BIN. */ bin.compactMemory(); assert bin.verifyMemorySize(); /* Cannot evict between BINs here, because a latch is held. */ bin = bin.getDatabase().getTree().getNextBin(bin, CacheMode.UNCHANGED); if (bin == null) { return false; } index = 0; return true; } /** * Converts the bin/index slot, whether a singleton LN or a DIN root. * * Enter/leave with bin field latched, although bin field may change. * * When a singleton LN is converted, leaves with bin/index fields * unchanged. * * When a dup tree is converted, leaves with bin/index fields set to last * inserted slot. This is the slot of the highest key in the dup tree. */ private void convertBinSlot() { if (DEBUG) { System.out.println("DupConvert BIN LSN " + DbLsn.getNoFormatString(bin.getLsn(index)) + " index " + index + " nEntries " + bin.getNEntries()); } /* Delete slot if LN is deleted. */ final boolean isDeleted; if (isLNDeleted(bin, index)) { deleteSlot(); return; } final Node node = bin.fetchTarget(index); if (!node.containsDuplicates()) { if (DEBUG) { System.out.println("DupConvert BIN LN " + Key.dumpString(bin.getKey(index), 0)); } /* Fetching a non-deleted LN updates the slot key; we're done. */ assert node instanceof LN; nConverted += 1; return; } /* * Delete the slot containing the DIN before re-inserting the dup tree, * so that the DIN slot key doesn't interfere with insertions. * * The DIN is evicted and memory usage is decremented. This is not * exactly correct because we keep a local reference to the DIN until * the dup tree is converted, but we tolerate this temporary * inaccuracy. */ final byte[] binKey = bin.getKey(index); deleteSlot(); final DIN din = (DIN) node; envImpl.getInMemoryINs().remove(din); convertDin(din, binKey); } /** * Returns true if the LN at the given bin/index slot is permanently * deleted. Returns false if it is not deleted, or if it is deleted but * part of an unclosed, resurrected txn. * * Enter/leave with bin field latched. */ private boolean isLNDeleted(BIN checkBin, int checkIndex) { if (!checkBin.isEntryKnownDeleted(checkIndex) && !checkBin.isEntryPendingDeleted(checkIndex)) { /* Not deleted. */ return false; } final long lsn = checkBin.getLsn(checkIndex); if (lsn == DbLsn.NULL_LSN) { /* Can discard a NULL_LSN entry without locking. */ return true; } /* Lock LSN to guarantee deletedness. */ final BasicLocker lockingTxn = BasicLocker.createBasicLocker(envImpl); /* Don't allow this short-lived lock to be preempted/stolen. */ lockingTxn.setPreemptable(false); try { final LockResult lockRet = lockingTxn.nonBlockingLock (lsn, LockType.READ, false /*jumpAheadOfWaiters*/, checkBin.getDatabase()); if (lockRet.getLockGrant() == LockGrantType.DENIED) { /* Is locked by a resurrected txn. */ return false; } return true; } finally { lockingTxn.operationEnd(); } } /** * Deletes the bin/index slot, assigned a new identifier key if needed. * * Enter/leave with bin field latched. */ private void deleteSlot() { bin.deleteEntry(index, true /*maybeValidate*/); if (index == 0 && bin.getNEntries() != 0) { bin.setIdentifierKey(bin.getKey(0)); } index -= 1; } /** * Converts the given DIN and its descendants. * * Enter/leave with bin field latched, although bin field will change to * last inserted slot. */ private void convertDin(final DIN din, final byte[] binKey) { din.latch(); try { for (int i = 0; i < din.getNEntries(); i += 1) { final IN child = (IN) din.fetchTargetWithExclusiveLatch(i); if (child instanceof DBIN) { final DBIN dbin = (DBIN) child; dbin.latch(); try { for (int j = 0; j < dbin.getNEntries(); j += 1) { if (!isLNDeleted(dbin, j)) { convertDbinSlot(dbin, j, binKey); } } assert dbin.verifyMemorySize(); /* Count DBIN obsolete. */ if (dbin.getLastLoggedVersion() != DbLsn.NULL_LSN) { localTracker.countObsoleteNodeInexact (dbin.getLastLoggedVersion(), dbin.getLogType(), 0, dbin.getDatabase()); } } finally { dbin.releaseLatch(); } } else { convertDin((DIN) child, binKey); } /* Evict DIN child. */ din.updateNode(i, null, null); envImpl.getInMemoryINs().remove(child); } assert din.verifyMemorySize(); /* Count DIN and DupCountLN obsolete. */ if (din.getLastLoggedVersion() != DbLsn.NULL_LSN) { localTracker.countObsoleteNodeInexact (din.getLastLoggedVersion(), din.getLogType(), 0, din.getDatabase()); } final ChildReference dupCountRef = din.getDupCountLNRef(); if (dupCountRef != null && dupCountRef.getLsn() != DbLsn.NULL_LSN) { localTracker.countObsoleteNodeInexact (dupCountRef.getLsn(), LogEntryType.LOG_DUPCOUNTLN, 0, din.getDatabase()); } } finally { din.releaseLatch(); } } /** * Converts the given DBIN slot, leaving bin/index set to the inserted * BIN slot. * * Enter/leave with bin field latched, although bin field may change. * * If slot is inserted into current bin, leave bin field unchanged and * set index field to inserted slot. * * If slot is inserted into a different bin, set bin/index fields to * inserted slot. */ private void convertDbinSlot(final DBIN dbin, final int dbinIndex, final byte[] binKey) { final byte[] newKey = DupKeyData.replaceData(binKey, dbin.getKey(dbinIndex)); if (DEBUG) { System.out.println("DupConvert DBIN LN " + Key.dumpString(newKey, 0)); } /* * If the current BIN can hold the new slot, don't bother to do a * search to find it. */ if (bin.needsSplitting() || !bin.isKeyInBounds(newKey)) { /* Compact keys after finishing with a BIN. */ bin.compactMemory(); /* Evict without latches, before moving to a new BIN. */ bin.releaseLatch(); envImpl.daemonEviction(false /*backgroundIO*/); /* Find a BIN for insertion, split if necessary. */ bin = (BIN) dbin.getDatabase().getTree().searchSplitsAllowed (newKey, CacheMode.UNCHANGED, null /*searchComparator*/); } final ChildReference childRef = new ChildReference (null /*ln*/, newKey, dbin.getLsn(dbinIndex), dbin.getState(dbinIndex)); final int newIndex = bin.insertEntry1(childRef); if ((newIndex & IN.INSERT_SUCCESS) == 0) { throw EnvironmentFailureException.unexpectedState ("Key not inserted: " + Key.dumpString(newKey, 0) + " DB: " + dbin.getDatabase().getId()); } index = newIndex & ~IN.INSERT_SUCCESS; /* * Evict LN from DBIN slot. Although we don't explicitly load DBIN LNs, * it may have been loaded by recovery. */ dbin.updateNode(dbinIndex, null, null); nConverted += 1; } /** * Changes all keys to "prefix keys" in the given IN. Called after reading * an IN from disk via IN.postFetchInit. * * The conversion of IN keys is invoked from the IN class when an IN is * fetched, rather than invoked from the DupConvert class directly, for * performance and simplicity. If it were invoked from the DupConvert * class, we would have to iterate over all INs in a separate initial pass. * This is both more time consuming, and more complex to implement properly * so that eviction is possible. Instead, conversion occurs when an old * format IN is loaded. * * Enter/leave with 'in' unlatched. */ public static void convertInKeys(final DatabaseImpl dbImpl, final IN in) { /* Nothing to convert for non-duplicates DB. */ if (!dbImpl.getSortedDuplicates()) { return; } /* DIN/DBIN do not need conversion either. */ if (in instanceof DIN || in instanceof DBIN) { return; } in.latch(); try { for (int i = 0; i < in.getNEntries(); i += 1) { byte[] oldKey = in.getKey(i); byte[] newKey = DupKeyData.makePrefixKey(oldKey, 0, oldKey.length); in.updateEntry(i, in.getTarget(i), in.getLsn(i), newKey); } byte[] oldKey = in.getIdentifierKey(); byte[] newKey = DupKeyData.makePrefixKey(oldKey, 0, oldKey.length); in.setIdentifierKey(newKey); assert in.verifyMemorySize(); } finally { in.releaseLatch(); } } }
prat0318/dbms
mini_dbms/je-5.0.103/src/com/sleepycat/je/tree/dupConvert/DupConvert.java
Java
mit
20,648
<?php class Form extends CI_Controller{ public function form_view(){ $this->load->view('login'); } public function check(){ $this->form_validation->set_message('min_length', 'полето {field} изисква {param} знака!'); $this->form_validation->set_message('required', '{field} е задължително!'); $this->form_validation->set_message('max_length', '{field} е задължително!'); $this->form_validation->set_rules('user_name', 'Потребителско име', 'required|min_length[3]'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_error_delimiters('<div class="error">', '</div>'); if ($this->form_validation->run() == FALSE) { $this->form_view(); } else { $user_name = $this->input->post('user_name'); $password = $this->input->post('password'); $this->load->model('form_model'); $result2=$this->form_model->get_name($user_name); if ($result2 && $password == $result2['password']) { $this->load->library('session'); // $_SESSION['user_id']=$result2['user_id']; $_SESSION['first_name']=$result2['first_name']; $_SESSION['username']=$result2['user_name']; $_SESSION['phone']=$result2['phone']; $_SESSION['photo']=$result2['photo']; $_SESSION['password']=$result2['password']; $_SESSION['tickets']=$result2['tickets']; $this->load->view('success'); }else{ echo "Грешен потребител или парола !"; // echo "<p><pre><a href='form_view'>НАЗАД</a></pre></p>"; $this->form_view(); } } // $user_name = $this->input->post('user_name'); // //echo "$user_name"; // $this->load->model('form_model'); // $result2=$this->form_model->get_name($user_name); // // $result3=$this->form_model->get_first_name($user_name); // if ($result2) { // // session_destroy(); // // session_start(); // $this->load->library('session'); // $_SESSION['first_name']=$result2['first_name']; // $_SESSION['username']=$result2['user_name']; // $_SESSION['phone']=$result2['phone']; // $_SESSION['photo']=$result2['photo']; // $this->load->view('success'); // }else{ // $this->form_view(); // } } public function first(){ // $prefs = array( // 'start_day' => 'monday', // 'month_type' => 'short', // 'day_type' => 'long', // // 'show_next_prev' => TRUE, // // 'next_prev_url' => 'http://localhost/code_with_login/index.php/form/first' // ); // $this->load->library('calendar',$prefs); // $events = array( // 3 => 'http://www.google.bg', // 7 => 'http://example.com/news/article/2006/07/', // 13 => 'http://example.com/news/article/2006/13/', // 26 => 'http://example.com/news/article/2006/26/' // ); // $data['calendar']=$this->calendar->generate(2016,7,$events); // session_start(); $this->load->library('session'); $this->load->view('first_name'); } public function edit_first(){ $this->load->library('session'); $the_first_name=$this->input->post('first_name'); $new_first_name=$this->input->post('new_first_name'); $_SESSION['new_first_name']=$new_first_name; if (empty($new_first_name)) { $this->load->view('edit_first_name'); }else{ $this->load->model('form_model'); $result3=$this->form_model->update_first($the_first_name,$new_first_name); $this->load->view('edited_profile'); } } public function edit_phone(){ $this->load->library('session'); $phone=$this->input->post('phone'); $new_phone=$this->input->post('new_phone'); $_SESSION['new_phone']=$new_phone; if (empty($new_phone)) { $this->load->view('edit_phone'); }else{ $this->load->model('form_model'); $result3=$this->form_model->update_phone($phone,$new_phone); $this->load->view('edited_profile2'); } } public function edited(){ $this->load->library('session'); if (!empty($_SESSION['new_first_name'])) { $_SESSION['first_name']=$_SESSION['new_first_name']; } $this->load->view('first_name'); } public function logout(){ $this->session->sess_destroy(); $this->load->view('login_form'); } public function buy_tickets(){ $this->load->library('session'); $this->load->model('form_model'); $data['all_movies']=$this->form_model->get_movies(); $this->load->view('template/header'); $this->load->view('view_movies',$data); $this->load->view('template/footer'); } public function get_movie_info(){ $id=$this->uri->segment(3); $this->load->library('session'); $this->load->model('form_model'); $data['movie_info']=$this->form_model->get_info($id); $this->load->view('template/header'); $this->load->view('movie_info',$data); $this->load->view('template/footer'); } }
Konvict5/Movie_Tickets
application/controllers/form.php
PHP
mit
5,889
import { StackNavigator, TabNavigator, TabBarBottom } from 'react-navigation' import ScheduleScreen from '../Containers/ScheduleScreen' import TalkDetailScreen from '../Containers/TalkDetailScreen' import BreakDetailScreen from '../Containers/BreakDetailScreen' import LocationScreen from '../Containers/LocationScreen' import AboutScreen from '../Containers/AboutScreen' import styles from './Styles/NavigationStyles' const ScheduleStack = StackNavigator({ Home: { screen: ScheduleScreen }, TalkDetail: { screen: TalkDetailScreen }, BreakDetail: { screen: BreakDetailScreen } }, { headerMode: 'none', initialRouteName: 'Home', cardStyle: styles.card }) const TabNav = TabNavigator({ Schedule: { screen: ScheduleStack }, Location: { screen: LocationScreen }, About: { screen: AboutScreen } }, { key: 'Schedule', tabBarComponent: TabBarBottom, tabBarPosition: 'bottom', animationEnabled: true, swipeEnabled: true, headerMode: 'none', initialRouteName: 'Schedule', tabBarOptions: { style: styles.tabBar, labelStyle: styles.tabBarLabel, activeTintColor: 'white', inactiveTintColor: 'white' } }) export default TabNav
infinitered/ChainReactApp
App/Navigation/AppNavigation.js
JavaScript
mit
1,169
<?php /** * Register widget areas * * @package FoundationPress * @since FoundationPress 1.0.0 */ if ( ! function_exists( 'foundationpress_sidebar_widgets' ) ) : function foundationpress_sidebar_widgets() { register_sidebar(array( 'id' => 'sidebar-widgets', 'name' => __( 'Sidebar widgets', 'foundationpress' ), 'description' => __( 'Drag widgets to this sidebar container.', 'foundationpress' ), 'before_widget' => '<article id="%1$s" class="widget %2$s">', 'after_widget' => '</article>', 'before_title' => '<h6>', 'after_title' => '</h6>', )); register_sidebar(array( 'id' => 'footer-widgets', 'name' => __( 'Footer widgets', 'foundationpress' ), 'description' => __( 'Drag widgets to this footer container', 'foundationpress' ), 'before_widget' => '<article id="%1$s" class="small-12 columns widget %2$s">', 'after_widget' => '</article>', 'before_title' => '<h6>', 'after_title' => '</h6>', )); } add_action( 'widgets_init', 'foundationpress_sidebar_widgets' ); endif;
kaneohe/kaneohe
library/widget-areas.php
PHP
mit
1,023
using System; using Silphid.Extensions; using UniRx; using UnityEngine; using UnityEngine.UI; namespace Silphid.Tweenzup { public static class Tween { #region Range public static IObservable<float> Range(float duration, IEaser easer = null) => new TweenObservable(duration, easer); public static IObservable<float> Range(Func<float> selector, float target, float duration, IEaser easer = null) => Observable.Defer( () => { var source = selector(); return source.IsAlmostEqualTo(target) ? Observable.Return(target) : Range(duration, easer) .Lerp(source, target); }); public static IObservable<Vector2> Range(Func<Vector2> selector, Vector2 target, float duration, IEaser easer = null) => Observable.Defer( () => { var source = selector(); return source.IsAlmostEqualTo(target) ? Observable.Return(target) : Range(duration, easer) .Lerp(source, target); }); public static IObservable<Vector3> Range(Func<Vector3> selector, Vector3 target, float duration, IEaser easer = null) => Observable.Defer( () => { var source = selector(); return source.IsAlmostEqualTo(target) ? Observable.Return(target) : Range(duration, easer) .Lerp(source, target); }); public static IObservable<Quaternion> Range(Func<Quaternion> selector, Quaternion target, float duration, IEaser easer = null) => Observable.Defer( () => { var source = selector(); return source.IsAlmostEqualTo(target) ? Observable.Return(target) : Range(duration, easer) .Lerp(source, target); }); public static IObservable<Color> Range(Func<Color> selector, Color target, float duration, IEaser easer = null) => Observable.Defer( () => { var source = selector(); return source.IsAlmostEqualTo(target) ? Observable.Return(target) : Range(duration, easer) .Lerp(source, target); }); public static IObservable<DateTime> Range(Func<DateTime> selector, DateTime target, float duration, IEaser easer = null) => Observable.Defer( () => { var source = selector(); return source == target ? Observable.Return(target) : Range(duration, easer) .Lerp(source, target); }); public static IObservable<TimeSpan> Range(Func<TimeSpan> selector, TimeSpan target, float duration, IEaser easer = null) => Observable.Defer( () => { var source = selector(); return source == target ? Observable.Return(target) : Range(duration, easer) .Lerp(source, target); }); #endregion #region ReactiveProperty TweenTo public static ICompletable TweenTo(this IReactiveProperty<float> This, float target, float duration, IEaser easer = null) => Range(() => This.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<float?> This, float target, float duration, IEaser easer = null) => Range(() => This.Value.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<float> This, float target, float duration, Func<float> velocitySelector, IEaser easer = null) => new TweenFloatWithInitialVelocityObservable(() => This.Value, velocitySelector, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<float?> This, float target, float duration, Func<float> velocitySelector, IEaser easer = null) => new TweenFloatWithInitialVelocityObservable( () => This.Value.Value, velocitySelector, target, duration, easer).Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenToShiftingTarget(this IReactiveProperty<float> This, IObservable<float> target, float duration, IEaser easer = null) => new TweenFloatToShiftingTargetCompletable(This, target, duration, easer); public static ICompletable TweenTo(this IReactiveProperty<Vector2> This, Vector2 target, float duration, IEaser easer = null) => Range(() => This.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Vector2?> This, Vector2 target, float duration, IEaser easer = null) => Range(() => This.Value.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Vector2> This, Vector2 target, float duration, Func<Vector2> velocitySelector, IEaser easer = null) => new TweenVector2WithInitialVelocityObservable(() => This.Value, velocitySelector, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Vector2?> This, Vector2 target, float duration, Func<Vector2> velocitySelector, IEaser easer = null) => new TweenVector2WithInitialVelocityObservable( () => This.Value.Value, velocitySelector, target, duration, easer).Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenToShiftingTarget(this IReactiveProperty<Vector2> This, IObservable<Vector2> target, float duration, IEaser easer = null) => new TweenVector2ToShiftingTargetCompletable(This, target, duration, easer); public static ICompletable TweenTo(this IReactiveProperty<Vector3> This, Vector3 target, float duration, IEaser easer = null) => Range(() => This.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Vector3?> This, Vector3 target, float duration, IEaser easer = null) => Range(() => This.Value.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Vector3> This, Vector3 target, float duration, Func<Vector3> velocitySelector, IEaser easer = null) => new TweenVector3WithInitialVelocityObservable(() => This.Value, velocitySelector, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Vector3?> This, Vector3 target, float duration, Func<Vector3> velocitySelector, IEaser easer = null) => new TweenVector3WithInitialVelocityObservable( () => This.Value.Value, velocitySelector, target, duration, easer).Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenToShiftingTarget(this IReactiveProperty<Vector3> This, IObservable<Vector3> target, float duration, IEaser easer = null) => new TweenVector3ToShiftingTargetCompletable(This, target, duration, easer); public static ICompletable TweenTo(this IReactiveProperty<Quaternion> This, Quaternion target, float duration, IEaser easer = null) => Range(() => This.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Quaternion?> This, Quaternion target, float duration, IEaser easer = null) => Range(() => This.Value.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Color> This, Color target, float duration, IEaser easer = null) => Range(() => This.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<Color?> This, Color target, float duration, IEaser easer = null) => Range(() => This.Value.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<DateTime> This, DateTime target, float duration, IEaser easer = null) => Range(() => This.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<DateTime?> This, DateTime target, float duration, IEaser easer = null) => Range(() => This.Value.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<TimeSpan> This, TimeSpan target, float duration, IEaser easer = null) => Range(() => This.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); public static ICompletable TweenTo(this IReactiveProperty<TimeSpan?> This, TimeSpan target, float duration, IEaser easer = null) => Range(() => This.Value.Value, target, duration, easer) .Do(x => This.Value = x) .AsCompletable(); #endregion #region Unity public static ICompletable FadeTo(this CanvasGroup This, float target, float duration, IEaser easer = null) => Range(() => This.alpha, target, duration, easer) .Do(x => This.alpha = x) .AsCompletable(); public static ICompletable FadeIn(this CanvasGroup This, float duration, IEaser easer = null) => Range(() => This.alpha, 1f, duration, easer) .Do(x => This.alpha = x) .AsCompletable(); public static ICompletable FadeOut(this CanvasGroup This, float duration, IEaser easer = null) => Range(() => This.alpha, 0f, duration, easer) .Do(x => This.alpha = x) .AsCompletable(); public static ICompletable TweenColorTo(this Graphic This, Color target, float duration, IEaser easer = null) => Range(() => This.color, target, duration, easer) .Do(x => This.color = x) .AsCompletable(); public static ICompletable MoveTo(this Transform This, Vector3 target, float duration, IEaser easer = null) => Range(() => This.localPosition, target, duration, easer) .Do(x => This.localPosition = x) .AsCompletable(); public static ICompletable MoveXBy(this Transform This, float delta, float duration, IEaser easer = null) => This.MoveBy(delta * Vector3.right, duration, easer); public static ICompletable MoveYBy(this Transform This, float delta, float duration, IEaser easer = null) => This.MoveBy(delta * Vector3.up, duration, easer); public static ICompletable MoveZBy(this Transform This, float delta, float duration, IEaser easer = null) => This.MoveBy(delta * Vector3.forward, duration, easer); public static ICompletable MoveBy(this Transform This, Vector3 delta, float duration, IEaser easer = null) => Completable.Defer( () => { var source = This.localPosition; var target = source + delta; return Range(duration, easer) .Lerp(source, target) .Do(x => This.localPosition = x) .AsCompletable(); }); public static ICompletable WorldMoveTo(this Transform This, Vector3 target, float duration, IEaser easer = null) => Range(() => This.position, target, duration, easer) .Do(x => This.position = x) .AsCompletable(); public static ICompletable LocalMoveToWorld(this Transform This, Vector3 target, float duration, IEaser easer = null) { var localTarget = This.parent.InverseTransformPoint(target); return Range(() => This.localPosition, localTarget, duration, easer) .Do(x => This.localPosition = x) .AsCompletable(); } public static ICompletable RotateTo(this Transform This, Quaternion target, float duration, IEaser easer = null) => Range(() => This.localRotation, target, duration, easer) .Do(x => This.localRotation = x) .AsCompletable(); public static ICompletable RotateTo(this Transform This, Vector3 target, float duration, IEaser easer = null) => Range(() => This.localRotation, Quaternion.Euler(target), duration, easer) .Do(x => This.localRotation = x) .AsCompletable(); public static ICompletable WorldRotateTo(this Transform This, Quaternion target, float duration, IEaser easer = null) => Range(() => This.rotation, target, duration, easer) .Do(x => This.rotation = x) .AsCompletable(); public static ICompletable WorldRotateTo(this Transform This, Vector3 target, float duration, IEaser easer = null) => Range(() => This.rotation, Quaternion.Euler(target), duration, easer) .Do(x => This.rotation = x) .AsCompletable(); public static ICompletable ScaleTo(this Transform This, Vector3 target, float duration, IEaser easer = null) => Range(() => This.localScale, target, duration, easer) .Do(x => This.localScale = x) .AsCompletable(); public static ICompletable ScaleTo(this Transform This, float target, float duration, IEaser easer = null) => Range(() => This.localScale, new Vector3(target, target, target), duration, easer) .Do(x => This.localScale = x) .AsCompletable(); public static ICompletable MoveAnchorTo(this RectTransform This, Vector2 target, float duration, IEaser easer = null) => Range(() => This.anchoredPosition, target, duration, easer) .Do(x => This.anchoredPosition = x) .AsCompletable(); public static ICompletable MoveAnchorXTo(this RectTransform This, float target, float duration, IEaser easer = null) => Range(() => This.anchoredPosition.x, target, duration, easer) .Do(x => This.anchoredPosition = This.anchoredPosition.WithX(x)) .AsCompletable(); public static ICompletable MoveAnchorYTo(this RectTransform This, float target, float duration, IEaser easer = null) => Range(() => This.anchoredPosition.y, target, duration, easer) .Do(y => This.anchoredPosition = This.anchoredPosition.WithY(y)) .AsCompletable(); public static ICompletable ChangeTopOffsetBy(this RectTransform This, float target, float duration, IEaser easer = null) => Range(() => This.offsetMax.y, This.offsetMax.y - target, duration, easer) .Do(y => This.offsetMax = new Vector2(This.offsetMax.x, y)) .AsCompletable(); #endregion } }
Silphid/Silphid.Unity
Sources/Tweenzup/Tween.cs
C#
mit
22,290
package bright.zheng.android.httpclient; import java.io.IOException; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import org.apache.http.HttpEntity; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONTokener; import android.util.Log; import bright.zheng.android.Constants; /** * A handler wrapper for bridging the response and the callback. * * @author bright_zheng * */ public class AsyncResponseHandler{ private Type type; @SuppressWarnings("unchecked") public <E> void onResponseReceived(HttpEntity response, ResponseCallback<E> callback){ this.type = getType(getGenericClass(callback.getClass())); Object genericResponse = null; try { switch(this.type){ case JSONArray:{ String responseBody = EntityUtils.toString(response); Log.i(Constants.TAG, "Return JSON String: " + responseBody); if(responseBody!=null && responseBody.trim().length()>0){ genericResponse = new JSONTokener(responseBody).nextValue(); } break; } case JSONObject:{ String responseBody = EntityUtils.toString(response); Log.i(Constants.TAG, "Return JSON String: " + responseBody); if(responseBody!=null && responseBody.trim().length()>0){ genericResponse = new JSONTokener(responseBody).nextValue(); } break; } case InputStream:{ genericResponse = response.getContent(); break; } default:{ genericResponse = EntityUtils.toString(response); } } callback.onSuccess((E) genericResponse); } catch(IOException e) { callback.onFailure(e); } catch (JSONException e) { callback.onFailure(e); } } public <E> void onResponseReceived(Throwable response, ResponseCallback<E> callback){ callback.onFailure(response); } private Class<?> getGenericClass(Class<?> cls) { ParameterizedType parameterizedType = ((ParameterizedType) cls.getGenericInterfaces()[0]); Object genericClass = parameterizedType.getActualTypeArguments()[0]; if (genericClass instanceof ParameterizedType) { return (Class<?>) ((ParameterizedType) genericClass).getRawType(); } else if (genericClass instanceof GenericArrayType) { return (Class<?>) ((GenericArrayType) genericClass).getGenericComponentType(); } else { return (Class<?>) genericClass; } } private Type getType(Class<?> clazz){ Type result = Type.String; for (Type type: Type.values()){ if (type.value.equals(clazz.getSimpleName())){ result = type; break; } } return result; } private enum Type { JSONArray ("JSONArray"), JSONObject ("JSONObject"), InputStream ("InputStream"), String ("String"); private final String value; Type(String value){ this.value = value; } } }
itstarting/android-async-httpclient
src/main/bright/zheng/android/httpclient/AsyncResponseHandler.java
Java
mit
3,026
describe("Conversion for", function() { describe("arffToJson", function() { it("convert arff file, basic types", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n@ATTRIBUTE see STRING\n\n@DATA\n1,3.5,do\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].bar).toBe(3.5); expect(json[0].see).toBe('do'); }); }); it("convert arff file, include carriage returns", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n1,3.5,do\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].bar).toBe(3.5); expect(json[0].see).toBe('do'); }); }); it("convert arff file, empty data", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n,2.0,saw\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(isNaN(json[0].foo)).toBe(true); expect(json[0].bar).toBe(2.0); expect(json[0].see).toBe('saw'); }); }); it("convert arff file, wrong type, numeric - string", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\nbleh,2.0,saw\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(isNaN(json[0].foo)).toBe(true); expect(json[0].bar).toBe(2.0); expect(json[0].see).toBe('saw'); }); }); it("convert arff file, wrong type, real - string", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n1,$,saw\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(isNaN(json[0].bar)).toBe(true); expect(json[0].see).toBe('saw'); }); }); it("convert arff file, wrong type, string - numeric", function() { //Given: var arff = "@RELATION iris\n\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n\n@ATTRIBUTE see STRING\n\n@DATA\n1,2.0,2\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].bar).toBe(2.0); expect(json[0].see).toBe('2'); }); }); it("convert arff file, missing data value", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE bar REAL\n@ATTRIBUTE see STRING\n\n@DATA\n3.5,do\n2,2.5,while\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(2); expect(json[0].bar).toBe(2.5); expect(json[0].see).toBe('while'); expect(errors[0].message).toBe('data missing, not enough values to fill expected attributes'); }); }); it("convert arff file, basic types", function() { //Given: var arff = "@RELATION iris\n\n@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE class {lots,of,things}\n@ATTRIBUTE see STRING\n\n@DATA\n1,of,do\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].class).toBe('of'); expect(json[0].see).toBe('do'); }); }); it("convert arff file, carriage return", function() { //Given: var arff = "@RELATION iris\r@ATTRIBUTE foo NUMERIC\n@ATTRIBUTE class {lots,of,things}\r\n@ATTRIBUTE see STRING\r\r@DATA\r1,of,do\r\r"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1); expect(json[0].class).toBe('of'); expect(json[0].see).toBe('do'); }); }); it("convert arff file, tabs in attributes", function() { //Given: var arff = "@RELATION iris\n@ATTRIBUTE foo REAL\n@ATTRIBUTE bar \t REAL\n@ATTRIBUTE joe \tREAL\n@ATTRIBUTE see\tREAL\n\n@DATA\n1.1,2.2,3.3,4.4\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1.1); expect(json[0].bar).toBe(2.2); expect(json[0].joe).toBe(3.3); expect(json[0].see).toBe(4.4); }); }); it("convert arff file, value wrapped in string", function() { //Given: var arff = "@RELATION iris\n@ATTRIBUTE foo REAL\n@ATTRIBUTE bar string\n\n@DATA\n1.1,do\n2.2,\'while\'\n\n"; insight.conversion.arffToJson(arff, function(errors, json) { //Then: expect(json[0].foo).toBe(1.1); expect(json[0].bar).toBe('do'); expect(json[1].foo).toBe(2.2); expect(json[1].bar).toBe('while'); }); }); }); });
ScottLogic/insight
tests/utils/Conversion.spec.js
JavaScript
mit
5,806
/** * @file This prototype manages all game entities. * * @author Human Interactive */ "use strict"; var GameEntity = require( "./GameEntity" ); var Player = require( "./Player" ); var Vehicle = require( "./Vehicle" ); /** * Creates the entity manager. * * @constructor */ function EntityManager() { Object.defineProperties( this, { entities : { value : [], configurable : false, enumerable : false, writable : false } } ); } /** * Creates the player object * * @param {World} world - The reference to the world object. * * @returns {Player} The new player. */ EntityManager.prototype.createPlayer = function( world ) { var player = new Player( world ); this.addEntity( player ); return player; }; /** * Creates a vehicle, a moving entity that uses steering behaviors. * * @param {World} world - The reference to the world object. * @param {THREE.Object3D} object3D - The 3D object of the entity. * @param {number} numSamplesForSmoothing - How many samples the smoother will use to average the velocity. * * @returns {Vehicle} The new vehicle. */ EntityManager.prototype.createVehicle = function( world, object3D, numSamplesForSmoothing ) { var vehicle = new Vehicle( world, object3D, numSamplesForSmoothing ); this.addEntity( vehicle ); return vehicle; }; /** * Updates all entities. * * @param {number} delta - The time delta value. */ EntityManager.prototype.update = function( delta ) { for ( var index = 0; index < this.entities.length; index++ ) { this.entities[ index ].update( delta ); } }; /** * Gets an entity by its ID. * * @param {number} id - The ID of the entity. * * @returns {GameEntity} The entity. */ EntityManager.prototype.getEntity = function( id ) { var entity = null; for ( var index = 0; index < this.entities.length; index++ ) { if ( this.entities[ index ].id === id ) { entity = this.entities[ index ]; break; } } if ( entity === null ) { throw "ERROR: EntityManager: Entity with ID " + id + " not existing."; } else { return entity; } }; /** * Adds a single entity to the internal array. * * @param {GameEntity} entity - The entity to add. */ EntityManager.prototype.addEntity = function( entity ) { this.entities.push( entity ); }; /** * Removes a single entity from the internal array. * * @param {GameEntity} entity - The entity to remove. */ EntityManager.prototype.removeEntity = function( entity ) { var index = this.entities.indexOf( entity ); this.entities.splice( index, 1 ); }; /** * Removes all entities from the internal array. * * @param {boolean} isClear - Should also all world entities be removed? */ EntityManager.prototype.removeEntities = function( isClear ) { if ( isClear === true ) { this.entities.length = 0; } else { for ( var index = this.entities.length - 1; index >= 0; index-- ) { // only remove entities with scope "STAGE" if ( this.entities[ index ].scope === GameEntity.SCOPE.STAGE ) { this.remove( this.children[ index ] ); } } } }; module.exports = new EntityManager();
Mugen87/yume
src/javascript/engine/game/entity/EntityManager.js
JavaScript
mit
3,096
from uiot import * d("led", "blue", onboardled, "off", "on") d("button", "forward", d3, 0, 1) d("button", "back", d4, 0, 1) run()
ulno/micropython-extra-ulno
examples/presentation_remote/remote1/copy/autostart.py
Python
mit
132
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Sayings of the Messenger P.B.U.H</title> <link rel="stylesheet" href="https://bootswatch.com/slate/bootstrap.min.css"> <?= link_tag('assets/css/ahadith.css') ?> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Sayings Of the Messenger P.B.U.H</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li ><a href="<?php echo site_url('subscribe') ?>">Subscribe</a></li> <li><a href="<?php echo site_url('message') ?>">Message</a></li> <li ><a href="<?php echo site_url('hadith') ?>">Hadith</a></li> <li ><a href="<?php echo site_url('twitter') ?>">Twitter</a></li> <li class="active"><a href="<?php echo site_url('telegram') ?>">Telegram</a></li> </ul> </div> </div> </nav> </head> <body> <div class="container"> <?php echo form_open_multipart('telegram/send', ['class'=>'form-horizontal']) ?> <?= form_hidden('created_at', date('Y-m-d H:i:s')) ?> <fieldset> <legend>Telegram</legend> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label for="inputEmail" class="col-lg-4 control-label">Write Text</label> <div class="col-lg-8"> <?php echo form_textarea(['name'=>'body','class'=>'form-control','placeholder'=>'Text', 'value'=> set_value('body')]) ?> </div> </div> </div> <div class="col-lg-6"> <?php echo form_error('body'); ?> </div> </div> <div class="row"> <div class="col-lg-6"> <div class="form-group"> <label for="inputEmail" class="col-lg-4 control-label">Select Image</label> <div class="col-lg-8"> <?php echo form_upload(['name'=>'image','class'=>'form-control']); ?> </div> </div> </div> <div class="col-lg-6"> <?php if(isset($upload_error)) echo $upload_error ?> </div> </div> <div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <?php echo form_reset(['name'=>'reset','value'=>'Reset','class'=>'btn btn-default']), form_submit(['name'=>'submit','value'=>'Submit','class'=>'btn btn-primary']); ?> </div> </div> </fieldset> </form> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script> </body> </html>
naanT/Subscribe
application/views/telegram.php
PHP
mit
3,361
using System; using Aspose.Email.Exchange; namespace Aspose.Email.Examples.CSharp.Email.Exchange_EWS { class SaveExchangeTaskToDisc { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_Exchange(); string dstEmail = dataDir + "Message.msg"; // ExStart:SaveExchangeTaskToDisc ExchangeTask task = new ExchangeTask(); task.Subject = "TASK-ID - " + Guid.NewGuid(); task.Status = ExchangeTaskStatus.InProgress; task.StartDate = DateTime.Now; task.DueDate = task.StartDate.AddDays(3); task.Save(dstEmail); // ExEnd:SaveExchangeTaskToDisc Console.WriteLine(Environment.NewLine + "Task saved on disk successfully at " + dstEmail); } } }
maria-shahid-aspose/Aspose.Email-for-.NET
Examples/CSharp/Exchange_EWS/SaveExchangeTaskToDisc.cs
C#
mit
865
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ServiceBus.Messaging; namespace EReaderConsole { class Program { static void Main(string[] args) { ReceiveLoop(); Console.ReadLine(); } private static async void ReceiveLoop() { var ehClient = EventHubClient.CreateFromConnectionString("Endpoint=sb://myiotdemo-ns.servicebus.windows.net/;SharedAccessKeyName=Listen;SharedAccessKey=unr9vekIY5y0Km4l4l4loATBjoaw6J6lvmaYNv+MYhU=", "myiotdemoeventhub"); var ehReceiver = await ehClient.GetConsumerGroup(EventHubConsumerGroup.DefaultGroupName).CreateReceiverAsync(("1")); do { try { var message = await ehReceiver.ReceiveAsync(); if (message != null) { string msg; var info = message.GetBytes(); msg = Encoding.UTF8.GetString(info); Console.WriteLine("Processing: Seq number {0} Offset {1} Partition {2} EnqueueTimeUtc {3} Message {4}", message.SequenceNumber, message.Offset, message.PartitionKey, message.EnqueuedTimeUtc.ToShortTimeString(), msg); } } catch (Exception exception) { Console.WriteLine("exception on receive {0}", exception.Message); } } while (true); } } }
DotNETForDevices/IoTSamples
EventHubSample/EReaderConsole/Program.cs
C#
mit
1,625
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2018_08_01 module Models # # The serviceName of an AvailableDelegation indicates a possible delegation # for a subnet. # class AvailableDelegation include MsRestAzure # @return [String] The name of the AvailableDelegation resource. attr_accessor :name # @return [String] A unique identifier of the AvailableDelegation # resource. attr_accessor :id # @return [String] Resource type. attr_accessor :type # @return [String] The name of the service and resource attr_accessor :service_name # @return [Array<String>] Describes the actions permitted to the service # upon delegation attr_accessor :actions # # Mapper for AvailableDelegation class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'AvailableDelegation', type: { name: 'Composite', class_name: 'AvailableDelegation', model_properties: { name: { client_side_validation: true, required: false, serialized_name: 'name', type: { name: 'String' } }, id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, type: { client_side_validation: true, required: false, serialized_name: 'type', type: { name: 'String' } }, service_name: { client_side_validation: true, required: false, serialized_name: 'serviceName', type: { name: 'String' } }, actions: { client_side_validation: true, required: false, serialized_name: 'actions', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2018-08-01/generated/azure_mgmt_network/models/available_delegation.rb
Ruby
mit
2,863
require "securerandom" require "monitor" require "dalli" require "dalli/cas/client" require "redis" require "msgpack" require "suo/version" require "suo/errors" require "suo/client/base" require "suo/client/memcached" require "suo/client/redis"
nickelser/suo
lib/suo.rb
Ruby
mit
250
import unittest from Hero import Hero class HeroTest(unittest.TestCase): def setUp(self): self.hero = Hero(10, 0) def test_hero_default(self): self.assertEqual( (self.hero.health, self.hero.magic, self.hero.x, self.hero.y), (10, 0, None, None)) def test_setHealth(self): self.hero.setHealth(-1) self.assertEqual(self.hero.health, 0) self.hero.setHealth(5) self.assertEqual(self.hero.health, 5) if __name__ == '__main__': unittest.main()
vpachedzhi/Hero_Game_Qt
tests.py
Python
mit
561
using System.Diagnostics.CodeAnalysis; using System.Linq; using ContentPatcher.Framework.Conditions; using ContentPatcher.Framework.ConfigModels; using ContentPatcher.Framework.Lexing; using Pathoschild.Stardew.Common.Utilities; using StardewModdingAPI; namespace ContentPatcher.Framework.Migrations { /// <summary>Validates patches for format version 1.19.</summary> [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "Named for clarity.")] internal class Migration_1_19 : BaseMigration { /********* ** Fields *********/ /// <summary>Handles parsing raw strings into tokens.</summary> private readonly Lexer Lexer = Lexer.Instance; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> public Migration_1_19() : base(new SemanticVersion(1, 19, 0)) { this.AddedTokens.AddMany( ConditionType.Time.ToString() ); } /// <inheritdoc /> public override bool TryMigrate(ContentConfig content, out string error) { if (!base.TryMigrate(content, out error)) return false; foreach (PatchConfig patch in content.Changes) { // 1.19 adds PatchMode for maps if (patch.PatchMode != null && this.GetAction(patch) == PatchType.EditMap) { error = this.GetNounPhraseError($"using {nameof(patch.PatchMode)} for a map patch"); return false; } // 1.19 adds OnTimeChange update rate if (this.GetEnum<UpdateRate>(patch.Update) == UpdateRate.OnTimeChange) { error = this.GetNounPhraseError($"using the {nameof(UpdateRate.OnTimeChange)} update rate"); return false; } // 1.19 adds multiple FromFile values if (this.HasMultipleValues(patch.FromFile)) { error = this.GetNounPhraseError($"specifying multiple {nameof(PatchConfig.FromFile)} values"); return false; } } return true; } /// <inheritdoc /> public override bool TryMigrate(Condition condition, out string error) { // 1.19 adds boolean query expressions bool isQuery = condition.Name?.EqualsIgnoreCase(nameof(ConditionType.Query)) == true; if (isQuery) { InvariantHashSet values = condition.Values?.SplitValuesUnique(); if (values?.Any() == true && values.All(p => bool.TryParse(p, out bool _))) { error = "using boolean query expressions"; return false; } } return base.TryMigrate(condition, out error); } /********* ** Private methods *********/ /// <summary>Get whether a value has multiple top-level lexical values.</summary> /// <param name="raw">The raw unparsed value.</param> private bool HasMultipleValues(string raw) { // quick check if (raw?.Contains(",") != true) return false; // lexical check (this ensures a value like '{{Random: a, b}}' isn't incorrectly treated as two values) return this.Lexer .SplitLexically(raw) .Take(2) .Count() > 1; } } }
Pathoschild/StardewMods
ContentPatcher/Framework/Migrations/Migration_1_19.cs
C#
mit
3,626
Cliente = Backbone.Model.extend({ defaults: { empresa: 'Unknow', telefonos: [] }, initialize: function(attrs, opts){ } }); var cliente = new Cliente({nombre: 'Antonio', apellidos: 'García Ros'}); cliente.set({edad: 31, soltero: false}); alert(cliente.get('edad')); // 31
jesuscuesta/Backbone
02.- Modelos/07.- Model - modificando atributos/hello.js
JavaScript
mit
304
module.exports.up = async db => { await db.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"'); await db.raw('CREATE EXTENSION IF NOT EXISTS "hstore"'); await db.schema.createTable('role', table => { // pk table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('name', 64).notNullable().unique(); table.string('image', 200).nullable(); table.text('description').nullable(); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); // indexes table.index('name'); table.index('uuid'); }); await db.schema.createTable('user', table => { // pk table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('email', 100).unique().notNullable(); table.string('password', 64).notNullable(); table.string('firstName', 50).notNullable(); table.string('lastName', 50).notNullable(); table.string('username', 115).unique().notNullable(); table .string('avatarUrl', 255) .defaultTo('https://boldr.io/images/unknown-avatar.png'); table.string('profileImage', 255).nullable(); table.string('location', 100).nullable(); table.text('bio').nullable(); table.date('birthday', 8).nullable(); table.string('website', 100).nullable(); table.string('language', 10).notNullable().defaultTo('en_US'); table.json('social').nullable(); table.boolean('verified').defaultTo(false); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.timestamp('deletedAt').nullable().defaultTo(null); // fk // indexes table.index('username'); table.index('verified'); table.index('email'); }); await db.schema.createTable('verification_token', table => { // pk table.increments('id').unsigned().primary(); table.string('ip', 32); table.string('token'); table.boolean('used').defaultTo(false); table.uuid('userId').unsigned(); table.timestamp('createdAt').defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); // fk table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); // indexes table.index('token'); }); await db.schema.createTable('reset_token', table => { // pk table.increments('id').unsigned().primary(); table.string('ip', 32); table.string('token', 255).comment('hashed token'); table.dateTime('expiration'); table.boolean('used').defaultTo(false); table.uuid('userId').unsigned(); table.timestamp('createdAt').defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); // fk table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); // indexes table.index('token'); }); await db.schema.createTable('tag', table => { table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('name').notNullable().unique(); table.string('description').nullable(); table.index('name'); }); await db.schema.createTable('post', table => { // pk | uuid table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('title', 140).unique().notNullable(); table.string('slug', 140).unique().notNullable(); table.string('featureImage', 255).nullable(); table.json('attachments').nullable(); table.json('meta').nullable(); table.boolean('featured').defaultTo(false); table.json('rawContent'); table.text('content').notNullable(); table.text('excerpt').notNullable(); table.uuid('userId').unsigned().notNullable(); table.boolean('published').defaultTo(true); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.timestamp('deletedAt').nullable().defaultTo(null); // fk | uuid table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table.index('slug'); table.index('published'); table.index('createdAt'); }); await db.schema.createTable('attachment', table => { // pk | uuid table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('fileName').notNullable(); table.string('safeName').notNullable(); table.string('fileDescription'); table.string('fileType'); table.string('path'); table.uuid('userId').unsigned().notNullable(); table.string('url').notNullable(); table.timestamp('createdAt').defaultTo(db.fn.now()); table.timestamp('updatedAt').defaultTo(db.fn.now()); table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('setting', table => { table.increments('id').unsigned().primary(); table.string('key', 100).notNullable(); table.string('label', 100).notNullable(); table.string('value', 255).notNullable(); table.string('description', 255).notNullable(); table.index('key'); table.index('value'); }); await db.schema.createTable('menu', table => { table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('name').notNullable(); table.string('safeName').notNullable(); table.json('attributes').nullable(); table.boolean('restricted').default(false); table.index('safeName'); table.index('uuid'); }); await db.schema.createTable('menu_detail', table => { table.increments('id').unsigned().primary(); // uuid table.uuid('uuid').notNullable().defaultTo(db.raw('uuid_generate_v4()')); table.string('safeName', 50).notNullable(); table.string('name', 50).notNullable(); table.string('cssClassname', 255).nullable(); table.boolean('hasDropdown').default(false); table.integer('order'); table .string('mobileHref', 255) .nullable() .comment( 'Mobile href is applicable in cases where the item is a dropdown' + 'trigger on desktop. Without a mobile href, it will only be text.'); // eslint-disable-line table.string('href').notNullable(); table.string('icon').nullable(); table.json('children'); table.index('safeName'); table.index('uuid'); table.index('href'); }); await db.schema.createTableIfNotExists('template', table => { table.increments('id').unsigned().primary(); table.uuid('uuid'); table.string('name', 100).unique().notNullable(); table.string('slug', 110).notNullable(); table.json('meta'); table.json('content'); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.index('slug'); table.index('uuid'); }); await db.schema.createTable('page', table => { table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.string('name').unique().notNullable(); table.string('slug').unique(); table.string('url').unique().notNullable(); table.json('layout'); table.json('data'); table.enu('status', ['published', 'draft', 'archived']).defaultTo('draft'); table.boolean('restricted').default(false); table.json('meta'); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table.index('name'); }); await db.schema.createTable('activity', table => { table .uuid('id') .notNullable() .defaultTo(db.raw('uuid_generate_v4()')) .primary(); table.uuid('userId').unsigned().notNullable(); table.enu('type', ['create', 'update', 'delete', 'register']).notNullable(); table.uuid('activityPost').unsigned(); table.uuid('activityUser').unsigned(); table.uuid('activityAttachment').unsigned(); table.integer('activityTag').unsigned(); table.integer('activityMenuDetail').unsigned(); table.integer('activityTemplate').unsigned(); table.uuid('activityPage').unsigned(); table.integer('activityRole').unsigned(); table.timestamp('createdAt').notNullable().defaultTo(db.fn.now()); table.timestamp('updatedAt').nullable().defaultTo(null); table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityPost') .references('id') .inTable('post') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityUser') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityAttachment') .references('id') .inTable('attachment') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityTag') .references('id') .inTable('tag') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityMenuDetail') .references('id') .inTable('menu_detail') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityTemplate') .references('id') .inTable('template') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityPage') .references('id') .inTable('page') .onDelete('cascade') .onUpdate('cascade'); table .foreign('activityRole') .references('id') .inTable('role') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('post_tag', table => { table.increments('id').primary(); table.uuid('postId').unsigned().notNullable(); table.integer('tagId').unsigned().notNullable(); table.unique(['postId', 'tagId']); table .foreign('postId') .references('id') .inTable('post') .onDelete('cascade') .onUpdate('cascade'); table .foreign('tagId') .references('id') .inTable('tag') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('user_role', table => { table.increments('id').primary(); table.uuid('userId').unsigned().notNullable(); table.integer('roleId').unsigned().notNullable(); table.unique(['userId', 'roleId']); table .foreign('userId') .references('id') .inTable('user') .onDelete('cascade') .onUpdate('cascade'); table .foreign('roleId') .references('id') .inTable('role') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('template_page', table => { table.increments('id').primary(); table.uuid('pageId').unsigned().notNullable(); table.integer('templateId').unsigned().notNullable(); table.unique(['pageId', 'templateId']); table .foreign('pageId') .references('id') .inTable('page') .onDelete('cascade') .onUpdate('cascade'); table .foreign('templateId') .references('id') .inTable('template') .onDelete('cascade') .onUpdate('cascade'); }); await db.schema.createTable('menu_menu_detail', table => { table.integer('menuId').notNullable().references('id').inTable('menu'); table .integer('menuDetailId') .notNullable() .references('id') .inTable('menu_detail'); table.primary(['menuId', 'menuDetailId']); }); }; module.exports.down = async db => { await db.schema.dropTableIfExists('role'); await db.schema.dropTableIfExists('user'); await db.schema.dropTableIfExists('tag'); await db.schema.dropTableIfExists('post'); await db.schema.dropTableIfExists('attachment'); await db.schema.dropTableIfExists('setting'); await db.schema.dropTableIfExists('menu'); await db.schema.dropTableIfExists('menu_detail'); await db.schema.dropTableIfExists('template'); await db.schema.dropTableIfExists('page'); await db.schema.dropTableIfExists('activity'); await db.schema.dropTableIfExists('verification_token'); await db.schema.dropTableIfExists('reset_token'); await db.schema.dropTableIfExists('post_tag'); await db.schema.dropTableIfExists('user_role'); await db.schema.dropTableIfExists('template_page'); await db.schema.dropTableIfExists('menu_menu_detail'); }; module.exports.configuration = { transaction: true };
boldr/boldr-api
db/migrations/201701270219_initial.js
JavaScript
mit
12,958
// The csuuid package generates and parses C# formatted UUIDs. package csuuid import ( "strings" "encoding/hex" "errors" ) var ( ErrInvalid error = errors.New("csuuid: invalid uuid") ) // CSUUID converts the provided byte slice representation of a C# encoded UUID to the // proper string represntation of that UUID, consistant with the string representation that would // be produced by C# backed APIs using the same data. func CSUUID(bd []byte) (string, error) { if len(bd) != 16 { return "", ErrInvalid } hx := make([]byte, 36) // Encode raw bytes to hex prior to rearranging. hex.Encode(hx, bd) // Non transposed bytes appended to end. copy(hx[24:], hx[20:]) copy(hx[19:], hx[16:20]) // Helper function to mirror and move character pairs. transpose := func(offset, dest, chars int) { for i := 0; i < chars/2; i += 2 { start, end := offset+i, offset+chars-i-1 hx[start], hx[start+1], hx[end], hx[end-1] = hx[end-1], hx[end], hx[start+1], hx[start] } if offset != dest { copy(hx[dest:], hx[offset:offset+chars]) } } // Transpose and move byte portions to the correct locations. transpose(12, 14, 4) transpose(8, 9, 4) transpose(0, 0, 8) // Insert seperating dashes into the correct positions. hx[8], hx[13], hx[18], hx[23] = '-', '-', '-', '-' return string(hx), nil } // FromCSUUID converts the provided UUID string representation to C# encoded // byte slice data. func FromCSUUID(formatted string) ([]byte, error) { if (len(formatted) != 36) { return nil, ErrInvalid } cleared := make([]byte, 16) // Decode the formatted UUID string from dash-separated hex to a byte slice. if _, err := hex.Decode(cleared, []byte(strings.Replace(formatted, "-", "", -1))); err != nil { return nil, err } // Helper function to mirror and move byte sets. transpose := func(offset, chars int) { for i := 0; i < chars/2; i += 1 { start, end := offset+i, offset+chars-i-1 cleared[start], cleared[end] = cleared[end], cleared[start] } } // Transpose and move byte segments to match the MS format format. transpose(6, 2) transpose(4, 2) transpose(0, 4) return cleared, nil }
ecofit-networks/go-csuuid
csuuid.go
GO
mit
2,150
import numpy as np import matplotlib import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as anm #plt.rcParams['animation.ffmpeg_path'] = '/usr/bin/ffmpeg' plt.close('all') data = np.loadtxt('solar_system.dat') data2 = data[:,0:15] fig = plt.figure() ax = p3.Axes3D(fig) ax.set_xlim3d([np.min(data2[:,0::3]), np.max(data2[:,0::3])]) ax.set_xlabel('X') ax.set_ylim3d([np.min(data2[:,1::3]), np.max(data2[:,1::3])]) ax.set_ylabel('Y') ax.set_zlim3d([np.min(data2[:,2::3]), np.max(data2[:,2::3])]) ax.set_zlabel('Z') # choose a different color for each trajectory colors = plt.cm.jet(np.linspace(0, 1, np.size(data2[0,:])/3)) # set up lines and points lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], []) pts = sum([ax.plot([], [], [], 'o', c=c) for c in colors], []) ax.view_init(30, 0) data3 = np.reshape(data2,(np.size(data2[0,:])/3,np.size(data2[:,0]),3)) n = 0 for i in np.arange(0,int(np.size(data2[0,:])/3),1): data3[i,:,0:3] = data2[:,i+n:i+n+3] n = n + 2 def init(): for line, pt in zip(lines, pts): line.set_data([], []) line.set_3d_properties([]) pt.set_data([], []) pt.set_3d_properties([]) return pts + lines, def animate(i): # we'll step two time-steps per frame. This leads to nice results. #i = (2 * i) % data3.shape[1] for line, pt, xi in zip(lines, pts, data3): x, y, z = xi[:i,0:3].T line.set_data(x, y) line.set_3d_properties(z) pt.set_data(x[-1:], y[-1:]) pt.set_3d_properties(z[-1:]) ax.view_init(30, 0.3 * i) fig.canvas.draw() return pts + lines anim = anm.FuncAnimation(fig, animate, init_func=init, frames=int(np.size(data2[:,0])), interval=1, blit=True) writer = anm.writers['ffmpeg'](fps=30) anim.save('inner_sol_sys.mp4', writer = writer)#, 'ffmpeg_file', fps=15, extra_args=['-vcodec', 'libx264']
dcelisgarza/applied_math
solar_system/animatep2.py
Python
mit
1,987
#!/usr/bin/env python3 __author__ = "Jeremy Brown" __copyright__ = "2014 Jeremy Brown" __license__ = "MIT" """ Improved Eurler's Method solver Inspired by my math homework, which showed me that Euler's Method is a very repetitive process. I couldn't find a tool that would easily let me solve using this method and I didn't want to enter a few very similar forumlas 10 times with different values, so I wrote one myself. I also prefer coding to doing my math homework so this is a compromise. ----------------------------------------------------------------------------- The MIT License (MIT) 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. ----------------------------------------------------------------------------- Uses the simpleeval library by Daniel Fairhead for parsing equations. https://github.com/danthedeckie/simpleeval Distributed under the MIT License ----------------------------------------------------------------------------- Usage: The script prompts for: - the ODE - initial value of x - initial value of y - value to calculate up to (last value of the table) - step value (h), the increment of x for each result and outputs a quick 2-column table of results. Supported functions: - Floor - Ceiling - Exponential - Logarithm (natural, base 10, any base) - Power - Square root - Sin, cos, tan - asin, acos, atan - sinh, cosh, tanh - asinh, acosh, atanh """ """ no y' = xy^2 - y/x """ from simpleeval.simpleeval import SimpleEval import math def function(x, y, formula_string): """Evaluate the passed formula using passed variables.""" return evaluator.eval(formula_string) def func_y_star(x, y, h, formula_string): """Calculates the y*(n+1) using the formula and passed variables.""" return y + h * function(x, y, formula_string) def func_y(x, y, h, formula_string): """Calculates the y(n+1) using the formula and passed variables.""" return y + h * (function(x, y, formula_string) + function(x + h, func_y_star(x, y, h, formula_string), formula_string)) / 2 def print_table(results): """Prints the presults to the console.""" print("\n---RESULTS---\n") for r in results: print(r[0], "\t", r[1]) print() def prompt_value(message): """Prompts the user for a value and converts it to a float""" val = input(message) while not val or not (val.isdigit() or is_float(val)): if not (val.isdigit() or is_float(val)): print("Invalid input, please enter a valid number") val = input(message) return float(val) def is_float(value): """Checks if the specified value is a float""" try: float(value) return True except ValueError: return False supported_functions = {"ceil": math.ceil, "floor": math.floor, "factorial": math.factorial, "exp": math.exp, "ln": math.log, "log": math.log, "log10": math.log10, "pow": math.pow, "sqrt": math.sqrt, "sin": math.sin, "cos": math.cos, "tan": math.tan, "asin": math.asin, "acos": math.acos, "atan": math.atan, "sinh": math.sinh, "cosh": math.cosh, "tanh": math.tanh, "asinh": math.asinh, "acosh": math.acosh, "atanh": math.atanh} print("\nImproved Euler's Method ODE solver\nCopyright 2014 Jeremy Brown") formula_string = str(input("\nEnter an ODE (with all operators, incl. *) to be solved: ")) x = prompt_value("Enter an initial x: ") y = prompt_value("Enter an initial y: ") MAX = prompt_value("Enter the value to calculate up to: ") h = prompt_value("Enter the step value (h) to use for the calculation: ") results = [] results.append([x, y]) evaluator = SimpleEval(names={"x": x, "y": y, "pi": math.pi, "e": math.e}, functions=supported_functions) while x <= MAX: y = func_y(x, y, h, formula_string) x += h vals = [float("{0:.4f}".format(x)), float("{0:.4f}".format(y))] results.append(vals) print_table(results)
j-bro/improved-eulers-method
euler.py
Python
mit
4,813
using System; using MonoTouch.UIKit; namespace Mappir { public class TableItemRutaEncon { public int tipo { get; set; } public int casetasNo { get; set; } public float casetasTotal { get; set; } public float tiempoTotal { get; set; } public float distanciaTotal { get; set; } public float gasTotal { get; set; } public float total { get; set; } public string origen { get; set; } public string destino { get; set; } public string especiAuto { get; set; } public string especiEjes { get; set; } public string especiRendi { get; set; } public string especInciden { get; set; } public UITableViewCellStyle CellStyle { get { return cellStyle; } set { cellStyle = value; } } protected UITableViewCellStyle cellStyle = UITableViewCellStyle.Default; public UITableViewCellAccessory CellAccessory { get { return cellAccessory; } set { cellAccessory = value; } } protected UITableViewCellAccessory cellAccessory = UITableViewCellAccessory.None; public TableItemRutaEncon () { } public TableItemRutaEncon (int tip) { tipo = tip; } } }
FenixStudios/DescubriendoTuRuta
MappirMovil/Mappir/RutasEncontradas/TableItemRutaEncon.cs
C#
mit
1,131
/*! Drag Multiple Plugin - v0.1.2 - 2017-10-16 * https://github.com/javadoug/jquery.drag-multiple * Copyright (c) 2017 Doug Ross; Licensed MIT */ /*globals jQuery */ (function ($) { "use strict"; var options = { // allow consumer to specify the selection items: function getSelectedItems() { return $(".ui-draggable.ui-selected"); }, // allow consumer to cancel drag multiple beforeStart: function beforeDragMultipleStart() { // make sure target is selected, otherwise deselect others if (!(this.is('.ui-draggable') && this.is('.ui-selected'))) { $(".ui-draggable").removeClass('ui-selected'); return false; } }, // notify consumer of drag multiple beforeDrag: $.noop, // notify consumer of drag multiple stop beforeStop: $.noop, // multiple.stack stack: false }; function preventDraggableRevert() { return false; } /** given an instance return the options hash */ function initOptions(instance) { return $.extend({}, options, instance.options.multiple); } function callback(handler, element, jqEvent, ui) { if ($.isFunction(handler)) { return handler.call(element, jqEvent, ui); } } function notifyBeforeStart(element, options, jqEvent, ui) { return callback(options.beforeStart, element, jqEvent, ui); } function notifyBeforeDrag(element, options, jqEvent, ui) { return callback(options.beforeDrag, element, jqEvent, ui); } function notifyBeforeStop(element, options, jqEvent, ui) { return callback(options.beforeStop, element, jqEvent, ui); } $.ui.plugin.add("draggable", "multiple", { /** initialize the selected elements for dragging as a group */ start: function (ev, ui) { var element, instance, selected, options; // the draggable element under the mouse element = this; // the draggable instance instance = element.data('draggable') || element.data('ui-draggable'); // initialize state instance.multiple = {}; // the consumer provided option overrides options = instance.multiple.options = initOptions(instance); // the consumer provided selection selected = options.items(); // notify consumer before starting if (false === notifyBeforeStart(element, options, ev, ui)) { options.dragCanceled = true; return false; } // cache respective origins selected.each(function () { var position = $(this).position(); $(this).data('dragmultiple:originalPosition', $.extend({}, position)); }); // TODO: support the 'valid, invalid and function' values // currently only supports true // disable draggable revert, we will handle the revert instance.originalRevert = options.revert = instance.options.revert; instance.options.revert = preventDraggableRevert; // stack groups of elements // (adapted from jQuery UI 1.12.1-pre draggable) if (false !== options.stack) { var min, group; group = $.makeArray($(options.stack)).sort(function(a, b) { return (parseInt($(a).css("zIndex"), 10) || 0) - (parseInt($(b).css("zIndex"), 10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $( this ).css("zIndex", min + i); }); selected.each(function () { $(this).css("zIndex", min + group.length); }); } }, // move the selected draggables drag: function (ev, ui) { var element, instance, options; element = this; instance = element.data('draggable') || element.data('ui-draggable'); options = instance.multiple.options; if (options.dragCanceled) { return false; } notifyBeforeDrag(element, options, ev, ui); // check to see if consumer updated the revert option if (preventDraggableRevert !== instance.options.revert) { options.revert = instance.options.revert; instance.options.revert = preventDraggableRevert; } // TODO: make this as robust as draggable's positioning options.items().each(function () { var origPosition = $(this).data('dragmultiple:originalPosition'); // NOTE: this only works on elements that are already positionable $(this).css({ top: origPosition.top + (ui.position.top - ui.originalPosition.top), left: origPosition.left + (ui.position.left - ui.originalPosition.left) }); }); }, stop: function (ev, ui) { var element, instance, options; element = this; instance = element.data('draggable') || element.data('ui-draggable'); options = instance.multiple.options; if (options.dragCanceled) { return false; } notifyBeforeStop(element, options, ev, ui); // TODO: mimic the revert logic from draggable if (options.revert === true) { options.items().each(function () { var position = $(this).data('dragmultiple:originalPosition'); $(this).css(position); }); } // clean up options.items().each(function () { $(this).removeData('dragmultiple:originalPosition'); }); // restore orignal revert setting instance.options.revert = instance.originalRevert; } }); }(jQuery));
javadoug/jquery.drag-multiple
dist/jquery-ui.drag-multiple.js
JavaScript
mit
6,262
import GLBoost from '../../globals'; import GLBoostObject from '../core/GLBoostObject'; import GLExtensionsManager from '../core/GLExtensionsManager'; import MathClassUtil from '../../low_level/math/MathClassUtil'; import DrawKickerWorld from '../../middle_level/draw_kickers/DrawKickerWorld'; import VertexWorldShaderSource from '../../middle_level/shaders/VertexWorldShader'; import AABB from '../../low_level/math/AABB'; import Vector3 from '../../low_level/math/Vector3'; import Vector2 from '../../low_level/math/Vector2'; import FreeShader from '../../middle_level/shaders/FreeShader'; import Matrix33 from '../math/Matrix33'; export default class Geometry extends GLBoostObject { constructor(glBoostContext) { super(glBoostContext); this._materials = []; this._vertexN = 0; this._vertices = null; this._indicesArray = null; this._indexStartOffsetArray = []; this._performanceHint = null; this._defaultMaterial = null; this._vertexData = []; this._extraDataForShader = {}; this._vboObj = {}; this._AABB = new AABB(); this._drawKicker = DrawKickerWorld.getInstance(); } _createShaderInstance(glBoostContext, shaderClass) { let shaderInstance = new shaderClass(glBoostContext, VertexWorldShaderSource); return shaderInstance; } /** * return all vertex attribute name list */ _allVertexAttribs(vertices) { var attribNameArray = []; for (var attribName in vertices) { if (attribName !== 'components' && attribName !== 'componentBytes' && attribName !== 'componentType') { attribNameArray.push(attribName); } } return attribNameArray; } _checkAndSetVertexComponentNumber(allVertexAttribs) { allVertexAttribs.forEach((attribName)=> { let element = this._vertices[attribName][0]; let componentN = MathClassUtil.compomentNumberOfVector(element); if (componentN === 0) { // if 0, it must be a number. so users must set components info. return; } if (typeof this._vertices.components === 'undefined') { this._vertices.components = {}; } if (typeof this._vertices.componentType === 'undefined') { this._vertices.componentType = {}; } this._vertices.components[attribName] = componentN; this._vertices.componentType[attribName] = 5126; }); } _calcBaryCentricCoord(vertexNum, positionElementNumPerVertex) { this._vertices.barycentricCoord = new Float32Array(vertexNum*positionElementNumPerVertex); this._vertices.components.barycentricCoord = 3; this._vertices.componentType.barycentricCoord = 5126; // gl.FLOAT if (!this._indicesArray) { for (let i=0; i<vertexNum; i++) { this._vertices.barycentricCoord[i*positionElementNumPerVertex+0] = (i % 3 === 0) ? 1 : 0; // 1 0 0 1 0 0 1 0 0 this._vertices.barycentricCoord[i*positionElementNumPerVertex+1] = (i % 3 === 1) ? 1 : 0; // 0 1 0 0 1 0 0 1 0 this._vertices.barycentricCoord[i*positionElementNumPerVertex+2] = (i % 3 === 2) ? 1 : 0; // 0 0 1 0 0 1 0 0 1 } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length; j++) { this._vertices.barycentricCoord[vertexIndices[j]*positionElementNumPerVertex+0] = (j % 3 === 0) ? 1 : 0; // 1 0 0 1 0 0 1 0 0 this._vertices.barycentricCoord[vertexIndices[j]*positionElementNumPerVertex+1] = (j % 3 === 1) ? 1 : 0; // 0 1 0 0 1 0 0 1 0 this._vertices.barycentricCoord[vertexIndices[j]*positionElementNumPerVertex+2] = (j % 3 === 2) ? 1 : 0; // 0 0 1 0 0 1 0 0 1 } } } } _calcTangentPerVertex(pos0Vec3, pos1Vec3, pos2Vec3, uv0Vec2, uv1Vec2, uv2Vec2) { let cp0 = [ new Vector3( pos0Vec3.x, uv0Vec2.x, uv0Vec2.y ), new Vector3( pos0Vec3.y, uv0Vec2.x, uv0Vec2.y ), new Vector3( pos0Vec3.z, uv0Vec2.x, uv0Vec2.y ) ]; let cp1 = [ new Vector3( pos1Vec3.x, uv1Vec2.x, uv1Vec2.y ), new Vector3( pos1Vec3.y, uv1Vec2.x, uv1Vec2.y ), new Vector3( pos1Vec3.z, uv1Vec2.x, uv1Vec2.y ) ]; let cp2 = [ new Vector3( pos2Vec3.x, uv2Vec2.x, uv2Vec2.y ), new Vector3( pos2Vec3.y, uv2Vec2.x, uv2Vec2.y ), new Vector3( pos2Vec3.z, uv2Vec2.x, uv2Vec2.y ) ]; let u = []; let v = []; for ( let i = 0; i < 3; i++ ) { let v1 = Vector3.subtract(cp1[i], cp0[i]); let v2 = Vector3.subtract(cp2[i], cp1[i]); let abc = Vector3.cross(v1, v2); let validate = Math.abs(abc.x) < Number.EPSILON; if (validate) { console.assert(validate, "Polygons or polygons on UV are degenerate!"); return new Vector3(0, 0, 0); } u[i] = - abc.y / abc.x; v[i] = - abc.z / abc.x; } return (new Vector3(u[0], u[1], u[2])).normalize(); } _calcTangentFor3Vertices(vertexIndices, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, uv0IndexBase, uv1IndexBase, uv2IndexBase, incrementNum) { let pos0Vec3 = new Vector3( this._vertices.position[pos0IndexBase], this._vertices.position[pos0IndexBase + 1], this._vertices.position[pos0IndexBase + 2] ); let pos1Vec3 = new Vector3( this._vertices.position[pos1IndexBase], this._vertices.position[pos1IndexBase + 1], this._vertices.position[pos1IndexBase + 2] ); let pos2Vec3 = new Vector3( this._vertices.position[pos2IndexBase], this._vertices.position[pos2IndexBase + 1], this._vertices.position[pos2IndexBase + 2] ); let uv0Vec2 = new Vector2( this._vertices.texcoord[uv0IndexBase], this._vertices.texcoord[uv0IndexBase + 1] ); let uv1Vec2 = new Vector2( this._vertices.texcoord[uv1IndexBase], this._vertices.texcoord[uv1IndexBase + 1] ); let uv2Vec2 = new Vector2( this._vertices.texcoord[uv2IndexBase], this._vertices.texcoord[uv2IndexBase + 1] ); const componentNum3 = 3; let tan0IndexBase = (i ) * componentNum3; let tan1IndexBase = (i + 1) * componentNum3; let tan2IndexBase = (i + 2) * componentNum3; if (vertexIndices) { tan0IndexBase = vertexIndices[i] * componentNum3; tan1IndexBase = vertexIndices[i + 1] * componentNum3; tan2IndexBase = vertexIndices[i + 2] * componentNum3; } let tan0Vec3 = this._calcTangentPerVertex(pos0Vec3, pos1Vec3, pos2Vec3, uv0Vec2, uv1Vec2, uv2Vec2); this._vertices.tangent[tan0IndexBase] = tan0Vec3.x; this._vertices.tangent[tan0IndexBase + 1] = tan0Vec3.y; this._vertices.tangent[tan0IndexBase + 2] = tan0Vec3.z; let tan1Vec3 = this._calcTangentPerVertex(pos1Vec3, pos2Vec3, pos0Vec3, uv1Vec2, uv2Vec2, uv0Vec2); this._vertices.tangent[tan1IndexBase] = tan1Vec3.x; this._vertices.tangent[tan1IndexBase + 1] = tan1Vec3.y; this._vertices.tangent[tan1IndexBase + 2] = tan1Vec3.z; let tan2Vec3 = this._calcTangentPerVertex(pos2Vec3, pos0Vec3, pos1Vec3, uv2Vec2, uv0Vec2, uv1Vec2); this._vertices.tangent[tan2IndexBase] = tan2Vec3.x; this._vertices.tangent[tan2IndexBase + 1] = tan2Vec3.y; this._vertices.tangent[tan2IndexBase + 2] = tan2Vec3.z; } _calcTangent(vertexNum, positionElementNumPerVertex, texcoordElementNumPerVertex, primitiveType) { this._vertices.tangent = new Float32Array(vertexNum*positionElementNumPerVertex); this._vertices.components.tangent = 3; this._vertices.componentType.tangent = 5126; // gl.FLOAT let incrementNum = 3; // gl.TRIANGLES if (primitiveType === GLBoost.TRIANGLE_STRIP) { // gl.TRIANGLE_STRIP incrementNum = 1; } if ( this._vertices.texcoord ) { if (!this._indicesArray) { for (let i=0; i<vertexNum-2; i+=incrementNum) { let pos0IndexBase = i * positionElementNumPerVertex; let pos1IndexBase = (i + 1) * positionElementNumPerVertex; let pos2IndexBase = (i + 2) * positionElementNumPerVertex; let uv0IndexBase = i * texcoordElementNumPerVertex; let uv1IndexBase = (i + 1) * texcoordElementNumPerVertex; let uv2IndexBase = (i + 2) * texcoordElementNumPerVertex; this._calcTangentFor3Vertices(null, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, uv0IndexBase, uv1IndexBase, uv2IndexBase, incrementNum); } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length-2; j+=incrementNum) { let pos0IndexBase = vertexIndices[j ] * positionElementNumPerVertex; /// 0つ目の頂点 let pos1IndexBase = vertexIndices[j + 1] * positionElementNumPerVertex; /// 1つ目の頂点 let pos2IndexBase = vertexIndices[j + 2] * positionElementNumPerVertex; /// 2つ目の頂点 let uv0IndexBase = vertexIndices[j ] * texcoordElementNumPerVertex; let uv1IndexBase = vertexIndices[j + 1] * texcoordElementNumPerVertex; let uv2IndexBase = vertexIndices[j + 2] * texcoordElementNumPerVertex; this._calcTangentFor3Vertices(vertexIndices, j, pos0IndexBase, pos1IndexBase, pos2IndexBase, uv0IndexBase, uv1IndexBase, uv2IndexBase, incrementNum); } } } } } setVerticesData(vertices, indicesArray, primitiveType = GLBoost.TRIANGLES, performanceHint = GLBoost.STATIC_DRAW) { this._vertices = vertices; this._indicesArray = indicesArray; let allVertexAttribs = this._allVertexAttribs(this._vertices); this._checkAndSetVertexComponentNumber(allVertexAttribs); let vertexNum = 0; let positionElementNum = 0; let positionElementNumPerVertex = this._vertices.components.position; let texcoordElementNumPerVertex = this._vertices.components.texcoord; if (typeof this._vertices.position.buffer !== 'undefined') { vertexNum = this._vertices.position.length / positionElementNumPerVertex; positionElementNum = this._vertices.position.length; } else { vertexNum = this._vertices.position.length; // vertices must be type of Vector3 positionElementNum = this._vertices.position.length * positionElementNumPerVertex; } // for Wireframe this._calcBaryCentricCoord(vertexNum, positionElementNumPerVertex); allVertexAttribs = this._allVertexAttribs(this._vertices); this._checkAndSetVertexComponentNumber(allVertexAttribs); // vector to array allVertexAttribs.forEach((attribName)=> { if (attribName === 'barycentricCoord') { return; } if (attribName === 'tangent') { return; } if (typeof this._vertices[attribName].buffer !== 'undefined') { return; } let vertexAttribArray = []; this._vertices[attribName].forEach((elem, index) => { let element = this._vertices[attribName][index]; Array.prototype.push.apply(vertexAttribArray, MathClassUtil.vectorToArray(element)); }); this._vertices[attribName] = vertexAttribArray; }); // for Tangent if (this._vertices.texcoord) { this._calcTangent(vertexNum, positionElementNumPerVertex, texcoordElementNumPerVertex, primitiveType); } // for Raycast Picking this._calcArenbergInverseMatrices(primitiveType); // Normal Array to Float32Array allVertexAttribs.forEach((attribName)=> { if (typeof this._vertices[attribName].buffer === 'undefined') { this._vertices[attribName] = new Float32Array(this._vertices[attribName]); } }); for (let i=0; i<vertexNum; i++) { this._AABB.addPositionWithArray(this._vertices.position, i * positionElementNumPerVertex); } this._AABB.updateAllInfo(); let gl = this._glContext.gl; let primitiveTypeStr = GLBoost.getValueOfGLBoostConstant(primitiveType); this._primitiveType = gl[primitiveTypeStr]; let performanceHintStr = GLBoost.getValueOfGLBoostConstant(performanceHint); this._performanceHint = gl[performanceHintStr]; } updateVerticesData(vertices, skipUpdateAABB = false) { let gl = this._glContext.gl; for (let attribName in vertices) { let vertexAttribArray = []; this._vertices[attribName].forEach((elem, index) => { let element = vertices[attribName][index]; Array.prototype.push.apply(vertexAttribArray, MathClassUtil.vectorToArray(element)); if (attribName === 'position' && !(skipUpdateAABB === true)) { let componentN = this._vertices.components[attribName]; this._AABB.addPositionWithArray(vertexAttribArray, index * componentN); } this._vertices[attribName] = vertexAttribArray; }); } if(!(skipUpdateAABB === true)) { this._AABB.updateAllInfo(); } for (let attribName in vertices) { if (this._vboObj[attribName]) { let float32AryVertexData = new Float32Array(this._vertices[attribName]); gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.bufferSubData(gl.ARRAY_BUFFER, 0, float32AryVertexData); gl.bindBuffer(gl.ARRAY_BUFFER, null); } else { return false; } } return true; } setUpVertexAttribs(gl, glslProgram, allVertexAttribs) { var optimizedVertexAttribs = glslProgram.optimizedVertexAttribs; // setup vertex layouts allVertexAttribs.forEach((attribName)=> { if (optimizedVertexAttribs.indexOf(attribName) != -1) { let vertexAttribName = null; gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.vertexAttribPointer(glslProgram['vertexAttribute_' + attribName], this._vertices.components[attribName], this._vertices.componentType[attribName], false, 0, 0); } }); } setUpEnableVertexAttribArrays(gl, glslProgram, allVertexAttribs) { var optimizedVertexAttribs = glslProgram.optimizedVertexAttribs; allVertexAttribs.forEach((attribName)=> { if (optimizedVertexAttribs.indexOf(attribName) != -1) { gl.enableVertexAttribArray(glslProgram['vertexAttribute_' + attribName]); } }); } setUpDisableAllVertexAttribArrays(gl, glslProgram) { for (let i=0; i<8; i++) { gl.disableVertexAttribArray(i); } } setUpDisableVertexAttribArrays(gl, glslProgram, allVertexAttribs) { var optimizedVertexAttribs = glslProgram.optimizedVertexAttribs; allVertexAttribs.forEach((attribName)=> { if (optimizedVertexAttribs.indexOf(attribName) != -1) { gl.disableVertexAttribArray(glslProgram['vertexAttribute_' + attribName]); } }); } _getVAO() { return Geometry._vaoDic[this.toString()]; } _getAllVertexAttribs() { return this._allVertexAttribs(this._vertices); } prepareGLSLProgram(expression, material, existCamera_f, lights, shaderClass = void 0, argShaderInstance = void 0) { let vertices = this._vertices; let _optimizedVertexAttribs = this._allVertexAttribs(vertices, material); let shaderInstance = null; if (argShaderInstance) { shaderInstance = argShaderInstance; } else { if (shaderClass) { shaderInstance = this._createShaderInstance(this._glBoostSystem, shaderClass); } else { shaderInstance = this._createShaderInstance(this._glBoostSystem, material.shaderClass); } } shaderInstance.getShaderProgram(expression, _optimizedVertexAttribs, existCamera_f, lights, material, this._extraDataForShader); return shaderInstance; } _setVertexNtoSingleMaterial(material, index) { // if this mesh has only one material... //if (material.getVertexN(this) === 0) { if (this._indicesArray && this._indicesArray.length > 0) { material.setVertexN(this, this._indicesArray[index].length); } else { material.setVertexN(this, this._vertexN); } //} } _getAppropriateMaterials(mesh) { let materials = null; if (this._materials.length > 0) { materials = this._materials; } else if (mesh.material){ materials = [mesh.material]; } else { mesh.material = this._glBoostSystem._defaultMaterial; materials = [mesh.material]; } return materials; } getIndexStartOffsetArrayAtMaterial(i) { return this._indexStartOffsetArray[i]; } prepareToRender(expression, existCamera_f, lights, meshMaterial, mesh, shaderClass = void 0, argMaterials = void 0) { var vertices = this._vertices; var gl = this._glContext.gl; var glem = GLExtensionsManager.getInstance(this._glContext); this._vertexN = vertices.position.length / vertices.components.position; var allVertexAttribs = this._allVertexAttribs(vertices); // create VAO if (Geometry._vaoDic[this.toString()]) { } else { var vao = this._glContext.createVertexArray(this); Geometry._vaoDic[this.toString()] = vao; } glem.bindVertexArray(gl, Geometry._vaoDic[this.toString()]); let doAfter = false; allVertexAttribs.forEach((attribName)=> { // create VBO if (this._vboObj[attribName]) { gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); } else { let vbo = this._glContext.createBuffer(this); this._vboObj[attribName] = vbo; gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); // if (typeof this._vertices[attribName].buffer !== 'undefined') { gl.bufferData(gl.ARRAY_BUFFER, this._vertices[attribName], this._performanceHint); // } else { // gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(this._vertices[attribName]), this._performanceHint); // } //gl.bindBuffer(gl.ARRAY_BUFFER, null); doAfter = true; } }); if (doAfter) { if (Geometry._iboArrayDic[this.toString()]) { gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Geometry._iboArrayDic[this.toString()] ); } else { if (this._indicesArray) { let indices = []; for (let i=0; i<this._indicesArray.length; i++) { if (i==0) { this._indexStartOffsetArray[i] = 0; } this._indexStartOffsetArray[i+1] = this._indexStartOffsetArray[i] + this._indicesArray[i].length; //Array.prototype.push.apply(indices, this._indicesArray[i]); indices = indices.concat(this._indicesArray[i]); } // create Index Buffer var ibo = this._glContext.createBuffer(this); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo ); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, glem.createUintArrayForElementIndex(gl, indices), gl.STATIC_DRAW); Geometry._iboArrayDic[this.toString()] = ibo; } } } let materials = argMaterials; if (argMaterials === void 0) { materials = this._getAppropriateMaterials(mesh); } //let materials = this._getAppropriateMaterials(mesh); for (let i=0; i<materials.length;i++) { let shaderInstance = null; /* if (argMaterials !== void 0 && argMaterials[i].shaderInstance !== null) { shaderInstance = argMaterials[i].shaderInstance; } else if (materials[i].shaderInstance !== null) { shaderInstance = materials[i].shaderInstance; } else { */ if (materials[i].shaderInstance && materials[i].shaderInstance.constructor === FreeShader) { shaderInstance = this.prepareGLSLProgram(expression, materials[i], existCamera_f, lights, void 0, materials[i].shaderInstance); } else { shaderInstance = this.prepareGLSLProgram(expression, materials[i], existCamera_f, lights, shaderClass); } // } this._setVertexNtoSingleMaterial(materials[i], i); shaderInstance.vao = Geometry._vaoDic[this.toString()]; this.setUpVertexAttribs(gl, shaderInstance._glslProgram, allVertexAttribs); if (argMaterials === void 0) { materials[i].shaderInstance = shaderInstance; } else { argMaterials[i].shaderInstance = shaderInstance; } } glem.bindVertexArray(gl, null); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); return materials; } _setUpVertexAttibsWrapper(glslProgram) { this.setUpVertexAttribs(this._glContext.gl, glslProgram, this._getAllVertexAttribs()); } draw(data) { const gl = this._glContext.gl; const glem = GLExtensionsManager.getInstance(this._glContext); let materials = this._getAppropriateMaterials(data.mesh); const thisName = this.toString(); this._drawKicker.draw( { gl: gl, glem: glem, expression: data.expression, lights: data.lights, camera: data.camera, mesh: data.mesh, scene: data.scene, renderPassIndex: data.renderPassIndex, materials: materials, vertices: this._vertices, vaoDic: Geometry._vaoDic, vboObj: this._vboObj, iboArrayDic: Geometry._iboArrayDic, geometry: this, geometryName: thisName, primitiveType: this._primitiveType, vertexN: this._vertexN, viewport: data.viewport, isWebVRMode: data.isWebVRMode, webvrFrameData: data.webvrFrameData, forceThisMaterial: data.forceThisMaterial }); } drawIntermediate() {} merge(geometrys) { if (Array.isArray(geometrys)) { let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let allGeomLength = 0; geometrys.forEach((geometry) => { allGeomLength += geometry._vertices[attribName].length; }); typedArrayDic[attribName] = new Float32Array(thisLength + allGeomLength); }); let lastThisLengthDic = {}; allVertexAttribs.forEach((attribName)=> { lastThisLengthDic[attribName] = 0; }); geometrys.forEach((geometry, index) => { let typedSubArrayDic = {}; allVertexAttribs.forEach((attribName)=> { let typedArray = typedArrayDic[attribName]; if (index === 0) { lastThisLengthDic[attribName] = geometrys[index]._vertices[attribName].length; } let end = (typeof geometrys[index+1] !== 'undefined') ? lastThisLengthDic[attribName] + geometrys[index+1]._vertices[attribName].length : void 0; typedSubArrayDic[attribName] = typedArray.subarray(0, end); lastThisLengthDic[attribName] = end; }); this.mergeInner(geometry, typedSubArrayDic, (index === 0)); }); } else { let geometry = geometrys; let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; typedArrayDic[attribName] = new Float32Array(thisLength + geomLength); }); this.mergeInner(geometry, typedArrayDic); } } /** * */ mergeInner(geometry, typedArrayDic, isFirst = false) { let gl = this._glContext.gl; let baseLen = this._vertices.position.length / this._vertices.components.position;; if (this === geometry) { console.assert('don\'t merge same geometry!'); } let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; let float32array = typedArrayDic[attribName]; if (isFirst) { float32array.set(this._vertices[attribName], 0); } float32array.set(geometry._vertices[attribName], thisLength); this._vertices[attribName] = float32array; if (typeof this._vboObj[attribName] !== 'undefined') { gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.bufferData(gl.ARRAY_BUFFER, this._vertices[attribName], this._performanceHint); gl.bindBuffer(gl.ARRAY_BUFFER, null); } }); let geometryIndicesN = geometry._indicesArray.length; for (let i = 0; i < geometryIndicesN; i++) { for (let j = 0; j < geometry._indicesArray[i].length; j++) { geometry._indicesArray[i][j] += baseLen; } this._indicesArray.push(geometry._indicesArray[i]); if (geometry._materials[i]) { this._materials.push(geometry._materials[i]); } } this._vertexN += geometry._vertexN; } mergeHarder(geometrys) { if (Array.isArray(geometrys)) { let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let allGeomLength = 0; geometrys.forEach((geometry) => { allGeomLength += geometry._vertices[attribName].length; }); typedArrayDic[attribName] = new Float32Array(thisLength + allGeomLength); }); let lastThisLengthDic = {}; allVertexAttribs.forEach((attribName)=> { lastThisLengthDic[attribName] = 0; }); geometrys.forEach((geometry, index) => { let typedSubArrayDic = {}; allVertexAttribs.forEach((attribName)=> { let typedArray = typedArrayDic[attribName]; if (index === 0) { lastThisLengthDic[attribName] = geometrys[index]._vertices[attribName].length; } let end = (typeof geometrys[index+1] !== 'undefined') ? lastThisLengthDic[attribName] + geometrys[index+1]._vertices[attribName].length : void 0; typedSubArrayDic[attribName] = typedArray.subarray(0, end); lastThisLengthDic[attribName] = end; }); this.mergeHarderInner(geometry, typedSubArrayDic, (index === 0)); }); } else { let geometry = geometrys; let typedArrayDic = {}; let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; typedArrayDic[attribName] = new Float32Array(thisLength + geomLength); }); this.mergeHarderInner(geometry, typedArrayDic); } } /** * take no thought geometry's materials * */ mergeHarderInner(geometry, typedArrayDic, isFirst = false) { let gl = this._glContext.gl; let baseLen = this._vertices.position.length / this._vertices.components.position; if (this === geometry) { console.assert('don\'t merge same geometry!'); } let allVertexAttribs = this._allVertexAttribs(this._vertices); allVertexAttribs.forEach((attribName)=> { let thisLength = this._vertices[attribName].length; let geomLength = geometry._vertices[attribName].length; let float32array = typedArrayDic[attribName]; if (isFirst) { float32array.set(this._vertices[attribName], 0); } float32array.set(geometry._vertices[attribName], thisLength); this._vertices[attribName] = float32array; if (typeof this._vboObj[attribName] !== 'undefined') { gl.bindBuffer(gl.ARRAY_BUFFER, this._vboObj[attribName]); gl.bufferData(gl.ARRAY_BUFFER, this._vertices[attribName], this._performanceHint); gl.bindBuffer(gl.ARRAY_BUFFER, null); } }); for (let i = 0; i < this._indicesArray.length; i++) { let len = geometry._indicesArray[i].length; for (let j = 0; j < len; j++) { let idx = geometry._indicesArray[i][j]; this._indicesArray[i].push(baseLen + idx); } if (this._materials[i]) { this._materials[i].setVertexN(this, this._materials[i].getVertexN(geometry)); } } this._vertexN += geometry._vertexN; } set materials(materials) { this._materials = materials; } get materials() { return this._materials; } get centerPosition() { return this._AABB.centerPoint; } setExtraDataForShader(name, value) { this._extraDataForShader[name] = value; } getExtraDataForShader(name) { return this._extraDataForShader[name]; } isTransparent(mesh) { let materials = this._getAppropriateMaterials(mesh); let isTransparent = false; materials.forEach((material)=>{ if (material.isTransparent()) { isTransparent = true; } }); return isTransparent; } get AABB() { return this._AABB;//.clone(); } get rawAABB() { return this._AABB; } isIndexed() { return !!Geometry._iboArrayDic[this.toString()]; } getTriangleCount(mesh) { let gl = this._glContext.gl; let materials = this._getAppropriateMaterials(mesh); let count = 0; for (let i=0; i<materials.length;i++) { let material = materials[i]; if (this._primitiveType === gl.TRIANGLES) { if (this.isIndexed()) { count += material.getVertexN(this.toString()) / 3; } else { count += this._vertexN / 3; } } else if (this._primitiveType === gl.TRIANGLE_STRIP) { if (this.isIndexed()) { count += material.getVertexN(this.toString()) - 2; } else { count += this._vertexN - 2; } } } return count; } getVertexCount() { let gl = this._glContext.gl; let count = 0; if (this._vertices) { count = this._vertices.position.length; } return count; } rayCast(origVec3, dirVec3, isFrontFacePickable, isBackFacePickable) { let currentShortestT = Number.MAX_VALUE; let currentShortestIntersectedPosVec3 = null; const positionElementNumPerVertex = this._vertices.components.position; let incrementNum = 3; // gl.TRIANGLES if (this._primitiveType === GLBoost.TRIANGLE_STRIP) { // gl.TRIANGLE_STRIP incrementNum = 1; } if (!this._indicesArray) { for (let i=0; i<vertexNum; i++) { const j = i * incrementNum; let pos0IndexBase = j * positionElementNumPerVertex; let pos1IndexBase = (j + 1) * positionElementNumPerVertex; let pos2IndexBase = (j + 2) * positionElementNumPerVertex; const result = this._rayCastInner(origVec3, dirVec3, j, pos0IndexBase, pos1IndexBase, pos2IndexBase, isFrontFacePickable, isBackFacePickable); if (result === null) { continue; } const t = result[0]; if (result[0] < currentShortestT) { currentShortestT = t; currentShortestIntersectedPosVec3 = result[1]; } } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length; j++) { const k = j * incrementNum; let pos0IndexBase = vertexIndices[k ] * positionElementNumPerVertex; let pos1IndexBase = vertexIndices[k + 1] * positionElementNumPerVertex; let pos2IndexBase = vertexIndices[k + 2] * positionElementNumPerVertex; if (vertexIndices[k + 2] === void 0) { break; } const result = this._rayCastInner(origVec3, dirVec3, vertexIndices[k], pos0IndexBase, pos1IndexBase, pos2IndexBase, isFrontFacePickable, isBackFacePickable); if (result === null) { continue; } const t = result[0]; if (result[0] < currentShortestT) { currentShortestT = t; currentShortestIntersectedPosVec3 = result[1]; } } } } return [currentShortestIntersectedPosVec3, currentShortestT]; } _rayCastInner(origVec3, dirVec3, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, isFrontFacePickable, isBackFacePickable) { if (!this._vertices.arenberg3rdPosition[i]) { return null; } const faceNormal = this._vertices.faceNormal[i]; if (faceNormal.dotProduct(dirVec3) < 0 && !isFrontFacePickable) { // ---> <--- return null; } if (faceNormal.dotProduct(dirVec3) > 0 && !isBackFacePickable) { // ---> ---> return null; } const vec3 = Vector3.subtract(origVec3, this._vertices.arenberg3rdPosition[i]); const convertedOrigVec3 = this._vertices.inverseArenbergMatrix[i].multiplyVector(vec3); const convertedDirVec3 = this._vertices.inverseArenbergMatrix[i].multiplyVector(dirVec3); if (convertedDirVec3.z >= -(1e-6) && convertedDirVec3.z <= (1e-6)) { return null; } const t = -convertedOrigVec3.z / convertedDirVec3.z; if(t <= (1e-5)) { return null; } const u = convertedOrigVec3.x + t * convertedDirVec3.x; const v = convertedOrigVec3.y + t * convertedDirVec3.y; if (u < 0.0 || v < 0.0 || (u + v) > 1.0) { return null; } const fDat = 1.0 - u - v; const pos0Vec3 = new Vector3( this._vertices.position[pos0IndexBase], this._vertices.position[pos0IndexBase + 1], this._vertices.position[pos0IndexBase + 2] ); const pos1Vec3 = new Vector3( this._vertices.position[pos1IndexBase], this._vertices.position[pos1IndexBase + 1], this._vertices.position[pos1IndexBase + 2] ); const pos2Vec3 = new Vector3( this._vertices.position[pos2IndexBase], this._vertices.position[pos2IndexBase + 1], this._vertices.position[pos2IndexBase + 2] ); const pos0 = Vector3.multiply(pos0Vec3, u); const pos1 = Vector3.multiply(pos1Vec3, v); const pos2 = Vector3.multiply(pos2Vec3, fDat); const intersectedPosVec3 = Vector3.add(Vector3.add(pos0, pos1), pos2); return [t, intersectedPosVec3]; } _calcArenbergInverseMatrices(primitiveType) { const positionElementNumPerVertex = this._vertices.components.position; let incrementNum = 3; // gl.TRIANGLES if (primitiveType === GLBoost.TRIANGLE_STRIP) { // gl.TRIANGLE_STRIP incrementNum = 1; } this._vertices.inverseArenbergMatrix = []; this._vertices.arenberg3rdPosition = []; this._vertices.faceNormal = []; if (!this._indicesArray) { for (let i=0; i<this._vertexN-2; i+=incrementNum) { let pos0IndexBase = i * positionElementNumPerVertex; let pos1IndexBase = (i + 1) * positionElementNumPerVertex; let pos2IndexBase = (i + 2) * positionElementNumPerVertex; this._calcArenbergMatrixFor3Vertices(null, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, incrementNum); } } else { for (let i=0; i<this._indicesArray.length; i++) { let vertexIndices = this._indicesArray[i]; for (let j=0; j<vertexIndices.length-2; j+=incrementNum) { let pos0IndexBase = vertexIndices[j ] * positionElementNumPerVertex; let pos1IndexBase = vertexIndices[j + 1] * positionElementNumPerVertex; let pos2IndexBase = vertexIndices[j + 2] * positionElementNumPerVertex; if (vertexIndices[j + 2] === void 0) { break; } this._calcArenbergMatrixFor3Vertices(vertexIndices, j, pos0IndexBase, pos1IndexBase, pos2IndexBase, incrementNum); } } } } _calcArenbergMatrixFor3Vertices(vertexIndices, i, pos0IndexBase, pos1IndexBase, pos2IndexBase, incrementNum) { const pos0Vec3 = new Vector3( this._vertices.position[pos0IndexBase], this._vertices.position[pos0IndexBase + 1], this._vertices.position[pos0IndexBase + 2] ); const pos1Vec3 = new Vector3( this._vertices.position[pos1IndexBase], this._vertices.position[pos1IndexBase + 1], this._vertices.position[pos1IndexBase + 2] ); const pos2Vec3 = new Vector3( this._vertices.position[pos2IndexBase], this._vertices.position[pos2IndexBase + 1], this._vertices.position[pos2IndexBase + 2] ); const ax = pos0Vec3.x - pos2Vec3.x; const ay = pos0Vec3.y - pos2Vec3.y; const az = pos0Vec3.z - pos2Vec3.z; const bx = pos1Vec3.x - pos2Vec3.x; const by = pos1Vec3.y - pos2Vec3.y; const bz = pos1Vec3.z - pos2Vec3.z; let nx = ay * bz - az * by; let ny = az * bx - ax * bz; let nz = ax * by - ay * bx; let da = Math.sqrt(nx * nx + ny * ny + nz * nz); if (da <= 1e-6) { return 0; } da = 1.0 / da; nx *= da; ny *= da; nz *= da; const arenbergMatrix = new Matrix33( pos0Vec3.x - pos2Vec3.x, pos1Vec3.x - pos2Vec3.x, nx - pos2Vec3.x, pos0Vec3.y - pos2Vec3.y, pos1Vec3.y - pos2Vec3.y, ny - pos2Vec3.y, pos0Vec3.z - pos2Vec3.z, pos1Vec3.z - pos2Vec3.z, nz - pos2Vec3.z ); const inverseArenbergMatrix = arenbergMatrix.invert(); let arenberg0IndexBase = (i ); let arenberg1IndexBase = (i + 1); let arenberg2IndexBase = (i + 2); if (vertexIndices) { arenberg0IndexBase = vertexIndices[i]; arenberg1IndexBase = vertexIndices[i + 1]; arenberg2IndexBase = vertexIndices[i + 2]; } // const triangleIdx = i/incrementNum; this._vertices.inverseArenbergMatrix[arenberg0IndexBase] = inverseArenbergMatrix; this._vertices.arenberg3rdPosition[arenberg0IndexBase] = pos2Vec3; this._vertices.faceNormal[arenberg0IndexBase] = new Vector3(nx, ny, nz); } } Geometry._vaoDic = {}; Geometry._iboArrayDic = {};
cx20/GLBoost
src/low_level/geometries/Geometry.js
JavaScript
mit
37,614
import * as React from "react"; import { Helper, SPTypes } from "gd-sprest"; import { Label, ILabelProps } from "@fluentui/react/lib/Label"; import { IPeoplePickerProps } from "@fluentui/react/lib/Pickers"; import { SPPeoplePicker } from "../components"; import { IFieldUserProps, IFieldUserState } from "./types"; import { BaseField } from "."; /** * User Field */ export class FieldUser extends BaseField<IFieldUserProps, IFieldUserState> { /** * Render the field */ renderField = () => { // See if a custom render method exists if (this.props.onRender) { return this.props.onRender(this.state.fieldInfo); } // Update the label properties let lblProps: ILabelProps = this.props.lblProps || {}; lblProps.required = typeof (lblProps.required) === "boolean" ? lblProps.required : this.state.fieldInfo.required; // Set the picker props let props: IPeoplePickerProps = this.props.pickerProps || {} as any; props.disabled = this.state.fieldInfo.readOnly || this.props.controlMode == SPTypes.ControlMode.Display; props.onChange = this.onChange; // Render the component return ( <div className={(this.props.className || "")}> <Label {...lblProps as any}>{lblProps.defaultValue || this.state.fieldInfo.title}</Label> <SPPeoplePicker allowGroups={this.state.fieldInfo.allowGroups} allowMultiple={this.state.fieldInfo.multi} fieldValue={this.state.value ? this.state.value.results || [this.state.value] : null} props={props} webUrl={this.props.webUrl} /> </div> ); } /** * Methods */ /** * The get field value method */ getFieldValue = () => { let fieldValue = this.state.value; // See if results exist if (fieldValue && fieldValue.results) { let results = []; // Parse the results for (let i = 0; i < fieldValue.results.length; i++) { let lookupValue = fieldValue.results[i]; // Add the lookup id results.push(lookupValue.ID || lookupValue); } // Update the field value fieldValue = { results: results }; } else { // See if this is a multi value if (this.state.fieldInfo.multi) { // Ensure a value exists fieldValue = fieldValue || { results: [] }; } else { // Ensure the value is valid let userId = fieldValue.ID || fieldValue; fieldValue = userId > 0 ? userId : null; } } // Return the field value return fieldValue; } /** * The change event * @param personas - The user personas. */ onChange = (personas) => { // Update the field value this.updateValue(SPPeoplePicker.convertToFieldValue(personas, this.state.fieldInfo.multi)); } /** * The field loaded event * @param info - The field information. * @param state - The current state. */ onFieldLoaded = (info, state: IFieldUserState) => { let fldInfo = info as Helper.IListFormUserFieldInfo; // Default the value state.value = this.props.defaultValue || fldInfo.defaultValue; // See if this is a multi-lookup field if (fldInfo.multi) { let results = []; // Parse the users let users = (state.value ? state.value.results : state.value) || []; for (let i = 0; i < users.length; i++) { // Add the item id results.push(users[i].ID || users[i]); } // Set the value state.value = { results }; } // Else, see if the value exists else if (state.value) { // Set the value state.value = state.value || state.value.ID; } } }
gunjandatta/sprest-react
src/fields/fieldUser.tsx
TypeScript
mit
4,114
# -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# # these are system modules import commands import numpy import os import sys # these are my local modules from env import gidgetConfigVars import miscIO import miscTCGA import path import tsvIO # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# NA_VALUE = -999999 debugON = 0 ## debugON = 1 # NOTE: this is a modified script that handles ONLY the microRNAseq data # from BCGSC platformStrings = [ 'bcgsc.ca/illuminaga_mirnaseq/mirnaseq/', 'bcgsc.ca/illuminahiseq_mirnaseq/mirnaseq/'] dataTypeDict = {} dataTypeDict["IlluminaGA_miRNASeq"] = ["N", "MIRN"] dataTypeDict["IlluminaHiSeq_miRNASeq"] = ["N", "MIRN"] # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# # from Timo's resegmentation code: class AutoVivification(dict): """Implementation of perl's autovivification feature.""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# def getLastBit(aName): ii = len(aName) - 1 while (aName[ii] != '/'): ii -= 1 # print ' <%s> <%s> ' % ( aName, aName[ii+1:] ) return (aName[ii + 1:]) # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# def loadNameMap(mapFilename): metaData = {} fh = file(mapFilename) for aLine in fh: aLine = aLine.strip() tokenList = aLine.split('\t') metaData[tokenList[1]] = tokenList[0] fh.close() return (metaData) # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# # hsa-let-7a-2 MIMAT0010195 N:MIRN:hsa-let-7a-2:::::MIMAT0010195 def makeFeatureName(tok0, tok1, metaData): try: featName = "N:MIRN:" + metaData[tok1] + ":::::" + tok1 print " all good : ", tok0, tok1, featName except: featName = "N:MIRN:" + tok0 + ":::::" + tok1 print " BAD ??? ", tok0, tok1, featName return (featName) # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# def makeOutputFilename(outDir, tumorList, zString, outSuffix): if (len(tumorList) == 1): zCancer = tumorList[0] else: tumorList.sort() zCancer = tumorList[0] for aCancer in tumorList[1:]: zCancer = zCancer + '_' + aCancer print " --> combined multi-cancer name : <%s> " % zCancer # start by pasting together the outDir, cancer sub-dir, then '/' # and then the cancer name again, followed by a '.' outFilename = outDir + zCancer + "/" + zCancer + "." # now we are just going to assume that we are writing to the current # working directory (21dec12) outFilename = outDir + zCancer + "." # next we want to replace all '/' in the platform string with '__' i1 = 0 while (i1 >= 0): i2 = zString.find('/', i1) if (i1 > 0 and i2 > 0): outFilename += "__" if (i2 > 0): outFilename += zString[i1:i2] i1 = i2 + 1 else: i1 = i2 # and finally we add on the suffix (usually something like '25jun') if (not outSuffix.startswith(".")): outFilename += "." outFilename += outSuffix return (outFilename) # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-# if __name__ == "__main__": # list of cancer directory names cancerDirNames = [ 'acc', 'blca', 'brca', 'cesc', 'cntl', 'coad', 'dlbc', 'esca', 'gbm', 'hnsc', 'kich', 'kirc', 'kirp', 'laml', 'lcll', 'lgg', 'lihc', 'lnnh', 'luad', 'lusc', 'ov', 'paad', 'prad', 'read', 'sarc', 'skcm', 'stad', 'thca', 'ucec', 'lcml', 'pcpg', 'meso', 'tgct', 'ucs' ] if (1): if (len(sys.argv) < 4): print " Usage: %s <outSuffix> <platformID> <tumorType#1> [tumorType#2 ...] [snapshot-name]" print " currently supported platforms : ", platformStrings print " currently supported tumor types : ", cancerDirNames print " ERROR -- bad command line arguments " sys.exit(-1) else: # output suffix ... outSuffix = sys.argv[1] # specified platform ... platformID = sys.argv[2] if (platformID[-1] != '/'): platformID += '/' if (platformID not in platformStrings): print " platform <%s> is not supported " % platformID print " currently supported platforms are: ", platformStrings sys.exit(-1) platformStrings = [platformID] # assume that the default snapshotName is "dcc-snapshot" snapshotName = "dcc-snapshot" # specified tumor type(s) ... argList = sys.argv[3:] # print argList tumorList = [] for aType in argList: tumorType = aType.lower() if (tumorType in cancerDirNames): tumorList += [tumorType] elif (tumorType.find("snap") >= 0): snapshotName = tumorType print " using this snapshot : <%s> " % snapshotName else: print " ERROR ??? tumorType <%s> not in list of known tumors ??? " % tumorType print cancerDirNames if (len(tumorList) < 1): print " ERROR ??? have no tumor types in list ??? ", tumorList sys.exit(-1) print " tumor type(s) list : ", tumorList # -------------------------------------- # HERE is where the real work starts ... # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # now we need to get set up for writing the output ... # NEW: 21dec12 ... assuming that we will write to current working directory outDir = "./" outFilename = makeOutputFilename( outDir, tumorList, platformID, outSuffix) # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # initialize a bunch of things ... sampleList = [] gotFiles = [] geneList = [] numGenes = 0 numProc = 0 iS = 0 # and then loop over tumor types ... for zCancer in tumorList: print ' ' print ' ********************************** ' print ' LOOP over %d CANCER TYPES ... %s ' % (len(tumorList), zCancer) # piece together the directory name ... ## topDir = gidgetConfigVars['TCGAFMP_DCC_REPOSITORIES'] + "/dcc-snapshot/public/tumor/" + zCancer + "/cgcc/" + platformID topDir = gidgetConfigVars['TCGAFMP_DCC_REPOSITORIES'] + "/" + \ snapshotName + "/public/tumor/" + zCancer + "/cgcc/" + platformID print ' starting from top-level directory ', topDir dMatch = "Level_3" if (not os.path.exists(topDir)): print ' --> <%s> does not exist ' % topDir continue d1 = path.path(topDir) for dName in d1.dirs(): print dName if (dName.find(dMatch) >= 0): print ' ' print ' found a <%s> directory : <%s> ' % (dMatch, dName) archiveName = getLastBit(dName) print ' archiveName : ', archiveName if (dName.find("IlluminaHiSeq") > 0): zPlat = "IlluminaHiSeq_miRNASeq" elif (dName.find("IlluminaGA") > 0): zPlat = "IlluminaGA_miRNASeq" else: print " not a valid platform: %s ??? !!! " % (dName) sys.exit(-1) cmdString = "%s/shscript/expression_matrix_mimat.pl " % gidgetConfigVars['TCGAFMP_ROOT_DIR'] cmdString += "-m " + gidgetConfigVars['TCGAFMP_DCC_REPOSITORIES'] + "/mirna_bcgsc/tcga_mirna_bcgsc_hg19.adf " cmdString += "-o %s " % outDir cmdString += "-p %s " % topDir cmdString += "-n %s " % zPlat print " " print cmdString print " " (status, output) = commands.getstatusoutput(cmdString) normMatFilename = outDir + "/expn_matrix_mimat_norm_%s.txt" % (zPlat) print " normMatFilename = <%s> " % normMatFilename # make sure that we can open this file ... try: fh = file(normMatFilename, 'r') gotFiles += [normMatFilename] fh.close() except: print " " print " Not able to open expn_matrix_mimat_norm file ??? " print " " sys.exit(-1) print " " print " " if (len(gotFiles) == 0): print " ERROR in new_Level3_miRNAseq ... no data files found " sys.exit(-1) if (len(gotFiles) > 1): print " ERROR ??? we should have only one file at this point " print gotFiles sys.exit(-1) # if we get this far, we should make sure that the output directory we # want exists print " --> testing that we have an output directory ... <%s> " % outDir tsvIO.createDir(outDir) print " output file name will be called <%s> " % outFilename # we also need to read in the mapping file ... metaData = loadNameMap( gidgetConfigVars['TCGAFMP_DCC_REPOSITORIES'] + "/mirna_bcgsc/mature.fa.flat.human.mirbase_v19.txt") if (1): fh = file(gotFiles[0], 'r') numRow = miscIO.num_lines(fh) - 1 numCol = miscIO.num_cols(fh, '\t') - 1 rowLabels = [] dataMatrix = [0] * numRow for iR in range(numRow): dataMatrix[iR] = [0] * numCol hdrLine = fh.readline() hdrLine = hdrLine.strip() hdrTokens = hdrLine.split('\t') if (len(hdrTokens) != (numCol + 1)): print " ERROR #1 ??? " sys.exit(-1) done = 0 iR = 0 numNA = 0 while (not done): aLine = fh.readline() aLine = aLine.strip() tokenList = aLine.split('\t') if (len(tokenList) != (numCol + 1)): done = 1 else: aLabel = tokenList[0] # print " label = <%s> " % aLabel labelTokens = aLabel.split('.') # print labelTokens featName = makeFeatureName( labelTokens[0], labelTokens[1], metaData) # print featName rowLabels += [featName] for iC in range(numCol): try: fVal = float(tokenList[iC + 1]) dataMatrix[iR][iC] = fVal except: dataMatrix[iR][iC] = NA_VALUE numNA += 1 iR += 1 print " iR=%d numNA=%d " % (iR, numNA) dataD = {} dataD['rowLabels'] = rowLabels dataD['colLabels'] = hdrTokens[1:] dataD['dataMatrix'] = dataMatrix dataD['dataType'] = "N:MIRN" print ' writing out data matrix to ', outFilename newFeatureName = "C:SAMP:mirnPlatform:::::seq" newFeatureValue = zPlat dataD = tsvIO.addConstFeature(dataD, newFeatureName, newFeatureValue) sortRowFlag = 0 sortColFlag = 0 tsvIO.writeTSV_dataMatrix( dataD, sortRowFlag, sortColFlag, outFilename) print ' ' print ' DONE !!! ' print ' ' # -#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#
cancerregulome/gidget
commands/feature_matrix_construction/main/new_Level3_miRNAseq.py
Python
mit
11,860
# -*- coding: utf-8 -*- from datetime import timedelta from workalendar.core import WesternCalendar, ChristianMixin class Cyprus(WesternCalendar, ChristianMixin): "Cyprus" include_epiphany = True include_clean_monday = True include_good_friday = True include_easter_saturday = True include_easter_sunday = True include_easter_monday = True include_whit_monday = True whit_monday_label = 'Pentecost Monday' include_christmas_eve = True include_christmas_day = True include_boxing_day = True FIXED_HOLIDAYS = WesternCalendar.FIXED_HOLIDAYS + ( (3, 25, "Greek Independence Day"), (4, 1, "Cyprus National Day"), (5, 1, "Labour Day"), (7, 15, "Dormition of the Theotokos"), (10, 1, "Cyprus Independence Day"), (10, 28, "Greek National Day"), ) def get_variable_days(self, year): days = super(Cyprus, self).get_variable_days(year) days.append((self.get_easter_monday(year) + timedelta(days=1), "Easter Tuesday")) return days
gregn610/workalendar
workalendar/europe/cyprus.py
Python
mit
1,077
## # This concern adds a monthly calendar view of reservations for a given resource # to a controller. It can be used to provide a standalone view with the # appropriate routing, but can also be used to insert a `calendar` partial into # other views. It requires that the `GET :calendar` route be added to the # relevant resource and that the following (private) methods be implemented: # # === generate_calendar_reservations # This method should return the relevant list of reservations to display in # the calendar # # === generate_calendar_resource # This method should return the relevant instance of the current controller's # model (e.g. the equipment model whose calendar is being requested) # # === calendar_name_method # This is the method that will be called to get the title of each "event". It # is a symbol that will be called on an instance of Reservation whose return # value should accept a #name method (e.g. `reserver` or `equipment_model`) module Calendarable extend ActiveSupport::Concern ## # This method responds to requests for /[RESOURCE_ROUTE]/calendar (e.g. # /equipment_models/:id/calendar. It responds to three formats - HTML, which # is used for the actual page; JSON, which is used to return source data for # the FullCalendar calendar; and ICS, which is used to return an # iCalendar-compatible calendar for use with Google Calendar. def calendar # rubocop:disable AbcSize, MethodLength prepare_calendar_vars # extract calendar data respond_to do |format| format.html format.json { @calendar_res = generate_calendar_reservations } # generate iCal version # see https://gorails.com/forum/multi-event-ics-file-generation format.ics do @calendar_res = generate_calendar_reservations cal = Icalendar::Calendar.new @calendar_res.each do |r| event = Icalendar::Event.new event.dtstart = Icalendar::Values::Date.new(r.start_date) event.dtend = Icalendar::Values::Date.new(r.end_date + 1.day) event.summary = r.reserver.name event.location = r.equipment_item.name unless r.equipment_item.nil? event.url = reservation_url(r, format: :html) cal.add_event(event) end cal.publish response.headers['Content-Type'] = 'text/calendar' response.headers['Content-Disposition'] = 'attachment; filename=reservations.ics' render text: cal.to_ical end end end private ## # Prepares all necessary instance variables for calendar; calls the necessary # private methods (see above). def prepare_calendar_vars @start_date = calendar_start_date @end_date = calendar_end_date @resource = generate_calendar_resource @src_path = generate_source_path @name_method = calendar_name_method end ## # Returns the start date for the calendar view / export, defaulting to 6 # months prior to today and otherwise reading values from either # params[:start] (for requests from FullCalendar) or # params[:calendar][:start_date] (for export requests). def calendar_start_date if params[:start] Time.zone.parse(params[:start]).to_date elsif params[:calendar] && params[:calendar][:start_date] Time.zone.parse(params[:calendar][:start_date]).to_date else Time.zone.today - 6.months end end ## # Returns the end date for the calendar view / export, defaulting to 6 months # from today and otherwise reading values from either params[:end] (for # requests from FullCalendar) or params[:calendar][:end_date] (for export # requests). def calendar_end_date if params[:end] Time.zone.parse(params[:end]).to_date elsif params[:calendar] && params[:calendar][:end_date] Time.zone.parse(params[:calendar][:end_date]).to_date else Time.zone.today + 6.months end end ## # This method should return the relevant list of reservations to display in # the calendar def generate_calendar_reservations raise NotImplementedError end ## # This method should return the relevant instance of the current controller's # model (e.g. the equipment model whose calendar is being requested) def generate_calendar_resource raise NotImplementedError end ## # Returns the Rails URL helper for the current calendar view (used to # generate the JSON source URL) def generate_source_path "calendar_#{@resource.class.to_s.underscore}_path".to_sym end ## # This is the method that will be called to get the title of each "event". It # is a symbol that will be called on an instance of Reservation whose return # value should accept a #name method (e.g. `reserver` or `equipment_model`) def calendar_name_method raise NotImplementedError end end
nickholden101/reservations
app/controllers/concerns/calendarable.rb
Ruby
mit
4,810
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0);cin.tie(0); bool seen[181] = {}; int h=0, m=0; for (int i=1; i<=720; ++i) { if (i%12==0) h = (h + 1) % 60; m = (m + 1) % 60; int d = fabs(m-h); if (d > 30) d -= 30; seen[d * 6] = true; } while (cin >> m) cout << (seen[m] ? "Y\n" : "N\n"); }
arash16/prays
UVA/vol-125/12531.cpp
C++
mit
418
/*!-------------------------------------------------------- * Copyright (C) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ /*--------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. *--------------------------------------------------------*/ define("vs/workbench/parts/git/node/askpass.nls", { "vs/base/common/errors": [ "{0}. Error code: {1}", "Permission Denied (HTTP {0})", "Permission Denied", "{0} (HTTP {1}: {2})", "{0} (HTTP {1})", "Unknown Connection Error ({0})", "An unknown connection error occurred. Either you are no longer connected to the internet or the server you are connected to is offline.", "{0}: {1}", "An unknown error occurred. Please consult the log for more details.", "A system error occured ({0})", "An unknown error occurred. Please consult the log for more details.", "{0} ({1} errors in total)", "An unknown error occurred. Please consult the log for more details.", "Not Implemented", "Illegal argument: {0}", "Illegal argument", "Illegal state: {0}", "Illegal state", "Failed to load a required file. Either you are no longer connected to the internet or the server you are connected to is offline. Please refresh the browser to try again.", "Failed to load a required file. Please restart the application to try again. Details: {0}" ] });
KTXSoftware/KodeStudio-linux32
resources/app/out/vs/workbench/parts/git/node/askpass.nls.js
JavaScript
mit
1,436
<?php class Menu_controller extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('myaccount_model'); $this->load->model('sitesetting_model'); $this->load->model('common_model'); $this->load->model('User_email_model'); $this->load->library('ImageThumb'); } /** * Load the main view with all the current model model's data. * @return void */ public function index() { $user_id = ($this->session->userdata('user_id_hotcargo')) ? $this->session->userdata('user_id_hotcargo') : 1; $setting_data = $this->myaccount_model->get_account_data($user_id); $data['data']['setting_data'] = $setting_data; $data['data']['settings'] = $this->sitesetting_model->get_settings(); $data['data']['dealer_id'] = $user_id; //settings data $data['myaccount_data'] = $this->myaccount_model->get_account_data($user_id); $this->mongo_db->where(array('menu_type' => '0')); $all_admin_menus = $this->mongo_db->get('menus'); $this->mongo_db->where(array('menu_type' => '1')); $all_site_menus = $this->mongo_db->get('menus'); $data['data']['all_admin_menus'] = $all_admin_menus; $data['data']['all_site_menus'] = $all_site_menus; //$data['data']['all_forms'] = array(); $data['view_link'] = 'admin/menus/index'; $this->load->view('includes/template', $data); } public function show_menus() { $menu_type = $this->uri->segment(3); $user_id = ($this->session->userdata('user_id_hotcargo')) ? $this->session->userdata('user_id_hotcargo') : 1; $setting_data = $this->myaccount_model->get_account_data($user_id); $data['data']['setting_data'] = $setting_data; $data['data']['settings'] = $this->sitesetting_model->get_settings(); $data['data']['dealer_id'] = $user_id; //settings data $data['myaccount_data'] = $this->myaccount_model->get_account_data($user_id); if($menu_type == 'admin') $this->mongo_db->where(array('menu_type' => '0')); elseif($menu_type == 'site') $this->mongo_db->where(array('menu_type' => '1')); $all_menus = $this->mongo_db->get('menus'); $data['data']['all_menus'] = $all_menus; //$data['data']['all_forms'] = array(); $data['view_link'] = 'admin/menus/show_menus'; $this->load->view('includes/template', $data); } } ?>
ArijitK2015/love_-architect
application/controllers/Menu_controller.php
PHP
mit
2,403
<?php namespace Geos\UserBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class GeosUserExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.xml'); } }
spatindsaongo/geos
src/Geos/UserBundle/DependencyInjection/GeosUserExtension.php
PHP
mit
874
import { CodeNameCodeSequenceValues } from '../enums'; import getSequenceAsArray from './getSequenceAsArray'; import getMergedContentSequencesByTrackingUniqueIdentifiers from './getMergedContentSequencesByTrackingUniqueIdentifiers'; import processMeasurement from './processMeasurement'; const getMeasurements = ( ImagingMeasurementReportContentSequence, displaySet ) => { const ImagingMeasurements = ImagingMeasurementReportContentSequence.find( item => item.ConceptNameCodeSequence.CodeValue === CodeNameCodeSequenceValues.ImagingMeasurements ); const MeasurementGroups = getSequenceAsArray( ImagingMeasurements.ContentSequence ).filter( item => item.ConceptNameCodeSequence.CodeValue === CodeNameCodeSequenceValues.MeasurementGroup ); const mergedContentSequencesByTrackingUniqueIdentifiers = getMergedContentSequencesByTrackingUniqueIdentifiers( MeasurementGroups ); let measurements = []; Object.keys(mergedContentSequencesByTrackingUniqueIdentifiers).forEach( trackingUniqueIdentifier => { const mergedContentSequence = mergedContentSequencesByTrackingUniqueIdentifiers[ trackingUniqueIdentifier ]; const measurement = processMeasurement(mergedContentSequence, displaySet); if (measurement) { measurements.push(measurement); } } ); return measurements; }; export default getMeasurements;
OHIF/Viewers
platform/core/src/DICOMSR/SCOORD3D/utils/getMeasurements.js
JavaScript
mit
1,434
using System; namespace BankSystem { public interface IWithdrawable { void Withdraw(decimal amount); } }
kalinalazarova1/TelerikAcademy
Programming/3. OOP/OOP_05.Fundamental Principles Part 2/02. BankSystem/IWithdrawable.cs
C#
mit
129
describe('GET /docs/:docUUID', function() { beforeEach(function *() { yield fixtures.load(); this.reader = fixtures.users[1]; yield this.reader.addTeam(fixtures.teams[0]); yield fixtures.teams[0].addProject(fixtures.projects[0], { permission: 'read' }); this.collection = fixtures.collections[0]; yield fixtures.projects[0].addCollection(this.collection); this.doc = fixtures.docs[0]; yield this.collection.addDoc(this.doc); }); it('should return Unauthorized when user is unauthorized', function *() { try { yield API.docs(this.doc.UUID).get(); throw new Error('should reject'); } catch (err) { expect(err).to.be.an.error(HTTP_ERROR.Unauthorized); } }); it('should return NotFound when doc is not found', function *() { try { yield API.$auth(this.reader.email, this.reader.password).docs('not exists UUID').get(); throw new Error('should reject'); } catch (err) { expect(err).to.be.an.error(HTTP_ERROR.NotFound); } }); it('should return NoPermission when the user don\'t have read permission', function *() { var guest = fixtures.users[2]; try { yield API.$auth(guest.email, guest.password).docs(this.doc.UUID).get(); throw new Error('should reject'); } catch (err) { expect(err).to.be.an.error(HTTP_ERROR.NoPermission); } }); it('should return the current version', function *() { yield Doc.createWithTransaction({ UUID: this.doc.UUID, CollectionId: this.doc.CollectionId, title: 'new title', content: 'new content' }); var doc = yield API.$auth(this.reader.email, this.reader.password).docs(this.doc.UUID).get(); expect(doc.title).to.eql('new title'); expect(doc.content).to.eql('new content'); expect(doc.current).to.eql(true); expect(doc.UUID).to.eql(this.doc.UUID); }); describe('?version=:version', function() { it('should return the specified version', function *() { var version1 = yield Doc.createWithTransaction({ UUID: this.doc.UUID, CollectionId: this.doc.CollectionId, title: 'version1', content: 'version 1' }); var version2 = yield Doc.createWithTransaction({ UUID: this.doc.UUID, CollectionId: this.doc.CollectionId, title: 'version2', content: 'version 2' }); var doc = yield API.$auth(this.reader.email, this.reader.password).docs(this.doc.UUID).get({ version: version1.version }); expect(doc.title).to.eql(version1.title); expect(doc.content).to.eql(version1.content); expect(doc.version).to.eql(version1.version); }); }); });
wikilab/wikilab-api
test/api/routes/docs/get_doc.js
JavaScript
mit
2,676
using System; ref struct Sample { public void Dispose() { Console.WriteLine("Disposed"); } } class Program { static void Main() { using(var s = new Sample()) { Console.WriteLine("Now working 'ref struct Sample!'"); } } }
autumn009/TanoCSharpSamples
Chap35/DisposeRefStruct/DisposeRefStruct/Program.cs
C#
mit
294
module Quotes module Gateways class PublicationsGateway < Gateway def initialize(backend = nil) @backend = backend || backend_for_publications @marshal = PublicationMarshal end def add(publication) ensure_valid!(publication) @backend.insert(serialized(publication)) end def get(uid) deserialize(@backend.get(uid)) end def all @backend.all.map do |publication| deserialize(publication) end end def update(publication) ensure_persisted!(publication.uid, 'update', 'publication') @backend.update(serialized(publication)) end def delete(uid) ensure_persisted!(uid, 'delete', 'publication') @backend.delete(uid) end private def marshal @marshal end class PublicationMarshal def self.dump(publication) { :publication_uid => publication.uid, :publication_added_by => publication.added_by, :author => publication.author, :title => publication.title, :publisher => publication.publisher, :year => publication.year } end def self.load(publication) return nil unless publication added_by = publication[:publication_added_by] author = publication[:author] title = publication[:title] publisher = publication[:publisher] year = publication[:year] uid = publication[:publication_uid] Entities::Publication.new(added_by, author, title, publisher, year, uid) end end end end end
daxadax/quotes
lib/quotes/gateways/publications_gateway.rb
Ruby
mit
1,706
<?php // src/Acme/UserBundle/Entity/User.php namespace Acme\UserBundle\Entity; use FOS\UserBundle\Model\User as BaseUser; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="acme_user") */ class User extends BaseUser { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; public function __construct() { parent::__construct(); // your own logic } }
pulwar/dom
src/Acme/UserBundle/Entity/User.php
PHP
mit
477
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Event extends MY_model{ public function getTable(){ return 'tb_event'; } public function rules(){ return [ ['name', 'alpha_numeric'], ['description', 'alpha_numeric'], ]; } public function currentEvents(){ $query = $this->db->get_where( 'tb_event', 'finished != 1' ); return $query->result(); } public function eventPackages( $event_id ){ $query = $this->db->get_where( 'tb_packages', "event_id = ".$event_id ); $packages = $query->result(); if( $query ){ $modifiers = []; $dates = []; $sql = $this->db->last_query(); foreach( $packages as $package ){ $modifiers[$package->id] = $this->packageModifiers( $package->id ); $dates[$package->id] = $this->packageDates( $package->id ); } return compact( 'packages', 'modifiers', 'dates', 'sql' ); } } public function packageModifiers( $package_id ){ $query = "SELECT pk_mod.* FROM tb_packages pk INNER JOIN tb_package_modifiers pk_mod ON pk_mod.package_id = pk.id WHERE pk.id = {$package_id}"; $modifiers = $this->db->query( $query ); return $modifiers->result(); } public function packageDates( $package_id ){ $query = "SELECT ev_dt.* FROM tb_package_dates pk_dt INNER JOIN tb_event_dates ev_dt ON ev_dt.id = pk_dt.event_date_id WHERE pk_dt.package_id = {$package_id}"; $dates = $this->db->query( $query ); return $dates->result(); } }
kaabsimas/caravana
application/models/Event.php
PHP
mit
1,494
<?php namespace Amp\Test; use Amp\Delayed; use Amp\Loop; use Amp\PHPUnit\TestCase; use function Amp\Promise\wait; abstract class BaseTest extends TestCase { public function tearDown(): void { parent::tearDown(); Loop::setErrorHandler(); $this->clearLoopRethrows(); } private function clearLoopRethrows() { $errors = []; retry: try { wait(new Delayed(0)); } catch (\Throwable $e) { $errors[] = (string) $e; goto retry; } if ($errors) { \set_error_handler(null); \trigger_error(\implode("\n", $errors), E_USER_ERROR); } $info = Loop::getInfo(); if ($info['enabled_watchers']['referenced'] + $info['enabled_watchers']['unreferenced'] > 0) { \set_error_handler(null); \trigger_error( "Found enabled watchers on test end: " . \json_encode($info, \JSON_PRETTY_PRINT), E_USER_ERROR ); } } }
amphp/amp
test/BaseTest.php
PHP
mit
1,050
<?php /* * The MIT License (MIT) * * Copyright (c) 2015 zepi * * 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. * */ /** * Generates and manages the cache for the asset files. * * @package Zepi\Web\General * @subpackage Manager * @author Matthias Zobrist <matthias.zobrist@zepi.net> * @copyright Copyright (c) 2016 zepi */ namespace Zepi\Web\General\Manager; use \Zepi\Turbo\Framework; use \Zepi\Turbo\Backend\ObjectBackendAbstract; use \Zepi\Turbo\Backend\FileBackend; use \Zepi\Web\General\Manager\AssetManager; use \Zepi\Web\General\Helper\CssHelper; use \Zepi\Web\General\Entity\Asset; /** * Generates and manages the cache for the asset files. * * @author Matthias Zobrist <matthias.zobrist@zepi.net> * @copyright Copyright (c) 2016 zepi */ class AssetCacheManager { /** * @access protected * @param array */ protected $assetTypes = array( AssetManager::CSS => array('minify' => true), AssetManager::JS => array('minify' => true), AssetManager::IMAGE => array('minify' => false), AssetManager::BINARY => array('minify' => false) ); /** * @access protected * @var array */ protected $cachedFiles = array(); /** * @var \Zepi\Turbo\Framework */ protected $framework; /** * @var \Zepi\Web\General\Manager\AssetManager */ protected $assetManager; /** * @access protected * @var \Zepi\Turbo\Backend\ObjectBackendAbstract */ protected $cachedFilesObjectBackend; /** * @access protected * @var \Zepi\Turbo\Backend\FileBackend */ protected $fileBackend; /** * @access protected * @var \Zepi\Web\General\Helper\CssHelper */ protected $cssHelper; /** * @access protected * @var boolean */ protected $minifyAssets; /** * @access protected * @var boolean */ protected $combineAssets; /** * Constructs the object * * @access public * @param \Zepi\Turbo\Framework $framework * @param \Zepi\Web\General\Manager\AssetManager $assetManager * @param \Zepi\Turbo\Backend\ObjectBackendAbstract $cachedFilesObjectBackend * @param \Zepi\Turbo\Backend\FileBackend $fileBackend * @param \Zepi\Web\General\Helper\CssHelper $cssHelper * @param boolean $minifyAssets * @param boolean $combineAssets */ public function __construct( Framework $framework, AssetManager $assetManager, ObjectBackendAbstract $cachedFilesObjectBackend, FileBackend $fileBackend, CssHelper $cssHelper, $minifyAssets, $combineAssets ) { $this->framework = $framework; $this->assetManager = $assetManager; $this->cachedFilesObjectBackend = $cachedFilesObjectBackend; $this->fileBackend = $fileBackend; $this->cssHelper = $cssHelper; $this->minifyAssets = $minifyAssets; $this->combineAssets = $combineAssets; } /** * Initializes the asset manager. * * @access public */ public function initializeAssetCacheManager() { $this->loadAssetsCache(); } /** * Loads cache data for the assets * * @access public */ protected function loadAssetsCache() { $cachedFiles = $this->cachedFilesObjectBackend->loadObject(); if (!is_array($cachedFiles)) { $cachedFiles = array(); } $this->cachedFiles = $cachedFiles; } /** * Saves the assets cache to the file backend. * * @access public */ protected function saveAssetsCache() { $this->cachedFilesObjectBackend->saveObject($this->cachedFiles); } /** * Returns the file path for the given type, hash and version. * * @access protected * @param string $type * @param string $hash * @param string $version * @return string */ protected function buildFilePath($type, $hash, $version) { return $type . '/' . $hash . '/' . $version; } /** * Returns true if the given file is cached, otherwise return false. * * @access public * @param string $type * @param string $hash * @param string $version * @return boolean */ public function isCached($type, $hash, $version) { // If the base file isn't cached we do not need to check the file names if (!isset($this->cachedFiles[$hash])) { return false; } $searchedFile = $this->buildFilePath($type, $hash, $version); foreach ($this->cachedFiles as $baseFileHash => $cachedFile) { if ($cachedFile['file'] === $searchedFile) { return true; } } return false; } /** * Returns the content of the given type and file. * * @access public * @param string $type * @param string $hash * @param string $version * @return string */ public function getAssetContent($type, $hash, $version) { if (!$this->isCached($type, $hash, $version)) { return ''; } $targetFile = $this->buildFilePath($type, $hash, $version); return $this->fileBackend->loadFromFile($targetFile); } /** * Returns the timestamp of the cached asset * * @param string $type * @param string $hash * @param string $version * @return integer */ public function getCachedAssetTimestamp($type, $hash, $version) { if (!$this->isCached($type, $hash, $version)) { return 0; } return $this->cachedFiles[$hash]['timestamp']; } /** * Make the cache for an asset type and display the html * code to include the asset type. * * @access public * @param string $type * @return string */ public function displayAssetType($type) { $files = $this->assetManager->getAssetFiles($type); // If there are no files for the given type return here. if ($files === false) { return; } if ($this->combineAssets) { $this->displayCombinedAssets($type, $files); } else { foreach ($files as $file) { $cachedFile = $this->generateCachedFile($type, $file->getFileName()); if ($cachedFile !== false) { echo $this->generateHtmlCode($type, $cachedFile['file']); } } } } /** * Displays the combined assets for the given asset type * * @param string $type * @param array $files */ protected function displayCombinedAssets($type, $files) { $isValid = $this->validateTypeCache($type, $files); // If the cache isn't valid, we build the cache $result = $isValid; if (!$isValid) { $result = $this->buildTypeCache($type, $files); } // If the cache is valid, load the file if ($result) { $hash = $this->getTypeHash($type); $cachedFile = $this->cachedFiles[$hash]['file']; echo $this->generateHtmlCode($type, $cachedFile); } } /** * Returns the url for one asset. * * @access public * @param string $type * @param string $assetName * @return string */ public function getAssetUrl($type, $assetName) { $file = $this->assetManager->getAssetFile($type, $assetName); if ($file === false) { return; } $cachedFile = $this->generateCachedFile($type, $file->getFileName()); return $this->getUrlToTheAssetLoader($cachedFile['file']); } /** * Generates a cached file for the given type and base file. * * @access public * @param string $type * @param string $fileName * @return string|false */ public function generateCachedFile($type, $fileName) { $isValid = $this->validateCache($fileName); // If the cache isn't valid, we build the cache $result = $isValid; if (!$isValid) { $result = $this->buildFileCache($type, $fileName); } // If the cache is valid, load the file if ($result) { $hash = $this->getHash($fileName); return $this->cachedFiles[$hash]; } return false; } /** * Returns the full url to the asset manager to load the * given file. * * @access public * @param string $file * @return string */ public function getUrlToTheAssetLoader($file) { return $this->framework->getRequest()->getFullRoute('/assets/' . $file); } /** * Clears the asset cache. * * @access public */ public function clearAssetCache() { foreach ($this->cachedFiles as $hash => $fileData) { if (!$this->fileBackend->isWritable($fileData['file'])) { continue; } $this->fileBackend->deleteFile($fileData['file']); } $this->cachedFiles = array(); $this->saveAssetsCache(); } /** * Builds the cache for an asset type * * @access protected * @param string $type * @param array $files * @return string */ protected function buildTypeCache($type, $files) { $typeContent = ''; $fileHashs = array(); // Generate the content for all the files foreach ($files as $file) { $fileName = $file->getFileName(); if (!file_exists($fileName)) { continue; } // Load the content $content = $this->fileBackend->loadFromFile($fileName); // Optimze the content $content = $this->optimizeContent($type, $fileName, $content); // Add the content and save the file hash $typeContent .= $content; $fileHashs[$this->getHash($fileName)] = md5_file($fileName); } // Minify the content, if possible and activated if (($type === AssetManager::CSS || $type === AssetManager::JS) && $this->minifyAssets) { $typeContent = $this->minifyContent($type, $typeContent); } // Generate the hash and the new file name $hash = $this->getTypeHash($type); $version = $type . '-' . uniqid() . '.' . $this->getExtensionForType($type); $targetFile = $this->buildFilePath($type, $hash, $version); // Save the cached file $this->removeOldTypeCacheFile($type); $this->fileBackend->saveToFile($typeContent, $targetFile); // Save the cached files in the data array $this->cachedFiles[$hash] = array( 'file' => $targetFile, 'checksums' => $fileHashs, 'timestamp' => time() ); $this->saveAssetsCache(); return $targetFile; } /** * Generates the cache for the given files. * * @access protected * @param string $type * @param string $fileName * @return false|string */ protected function buildFileCache($type, $fileName) { if (!file_exists($fileName)) { return false; } // Load the content $content = $this->fileBackend->loadFromFile($fileName); // Optimze the content $content = $this->optimizeContent($type, $fileName, $content); // Minify the content, if possible and activated if (($type === AssetManager::CSS || $type === AssetManager::JS) && $this->minifyAssets) { $content = $this->minifyContent($type, $content); } // Generate the new file name $fileInfo = pathinfo($fileName); $hash = $this->getHash($fileName); $version = $fileInfo['filename'] . '-' . uniqid() . '.' . $fileInfo['extension']; $targetFile = $this->buildFilePath($type, $hash, $version); // Save the cached file $this->removeOldCacheFile($fileName); $this->fileBackend->saveToFile($content, $targetFile); // Save the cached files in the data array $this->cachedFiles[$hash] = array( 'file' => $targetFile, 'checksum' => md5_file($fileName), 'timestamp' => time() ); $this->saveAssetsCache(); return $targetFile; } /** * Optimizes the content. Example: inserts the content of * the images in the css file and replaces all other files * with the absolute url through the asset manager. * * @access protected * @param string $type * @param string $file * @param string $content * @return string */ protected function optimizeContent($type, $file, $content) { if ($type === AssetManager::CSS) { $content = $this->cssHelper->optimizeCssContent($this, $content, $file); } return $content; } /** * Returns the minified version of the content. * Attention: this is only a easy minifing method! * * @access protected * @param string $type * @param string $content * @return string */ protected function minifyContent($type, $content) { $minifier = null; if ($type === AssetManager::CSS) { $minifier = new \MatthiasMullie\Minify\CSS($content); } else if ($type === AssetManager::JS) { $minifier = new \MatthiasMullie\Minify\JS($content); } if ($minifier !== null) { return $minifier->minify(); } return $content; } /** * Returns true if there is a cached file for the given * hash * * @access protected * @param string $hash * @return boolean */ protected function hasCachedFile($hash) { return (isset($this->cachedFiles[$hash])); } /** * Deletes the old cache file before a new one is saved. * * @access protected * @param string $file */ protected function removeOldCacheFile($file) { $hash = $this->getHash($file); $this->removeCacheFile($hash); } /** * Deletes the old type cache file before a new one is saved. * * @access protected * @param string $type */ protected function removeOldTypeCacheFile($type) { $hash = $this->getTypeHash($type); $this->removeCacheFile($hash); } /** * Deletes the cache file for the given hash * * @param string $hash * @return boolean */ protected function removeCacheFile($hash) { if (!$this->hasCachedFile($hash)) { return false; } $fileData = $this->cachedFiles[$hash]; $this->fileBackend->deleteFile($fileData['file']); } /** * Returns false, if the cached version of the given * file isn't up to date. * * @access protected * @param string $fileName * @return boolean */ protected function validateCache($fileName) { $hash = $this->getHash($fileName); if (!file_exists($fileName) || !isset($this->cachedFiles[$hash])) { return false; } $fileChecksum = md5_file($fileName); $cachedChecksum = $this->cachedFiles[$hash]['checksum']; if ($fileChecksum != $cachedChecksum) { return false; } return true; } /** * Validates the cache for an asset type. Return false, if the * cache isn't valid. * * @access protected * @param string $type * @param array $files * @return boolean */ protected function validateTypeCache($type, $files) { // If the files isn't cached we have to cache the file $hash = $this->getTypeHash($type); if (!isset($this->cachedFiles[$hash])) { return false; } $data = $this->cachedFiles[$hash]; $checksums = $data['checksums']; // Are all files existing? foreach ($files as $file) { if (!file_exists($file->getFileName())) { return false; } $fileHash = $this->getHash($file->getFileName()); $contentHash = md5_file($file->getFileName()); if (!isset($checksums[$fileHash]) || $contentHash !== $checksums[$fileHash]) { return false; } } return true; } /** * Returns the file extension for the given type. * * @access protected * @param string $type * @return string */ protected function getExtensionForType($type) { if ($type === AssetManager::CSS) { return 'css'; } else if ($type === AssetManager::JS) { return 'js'; } } /** * Generates the html code for the given asset * * @access protected * @param string $type * @param string $file * @return string */ protected function generateHtmlCode($type, $file) { // Generate the url $url = $this->getUrlToTheAssetLoader($file); // Return the correct html tag if ($type === AssetManager::CSS) { return '<link rel="stylesheet" type="text/css" href="' . $url . '">' . PHP_EOL; } else if ($type === AssetManager::JS) { return '<script type="text/javascript" src="' . $url . '"></script>' . PHP_EOL; } } /** * Returns the hash for the asset type. * * @access protected * @param string $type * @return string */ protected function getTypeHash($type) { return md5($type); } /** * Returns the hash for the given file path. * * @access protected * @param string $fileName * @return string */ protected function getHash($fileName) { return md5($fileName); } }
zepi/turbo-base
Zepi/Web/General/src/Manager/AssetCacheManager.php
PHP
mit
19,601
using System; using System.Reflection.Emit; namespace FluentMethods.UnitTests { public partial class ILGeneratorFixture { #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstInt32() { LoadConstInt32(-1); LoadConstInt32(0); LoadConstInt32(1); LoadConstInt32(2); LoadConstInt32(3); LoadConstInt32(4); LoadConstInt32(5); LoadConstInt32(6); LoadConstInt32(7); LoadConstInt32(8); LoadConstInt32(20); LoadConstInt32(200); LoadConstInt32(-200); LoadConstInt32(int.MinValue); LoadConstInt32(int.MaxValue); } private void LoadConstInt32(int value) { var method = new DynamicMethod("xm", typeof(int), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<int>)method.CreateDelegate(typeof(Func<int>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstUInt32() { LoadConstUInt32(0); LoadConstUInt32(1); LoadConstUInt32(2); LoadConstUInt32(3); LoadConstUInt32(4); LoadConstUInt32(5); LoadConstUInt32(6); LoadConstUInt32(7); LoadConstUInt32(8); LoadConstUInt32(20); LoadConstUInt32(200); LoadConstUInt32((uint)int.MaxValue + 20); LoadConstUInt32(uint.MinValue); LoadConstUInt32(uint.MaxValue); } private void LoadConstUInt32(uint value) { var method = new DynamicMethod("xm", typeof(uint), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<uint>)method.CreateDelegate(typeof(Func<uint>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstInt64() { LoadConstInt64(-1); LoadConstInt64(0); LoadConstInt64(1); LoadConstInt64(2); LoadConstInt64(3); LoadConstInt64(4); LoadConstInt64(5); LoadConstInt64(6); LoadConstInt64(7); LoadConstInt64(8); LoadConstInt64(20); LoadConstInt64(200); LoadConstInt64(-200); LoadConstInt64((long)int.MaxValue + 20); LoadConstInt64((long)int.MinValue - 20); LoadConstInt64(long.MaxValue); LoadConstInt64(long.MinValue); } private void LoadConstInt64(long value) { var method = new DynamicMethod("xm", typeof(long), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<long>)method.CreateDelegate(typeof(Func<long>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstUInt64() { LoadConstUInt64(0); LoadConstUInt64(1); LoadConstUInt64(2); LoadConstUInt64(3); LoadConstUInt64(4); LoadConstUInt64(5); LoadConstUInt64(6); LoadConstUInt64(7); LoadConstUInt64(8); LoadConstUInt64(20); LoadConstUInt64(200); LoadConstUInt64((ulong)long.MaxValue + 20); LoadConstUInt64(ulong.MaxValue); LoadConstUInt64(ulong.MinValue); } private void LoadConstUInt64(ulong value) { var method = new DynamicMethod("xm", typeof(ulong), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<ulong>)method.CreateDelegate(typeof(Func<ulong>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstFloat() { LoadConstFloat(0); LoadConstFloat((float)0.5); LoadConstFloat(float.MaxValue); LoadConstFloat(float.MinValue); } private void LoadConstFloat(float value) { var method = new DynamicMethod("xm", typeof(float), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<float>)method.CreateDelegate(typeof(Func<float>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstDouble() { LoadConstDouble(0); LoadConstDouble(0.5); LoadConstDouble(double.MaxValue); LoadConstDouble(double.MinValue); } private void LoadConstDouble(double value) { var method = new DynamicMethod("xm", typeof(double), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<double>)method.CreateDelegate(typeof(Func<double>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstBoolean() { LoadConstBoolean(true); LoadConstBoolean(false); } private void LoadConstBoolean(bool value) { var method = new DynamicMethod("xm", typeof(bool), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<bool>)method.CreateDelegate(typeof(Func<bool>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstChar() { LoadConstChar((char)0); LoadConstChar((char)32); LoadConstChar(char.MaxValue); LoadConstChar(char.MinValue); } private void LoadConstChar(char value) { var method = new DynamicMethod("xm", typeof(char), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<char>)method.CreateDelegate(typeof(Func<char>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstByte() { LoadConstByte(0); LoadConstByte(20); LoadConstByte(byte.MaxValue); LoadConstByte(byte.MinValue); } private void LoadConstByte(byte value) { var method = new DynamicMethod("xm", typeof(byte), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<byte>)method.CreateDelegate(typeof(Func<byte>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstSByte() { LoadConstSByte(0); LoadConstSByte(20); LoadConstSByte(-20); LoadConstSByte(sbyte.MinValue); LoadConstSByte(sbyte.MaxValue); } private void LoadConstSByte(sbyte value) { var method = new DynamicMethod("xm", typeof(sbyte), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<sbyte>)method.CreateDelegate(typeof(Func<sbyte>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstString() { LoadConstString(null); LoadConstString(string.Empty); LoadConstString("Fizz"); } private void LoadConstString(string value) { var method = new DynamicMethod("xm", typeof(string), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<string>)method.CreateDelegate(typeof(Func<string>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstDecimal() { LoadConstDecimal(0); LoadConstDecimal((decimal)12.345); LoadConstDecimal(decimal.MaxValue); LoadConstDecimal(decimal.MinValue); LoadConstDecimal(decimal.One); LoadConstDecimal(decimal.MinusOne); LoadConstDecimal(int.MaxValue); LoadConstDecimal(int.MinValue); LoadConstDecimal(long.MinValue); LoadConstDecimal(long.MaxValue); } private void LoadConstDecimal(decimal value) { var method = new DynamicMethod("xm", typeof(decimal), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<decimal>)method.CreateDelegate(typeof(Func<decimal>)); Assert.Equal(value, func()); } #if NetCore [Xunit.Fact] #else [NUnit.Framework.Test] #endif public void LoadConstDateTime() { LoadConstDateTime(DateTime.Now); LoadConstDateTime(DateTime.UtcNow); LoadConstDateTime(DateTime.MaxValue); LoadConstDateTime(DateTime.MinValue); LoadConstDateTime(DateTime.Today); } private void LoadConstDateTime(DateTime value) { var method = new DynamicMethod("xm", typeof(DateTime), new Type[0]); var il = method.GetILGenerator(); il.LoadConst(value); il.Emit(OpCodes.Ret); var func = (Func<DateTime>)method.CreateDelegate(typeof(Func<DateTime>)); Assert.Equal(value, func()); } } }
edwardmeng/FluentMethods
test/Core/System.Reflection.Emit.ILGenerator/Constant/LoadConst.cs
C#
mit
11,034
var test = require('tape') var secstamp = require('../') test('generates seconds properly', function (t) { t.equals(secstamp(42), '0:42') t.end() }) test('accepts string as input', function (t) { t.equals(secstamp(42), secstamp('42')) t.end() }) test('pads periods with 0s if needed', function (t) { t.equals(secstamp(34), '0:34', "doesn't pad seconds greater than 10") t.equals(secstamp(0), '0:00', 'pads seconds less than 10') t.equals(secstamp(1), '0:01', 'pads seconds less than 10') t.equals(secstamp(63), '1:03', "doesn't pad minutes when no hours present") t.equals(secstamp(4357), '1:12:37', "doesn't pad minutes when hours present and minutes >= 10") t.equals(secstamp(3657), '1:00:57', "pads minutes when hours present and minutes < 10") t.equals(secstamp(31337), '8:42:17', "doesn't pad minutes when minutes > 10") t.end() }) test("returns null if input isn't a number", function (t) { t.equals(secstamp('potato'), null) t.equals(secstamp(''), null) t.equals(secstamp(null), null) t.equals(secstamp(), null) t.end() })
sidd/secstamp
test/index.js
JavaScript
mit
1,068
<?php namespace ZfcDatagridTest\Column\Action; use InvalidArgumentException; use PHPUnit\Framework\TestCase; use ZfcDatagrid\Column\Action\Icon; /** * @group Column * @covers \ZfcDatagrid\Column\Action\Icon */ class IconTest extends TestCase { public function testConstruct() { $icon = new Icon(); $this->assertEquals([ 'href' => '#', ], $icon->getAttributes()); } public function testIconClass() { $icon = new Icon(); $this->assertFalse($icon->hasIconClass()); $icon->setIconClass('icon-add'); $this->assertEquals('icon-add', $icon->getIconClass()); $this->assertTrue($icon->hasIconClass()); $this->assertEquals('<a href="#"><i class="icon-add"></i></a>', $icon->toHtml([])); } public function testIconLink() { $icon = new Icon(); $this->assertFalse($icon->hasIconLink()); $icon->setIconLink('/images/21/add.png'); $this->assertEquals('/images/21/add.png', $icon->getIconLink()); $this->assertTrue($icon->hasIconLink()); $this->assertEquals('<a href="#"><img src="/images/21/add.png" /></a>', $icon->toHtml([])); } public function testException() { $icon = new Icon(); $this->expectException(InvalidArgumentException::class); $icon->toHtml([]); } }
zfc-datagrid/zfc-datagrid
tests/ZfcDatagridTest/Column/Action/IconTest.php
PHP
mit
1,370
import { routerStateReducer as router } from 'redux-router'; import { combineReducers } from 'redux'; import entities from './entities'; import app from './app'; import cardList from './cardList'; const rootReducer = combineReducers({ router, entities, app, cardList }); export default rootReducer;
Poplava/mtg-cards
client/reducers/index.js
JavaScript
mit
310
require 'spec_helper' describe RatingScalesController do before(:each) do @rating_scale = mock_model(RatingScale) @rating_scales = [@rating_scale] @rating_scales.stub(:find).and_return(@rating_scale) @rating_scales.stub(:new).and_return(@rating_scale) @question = mock_model(Question) @questions = [@question] @user = mock_model(User, :rating_scales => @rating_scales, :questions => @questions) controller.stub(:current_user).and_return(@user) end it "finds the current user" do controller.should_receive(:current_user).and_return(@user) get :index end context "when the rating scale is not found" do before(:each) do @rating_scales.stub(:find).and_raise(ActiveRecord::RecordNotFound) end it "sets the flash message" do get :show, :id => 1 flash[:notice].should eql("You do not have access to this asset.") end it "redirects to root_url" do get :show, :id => 1 response.should redirect_to(root_url) end end describe "GET index" do context "when session[:question_id] is valid" do before(:each) do @questions.stub(:find).and_return(@question) end it "finds the question to which the user can return" do @user.should_receive(:questions).and_return(@questions) @questions.should_receive(:find).with(@question.id.to_s) get :index, {}, :question_id => @question.id.to_s end it "assigns the found question to @question" do get :index, {}, :question_id => @question.id.to_s assigns[:question].should eql(@question) end end context "when session[:question_id] is invalid" do before(:each) do @questions.stub(:find).and_raise(ActiveRecord::RecordNotFound) end it "finds nothing and returns a nil value" do @user.should_receive(:questions).and_return(@questions) @questions.should_receive(:find).with(nil).and_raise(ActiveRecord::RecordNotFound) get :index end it "assigns nil to @question" do get :index assigns[:question].should be_nil end end it "finds the rating scales belonging to this user" do @user.should_receive(:rating_scales).and_return(@rating_scales) get :index end it "renders the index template" do get :index response.should render_template(:index) end end describe "GET show" do before(:each) do @params = { :id => @rating_scale.id.to_s } end it "finds the rating scale" do @user.should_receive(:rating_scales).and_return(@rating_scales) @rating_scales.should_receive(:find).with(@params[:id]).and_return(@rating_scale) get :show, @params end it "assigns the rating scale to @rating_scale" do get :show, @params assigns[:rating_scale].should eql(@rating_scale) end it "renders the new template" do get :show, @params response.should render_template(:show) end end describe "GET new" do it "creates a new rating scale" do @user.should_receive(:rating_scales).and_return(@rating_scales) @rating_scales.should_receive(:new).and_return(@rating_scale) get :new end it "assigns the new rating scale to @rating_scale" do get :new assigns[:rating_scale].should eql(@rating_scale) end it "renders the new template" do get :new response.should render_template(:new) end end describe "GET edit" do before(:each) do @params = { :id => @rating_scale.id.to_s } end it "finds the rating scale" do @user.should_receive(:rating_scales).and_return(@rating_scales) @rating_scales.should_receive(:find).with(@params[:id]).and_return(@rating_scale) get :edit, @params end it "assigns the rating scale to @rating_scale" do get :edit, @params assigns[:rating_scale].should eql(@rating_scale) end it "renders the edit template" do get :edit, @params response.should render_template(:edit) end end describe "POST create" do before(:each) do @params = { :rating_scale => { "name" => "name" } } @rating_scale.stub(:save) end it "creates a new rating scale with params[:rating_scale]" do @user.should_receive(:rating_scales).and_return(@rating_scales) @rating_scales.should_receive(:new).with(@params[:rating_scale]).and_return(@rating_scale) post :create, @params end it "assigns the new rating scale to @rating_scale" do post :create, @params assigns[:rating_scale].should eql(@rating_scale) end it "saves the new rating scale" do @rating_scale.should_receive(:save) post :create, @params end context "when the save is successful" do before(:each) do @rating_scale.stub(:save).and_return(true) end it "sets the flash message" do post :create, @params flash[:notice].should eql("Rating scale created.") end it "redirects to edit_rating_scale_path(@rating_scale)" do post :create, @params response.should redirect_to(edit_rating_scale_path(@rating_scale)) end end context "when the save is unsuccessful" do before(:each) do @rating_scale.stub(:save).and_return(false) end it "renders the new template" do post :create, @params response.should render_template(:new) end end end describe "PUT update" do before(:each) do @params = { :id => @rating_scale.id.to_s, :rating_scale => { "name" => "name" } } @rating_scale.stub(:update_attributes) end it "finds the rating scale" do @user.should_receive(:rating_scales).and_return(@rating_scales) @rating_scales.should_receive(:find).with(@params[:id]).and_return(@rating_scale) put :update, @params end it "assigns the found rating scale to @rating_scale" do put :update, @params assigns[:rating_scale].should eql(@rating_scale) end it "updates the rating scale with params[:rating_scale]" do @rating_scale.should_receive(:update_attributes).with(@params[:rating_scale]) put :update, @params end context "when the update is successful" do before(:each) do @rating_scale.stub(:update_attributes).and_return(true) end context "when params[:commit] == 'Add Label'" do before(:each) do @params.merge!(:commit => "Add Label") @rating_label = mock_model(RatingLabel) @rating_labels = [@rating_label] @rating_scale.stub_chain(:rating_labels, :new) end it "builds a new rating label for this rating scale" do @rating_scale.should_receive(:rating_labels).and_return(@rating_labels) @rating_labels.should_receive(:new) put :update, @params end it "renders the edit template" do put :update, @params response.should render_template(:edit) end end context "when params[:commit] != 'Add Label'" do before(:each) do @params.merge!(:commit => "Update") end it "sets the flash message" do put :update, @params flash[:notice].should eql("Rating scale updated.") end it "redirects_to rating_scale_path(@rating_scale)" do put :update, @params response.should redirect_to(rating_scale_path(@rating_scale)) end end end context "when the update is unsuccessful" do before(:each) do @rating_scale.stub(:update_attributes).and_return(false) end it "renders the edit template" do put :update, @params response.should render_template(:edit) end end end describe "DELETE destroy" do before(:each) do @params = { :id => @rating_scale.id.to_s } @rating_scale.stub(:destroy) end it "finds the rating scale" do @user.should_receive(:rating_scales).and_return(@rating_scales) @rating_scales.should_receive(:find).with(@params[:id]).and_return(@rating_scale) delete :destroy, @params end it "assigns the rating scale to @rating_scale" do delete :destroy, @params assigns[:rating_scale].should eql(@rating_scale) end it "destroys the rating scale" do @rating_scale.should_receive(:destroy) delete :destroy, @params end it "sets the flash message" do delete :destroy, @params flash[:notice].should eql("Rating scale deleted.") end it "redirects to rating_scales_path" do delete :destroy, @params response.should redirect_to(rating_scales_path) end end describe "GET confirm_delete" do before(:each) do @params = { :id => @rating_scale.id.to_s } @survey = mock_model(Survey) @surveys = [@survey] @questions.stub(:find_all_by_rating_scale_id).and_return(@questions) @question.stub_chain(:section, :survey).and_return(@survey) end it "finds the rating scale" do @user.should_receive(:rating_scales).and_return(@rating_scales) @rating_scales.should_receive(:find).with(@params[:id]).and_return(@rating_scale) get :confirm_delete, @params end it "assigns the rating scale to @rating_scale" do get :confirm_delete, @params assigns[:rating_scale].should eql(@rating_scale) end it "finds all questions using this rating scale" do @questions.should_receive(:find_all_by_rating_scale_id).with(@params[:id]).and_return(@questions) get :confirm_delete, @params end it "assigns these questions to @questions" do get :confirm_delete, @params assigns[:questions].should eql(@questions) end it "collects all unique surveys covered by these questions" do @questions.should_receive(:collect).and_return(@questions) @questions.should_receive(:uniq).and_return(@surveys) get :confirm_delete, @params end it "assigns the surveys to @surveys" do get :confirm_delete, @params assigns[:surveys].should eql(@surveys) end it "renders the confirm_delete template" do get :confirm_delete, @params response.should render_template(:confirm_delete) end end end
RevolutionPrep/surveyor
spec/controllers/rating_scales_controller_spec.rb
Ruby
mit
10,798
class DiffBench class Bm def initialize(&block) @measures = {} if block.arity == -1 || block.arity > 0 block.call(self) else instance_eval(&block) end puts Encoder.encode(@measures) end def report(label) @measures[label] = Benchmark.measure do yield end end end end
bogdan/diffbench
lib/diffbench/bm.rb
Ruby
mit
354
<?php class ZendR_Tool_Project_Context_Doctrine_MigrationsDirectory extends Zend_Tool_Project_Context_Filesystem_Directory { /** * @var string */ protected $_filesystemName = 'migrations'; /** * @return string */ public function getName() { return 'MigrationsDirectory'; } }
wchampi/zend-r
lib/ZendR/Tool/Project/Context/Doctrine/MigrationsDirectory.php
PHP
mit
346
import { AccesosService } from './../../../services/accesos.service'; import { Component, AfterViewInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Router } from '@angular/router'; // import { TdDataTableSortingOrder, TdDataTableService, ITdDataTableSortChangeEvent } from '@covalent/core'; // import { IPageChangeEvent } from '@covalent/core'; // import { DataTableModule, SharedModule } from 'primeng/primeng'; import { TerminalCustomerIdxService } from '../../../services/terminales_customer_idx.service'; import { ISolicitudTokensAdm } from '../../../interfaces/solicitud_tokens.interface'; import { MdSnackBar, MdDialog, MdDialogRef } from '@angular/material'; import { AuthenticationService } from './../../../services/authentication.service'; // import { Observable } from 'rxjs/Rx'; @Component({ // selector: 'product-stats', selector: 'carga-tokens', templateUrl: './carga-tokens.component.html', styleUrls: ['./carga-tokens.component.scss'], viewProviders: [ TerminalCustomerIdxService ], }) export class CargaTokensComponent implements AfterViewInit { private userID: number; selectedOption: string; solicitudes: ISolicitudTokensAdm[]; // sortOrder: TdDataTableSortingOrder = TdDataTableSortingOrder.Descending; public result: any; // private _dataTableService: TdDataTableService, // private _snackBarService: MdSnackBar, // public dialog: MdDialog, constructor(private _titleService: Title, // private authenticationService: AuthenticationService, private terminalCustomerIdxService: TerminalCustomerIdxService, // private dialogsService: DialogsService public dialog: MdDialog, public router: Router, private authenticationService: AuthenticationService, private accesosService: AccesosService ) { } ngAfterViewInit(): void { this._titleService.setTitle( 'Demo' ); this.userID = this.authenticationService.userID; this.CargaSolicitudTokensAdm(this.userID); } CargaSolicitudTokensAdm(userID: number): void { this.terminalCustomerIdxService.querySolicitudTokenAdm(userID). subscribe((data: ISolicitudTokensAdm[]) => { this.solicitudes = data; // console.log(this.solicitudes); setTimeout(() => { // this._loadingService.resolve('items.load'); }, 2000); }, (error: Error) => { // this._itemsService.staticQuery().subscribe((data2: Object[]) => { // this.data2 = data2; // setTimeout(() => { // this._loadingService.resolve('items.load'); // }, 2000); // }); } ); } onRowSelectTokenAdm(event: any): void { let dialogRef: MdDialogRef<ConfirmDialog>; // dialogRef = this.dialog.open(ConfirmDialog,{ // width: '1000px', // height: '400px' }); dialogRef = this.dialog.open(ConfirmDialog, { width: '1000px' }); dialogRef.componentInstance.idx = event.data.idx; dialogRef.componentInstance.comentario = event.data.observacion; dialogRef.componentInstance.title = 'Titulo'; // return dialogRef.afterClosed(); dialogRef.afterClosed().subscribe(result => { // this.selectedOption = result; // alert(result); if ( result !== 'CANCEL' && result !== undefined) { this.solicitudes = result; } }); } refresh(): void { // this.CargaSolicitudTokensAdm(this.userID); console.log(this.accesosService.AccesoModulo('incidencias')); console.log(this.accesosService.AccesoModulo('cesar')); } } @Component({ selector: 'confirm-dialog', template : ` <md-card> <md-card-title>Actualización de Estado de la Solicitud {{idx}}</md-card-title> <md-divider></md-divider> <md-card-content> <form> <div layout="row" layout-margin> <md-select flex="50" placeholder="Seleccion de estado" id="selectedEstado" [(ngModel)]="selectedEstado" name="selectedEstado"> <md-option *ngFor="let estado of estados" [value]="estado.value"> {{estado.viewValue}} </md-option> </md-select> </div> <div layout="row" layout-margin> <md-input-container flex> <textarea mdInput placeholder="Ingrese su comentario" name="comentario" [(ngModel)]="comentario"> </textarea> </md-input-container> </div> </form> </md-card-content> <md-divider></md-divider> <md-card-actions> <!-- <button type="button" md-raised-button (click)="dialogRef.close('OK')">OK</button> --> <button type="button" md-raised-button (click)="BottonOk()">OK</button> <button type="button" md-button (click)="dialogRef.close('CANCEL')">Cancel</button> </md-card-actions> </md-card>`, viewProviders: [ TerminalCustomerIdxService ], }) export class ConfirmDialog { private userID: number; solicitudes: ISolicitudTokensAdm[]; public idx: number; public title: string; public comentario: string; public selectedEstado: string = 'En Progreso'; // public selectedEstado: string = ''; estados: any[] = [ {value: 'Enviado', viewValue: 'Enviado'}, {value: 'En Progreso', viewValue: 'En Progreso'}, {value: 'Rechazado', viewValue: 'Rechazado'}, ]; constructor(public dialogRef: MdDialogRef<ConfirmDialog>, private terminalCustomerIdxService: TerminalCustomerIdxService, private _snackBarService: MdSnackBar, private authenticationService: AuthenticationService ) { // console.log('contriuctor ConfirmDialo'); this.userID = this.authenticationService.userID; // console.log(this.userID); } BottonOk(): void { if ( this.selectedEstado === '' ) { alert('ingrese estado'); return; } this.terminalCustomerIdxService.actualizarTokenAdm(this.idx, this.selectedEstado, this.comentario) .subscribe( data => { // this._router.navigate(['/']); // this.CargaSolicitudTokensAdm(); this._snackBarService.open('Registro exitoso', 'Ok', { duration: 5000 }); this.terminalCustomerIdxService.querySolicitudTokenAdm(this.userID). subscribe((data: ISolicitudTokensAdm[]) => { this.solicitudes = data; // console.log(this.solicitudes); return this.dialogRef.close(this.solicitudes); }, (error: Error) => { // this._itemsService.staticQuery().subscribe((data2: Object[]) => { // this.data2 = data2; // setTimeout(() => { // this._loadingService.resolve('items.load'); // }, 2000); // }); } ); }, error => { // this.loading = false; // this.dialog.open(LoginErrorDialogComponent01); }); } }
alvaradopcesar/ClaseFinal
src/app/dashboard-product/carga-tokens/carga-tokens.component.ts
TypeScript
mit
7,422
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace DotNetKit.Wpf.Printing.Demo.Samples.HelloWorldSample { /// <summary> /// HelloWorldPageControl.xaml の相互作用ロジック /// </summary> public partial class HelloWorldPageControl : UserControl { public HelloWorldPageControl() { InitializeComponent(); } } }
DotNetKit/DotNetKit.Wpf.Printing
DotNetKit.Wpf.Printing.Demo/Samples/HelloWorldSample/HelloWorldPageControl.xaml.cs
C#
mit
720
module Fastlane module CarthageCache VERSION = "0.1.1" end end
thii/fastlane-plugin-carthage_cache
lib/fastlane/plugin/carthage_cache/version.rb
Ruby
mit
71
package com.quexten.ravtech.net; import java.io.InputStream; import com.quexten.ravtech.RavTech; import com.quexten.ravtech.util.Debug; public class Player { Lobby lobby; Object connectionInformation; String username; public Player (Lobby lobby, Object connectionInformation, String username) { this.lobby = lobby; this.connectionInformation = connectionInformation; this.username = username; } public void send (Packet packet, boolean reliable) { packet.senderId = RavTech.net.lobby.ownId; lobby.network.sendTo(connectionInformation, packet, reliable); } public void sendStream (InputStream stream, int size, String type, Object additionalInformation) { lobby.network.sendStreamTo(connectionInformation, stream, size, type, additionalInformation); } public void sendLargePacket (Packet packet, String type, Object additionalInformation) { Debug.log("sendLargePacket", type); lobby.network.sendLargePacketTo(connectionInformation, packet, type, additionalInformation); } }
Quexten/RavTech
core/src/com/quexten/ravtech/net/Player.java
Java
mit
1,011
import psycopg2 def pg_connect( host, port, user, password, database): """ Small connection class If no password is suplied we try the default postgres user and expect a setted pg_ident or something similar """ #if DEBUG: keep("Model().pg_connect()") try: if password: conn = psycopg2.connect( database=database, user=user, port=port, password=str(password), host=host #connection_factory = psycopg2.extras.DictConnection ) else: conn = psycopg2.connect( database=database, user=user, port=port, password="", host=None #connection_factory = psycopg2.extras.DictConnection ) except psycopg2.Error, psy_err: print "The connection is not possible!" print psy_err print psycopg2.Error if host is None: raise psy_err conn.set_isolation_level(0) return conn def pg_get_data(connection, query): ''' Just a general method to fetch the date for different queries ''' #if DEBUG: keep("Model().pg_get_data()") cur = connection.cursor() cur.execute(query) data = cur.fetchall() column_headers = [desc[0] for desc in cur.description] return column_headers, data
ragged/yapgt
utils/connect.py
Python
mit
1,481
import React from 'react'; import PropTypes from 'prop-types'; import Navbar from './Navbar'; import Footer from './Footer'; class Layout extends React.Component { render() { return ( <div className='grid'> <Navbar /> <div className="container"> {this.props.children} </div> </div> ); } } Layout.propTypes = { children: PropTypes.element }; export default Layout;
dziksu/songs-manager
src/layouts/Layout.js
JavaScript
mit
429
/* * tiny-node.js * Description : A modern JavaScript utility library for browser. * Coder : shusiwei * Date : 2016-08-22 * Version : 1.0.0 * * https://github.com/shusiwei/tiny-node * Licensed under the MIT license. */ import {isUndefined, isNull, isPlainObject, isString, forEach, isPosiInteger, trim} from './index'; const {document} = window; const addEventListener = (el, fn, ...types) => { if (types.length === 0) throw new Error('at least one event name is required'); for (let type of types) { el.addEventListener(type, fn); }; return el; }; const removeEventListener = (el, fn, ...types) => { if (types.length === 0) throw new Error('at least one event name is required'); for (let type of types) { el.removeEventListener(type, fn); }; return el; }; /** * @name 创建一个带有类似数组长度的Object对象 * * @return 返回该对象 */ const makeArrayLikeObject = () => Object.defineProperty({}, 'length', {value: 0, writable: true, enumerable: false}); /** * @name 将一个对象序列化为一个queryString字符串 * * @param {Object} source * 操作的对象 * * @return {String} queryString字符串 */ export const serialize = (...sources) => { if (sources.length === 0) return ''; const result = []; for (let source of sources) { if (!isPlainObject(source)) throw new TypeError('source must b a plain Object'); for (let key in source) { if (!isUndefined(source[key]) && !isNull(source[key])) result.push(key + '=' + encodeURIComponent(trim(source[key].toString()))); }; }; return result.join('&'); }; /** * @name 将一个queryString字符串转化成一个对象 * * @param {String} source * 操作的对象 * @param {String} keys 需要返回值的key * * @return {Object} 当keys参数为空时,返回该对象,当keys参数只有一个时,则返回该对象中key为此参数的值,当keys参数有多个时,则以一个对象的形式返回该对象所有keys中的参数的值 */ export const queryParse = (source, ...keys) => { if (!isString(source)) throw new TypeError('source must b a String'); const result = makeArrayLikeObject(); forEach(source.replace(/^\?/, '').split('&'), string => { const item = string.split('='); result[item[0]] = item[1]; result.length++; }); if (keys.length === 0) return result; if (keys.length === 1) return result[keys[0]]; const dumpData = makeArrayLikeObject(); forEach(keys, key => { dumpData[key] = result[key]; dumpData.length++; }); return dumpData; }; /** * @name 将cookie字符串转化成一个对象 * * @param {String} keys 需要返回值的key * * @return {Object} 当keys参数为空时,返回该对象,当keys参数只有一个时,则返回该对象中key为此参数的值,当keys参数有多个时,则以一个对象的形式返回该对象所有keys中的参数的值 */ export const cookieParse = (...keys) => queryParse(document.cookie.replace(/; /g, '&'), ...keys); /** * @name 设置cookie * * @param {String} name * cookie名称 * @param {String} value * cookie值 * @param {Object} options 过期天数&其它参数 * @param {String} options.path cookie所在路径 * @param {String} options.domain cookie所在域 * @param {String} options.secure cookie是否只允许在安全链接中读取 */ export const setCookie = (name, value, ...options) => { let cookie = name + '=' + value; for (let option of options) { if (isPosiInteger(option)) { const date = new Date(); date.setTime(date.getTime() + option * 24 * 60 * 60 * 1000); cookie += ';expires=' + date.toGMTString(); }; if (isPlainObject(option)) { if (option.path) cookie += ';path=' + option.path; if (option.domain) cookie += ';domain=' + option.domain; if (option.secure) cookie += ';secure=' + option.secure; }; }; document.cookie = cookie; return cookieParse(); }; export class Sticky { constructor(target, body) { this.target = target; this.body = body; this.position = window.getComputedStyle(this.target).position; this.bind(); this.update(); } update() { if (this.checkIsHit()) { this.target.style.position = this.position; } else { this.target.style.position = 'fixed'; }; } checkIsHit() { const targetRect = this.target.getBoundingClientRect(); const bodyRect = this.body.getBoundingClientRect(); return window.pageYOffset + bodyRect.bottom + targetRect.height > window.innerHeight; } bind() { this.event = () => this.update(); addEventListener(window, this.event, 'resize', 'scroll'); } destroy() { removeEventListener(window, this.event, 'resize', 'scroll'); } }; export const isChildNode = (child, parent) => { if (child === parent) return true; let target = child; while (target && target.nodeType !== 11) { if (target === parent) { return true; } else { target = target.parentNode; }; }; return false; };
shusiwei/tiny
src/node.js
JavaScript
mit
5,044
using Xunit; using StarCommander.DefendImplement; using StarCommander.Factories; using StarCommander.Types; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StarCommander.DefendImplement.Tests { public class DeflectionShieldImplementTests { [Fact()] public void DeflectionShieldPowerBaseValueTest() { IDefendImplement defendImplement = DefendImplementFactory.CreateDefendImplement(DefendImplementType.DeflectionShield); Assert.Equal(60, defendImplement.Power); } [Fact()] public void DeflectionShieldSizeBaseValueTest() { IDefendImplement upgradeImplement = DefendImplementFactory.CreateDefendImplement(DefendImplementType.DeflectionShield); Assert.Equal(3, upgradeImplement.Size); } [Fact()] public void DeflectionShieldsHealthBaseValueTest() { IDefendImplement upgradeImplement = DefendImplementFactory.CreateDefendImplement(DefendImplementType.DeflectionShield); Assert.Equal(100, upgradeImplement.Health); } [Fact()] public void DeflectionShieldsShipHealthModificationBaseValueTest() { IDefendImplement upgradeImplement = DefendImplementFactory.CreateDefendImplement(DefendImplementType.DeflectionShield); Assert.Equal(20, upgradeImplement.ShipHealthModification); } [Fact()] public void DeflectionShieldsShipPowerModificationBaseValueTest() { IDefendImplement upgradeImplement = DefendImplementFactory.CreateDefendImplement(DefendImplementType.DeflectionShield); Assert.Equal(0, upgradeImplement.ShipPowerModification); } [Fact()] public void DeflectionShieldsShipSpeedModificationBaseValueTest() { IDefendImplement upgradeImplement = DefendImplementFactory.CreateDefendImplement(DefendImplementType.DeflectionShield); Assert.Equal(-4, upgradeImplement.ShipSpeedModification); } } }
jfrench7919/Star-Commander-Resume-Sample
StarCommanderTests/DefendImplement/DeflectionShieldImplementTests.cs
C#
mit
2,121
const {series, crossEnv, concurrent, rimraf} = require('nps-utils') // @if model.integrationTestRunner.id='protractor' const {config: {port : E2E_PORT}} = require('./test/protractor.conf') // @endif module.exports = { scripts: { default: 'nps webpack', test: { // @if testRunners.jest default: 'nps test.jest', // @endif // @if testRunners.jest // @if model.transpiler.id='babel' jest: { default: series( rimraf('test/coverage-jest'), crossEnv('BABEL_TARGET=node jest') ), accept: crossEnv('BABEL_TARGET=node jest -u'), watch: crossEnv('BABEL_TARGET=node jest --watch'), }, // @endif // @if model.transpiler.id='typescript' jest: { default: series( rimraf('test/coverage-jest'), 'jest' ), accept: 'jest -u', watch: 'jest --watch', }, // @endif // @endif // @if testRunners.karma // @if !testRunners.jest default: 'nps test.karma', // @endif karma: { default: series( rimraf('test/coverage-karma'), 'karma start test/karma.conf.js' ), watch: 'karma start test/karma.conf.js --auto-watch --no-single-run', debug: 'karma start test/karma.conf.js --auto-watch --no-single-run --debug' }, // @endif lint: { default: 'eslint src', fix: 'eslint src --fix' }, all: concurrent({ // @if testRunners.karma // @if testRunners.protractor browser: series.nps('test.karma', 'e2e'), // @endif // @if !testRunners.protractor browser: series.nps('test.karma'), // @endif // @endif // @if !testRunners.karma // @if testRunners.protractor browser: series.nps('e2e'), // @endif // @endif // @if testRunners.jest jest: 'nps test.jest', // @endif lint: 'nps test.lint' }) }, // @if model.integrationTestRunner.id='protractor' e2e: { default: concurrent({ webpack: `webpack-dev-server --inline --port=${E2E_PORT}`, protractor: 'nps e2e.whenReady', }) + ' --kill-others --success first', protractor: { install: 'webdriver-manager update', default: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js' ), debug: series( 'nps e2e.protractor.install', 'protractor test/protractor.conf.js --elementExplorer' ), }, whenReady: series( `wait-on --timeout 120000 http-get://localhost:${E2E_PORT}/index.html`, 'nps e2e.protractor' ), }, // @endif build: 'nps webpack.build', webpack: { default: 'nps webpack.server', build: { before: rimraf('dist'), default: 'nps webpack.build.production', development: { default: series( 'nps webpack.build.before', 'webpack --progress -d' ), extractCss: series( 'nps webpack.build.before', 'webpack --progress -d --env.extractCss' ), serve: series.nps( 'webpack.build.development', 'serve' ), }, production: { inlineCss: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production') ), default: series( 'nps webpack.build.before', crossEnv('NODE_ENV=production webpack --progress -p --env.production --env.extractCss') ), serve: series.nps( 'webpack.build.production', 'serve' ), } }, server: { default: `webpack-dev-server -d --devtool '#source-map' --inline --env.server`, extractCss: `webpack-dev-server -d --devtool '#source-map' --inline --env.server --env.extractCss`, hmr: `webpack-dev-server -d --devtool '#source-map' --inline --hot --env.server` }, }, serve: 'http-server dist --cors', }, }
zewa666/cli
lib/resources/content/package-scripts.template.js
JavaScript
mit
4,186
/** * Print locales settings. * @function print * @param {object} locales - locales settings to print. */ 'use strict' const colorprint = require('colorprint') const yaml = require('js-yaml') function _normalize (data) { switch (typeof data) { case 'number': case 'string': case 'boolean': case 'undefined': return data default: let values = {} for (let key of Object.keys(data)) { let value = _normalize(data[ key ]) if (typeof value === 'undefined') { continue } values[ key ] = value } let isEmpty = Object.keys(values).length === 0 if (isEmpty) { return undefined } return values } } /** @lends print */ function print (locales) { let values = _normalize(locales) colorprint.debug('') colorprint.debug('Locale Settings') colorprint.debug('------------') let msg = yaml.safeDump(values) colorprint.debug(colorprint.colors.blackBright(msg)) colorprint.debug('') colorprint.debug('') } module.exports = print
apeman-labo/apemanlocale
lib/print.js
JavaScript
mit
1,057
import FAnimation from './f-animation' import { left, right } from '../art/art-util' export default class ASleep extends FAnimation { constructor(old) { super(old) this.frames = [this.frame1] } frame1(g, x, y, friendo, blink, words) { // pre-compute constants for drawing for ease of readability const { thighGap } = friendo.element const bodyOffset = friendo.element.bodyOffset - (friendo.element.bodyOffset * 0.1) const legBrush = friendo.element.legBrush(friendo) const armBrush = friendo.element.armBrush(friendo) const armOffset = { x: friendo.element.armOffset.xOffset, y: friendo.element.legHeight - friendo.element.armOffset.yOffset, } const armAngle = 0.15 // pi radians left(g, x - thighGap, y, legBrush) // left leg right(g, x + thighGap, y, legBrush) // right leg left(g, x - armOffset.x, y - armOffset.y, armBrush, armAngle)// left arm right(g, x + armOffset.x, y - armOffset.y, armBrush, armAngle)// right arm const computedTethers = friendo.element.drawCore(g, x, y - bodyOffset, friendo, true) if (words) { friendo.element.speak(g, x + computedTethers.speech.x, computedTethers.speech.y, words) } } }
mattdelsordo/friendo
src/friendo/animation/sleep.js
JavaScript
mit
1,215
(function ($, SmallGrid) { "use strict"; $.extend(true, SmallGrid, { "Column": { "Create": CreateModel, "Model": ColumnModel, "ColumnData": ColumnData } }); function ColumnData() { } ColumnData.prototype.align = "";//column cells align - "" / center / right ColumnData.prototype.cellCssClass = "";//css class for column cells ColumnData.prototype.editable = true; //true when column cells editable ColumnData.prototype.editor = undefined; // name of editor ColumnData.prototype.editMode = false; //true when column cell in editMode ColumnData.prototype.field = ""; //cell content will be taken from value of this property in row ColumnData.prototype.filterable = false;//true when column is filterable ColumnData.prototype.formatter = "Default";//default cell content formatter ColumnData.prototype.headerFormatter = "Default";//default header cell content formatter ColumnData.prototype.headerCssClass = "";//css class for column header cell ColumnData.prototype.hidden = false;//true when column is visible ColumnData.prototype.id = undefined;//column unique indicator ColumnData.prototype.item = null; ColumnData.prototype.maxWidth = 9999; ColumnData.prototype.minWidth = 25; ColumnData.prototype.name = "";//column title in grid header ColumnData.prototype.resizeable = true;//true when column resizeable ColumnData.prototype.sortable = true;//true when column sortable ColumnData.prototype.sortComparer = "Default"; ColumnData.prototype.sortOrder = 0;//0, 1, -1 ColumnData.prototype.width = 50; function ColumnModel(settings) { var self = this; var data = []; this.items = { addItem: function (item) { addColumn(createColumn(item)); return self; }, addItems: function (items) { if (items.length) { self.onChange.lock(); for (var i = 0, len = items.length; i < len; i++) { self.items.addItem(items[i]); } self.onChange.notifyLocked(); } return self; }, deleteItems: function () { return deleteColumns(); }, deleteItemById: function (id) { return deleteColumnById(id); }, getItems: function () { var result = []; for (var i = 0, len = data.length; i < len; i++) { result.push(data[i].item); } return result; }, setItems: function (items) { if (items.length) { self.onChange.lock(); data = []; for (var i = 0, len = items.length; i < len; i++) { self.items.addItem(items[i]); } self.onChange.notifyLocked(); } return self; }, updateItemById: function (id, item) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { data[i].item = item; self.onChange.notify({ "id": id }); break; } } return self; }, updateItemByIndex: function (idx, item) { if (data[idx]) { data[idx].item = item; self.onChange.notify({ "id": data[idx].id }); } return self; } }; function destroy() { data = []; } function filter(callback) { if (data.length) { return data.filter(callback); } return []; } function reduce(callback, initialValue) { if (data.length) { return data.reduce(callback, initialValue); } } function sort(comparer) { if (data.length) { data.sort(comparer); } return self; } function isEmpty() { return data.length === 0; } function total() { return data.length; } function addColumn(column) { if (column instanceof ColumnData) { data.push(column); self.onChange.notify({ "id": column.id }); } return self; } function addColumns(columns) { if (columns.length) { self.onChange.lock(); for (var i = 0, len = columns.length; i < len; i++) { addColumn(columns[i]); } self.onChange.notifyLocked(); } return self; } function deleteColumn(column) { if (column instanceof ColumnData) { deleteColumnById(column.id); } return self; } function deleteColumnById(id) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { data.splice(i, 1); self.onChange.notify({ "id": id }); break; } } return self; } function deleteColumnByIndex(idx) { if (data[idx]) { var id = data[idx].id; data.splice(idx, 1); self.onChange.notify({ "id": id }); } return self; } function deleteColumns() { if (data.length) { self.onChange.lock(); data = []; self.onChange.notifyLocked(); } return self; } function getColumnById(id) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { return data[i]; } } } function getColumnByIndex(idx) { return data[idx]; } function getColumnIdByIndex(idx) { return data[idx].id; } function getColumnIndexById(id) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { return i; } } return -1; } function getColumnPropertyById(id, propertyName) { var column = getColumnById(id); if (column && propertyName && propertyName in column) { return column[propertyName]; } } function getColumnPropertyByIndex(idx, propertyName) { var column = getColumnByIndex(idx); if (column && propertyName && propertyName in column) { return column[propertyName]; } } function getColumns() { return data; } function insertColumnAfterId(id, column) { insertColumnAfterIndex( getColumnIndexById(id), column ); return self; } function insertColumnAfterIndex(idx, column) { if (column instanceof ColumnData) { data.splice( idx + 1, 0, column ); self.onChange.notify({ "id": column.id }); } return self; } function insertColumnBeforeId(id, column) { insertColumnBeforeIndex( getColumnIndexById(id), column ); return self; } function insertColumnBeforeIndex(idx, column) { if (column instanceof ColumnData) { data.splice( idx, 0, column ); self.onChange.notify({ "id": column.id }); } return self; } function setColumnPropertyById(id, propertyName, propertyValue) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { if (propertyName) { data[i][propertyName] = propertyValue; self.onChange.notify({ "id": id }); } break; } } return self; } function setColumnPropertyByIndex(idx, propertyName, propertyValue) { if (propertyName && data[idx]) { data[idx][propertyName] = propertyValue; self.onChange.notify({ "id": data[idx].id }); } return self; } function setColumns(columns) { if (columns.length) { self.onChange.lock(); data = []; for (var i = 0, len = columns.length; i < len; i++) { addColumn(columns[i]); } self.onChange.notifyLocked(); } return self; } function setColumnsProperty(propertyName, propertyValue) { self.onChange.lock(); for (var i = 0, len = data.length; i < len; i++) { data[i][propertyName] = propertyValue; self.onChange.notify({ "id": data[i].id }); } self.onChange.notifyLocked(); return self; } function updateColumn(column) { if (column instanceof ColumnData) { updateColumnById(column.id, column); } return self; } function updateColumnById(id, column) { if (column instanceof ColumnData) { for (var i = 0, len = data.length; i < len; i++) { if (data[i].id === id) { data[i] = column; self.onChange.notify({ "id": id }); break; } } } return self; } function updateColumnByIndex(idx, column) { if (column instanceof ColumnData) { if (data[idx]) { data[idx] = column; self.onChange.notify({ "id": column.id }); } } return self; } function updateColumns(columns) { if (columns.length) { self.onChange.lock(); for (var i = 0, len = columns.length; i < len; i++) { updateColumn(columns[i]); } self.onChange.notifyLocked(); } return self; } function createColumn(item) { if (item instanceof Object) { var column = new ColumnData(); if (SmallGrid.Utils.isProperty(settings.columns.idProperty, column)) { column.id = column[settings.columns.idProperty]; } else if (settings.columns.newIdType === "number") { column.id = SmallGrid.Utils.createId(); } else { column.id = SmallGrid.Utils.createGuid(); } column.name = item.name; column.field = item.field; column.item = item; if ("align" in item) column.align = item.align; if ("cellCssClass" in item) column.cellCssClass = item.cellCssClass; if ("editable" in item) column.editable = item.editable; if ("editor" in item) column.editor = item.editor; if ("editMode" in item) column.editMode = item.editMode; if ("filterable" in item) column.filterable = item.filterable; if ("formatter" in item) column.formatter = item.formatter; if ("headerFormatter" in item) column.headerFormatter = item.headerFormatter; if ("headerCssClass" in item) column.headerCssClass = item.headerCssClass; if ("hidden" in item) column.hidden = item.hidden; if ("maxWidth" in item) column.maxWidth = item.maxWidth; if ("minWidth" in item) column.minWidth = item.minWidth; if ("resizeable" in item) column.resizeable = item.resizeable; if ("sortable" in item) column.sortable = item.sortable; if ("sortOrder" in item) column.sortOrder = item.sortOrder; if ("sortComparer" in item) column.sortComparer = item.sortComparer; if ("width" in item) column.width = item.width; return column; } } $.extend(this, { "destroy": destroy, "onChange": SmallGrid.Callback.Create(), "filter": filter, "reduce": reduce, "sort": sort, "total": total, "addColumn": addColumn, "addColumns": addColumns, "createColumn": createColumn, "deleteColumn": deleteColumn, "deleteColumnById": deleteColumnById, "deleteColumnByIndex": deleteColumnByIndex, "deleteColumns": deleteColumns, "getColumnById": getColumnById, "getColumnByIndex": getColumnByIndex, "getColumnIdByIndex": getColumnIdByIndex, "getColumnIndexById": getColumnIndexById, "getColumnPropertyById": getColumnPropertyById, "getColumnPropertyByIndex": getColumnPropertyByIndex, "getColumns": getColumns, "insertColumnAfterId": insertColumnAfterId, "insertColumnAfterIndex": insertColumnAfterIndex, "insertColumnBeforeId": insertColumnBeforeId, "insertColumnBeforeIndex": insertColumnBeforeIndex, "isEmpty": isEmpty, "setColumnPropertyById": setColumnPropertyById, "setColumnPropertyByIndex": setColumnPropertyByIndex, "setColumns": setColumns, "setColumnsProperty": setColumnsProperty, "updateColumn": updateColumn, "updateColumnById": updateColumnById, "updateColumnByIndex": updateColumnByIndex, "updateColumns": updateColumns }); } function CreateModel(data, settings) { if (Array.isArray(data) === false) { throw new TypeError("Data is not defined"); } if (settings instanceof Object === false) { throw new TypeError("Settings is not defined"); } return new ColumnModel(settings).items.addItems(data); } })(jQuery, window.SmallGrid = window.SmallGrid || {});
truehot/smallGrid
core/column.js
JavaScript
mit
15,058
// Copyright 2011 Aaron Jacobs. All Rights Reserved. // Author: aaronjjacobs@gmail.com (Aaron Jacobs) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package oglematchers_test import ( "math" . "github.com/scaleway/scaleway-cli/vendor/github.com/smartystreets/assertions/internal/oglematchers" . "github.com/scaleway/scaleway-cli/vendor/github.com/smartystreets/assertions/internal/ogletest" ) //////////////////////////////////////////////////////////////////////// // Helpers //////////////////////////////////////////////////////////////////////// type GreaterOrEqualTest struct { } func init() { RegisterTestSuite(&GreaterOrEqualTest{}) } type geTestCase struct { candidate interface{} expectedResult bool shouldBeFatal bool expectedError string } func (t *GreaterOrEqualTest) checkTestCases(matcher Matcher, cases []geTestCase) { for i, c := range cases { err := matcher.Matches(c.candidate) ExpectThat( (err == nil), Equals(c.expectedResult), "Case %d (candidate %v)", i, c.candidate) if err == nil { continue } _, isFatal := err.(*FatalError) ExpectEq( c.shouldBeFatal, isFatal, "Case %d (candidate %v)", i, c.candidate) ExpectThat( err, Error(Equals(c.expectedError)), "Case %d (candidate %v)", i, c.candidate) } } //////////////////////////////////////////////////////////////////////// // Integer literals //////////////////////////////////////////////////////////////////////// func (t *GreaterOrEqualTest) IntegerCandidateBadTypes() { matcher := GreaterOrEqual(int(-150)) cases := []geTestCase{ geTestCase{true, false, true, "which is not comparable"}, geTestCase{complex64(-151), false, true, "which is not comparable"}, geTestCase{complex128(-151), false, true, "which is not comparable"}, geTestCase{[...]int{-151}, false, true, "which is not comparable"}, geTestCase{make(chan int), false, true, "which is not comparable"}, geTestCase{func() {}, false, true, "which is not comparable"}, geTestCase{map[int]int{}, false, true, "which is not comparable"}, geTestCase{&geTestCase{}, false, true, "which is not comparable"}, geTestCase{make([]int, 0), false, true, "which is not comparable"}, geTestCase{"-151", false, true, "which is not comparable"}, geTestCase{geTestCase{}, false, true, "which is not comparable"}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) FloatCandidateBadTypes() { matcher := GreaterOrEqual(float32(-150)) cases := []geTestCase{ geTestCase{true, false, true, "which is not comparable"}, geTestCase{complex64(-151), false, true, "which is not comparable"}, geTestCase{complex128(-151), false, true, "which is not comparable"}, geTestCase{[...]int{-151}, false, true, "which is not comparable"}, geTestCase{make(chan int), false, true, "which is not comparable"}, geTestCase{func() {}, false, true, "which is not comparable"}, geTestCase{map[int]int{}, false, true, "which is not comparable"}, geTestCase{&geTestCase{}, false, true, "which is not comparable"}, geTestCase{make([]int, 0), false, true, "which is not comparable"}, geTestCase{"-151", false, true, "which is not comparable"}, geTestCase{geTestCase{}, false, true, "which is not comparable"}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) StringCandidateBadTypes() { matcher := GreaterOrEqual("17") cases := []geTestCase{ geTestCase{true, false, true, "which is not comparable"}, geTestCase{int(0), false, true, "which is not comparable"}, geTestCase{int8(0), false, true, "which is not comparable"}, geTestCase{int16(0), false, true, "which is not comparable"}, geTestCase{int32(0), false, true, "which is not comparable"}, geTestCase{int64(0), false, true, "which is not comparable"}, geTestCase{uint(0), false, true, "which is not comparable"}, geTestCase{uint8(0), false, true, "which is not comparable"}, geTestCase{uint16(0), false, true, "which is not comparable"}, geTestCase{uint32(0), false, true, "which is not comparable"}, geTestCase{uint64(0), false, true, "which is not comparable"}, geTestCase{float32(0), false, true, "which is not comparable"}, geTestCase{float64(0), false, true, "which is not comparable"}, geTestCase{complex64(-151), false, true, "which is not comparable"}, geTestCase{complex128(-151), false, true, "which is not comparable"}, geTestCase{[...]int{-151}, false, true, "which is not comparable"}, geTestCase{make(chan int), false, true, "which is not comparable"}, geTestCase{func() {}, false, true, "which is not comparable"}, geTestCase{map[int]int{}, false, true, "which is not comparable"}, geTestCase{&geTestCase{}, false, true, "which is not comparable"}, geTestCase{make([]int, 0), false, true, "which is not comparable"}, geTestCase{geTestCase{}, false, true, "which is not comparable"}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) BadArgument() { panicked := false defer func() { ExpectThat(panicked, Equals(true)) }() defer func() { if r := recover(); r != nil { panicked = true } }() GreaterOrEqual(complex128(0)) } //////////////////////////////////////////////////////////////////////// // Integer literals //////////////////////////////////////////////////////////////////////// func (t *GreaterOrEqualTest) NegativeIntegerLiteral() { matcher := GreaterOrEqual(-150) desc := matcher.Description() expectedDesc := "greater than or equal to -150" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-(1 << 30), false, false, ""}, geTestCase{-151, false, false, ""}, geTestCase{-150, true, false, ""}, geTestCase{0, true, false, ""}, geTestCase{17, true, false, ""}, geTestCase{int(-(1 << 30)), false, false, ""}, geTestCase{int(-151), false, false, ""}, geTestCase{int(-150), true, false, ""}, geTestCase{int(0), true, false, ""}, geTestCase{int(17), true, false, ""}, geTestCase{int8(-127), true, false, ""}, geTestCase{int8(0), true, false, ""}, geTestCase{int8(17), true, false, ""}, geTestCase{int16(-(1 << 14)), false, false, ""}, geTestCase{int16(-151), false, false, ""}, geTestCase{int16(-150), true, false, ""}, geTestCase{int16(0), true, false, ""}, geTestCase{int16(17), true, false, ""}, geTestCase{int32(-(1 << 30)), false, false, ""}, geTestCase{int32(-151), false, false, ""}, geTestCase{int32(-150), true, false, ""}, geTestCase{int32(0), true, false, ""}, geTestCase{int32(17), true, false, ""}, geTestCase{int64(-(1 << 30)), false, false, ""}, geTestCase{int64(-151), false, false, ""}, geTestCase{int64(-150), true, false, ""}, geTestCase{int64(0), true, false, ""}, geTestCase{int64(17), true, false, ""}, // Unsigned integers. geTestCase{uint((1 << 32) - 151), true, false, ""}, geTestCase{uint(0), true, false, ""}, geTestCase{uint(17), true, false, ""}, geTestCase{uint8(0), true, false, ""}, geTestCase{uint8(17), true, false, ""}, geTestCase{uint8(253), true, false, ""}, geTestCase{uint16((1 << 16) - 151), true, false, ""}, geTestCase{uint16(0), true, false, ""}, geTestCase{uint16(17), true, false, ""}, geTestCase{uint32((1 << 32) - 151), true, false, ""}, geTestCase{uint32(0), true, false, ""}, geTestCase{uint32(17), true, false, ""}, geTestCase{uint64((1 << 64) - 151), true, false, ""}, geTestCase{uint64(0), true, false, ""}, geTestCase{uint64(17), true, false, ""}, geTestCase{uintptr((1 << 64) - 151), true, false, ""}, geTestCase{uintptr(0), true, false, ""}, geTestCase{uintptr(17), true, false, ""}, // Floating point. geTestCase{float32(-(1 << 30)), false, false, ""}, geTestCase{float32(-151), false, false, ""}, geTestCase{float32(-150.1), false, false, ""}, geTestCase{float32(-150), true, false, ""}, geTestCase{float32(-149.9), true, false, ""}, geTestCase{float32(0), true, false, ""}, geTestCase{float32(17), true, false, ""}, geTestCase{float32(160), true, false, ""}, geTestCase{float64(-(1 << 30)), false, false, ""}, geTestCase{float64(-151), false, false, ""}, geTestCase{float64(-150.1), false, false, ""}, geTestCase{float64(-150), true, false, ""}, geTestCase{float64(-149.9), true, false, ""}, geTestCase{float64(0), true, false, ""}, geTestCase{float64(17), true, false, ""}, geTestCase{float64(160), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) ZeroIntegerLiteral() { matcher := GreaterOrEqual(0) desc := matcher.Description() expectedDesc := "greater than or equal to 0" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-(1 << 30), false, false, ""}, geTestCase{-1, false, false, ""}, geTestCase{0, true, false, ""}, geTestCase{1, true, false, ""}, geTestCase{17, true, false, ""}, geTestCase{(1 << 30), true, false, ""}, geTestCase{int(-(1 << 30)), false, false, ""}, geTestCase{int(-1), false, false, ""}, geTestCase{int(0), true, false, ""}, geTestCase{int(1), true, false, ""}, geTestCase{int(17), true, false, ""}, geTestCase{int8(-1), false, false, ""}, geTestCase{int8(0), true, false, ""}, geTestCase{int8(1), true, false, ""}, geTestCase{int16(-(1 << 14)), false, false, ""}, geTestCase{int16(-1), false, false, ""}, geTestCase{int16(0), true, false, ""}, geTestCase{int16(1), true, false, ""}, geTestCase{int16(17), true, false, ""}, geTestCase{int32(-(1 << 30)), false, false, ""}, geTestCase{int32(-1), false, false, ""}, geTestCase{int32(0), true, false, ""}, geTestCase{int32(1), true, false, ""}, geTestCase{int32(17), true, false, ""}, geTestCase{int64(-(1 << 30)), false, false, ""}, geTestCase{int64(-1), false, false, ""}, geTestCase{int64(0), true, false, ""}, geTestCase{int64(1), true, false, ""}, geTestCase{int64(17), true, false, ""}, // Unsigned integers. geTestCase{uint((1 << 32) - 1), true, false, ""}, geTestCase{uint(0), true, false, ""}, geTestCase{uint(17), true, false, ""}, geTestCase{uint8(0), true, false, ""}, geTestCase{uint8(17), true, false, ""}, geTestCase{uint8(253), true, false, ""}, geTestCase{uint16((1 << 16) - 1), true, false, ""}, geTestCase{uint16(0), true, false, ""}, geTestCase{uint16(17), true, false, ""}, geTestCase{uint32((1 << 32) - 1), true, false, ""}, geTestCase{uint32(0), true, false, ""}, geTestCase{uint32(17), true, false, ""}, geTestCase{uint64((1 << 64) - 1), true, false, ""}, geTestCase{uint64(0), true, false, ""}, geTestCase{uint64(17), true, false, ""}, geTestCase{uintptr((1 << 64) - 1), true, false, ""}, geTestCase{uintptr(0), true, false, ""}, geTestCase{uintptr(17), true, false, ""}, // Floating point. geTestCase{float32(-(1 << 30)), false, false, ""}, geTestCase{float32(-1), false, false, ""}, geTestCase{float32(-0.1), false, false, ""}, geTestCase{float32(-0.0), true, false, ""}, geTestCase{float32(0), true, false, ""}, geTestCase{float32(0.1), true, false, ""}, geTestCase{float32(17), true, false, ""}, geTestCase{float32(160), true, false, ""}, geTestCase{float64(-(1 << 30)), false, false, ""}, geTestCase{float64(-1), false, false, ""}, geTestCase{float64(-0.1), false, false, ""}, geTestCase{float64(-0), true, false, ""}, geTestCase{float64(0), true, false, ""}, geTestCase{float64(17), true, false, ""}, geTestCase{float64(160), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) PositiveIntegerLiteral() { matcher := GreaterOrEqual(150) desc := matcher.Description() expectedDesc := "greater than or equal to 150" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-1, false, false, ""}, geTestCase{149, false, false, ""}, geTestCase{150, true, false, ""}, geTestCase{151, true, false, ""}, geTestCase{int(-1), false, false, ""}, geTestCase{int(149), false, false, ""}, geTestCase{int(150), true, false, ""}, geTestCase{int(151), true, false, ""}, geTestCase{int8(-1), false, false, ""}, geTestCase{int8(0), false, false, ""}, geTestCase{int8(17), false, false, ""}, geTestCase{int8(127), false, false, ""}, geTestCase{int16(-1), false, false, ""}, geTestCase{int16(149), false, false, ""}, geTestCase{int16(150), true, false, ""}, geTestCase{int16(151), true, false, ""}, geTestCase{int32(-1), false, false, ""}, geTestCase{int32(149), false, false, ""}, geTestCase{int32(150), true, false, ""}, geTestCase{int32(151), true, false, ""}, geTestCase{int64(-1), false, false, ""}, geTestCase{int64(149), false, false, ""}, geTestCase{int64(150), true, false, ""}, geTestCase{int64(151), true, false, ""}, // Unsigned integers. geTestCase{uint(0), false, false, ""}, geTestCase{uint(149), false, false, ""}, geTestCase{uint(150), true, false, ""}, geTestCase{uint(151), true, false, ""}, geTestCase{uint8(0), false, false, ""}, geTestCase{uint8(127), false, false, ""}, geTestCase{uint16(0), false, false, ""}, geTestCase{uint16(149), false, false, ""}, geTestCase{uint16(150), true, false, ""}, geTestCase{uint16(151), true, false, ""}, geTestCase{uint32(0), false, false, ""}, geTestCase{uint32(149), false, false, ""}, geTestCase{uint32(150), true, false, ""}, geTestCase{uint32(151), true, false, ""}, geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(149), false, false, ""}, geTestCase{uint64(150), true, false, ""}, geTestCase{uint64(151), true, false, ""}, geTestCase{uintptr(0), false, false, ""}, geTestCase{uintptr(149), false, false, ""}, geTestCase{uintptr(150), true, false, ""}, geTestCase{uintptr(151), true, false, ""}, // Floating point. geTestCase{float32(-1), false, false, ""}, geTestCase{float32(149), false, false, ""}, geTestCase{float32(149.9), false, false, ""}, geTestCase{float32(150), true, false, ""}, geTestCase{float32(150.1), true, false, ""}, geTestCase{float32(151), true, false, ""}, geTestCase{float64(-1), false, false, ""}, geTestCase{float64(149), false, false, ""}, geTestCase{float64(149.9), false, false, ""}, geTestCase{float64(150), true, false, ""}, geTestCase{float64(150.1), true, false, ""}, geTestCase{float64(151), true, false, ""}, } t.checkTestCases(matcher, cases) } //////////////////////////////////////////////////////////////////////// // Float literals //////////////////////////////////////////////////////////////////////// func (t *GreaterOrEqualTest) NegativeFloatLiteral() { matcher := GreaterOrEqual(-150.1) desc := matcher.Description() expectedDesc := "greater than or equal to -150.1" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-(1 << 30), false, false, ""}, geTestCase{-151, false, false, ""}, geTestCase{-150, true, false, ""}, geTestCase{0, true, false, ""}, geTestCase{17, true, false, ""}, geTestCase{int(-(1 << 30)), false, false, ""}, geTestCase{int(-151), false, false, ""}, geTestCase{int(-150), true, false, ""}, geTestCase{int(0), true, false, ""}, geTestCase{int(17), true, false, ""}, geTestCase{int8(-127), true, false, ""}, geTestCase{int8(0), true, false, ""}, geTestCase{int8(17), true, false, ""}, geTestCase{int16(-(1 << 14)), false, false, ""}, geTestCase{int16(-151), false, false, ""}, geTestCase{int16(-150), true, false, ""}, geTestCase{int16(0), true, false, ""}, geTestCase{int16(17), true, false, ""}, geTestCase{int32(-(1 << 30)), false, false, ""}, geTestCase{int32(-151), false, false, ""}, geTestCase{int32(-150), true, false, ""}, geTestCase{int32(0), true, false, ""}, geTestCase{int32(17), true, false, ""}, geTestCase{int64(-(1 << 30)), false, false, ""}, geTestCase{int64(-151), false, false, ""}, geTestCase{int64(-150), true, false, ""}, geTestCase{int64(0), true, false, ""}, geTestCase{int64(17), true, false, ""}, // Unsigned integers. geTestCase{uint((1 << 32) - 151), true, false, ""}, geTestCase{uint(0), true, false, ""}, geTestCase{uint(17), true, false, ""}, geTestCase{uint8(0), true, false, ""}, geTestCase{uint8(17), true, false, ""}, geTestCase{uint8(253), true, false, ""}, geTestCase{uint16((1 << 16) - 151), true, false, ""}, geTestCase{uint16(0), true, false, ""}, geTestCase{uint16(17), true, false, ""}, geTestCase{uint32((1 << 32) - 151), true, false, ""}, geTestCase{uint32(0), true, false, ""}, geTestCase{uint32(17), true, false, ""}, geTestCase{uint64((1 << 64) - 151), true, false, ""}, geTestCase{uint64(0), true, false, ""}, geTestCase{uint64(17), true, false, ""}, geTestCase{uintptr((1 << 64) - 151), true, false, ""}, geTestCase{uintptr(0), true, false, ""}, geTestCase{uintptr(17), true, false, ""}, // Floating point. geTestCase{float32(-(1 << 30)), false, false, ""}, geTestCase{float32(-151), false, false, ""}, geTestCase{float32(-150.2), false, false, ""}, geTestCase{float32(-150.1), true, false, ""}, geTestCase{float32(-150), true, false, ""}, geTestCase{float32(0), true, false, ""}, geTestCase{float32(17), true, false, ""}, geTestCase{float32(160), true, false, ""}, geTestCase{float64(-(1 << 30)), false, false, ""}, geTestCase{float64(-151), false, false, ""}, geTestCase{float64(-150.2), false, false, ""}, geTestCase{float64(-150.1), true, false, ""}, geTestCase{float64(-150), true, false, ""}, geTestCase{float64(0), true, false, ""}, geTestCase{float64(17), true, false, ""}, geTestCase{float64(160), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) PositiveFloatLiteral() { matcher := GreaterOrEqual(149.9) desc := matcher.Description() expectedDesc := "greater than or equal to 149.9" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-1, false, false, ""}, geTestCase{149, false, false, ""}, geTestCase{150, true, false, ""}, geTestCase{151, true, false, ""}, geTestCase{int(-1), false, false, ""}, geTestCase{int(149), false, false, ""}, geTestCase{int(150), true, false, ""}, geTestCase{int(151), true, false, ""}, geTestCase{int8(-1), false, false, ""}, geTestCase{int8(0), false, false, ""}, geTestCase{int8(17), false, false, ""}, geTestCase{int8(127), false, false, ""}, geTestCase{int16(-1), false, false, ""}, geTestCase{int16(149), false, false, ""}, geTestCase{int16(150), true, false, ""}, geTestCase{int16(151), true, false, ""}, geTestCase{int32(-1), false, false, ""}, geTestCase{int32(149), false, false, ""}, geTestCase{int32(150), true, false, ""}, geTestCase{int32(151), true, false, ""}, geTestCase{int64(-1), false, false, ""}, geTestCase{int64(149), false, false, ""}, geTestCase{int64(150), true, false, ""}, geTestCase{int64(151), true, false, ""}, // Unsigned integers. geTestCase{uint(0), false, false, ""}, geTestCase{uint(149), false, false, ""}, geTestCase{uint(150), true, false, ""}, geTestCase{uint(151), true, false, ""}, geTestCase{uint8(0), false, false, ""}, geTestCase{uint8(127), false, false, ""}, geTestCase{uint16(0), false, false, ""}, geTestCase{uint16(149), false, false, ""}, geTestCase{uint16(150), true, false, ""}, geTestCase{uint16(151), true, false, ""}, geTestCase{uint32(0), false, false, ""}, geTestCase{uint32(149), false, false, ""}, geTestCase{uint32(150), true, false, ""}, geTestCase{uint32(151), true, false, ""}, geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(149), false, false, ""}, geTestCase{uint64(150), true, false, ""}, geTestCase{uint64(151), true, false, ""}, geTestCase{uintptr(0), false, false, ""}, geTestCase{uintptr(149), false, false, ""}, geTestCase{uintptr(150), true, false, ""}, geTestCase{uintptr(151), true, false, ""}, // Floating point. geTestCase{float32(-1), false, false, ""}, geTestCase{float32(149), false, false, ""}, geTestCase{float32(149.8), false, false, ""}, geTestCase{float32(149.9), true, false, ""}, geTestCase{float32(150), true, false, ""}, geTestCase{float32(151), true, false, ""}, geTestCase{float64(-1), false, false, ""}, geTestCase{float64(149), false, false, ""}, geTestCase{float64(149.8), false, false, ""}, geTestCase{float64(149.9), true, false, ""}, geTestCase{float64(150), true, false, ""}, geTestCase{float64(151), true, false, ""}, } t.checkTestCases(matcher, cases) } //////////////////////////////////////////////////////////////////////// // Subtle cases //////////////////////////////////////////////////////////////////////// func (t *GreaterOrEqualTest) Int64NotExactlyRepresentableBySinglePrecision() { // Single-precision floats don't have enough bits to represent the integers // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value // and should be treated as equivalent when floats are in the mix. const kTwoTo25 = 1 << 25 matcher := GreaterOrEqual(int64(kTwoTo25 + 1)) desc := matcher.Description() expectedDesc := "greater than or equal to 33554433" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-1, false, false, ""}, geTestCase{kTwoTo25 + 0, false, false, ""}, geTestCase{kTwoTo25 + 1, true, false, ""}, geTestCase{kTwoTo25 + 2, true, false, ""}, geTestCase{int(-1), false, false, ""}, geTestCase{int(kTwoTo25 + 0), false, false, ""}, geTestCase{int(kTwoTo25 + 1), true, false, ""}, geTestCase{int(kTwoTo25 + 2), true, false, ""}, geTestCase{int8(-1), false, false, ""}, geTestCase{int8(127), false, false, ""}, geTestCase{int16(-1), false, false, ""}, geTestCase{int16(0), false, false, ""}, geTestCase{int16(32767), false, false, ""}, geTestCase{int32(-1), false, false, ""}, geTestCase{int32(kTwoTo25 + 0), false, false, ""}, geTestCase{int32(kTwoTo25 + 1), true, false, ""}, geTestCase{int32(kTwoTo25 + 2), true, false, ""}, geTestCase{int64(-1), false, false, ""}, geTestCase{int64(kTwoTo25 + 0), false, false, ""}, geTestCase{int64(kTwoTo25 + 1), true, false, ""}, geTestCase{int64(kTwoTo25 + 2), true, false, ""}, // Unsigned integers. geTestCase{uint(0), false, false, ""}, geTestCase{uint(kTwoTo25 + 0), false, false, ""}, geTestCase{uint(kTwoTo25 + 1), true, false, ""}, geTestCase{uint(kTwoTo25 + 2), true, false, ""}, geTestCase{uint8(0), false, false, ""}, geTestCase{uint8(255), false, false, ""}, geTestCase{uint16(0), false, false, ""}, geTestCase{uint16(65535), false, false, ""}, geTestCase{uint32(0), false, false, ""}, geTestCase{uint32(kTwoTo25 + 0), false, false, ""}, geTestCase{uint32(kTwoTo25 + 1), true, false, ""}, geTestCase{uint32(kTwoTo25 + 2), true, false, ""}, geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(kTwoTo25 + 0), false, false, ""}, geTestCase{uint64(kTwoTo25 + 1), true, false, ""}, geTestCase{uint64(kTwoTo25 + 2), true, false, ""}, geTestCase{uintptr(0), false, false, ""}, geTestCase{uintptr(kTwoTo25 + 0), false, false, ""}, geTestCase{uintptr(kTwoTo25 + 1), true, false, ""}, geTestCase{uintptr(kTwoTo25 + 2), true, false, ""}, // Floating point. geTestCase{float32(-1), false, false, ""}, geTestCase{float32(kTwoTo25 - 2), false, false, ""}, geTestCase{float32(kTwoTo25 - 1), true, false, ""}, geTestCase{float32(kTwoTo25 + 0), true, false, ""}, geTestCase{float32(kTwoTo25 + 1), true, false, ""}, geTestCase{float32(kTwoTo25 + 2), true, false, ""}, geTestCase{float32(kTwoTo25 + 3), true, false, ""}, geTestCase{float64(-1), false, false, ""}, geTestCase{float64(kTwoTo25 - 2), false, false, ""}, geTestCase{float64(kTwoTo25 - 1), false, false, ""}, geTestCase{float64(kTwoTo25 + 0), false, false, ""}, geTestCase{float64(kTwoTo25 + 1), true, false, ""}, geTestCase{float64(kTwoTo25 + 2), true, false, ""}, geTestCase{float64(kTwoTo25 + 3), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) Int64NotExactlyRepresentableByDoublePrecision() { // Double-precision floats don't have enough bits to represent the integers // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value // and should be treated as equivalent when floats are in the mix. const kTwoTo54 = 1 << 54 matcher := GreaterOrEqual(int64(kTwoTo54 + 1)) desc := matcher.Description() expectedDesc := "greater than or equal to 18014398509481985" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-1, false, false, ""}, geTestCase{1 << 30, false, false, ""}, geTestCase{int(-1), false, false, ""}, geTestCase{int(math.MaxInt32), false, false, ""}, geTestCase{int8(-1), false, false, ""}, geTestCase{int8(127), false, false, ""}, geTestCase{int16(-1), false, false, ""}, geTestCase{int16(0), false, false, ""}, geTestCase{int16(32767), false, false, ""}, geTestCase{int32(-1), false, false, ""}, geTestCase{int32(math.MaxInt32), false, false, ""}, geTestCase{int64(-1), false, false, ""}, geTestCase{int64(kTwoTo54 - 1), false, false, ""}, geTestCase{int64(kTwoTo54 + 0), false, false, ""}, geTestCase{int64(kTwoTo54 + 1), true, false, ""}, geTestCase{int64(kTwoTo54 + 2), true, false, ""}, // Unsigned integers. geTestCase{uint(0), false, false, ""}, geTestCase{uint(math.MaxUint32), false, false, ""}, geTestCase{uint8(0), false, false, ""}, geTestCase{uint8(255), false, false, ""}, geTestCase{uint16(0), false, false, ""}, geTestCase{uint16(65535), false, false, ""}, geTestCase{uint32(0), false, false, ""}, geTestCase{uint32(math.MaxUint32), false, false, ""}, geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(kTwoTo54 - 1), false, false, ""}, geTestCase{uint64(kTwoTo54 + 0), false, false, ""}, geTestCase{uint64(kTwoTo54 + 1), true, false, ""}, geTestCase{uint64(kTwoTo54 + 2), true, false, ""}, geTestCase{uintptr(0), false, false, ""}, geTestCase{uintptr(kTwoTo54 - 1), false, false, ""}, geTestCase{uintptr(kTwoTo54 + 0), false, false, ""}, geTestCase{uintptr(kTwoTo54 + 1), true, false, ""}, geTestCase{uintptr(kTwoTo54 + 2), true, false, ""}, // Floating point. geTestCase{float64(-1), false, false, ""}, geTestCase{float64(kTwoTo54 - 2), false, false, ""}, geTestCase{float64(kTwoTo54 - 1), true, false, ""}, geTestCase{float64(kTwoTo54 + 0), true, false, ""}, geTestCase{float64(kTwoTo54 + 1), true, false, ""}, geTestCase{float64(kTwoTo54 + 2), true, false, ""}, geTestCase{float64(kTwoTo54 + 3), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) Uint64NotExactlyRepresentableBySinglePrecision() { // Single-precision floats don't have enough bits to represent the integers // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value // and should be treated as equivalent when floats are in the mix. const kTwoTo25 = 1 << 25 matcher := GreaterOrEqual(uint64(kTwoTo25 + 1)) desc := matcher.Description() expectedDesc := "greater than or equal to 33554433" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-1, false, false, ""}, geTestCase{kTwoTo25 + 0, false, false, ""}, geTestCase{kTwoTo25 + 1, true, false, ""}, geTestCase{kTwoTo25 + 2, true, false, ""}, geTestCase{int(-1), false, false, ""}, geTestCase{int(kTwoTo25 + 0), false, false, ""}, geTestCase{int(kTwoTo25 + 1), true, false, ""}, geTestCase{int(kTwoTo25 + 2), true, false, ""}, geTestCase{int8(-1), false, false, ""}, geTestCase{int8(127), false, false, ""}, geTestCase{int16(-1), false, false, ""}, geTestCase{int16(0), false, false, ""}, geTestCase{int16(32767), false, false, ""}, geTestCase{int32(-1), false, false, ""}, geTestCase{int32(kTwoTo25 + 0), false, false, ""}, geTestCase{int32(kTwoTo25 + 1), true, false, ""}, geTestCase{int32(kTwoTo25 + 2), true, false, ""}, geTestCase{int64(-1), false, false, ""}, geTestCase{int64(kTwoTo25 + 0), false, false, ""}, geTestCase{int64(kTwoTo25 + 1), true, false, ""}, geTestCase{int64(kTwoTo25 + 2), true, false, ""}, // Unsigned integers. geTestCase{uint(0), false, false, ""}, geTestCase{uint(kTwoTo25 + 0), false, false, ""}, geTestCase{uint(kTwoTo25 + 1), true, false, ""}, geTestCase{uint(kTwoTo25 + 2), true, false, ""}, geTestCase{uint8(0), false, false, ""}, geTestCase{uint8(255), false, false, ""}, geTestCase{uint16(0), false, false, ""}, geTestCase{uint16(65535), false, false, ""}, geTestCase{uint32(0), false, false, ""}, geTestCase{uint32(kTwoTo25 + 0), false, false, ""}, geTestCase{uint32(kTwoTo25 + 1), true, false, ""}, geTestCase{uint32(kTwoTo25 + 2), true, false, ""}, geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(kTwoTo25 + 0), false, false, ""}, geTestCase{uint64(kTwoTo25 + 1), true, false, ""}, geTestCase{uint64(kTwoTo25 + 2), true, false, ""}, geTestCase{uintptr(0), false, false, ""}, geTestCase{uintptr(kTwoTo25 + 0), false, false, ""}, geTestCase{uintptr(kTwoTo25 + 1), true, false, ""}, geTestCase{uintptr(kTwoTo25 + 2), true, false, ""}, // Floating point. geTestCase{float32(-1), false, false, ""}, geTestCase{float32(kTwoTo25 - 2), false, false, ""}, geTestCase{float32(kTwoTo25 - 1), true, false, ""}, geTestCase{float32(kTwoTo25 + 0), true, false, ""}, geTestCase{float32(kTwoTo25 + 1), true, false, ""}, geTestCase{float32(kTwoTo25 + 2), true, false, ""}, geTestCase{float32(kTwoTo25 + 3), true, false, ""}, geTestCase{float64(-1), false, false, ""}, geTestCase{float64(kTwoTo25 - 2), false, false, ""}, geTestCase{float64(kTwoTo25 - 1), false, false, ""}, geTestCase{float64(kTwoTo25 + 0), false, false, ""}, geTestCase{float64(kTwoTo25 + 1), true, false, ""}, geTestCase{float64(kTwoTo25 + 2), true, false, ""}, geTestCase{float64(kTwoTo25 + 3), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) Uint64NotExactlyRepresentableByDoublePrecision() { // Double-precision floats don't have enough bits to represent the integers // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value // and should be treated as equivalent when floats are in the mix. const kTwoTo54 = 1 << 54 matcher := GreaterOrEqual(uint64(kTwoTo54 + 1)) desc := matcher.Description() expectedDesc := "greater than or equal to 18014398509481985" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{-1, false, false, ""}, geTestCase{1 << 30, false, false, ""}, geTestCase{int(-1), false, false, ""}, geTestCase{int(math.MaxInt32), false, false, ""}, geTestCase{int8(-1), false, false, ""}, geTestCase{int8(127), false, false, ""}, geTestCase{int16(-1), false, false, ""}, geTestCase{int16(0), false, false, ""}, geTestCase{int16(32767), false, false, ""}, geTestCase{int32(-1), false, false, ""}, geTestCase{int32(math.MaxInt32), false, false, ""}, geTestCase{int64(-1), false, false, ""}, geTestCase{int64(kTwoTo54 - 1), false, false, ""}, geTestCase{int64(kTwoTo54 + 0), false, false, ""}, geTestCase{int64(kTwoTo54 + 1), true, false, ""}, geTestCase{int64(kTwoTo54 + 2), true, false, ""}, // Unsigned integers. geTestCase{uint(0), false, false, ""}, geTestCase{uint(math.MaxUint32), false, false, ""}, geTestCase{uint8(0), false, false, ""}, geTestCase{uint8(255), false, false, ""}, geTestCase{uint16(0), false, false, ""}, geTestCase{uint16(65535), false, false, ""}, geTestCase{uint32(0), false, false, ""}, geTestCase{uint32(math.MaxUint32), false, false, ""}, geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(kTwoTo54 - 1), false, false, ""}, geTestCase{uint64(kTwoTo54 + 0), false, false, ""}, geTestCase{uint64(kTwoTo54 + 1), true, false, ""}, geTestCase{uint64(kTwoTo54 + 2), true, false, ""}, geTestCase{uintptr(0), false, false, ""}, geTestCase{uintptr(kTwoTo54 - 1), false, false, ""}, geTestCase{uintptr(kTwoTo54 + 0), false, false, ""}, geTestCase{uintptr(kTwoTo54 + 1), true, false, ""}, geTestCase{uintptr(kTwoTo54 + 2), true, false, ""}, // Floating point. geTestCase{float64(-1), false, false, ""}, geTestCase{float64(kTwoTo54 - 2), false, false, ""}, geTestCase{float64(kTwoTo54 - 1), true, false, ""}, geTestCase{float64(kTwoTo54 + 0), true, false, ""}, geTestCase{float64(kTwoTo54 + 1), true, false, ""}, geTestCase{float64(kTwoTo54 + 2), true, false, ""}, geTestCase{float64(kTwoTo54 + 3), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) Float32AboveExactIntegerRange() { // Single-precision floats don't have enough bits to represent the integers // near this one distinctly, so [2^25-1, 2^25+2] all receive the same value // and should be treated as equivalent when floats are in the mix. const kTwoTo25 = 1 << 25 matcher := GreaterOrEqual(float32(kTwoTo25 + 1)) desc := matcher.Description() expectedDesc := "greater than or equal to 3.3554432e+07" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{int64(-1), false, false, ""}, geTestCase{int64(kTwoTo25 - 2), false, false, ""}, geTestCase{int64(kTwoTo25 - 1), true, false, ""}, geTestCase{int64(kTwoTo25 + 0), true, false, ""}, geTestCase{int64(kTwoTo25 + 1), true, false, ""}, geTestCase{int64(kTwoTo25 + 2), true, false, ""}, geTestCase{int64(kTwoTo25 + 3), true, false, ""}, // Unsigned integers. geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(kTwoTo25 - 2), false, false, ""}, geTestCase{uint64(kTwoTo25 - 1), true, false, ""}, geTestCase{uint64(kTwoTo25 + 0), true, false, ""}, geTestCase{uint64(kTwoTo25 + 1), true, false, ""}, geTestCase{uint64(kTwoTo25 + 2), true, false, ""}, geTestCase{uint64(kTwoTo25 + 3), true, false, ""}, // Floating point. geTestCase{float32(-1), false, false, ""}, geTestCase{float32(kTwoTo25 - 2), false, false, ""}, geTestCase{float32(kTwoTo25 - 1), true, false, ""}, geTestCase{float32(kTwoTo25 + 0), true, false, ""}, geTestCase{float32(kTwoTo25 + 1), true, false, ""}, geTestCase{float32(kTwoTo25 + 2), true, false, ""}, geTestCase{float32(kTwoTo25 + 3), true, false, ""}, geTestCase{float64(-1), false, false, ""}, geTestCase{float64(kTwoTo25 - 2), false, false, ""}, geTestCase{float64(kTwoTo25 - 1), true, false, ""}, geTestCase{float64(kTwoTo25 + 0), true, false, ""}, geTestCase{float64(kTwoTo25 + 1), true, false, ""}, geTestCase{float64(kTwoTo25 + 2), true, false, ""}, geTestCase{float64(kTwoTo25 + 3), true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) Float64AboveExactIntegerRange() { // Double-precision floats don't have enough bits to represent the integers // near this one distinctly, so [2^54-1, 2^54+2] all receive the same value // and should be treated as equivalent when floats are in the mix. const kTwoTo54 = 1 << 54 matcher := GreaterOrEqual(float64(kTwoTo54 + 1)) desc := matcher.Description() expectedDesc := "greater than or equal to 1.8014398509481984e+16" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ // Signed integers. geTestCase{int64(-1), false, false, ""}, geTestCase{int64(kTwoTo54 - 2), false, false, ""}, geTestCase{int64(kTwoTo54 - 1), true, false, ""}, geTestCase{int64(kTwoTo54 + 0), true, false, ""}, geTestCase{int64(kTwoTo54 + 1), true, false, ""}, geTestCase{int64(kTwoTo54 + 2), true, false, ""}, geTestCase{int64(kTwoTo54 + 3), true, false, ""}, // Unsigned integers. geTestCase{uint64(0), false, false, ""}, geTestCase{uint64(kTwoTo54 - 2), false, false, ""}, geTestCase{uint64(kTwoTo54 - 1), true, false, ""}, geTestCase{uint64(kTwoTo54 + 0), true, false, ""}, geTestCase{uint64(kTwoTo54 + 1), true, false, ""}, geTestCase{uint64(kTwoTo54 + 2), true, false, ""}, geTestCase{uint64(kTwoTo54 + 3), true, false, ""}, // Floating point. geTestCase{float64(-1), false, false, ""}, geTestCase{float64(kTwoTo54 - 2), false, false, ""}, geTestCase{float64(kTwoTo54 - 1), true, false, ""}, geTestCase{float64(kTwoTo54 + 0), true, false, ""}, geTestCase{float64(kTwoTo54 + 1), true, false, ""}, geTestCase{float64(kTwoTo54 + 2), true, false, ""}, geTestCase{float64(kTwoTo54 + 3), true, false, ""}, } t.checkTestCases(matcher, cases) } //////////////////////////////////////////////////////////////////////// // String literals //////////////////////////////////////////////////////////////////////// func (t *GreaterOrEqualTest) EmptyString() { matcher := GreaterOrEqual("") desc := matcher.Description() expectedDesc := "greater than or equal to \"\"" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ geTestCase{"", true, false, ""}, geTestCase{"\x00", true, false, ""}, geTestCase{"a", true, false, ""}, geTestCase{"foo", true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) SingleNullByte() { matcher := GreaterOrEqual("\x00") desc := matcher.Description() expectedDesc := "greater than or equal to \"\x00\"" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ geTestCase{"", false, false, ""}, geTestCase{"\x00", true, false, ""}, geTestCase{"a", true, false, ""}, geTestCase{"foo", true, false, ""}, } t.checkTestCases(matcher, cases) } func (t *GreaterOrEqualTest) LongerString() { matcher := GreaterOrEqual("foo\x00") desc := matcher.Description() expectedDesc := "greater than or equal to \"foo\x00\"" ExpectThat(desc, Equals(expectedDesc)) cases := []geTestCase{ geTestCase{"", false, false, ""}, geTestCase{"\x00", false, false, ""}, geTestCase{"bar", false, false, ""}, geTestCase{"foo", false, false, ""}, geTestCase{"foo\x00", true, false, ""}, geTestCase{"fooa", true, false, ""}, geTestCase{"qux", true, false, ""}, } t.checkTestCases(matcher, cases) }
ebfe/scaleway-cli
vendor/github.com/smartystreets/assertions/internal/oglematchers/greater_or_equal_test.go
GO
mit
38,572
<?php namespace Lmc\Steward\Process; use Graphp\Algorithms\Tree\OutTree; /** * Interface for optimizers of tests order. */ interface OptimizeOrderInterface { /** * For each vertex in the tree (except root node) evaluate its order. * This determines the order in which tests (that have same time delay or no time delay) would be stared. * * @param OutTree $tree * @return array Array of [string key (= testclass fully qualified name) => int value (= test order)] */ public function optimize(OutTree $tree); }
tenerd/steward
src/Process/OptimizeOrderInterface.php
PHP
mit
551
using DarkSoulsII.DebugView.Core; namespace DarkSoulsII.DebugView.Model.Map.Location { public class MapGeneralStatueLocation : MapGeneralLocation, IReadable<MapGeneralStatueLocation> { public new MapGeneralStatueLocation Read(IPointerFactory pointerFactory, IReader reader, int address, bool relative = false) { base.Read(pointerFactory, reader, address, relative); return this; } } }
Atvaark/DarkSoulsII.DebugView
DarkSoulsII.DebugView.Model/Map/Location/MapGeneralStatueLocation.cs
C#
mit
448
'use strict'; class BookRecommendation extends React.Component { constructor(props) { super(props); // this.state = {count: props.initialCount}; } render() { return ( <div> <BookPicture {...this.props} horizontal={true} /> <div className='switch'> <label> <input type='checkbox' onClick={this.props.onSwitch} /> <span className='lever'></span> </label> </div> </div> ); } }
kar288/exquery
hello/static/src/bookRecommendation.js
JavaScript
mit
480
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'module-navigation', templateUrl: './app/widgets/navigation/navigation.component.html' }) export class ModNavigationComponent implements OnInit { constructor() { } ngOnInit() { } }
manhcuong06/angular_admin
src/app/widgets/navigation/navigation.component.ts
TypeScript
mit
272
/// <reference types="xrm" /> export declare class DeviceMock implements Xrm.Device { captureAudio(): Xrm.Async.PromiseLike<Xrm.Device.CaptureFileResponse>; captureImage(imageOptions: Xrm.Device.CaptureImageOptions): Xrm.Async.PromiseLike<Xrm.Device.CaptureFileResponse>; captureVideo(): Xrm.Async.PromiseLike<Xrm.Device.CaptureFileResponse>; getBarcodeValue(): Xrm.Async.PromiseLike<string>; getCurrentPosition(): Xrm.Async.PromiseLike<Xrm.Device.GetCurrentPositionResponse>; pickFile(pickFileOptions: Xrm.Device.PickFileOptions): Xrm.Async.PromiseLike<Xrm.Device.CaptureFileResponse[]>; }
camelCaseDave/xrm-mock
dist/xrm-mock/device/device.mock.d.ts
TypeScript
mit
615
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DMT.Partition.Interfaces; using DMT.Partition.Module.Exceptions; namespace DMT.Partition.Module { class PartitionRegistry { private List<IPartition> partitions; private int lastSelectedPartition = -1; public PartitionRegistry(IEnumerable<IPartition> partitions) { this.partitions = new List<IPartition>(partitions); } /// <summary> /// Gets a partition that has not been sent out to any matcher. /// </summary> /// <returns>the next partition to send out</returns> /// <exception cref="InvalidOperationException">When every partition has been sent out.</exception> public IPartition GetNextPartition() { if (this.partitions.Count <= this.lastSelectedPartition + 1) { throw new NoMorePartitionException("There are no more partitions to send out."); } lock (this) { ++this.lastSelectedPartition; return this.partitions[lastSelectedPartition]; } } } }
tmichel/thesis
Applications/DMT.Partition.Module/PartitionRegistry.cs
C#
mit
1,226
Capybara::SpecHelper.spec '#source' do it "should return the unmodified page source" do @session.visit('/') @session.source.should include('Hello world!') end it "should return the original, unmodified source of the page", :requires => [:js, :source] do @session.visit('/with_js') @session.send(method).should include('This is text') @session.send(method).should_not include('I changed it') end end
jarib/capybara
lib/capybara/spec/session/source_spec.rb
Ruby
mit
428
from binascii import hexlify from struct import pack, unpack import hashlib import time import sys import traceback import electrum_dgb as electrum from electrum_dgb.bitcoin import EncodeBase58Check, DecodeBase58Check, TYPE_ADDRESS, int_to_hex, var_int from electrum_dgb.i18n import _ from electrum_dgb.plugins import BasePlugin, hook from electrum_dgb.keystore import Hardware_KeyStore, parse_xpubkey from ..hw_wallet import HW_PluginBase from electrum_dgb.util import format_satoshis_plain, print_error try: import hid from btchip.btchipComm import HIDDongleHIDAPI, DongleWait from btchip.btchip import btchip from btchip.btchipUtils import compress_public_key,format_transaction, get_regular_input_script, get_p2sh_input_script from btchip.bitcoinTransaction import bitcoinTransaction from btchip.btchipFirmwareWizard import checkFirmware, updateFirmware from btchip.btchipException import BTChipException btchip.setAlternateCoinVersions = setAlternateCoinVersions BTCHIP = True BTCHIP_DEBUG = False except ImportError: BTCHIP = False class Ledger_Client(): def __init__(self, hidDevice): self.dongleObject = btchip(hidDevice) self.preflightDone = False def is_pairable(self): return True def close(self): self.dongleObject.dongle.close() def timeout(self, cutoff): pass def is_initialized(self): return True def label(self): return "" def i4b(self, x): return pack('>I', x) def get_xpub(self, bip32_path): self.checkDevice() # bip32_path is of the form 44'/0'/1' # S-L-O-W - we don't handle the fingerprint directly, so compute # it manually from the previous node # This only happens once so it's bearable #self.get_client() # prompt for the PIN before displaying the dialog if necessary #self.handler.show_message("Computing master public key") try: splitPath = bip32_path.split('/') if splitPath[0] == 'm': splitPath = splitPath[1:] bip32_path = bip32_path[2:] fingerprint = 0 if len(splitPath) > 1: prevPath = "/".join(splitPath[0:len(splitPath) - 1]) nodeData = self.dongleObject.getWalletPublicKey(prevPath) publicKey = compress_public_key(nodeData['publicKey']) h = hashlib.new('ripemd160') h.update(hashlib.sha256(publicKey).digest()) fingerprint = unpack(">I", h.digest()[0:4])[0] nodeData = self.dongleObject.getWalletPublicKey(bip32_path) publicKey = compress_public_key(nodeData['publicKey']) depth = len(splitPath) lastChild = splitPath[len(splitPath) - 1].split('\'') if len(lastChild) == 1: childnum = int(lastChild[0]) else: childnum = 0x80000000 | int(lastChild[0]) xpub = "0488B21E".decode('hex') + chr(depth) + self.i4b(fingerprint) + self.i4b(childnum) + str(nodeData['chainCode']) + str(publicKey) except Exception, e: #self.give_error(e, True) return None finally: #self.handler.clear_dialog() pass return EncodeBase58Check(xpub) def has_detached_pin_support(self, client): try: client.getVerifyPinRemainingAttempts() return True except BTChipException, e: if e.sw == 0x6d00: return False raise e def is_pin_validated(self, client): try: # Invalid SET OPERATION MODE to verify the PIN status client.dongle.exchange(bytearray([0xe0, 0x26, 0x00, 0x00, 0x01, 0xAB])) except BTChipException, e: if (e.sw == 0x6982): return False if (e.sw == 0x6A80): return True raise e def perform_hw1_preflight(self): try: firmware = self.dongleObject.getFirmwareVersion()['version'].split(".") if not checkFirmware(firmware): self.dongleObject.dongle.close() raise Exception("HW1 firmware version too old. Please update at https://www.ledgerwallet.com") try: self.dongleObject.getOperationMode() except BTChipException, e: if (e.sw == 0x6985): self.dongleObject.dongle.close() self.handler.get_setup( ) # Acquire the new client on the next run else: raise e if self.has_detached_pin_support(self.dongleObject) and not self.is_pin_validated(self.dongleObject) and (self.handler <> None): remaining_attempts = self.dongleObject.getVerifyPinRemainingAttempts() if remaining_attempts <> 1: msg = "Enter your Ledger PIN - remaining attempts : " + str(remaining_attempts) else: msg = "Enter your Ledger PIN - WARNING : LAST ATTEMPT. If the PIN is not correct, the dongle will be wiped." confirmed, p, pin = self.password_dialog(msg) if not confirmed: raise Exception('Aborted by user - please unplug the dongle and plug it again before retrying') pin = pin.encode() self.dongleObject.verifyPin(pin) except BTChipException, e: if (e.sw == 0x6faa): raise Exception("Dongle is temporarily locked - please unplug it and replug it again") if ((e.sw & 0xFFF0) == 0x63c0): raise Exception("Invalid PIN - please unplug the dongle and plug it again before retrying") raise e def checkDevice(self): if not self.preflightDone: try: self.perform_hw1_preflight() except BTChipException as e: if (e.sw == 0x6d00): raise BaseException("Device not in Bitcoin mode") raise e self.preflightDone = True def password_dialog(self, msg=None): response = self.handler.get_word(msg) if response is None: return False, None, None return True, response, response class Ledger_KeyStore(Hardware_KeyStore): hw_type = 'ledger' device = 'Ledger' def __init__(self, d): Hardware_KeyStore.__init__(self, d) # Errors and other user interaction is done through the wallet's # handler. The handler is per-window and preserved across # device reconnects self.force_watching_only = False self.signing = False self.cfg = d.get('cfg', {'mode':0,'pair':''}) def dump(self): obj = Hardware_KeyStore.dump(self) obj['cfg'] = self.cfg return obj def get_derivation(self): return self.derivation def get_client(self): return self.plugin.get_client(self) def give_error(self, message, clear_client = False): print_error(message) if not self.signing: self.handler.show_error(message) else: self.signing = False if clear_client: self.client = None raise Exception(message) def address_id_stripped(self, address): # Strip the leading "m/" change, index = self.get_address_index(address) derivation = self.derivation address_path = "%s/%d/%d"%(derivation, change, index) return address_path[2:] def decrypt_message(self, pubkey, message, password): raise RuntimeError(_('Encryption and decryption are currently not supported for %s') % self.device) def sign_message(self, sequence, message, password): self.signing = True # prompt for the PIN before displaying the dialog if necessary client = self.get_client() address_path = self.get_derivation()[2:] + "/%d/%d"%sequence self.handler.show_message("Signing message ...") try: info = self.get_client().signMessagePrepare(address_path, message) pin = "" if info['confirmationNeeded']: pin = self.handler.get_auth( info ) # does the authenticate dialog and returns pin if not pin: raise UserWarning(_('Cancelled by user')) pin = str(pin).encode() signature = self.get_client().signMessageSign(pin) except BTChipException, e: if e.sw == 0x6a80: self.give_error("Unfortunately, this message cannot be signed by the Ledger wallet. Only alphanumerical messages shorter than 140 characters are supported. Please remove any extra characters (tab, carriage return) and retry.") else: self.give_error(e, True) except UserWarning: self.handler.show_error(_('Cancelled by user')) return '' except Exception, e: self.give_error(e, True) finally: self.handler.clear_dialog() self.signing = False # Parse the ASN.1 signature rLength = signature[3] r = signature[4 : 4 + rLength] sLength = signature[4 + rLength + 1] s = signature[4 + rLength + 2:] if rLength == 33: r = r[1:] if sLength == 33: s = s[1:] r = str(r) s = str(s) # And convert it return chr(27 + 4 + (signature[0] & 0x01)) + r + s def sign_transaction(self, tx, password): if tx.is_complete(): return client = self.get_client() self.signing = True inputs = [] inputsPaths = [] pubKeys = [] chipInputs = [] redeemScripts = [] signatures = [] preparedTrustedInputs = [] changePath = "" changeAmount = None output = None outputAmount = None p2shTransaction = False reorganize = False pin = "" self.get_client() # prompt for the PIN before displaying the dialog if necessary # Fetch inputs of the transaction to sign derivations = self.get_tx_derivations(tx) for txin in tx.inputs(): if txin.get('is_coinbase'): self.give_error("Coinbase not supported") # should never happen if len(txin['pubkeys']) > 1: p2shTransaction = True for i, x_pubkey in enumerate(txin['x_pubkeys']): if x_pubkey in derivations: signingPos = i s = derivations.get(x_pubkey) hwAddress = "%s/%d/%d" % (self.get_derivation()[2:], s[0], s[1]) break else: self.give_error("No matching x_key for sign_transaction") # should never happen inputs.append([txin['prev_tx'].raw, txin['prevout_n'], txin.get('redeemScript'), txin['prevout_hash'], signingPos ]) inputsPaths.append(hwAddress) pubKeys.append(txin['pubkeys']) # Sanity check if p2shTransaction: for txinput in tx.inputs(): if len(txinput['pubkeys']) < 2: self.give_error("P2SH / regular input mixed in same transaction not supported") # should never happen txOutput = var_int(len(tx.outputs())) for txout in tx.outputs(): output_type, addr, amount = txout txOutput += int_to_hex(amount, 8) script = tx.pay_script(output_type, addr) txOutput += var_int(len(script)/2) txOutput += script txOutput = txOutput.decode('hex') # Recognize outputs - only one output and one change is authorized if not p2shTransaction: if len(tx.outputs()) > 2: # should never happen self.give_error("Transaction with more than 2 outputs not supported") for _type, address, amount in tx.outputs(): assert _type == TYPE_ADDRESS info = tx.output_info.get(address) if info is not None: index, xpubs, m = info changePath = self.get_derivation()[2:] + "/%d/%d"%index changeAmount = amount else: output = address outputAmount = amount self.handler.show_message(_("Confirm Transaction on your Ledger device...")) try: # Get trusted inputs from the original transactions for utxo in inputs: if not p2shTransaction: txtmp = bitcoinTransaction(bytearray(utxo[0].decode('hex'))) chipInputs.append(self.get_client().getTrustedInput(txtmp, utxo[1])) redeemScripts.append(txtmp.outputs[utxo[1]].script) else: tmp = utxo[3].decode('hex')[::-1].encode('hex') tmp += int_to_hex(utxo[1], 4) chipInputs.append({'value' : tmp.decode('hex')}) redeemScripts.append(bytearray(utxo[2].decode('hex'))) # Sign all inputs firstTransaction = True inputIndex = 0 rawTx = tx.serialize() self.get_client().enableAlternate2fa(False) while inputIndex < len(inputs): self.get_client().startUntrustedTransaction(firstTransaction, inputIndex, chipInputs, redeemScripts[inputIndex]) if not p2shTransaction: outputData = self.get_client().finalizeInput(output, format_satoshis_plain(outputAmount), format_satoshis_plain(tx.get_fee()), changePath, bytearray(rawTx.decode('hex'))) reorganize = True else: outputData = self.get_client().finalizeInputFull(txOutput) outputData['outputData'] = txOutput if firstTransaction: transactionOutput = outputData['outputData'] if outputData['confirmationNeeded']: outputData['address'] = output self.handler.clear_dialog() pin = self.handler.get_auth( outputData ) # does the authenticate dialog and returns pin if not pin: raise UserWarning() if pin != 'paired': self.handler.show_message(_("Confirmed. Signing Transaction...")) else: # Sign input with the provided PIN inputSignature = self.get_client().untrustedHashSign(inputsPaths[inputIndex], pin) inputSignature[0] = 0x30 # force for 1.4.9+ signatures.append(inputSignature) inputIndex = inputIndex + 1 if pin != 'paired': firstTransaction = False except UserWarning: self.handler.show_error(_('Cancelled by user')) return except BaseException as e: traceback.print_exc(file=sys.stdout) self.give_error(e, True) finally: self.handler.clear_dialog() # Reformat transaction inputIndex = 0 while inputIndex < len(inputs): if p2shTransaction: signaturesPack = [signatures[inputIndex]] * len(pubKeys[inputIndex]) inputScript = get_p2sh_input_script(redeemScripts[inputIndex], signaturesPack) preparedTrustedInputs.append([ ("\x00" * 4) + chipInputs[inputIndex]['value'], inputScript ]) else: inputScript = get_regular_input_script(signatures[inputIndex], pubKeys[inputIndex][0].decode('hex')) preparedTrustedInputs.append([ chipInputs[inputIndex]['value'], inputScript ]) inputIndex = inputIndex + 1 updatedTransaction = format_transaction(transactionOutput, preparedTrustedInputs) updatedTransaction = hexlify(updatedTransaction) if reorganize: tx.update(updatedTransaction) else: tx.update_signatures(updatedTransaction) self.signing = False class LedgerPlugin(HW_PluginBase): libraries_available = BTCHIP keystore_class = Ledger_KeyStore client = None DEVICE_IDS = [ (0x2581, 0x1807), # HW.1 legacy btchip (0x2581, 0x2b7c), # HW.1 transitional production (0x2581, 0x3b7c), # HW.1 ledger production (0x2581, 0x4b7c), # HW.1 ledger test (0x2c97, 0x0000), # Blue (0x2c97, 0x0001) # Nano-S ] def __init__(self, parent, config, name): HW_PluginBase.__init__(self, parent, config, name) if self.libraries_available: self.device_manager().register_devices(self.DEVICE_IDS) def btchip_is_connected(self, keystore): try: self.get_client(keystore).getFirmwareVersion() except Exception as e: return False return True def get_btchip_device(self, device): ledger = False if (device.product_key[0] == 0x2581 and device.product_key[1] == 0x3b7c) or (device.product_key[0] == 0x2581 and device.product_key[1] == 0x4b7c) or (device.product_key[0] == 0x2c97): ledger = True dev = hid.device() dev.open_path(device.path) dev.set_nonblocking(True) return HIDDongleHIDAPI(dev, ledger, BTCHIP_DEBUG) def create_client(self, device, handler): self.handler = handler client = self.get_btchip_device(device) if client <> None: client = Ledger_Client(client) return client def setup_device(self, device_info, wizard): devmgr = self.device_manager() device_id = device_info.device.id_ client = devmgr.client_by_id(device_id) #client.handler = wizard client.handler = self.create_handler(wizard) #client.get_xpub('m') client.get_xpub("m/44'/0'") # TODO replace by direct derivation once Nano S > 1.1 def get_xpub(self, device_id, derivation, wizard): devmgr = self.device_manager() client = devmgr.client_by_id(device_id) #client.handler = wizard client.handler = self.create_handler(wizard) client.checkDevice() xpub = client.get_xpub(derivation) return xpub def get_client(self, wallet, force_pair=True, noPin=False): aborted = False client = self.client if not client or client.bad: try: d = getDongle(BTCHIP_DEBUG) client = btchip(d) ver = client.getFirmwareVersion() firmware = ver['version'].split(".") wallet.canAlternateCoinVersions = (ver['specialVersion'] >= 0x20 and map(int, firmware) >= [1, 0, 1]) if not checkFirmware(firmware): d.close() try: updateFirmware() except Exception, e: aborted = True raise e d = getDongle(BTCHIP_DEBUG) client = btchip(d) try: client.getOperationMode() except BTChipException, e: if (e.sw == 0x6985): d.close() dialog = StartBTChipPersoDialog() dialog.exec_() # Then fetch the reference again as it was invalidated d = getDongle(BTCHIP_DEBUG) client = btchip(d) else: raise e if not noPin: # Immediately prompts for the PIN remaining_attempts = client.getVerifyPinRemainingAttempts() if remaining_attempts <> 1: msg = "Enter your Ledger PIN - remaining attempts : " + str(remaining_attempts) else: msg = "Enter your Ledger PIN - WARNING : LAST ATTEMPT. If the PIN is not correct, the dongle will be wiped." confirmed, p, pin = wallet.password_dialog(msg) if not confirmed: aborted = True raise Exception('Aborted by user - please unplug the dongle and plug it again before retrying') pin = pin.encode() client.verifyPin(pin) if wallet.canAlternateCoinVersions: client.setAlternateCoinVersions(30, 5) except BTChipException, e: try: client.dongle.close() except: pass client = None if (e.sw == 0x6faa): raise Exception("Dongle is temporarily locked - please unplug it and replug it again") if ((e.sw & 0xFFF0) == 0x63c0): raise Exception("Invalid PIN - please unplug the dongle and plug it again before retrying") raise e except Exception, e: try: client.dongle.close() except: pass client = None if not aborted: raise Exception("Could not connect to your Ledger wallet. Please verify access permissions, PIN, or unplug the dongle and plug it again") else: raise e client.bad = False wallet.device_checked = False wallet.proper_device = False self.client = client return self.client
protonn/Electrum-Cash
plugins/ledger/ledger.py
Python
mit
22,169
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ class FatFreeCRM::Tagging < ActsAsTaggableOn::Tagging ActiveSupport.run_load_hooks(:fat_free_crm_tagging, self) end
fkoessler/fat_free_crm
app/models/polymorphic/fat_free_crm/tagging.rb
Ruby
mit
408
import React from "react"; import { connect } from "react-redux"; import InviteNew from "./view"; import { selectUserInvitesRemaining, selectUserInviteNewIsPending, selectUserInviteNewErrorMessage, } from "redux/selectors/user"; import rewards from "rewards"; import { makeSelectRewardAmountByType } from "redux/selectors/rewards"; import { doUserInviteNew } from "redux/actions/user"; const select = state => { const selectReward = makeSelectRewardAmountByType(); return { errorMessage: selectUserInviteNewErrorMessage(state), invitesRemaining: selectUserInvitesRemaining(state), isPending: selectUserInviteNewIsPending(state), rewardAmount: selectReward(state, { reward_type: rewards.TYPE_REFERRAL }), }; }; const perform = dispatch => ({ inviteNew: email => dispatch(doUserInviteNew(email)), }); export default connect(select, perform)(InviteNew);
jsigwart/lbry-app
src/renderer/js/component/inviteNew/index.js
JavaScript
mit
886
import { OHIF } from 'meteor/ohif:core'; import { _ } from 'meteor/underscore'; // TODO: change this to a const after refactoring newMeasurements code on measurementTableView.js OHIF.measurements.getLocation = collection => { for (let i = 0; i < collection.length; i++) { if (collection[i].location) { return collection[i].location; } } }; /** * Group all measurements by its tool group and measurement number. * * @param measurementApi * @param timepointApi * @returns {*} A list containing each toolGroup and an array containing the measurement rows */ OHIF.measurements.getMeasurementsGroupedByNumber = (measurementApi, timepointApi) => { const getPath = OHIF.utils.ObjectPath.get; const configuration = OHIF.measurements.MeasurementApi.getConfiguration(); if (!measurementApi || !timepointApi || !configuration) return; // Check which tools are going to be displayed const displayToolGroupMap = {}; const displayToolList = []; configuration.measurementTools.forEach(toolGroup => { displayToolGroupMap[toolGroup.id] = false; toolGroup.childTools.forEach(tool => { const willDisplay = !!getPath(tool, 'options.measurementTable.displayFunction'); if (willDisplay) { displayToolList.push(tool.id); displayToolGroupMap[toolGroup.id] = true; } }); }); // Create the result object const groupedMeasurements = []; const baseline = timepointApi.baseline(); if (!baseline) return; configuration.measurementTools.forEach(toolGroup => { // Skip this tool group if it should not be displayed if (!displayToolGroupMap[toolGroup.id]) return; // Retrieve all the data for this Measurement type (e.g. 'targets') // which was recorded at baseline. const atBaseline = measurementApi.fetch(toolGroup.id, { timepointId: baseline.timepointId }); // Obtain a list of the Measurement Numbers from the // measurements which have baseline data const numbers = atBaseline.map(m => m.measurementNumber); // Retrieve all the data for this Measurement type which // match the Measurement Numbers obtained above const data = measurementApi.fetch(toolGroup.id, { toolId: { $in: displayToolList }, measurementNumber: { $in: numbers } }); // Group the Measurements by Measurement Number const groupObject = _.groupBy(data, entry => entry.measurementNumber); // Reformat the data for display in the table const measurementRows = Object.keys(groupObject).map(key => ({ measurementTypeId: toolGroup.id, measurementNumber: key, location: OHIF.measurements.getLocation(groupObject[key]), responseStatus: false, // TODO: Get the latest timepoint and determine the response status entries: groupObject[key] })); // Add the group to the result groupedMeasurements.push({ toolGroup, measurementRows }); }); return groupedMeasurements; };
NucleusIo/HealthGenesis
viewerApp/Packages/ohif-measurements/client/lib/getMeasurementsGroupedByNumber.js
JavaScript
mit
3,251
export declare class UIPasswordMeter { score: number; hasPassword: boolean; tooltip: string; maxStrength: number; readonly strength: { "--password-strength": string; } | { "--password-strength": number; }; }
adarshpastakia/aurelia-ui-framework
dist/typings/forms/ui-password-meter.d.ts
TypeScript
mit
252
<?php /** * CodeIgniter * * An open source application development framework for PHP * * This content is released under the MIT License (MIT) * * Copyright (c) 2014 - 2015, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * UnregisterConfirm Controller * * @author Stephanie */ class UnregisterConfirm extends Application { /** * Index Page for this controller. */ public function index() { //Renders pagebody. $this->data['pagebody'] = 'unregisterConfirm'; $this->render(); } } /* End of file unregisterConfirm.php */ /* Location: ./application/controllers/UnregisterConfirm.php */
SoL-Photo/SoL
application/controllers/UnregisterConfirm.php
PHP
mit
2,517
# -*- coding: utf-8 -*- """ Facade patterns """ class Power(object): """ SubSystem """ @staticmethod def start(): print "Power on!" class Display(object): """ Subsystem """ @staticmethod def start(): print "Display on!" class Client(object): """ Facade """ def __init__(self): self.power = Power() self.display = Display() self.components = [self.power, self.display] def start_all(self): for _component in self.components: _component.start() if __name__ == '__main__': client = Client() client.start_all()
xuwei0455/design_patterns
Facade.py
Python
mit
645
function MemberExpression(_path) { VISITOR.memberExpression(_path.node); } module.exports = MemberExpression;
seraum/nectarjs
compiler/native/visitor/plugin/MemberExpression.js
JavaScript
mit
113
# frozen_string_literal: true module SamlAuthentication class SessionsController < Devise::SamlSessionsController before_action :store_logging_out_username, only: :destroy after_action :store_winning_strategy, only: :create # Overrides SamlSessionsController. # # The default behavior for IdP-initiated signout uses a database-backed # User#saml_session_index_key, which upon invalidation will invalidate _all_ # NUcore sessions the user has open, even on other computers. With this override # you are only signed out the current browser's session. def idp_sign_out if params[:SAMLRequest] # IdP initiated logout idp_initiated_sign_out elsif params[:SAMLResponse] sp_initiated_sign_out else head :invalid_request end end protected # Remove recall, so failures redirect back to sign_in page def auth_options { scope: resource_name } end # Override SamlSessionsController # # Some IdP providers require the name_identifier_value of the LogoutRequest # to match the username of the current user. def after_sign_out_path_for(_resource_or_scope) idp_entity_id = get_idp_entity_id(params) request = OneLogin::RubySaml::Logoutrequest.new config = saml_config(idp_entity_id).dup config.name_identifier_value = @signed_out_username request.create(config) end private # SP is NUcore. User is already logged out by the sessions#delete call def sp_initiated_sign_out if Devise.saml_sign_out_success_url redirect_to Devise.saml_sign_out_success_url else redirect_to action: :new end end def idp_initiated_sign_out sign_out(resource_name) saml_config = saml_config(get_idp_entity_id(params)) logout_request = OneLogin::RubySaml::SloLogoutrequest.new(params[:SAMLRequest], settings: saml_config) redirect_to generate_idp_logout_response(saml_config, logout_request.id) end # Store the username for use in `after_sign_out_path_for` def store_logging_out_username @signed_out_username = current_user.public_send(Devise.saml_default_user_key) end # This will be used to choose which Logout link is shown to the user. # https://github.com/apokalipto/devise_saml_authenticatable/wiki/Supporting-multiple-authentication-strategies def store_winning_strategy warden.session(resource_name)[:strategy] = :saml_authenticatable end end end
tablexi/nucore-open
vendor/engines/saml_authentication/app/controllers/saml_authentication/sessions_controller.rb
Ruby
mit
2,520
'use strict'; var path = require('path'); var assert = require('yeoman-generator').assert; var helpers = require('yeoman-generator').test; var os = require('os'); describe('respec:app', function () { before(function (done) { helpers.run(path.join(__dirname, '../app')) .inDir(path.join(os.tmpdir(), './temp-test')) .withOptions({ 'skip-install': true }) .withPrompt({ someOption: true }) .on('end', done); }); it('creates files', function () { assert.file([ 'index.html', 'package.json', '.editorconfig' ]); }); });
adrianba/generator-respec
test/test-app.js
JavaScript
mit
595
package gk.nickles.ndimes.ui; import android.content.Context; import android.support.v4.app.Fragment; import com.google.inject.Inject; import java.util.List; import gk.nickles.ndimes.model.Event; import gk.nickles.ndimes.ui.adapter.EventDetailPagerAdapter; import gk.nickles.ndimes.ui.fragment.DebtsFragment; import gk.nickles.ndimes.ui.fragment.ExpensesFragment; import gk.nickles.ndimes.ui.fragment.ParticipantsFragment; import gk.nickles.splitty.R; import static com.google.inject.internal.util.$Preconditions.checkNotNull; import static java.util.Arrays.asList; import static roboguice.RoboGuice.getInjector; public class EventDetailTabs { @Inject private Context context; private Event event; private List<String> labels; public EventDetailTabs init(Event event) { checkNotNull(event); this.event = event; labels = asList( context.getString(R.string.overview), context.getString(R.string.expenses), context.getString(R.string.participants)); return this; } public int getTabPosition(String label) { return labels.indexOf(label); } public Event getEvent() { return event; } public String getLabel(int position) { return labels.get(position); } public Fragment getFragment(int position, EventDetailPagerAdapter pagerAdapter) { checkNotNull(event); switch (position) { case 0: return getInjector(context).getInstance(DebtsFragment.class).init(event, pagerAdapter); case 1: return getInjector(context).getInstance(ExpensesFragment.class).init(event, pagerAdapter); case 2: return getInjector(context).getInstance(ParticipantsFragment.class).init(event, pagerAdapter); default: throw new IllegalArgumentException("position"); } } public int numTabs() { return 3; } }
Gchorba/NickleAndDimed
app/src/main/java/gk/nickles/ndimes/ui/EventDetailTabs.java
Java
mit
1,996
require 'test_helper' module SelecaoAdmin class IntegraUserControllerTest < ActionController::TestCase test "should get index" do get :index assert_response :success end end end
swayzepatryck/selecao_admin
test/functional/selecao_admin/integra_user_controller_test.rb
Ruby
mit
206