code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
module.exports = require('./scaffold')
wearelucid/vuepack
template/plopfile.js
JavaScript
mit
39
import React, { Component } from 'react' import ReactDOM from 'react-dom' import Table from '../Table' import Toolbar from '../Toolbar' export default class ConversionTrainer extends Component { constructor (props) { super(props) this.refreshExample() } state = {} refreshExample () { fetch('http://discrete-eltech.eurodir.ru:8888/solve/conversion') .then(response => response.json()) .then(example => { let inputs = ReactDOM.findDOMNode(this).querySelectorAll('input[type="number"]'); // Fuck JavaScript [].forEach.call(inputs, input => { input.value = '' input.classList.remove('ok') input.classList.remove('wrong') }) this.setState(example) }) .catch(console.error) } check (event) { if (event.currentTarget.value != '') { if (event.currentTarget.value === event.currentTarget.dataset.original) { event.currentTarget.classList.remove('wrong') event.currentTarget.classList.add('ok') } else { event.currentTarget.classList.remove('ok') event.currentTarget.classList.add('wrong') } } } render () { return ( <div className="content-wrap"> <Toolbar /> <h1>Перевод из одной системы счисления в другую</h1> <h2>Тренажёр</h2> {this.state.input ? <div> <p>Певевести {this.state.input[0]}<sub>{this.state.input[1]}</sub> в систему счисления с основанием {this.state.input[2]}</p> <Table data={this.state.table.map(row => row.map(col => col !== '' ? ( <div className="input-number-wrap"> <input type="number" data-original={col} onBlur={e => this.check(e)}/> <i className="checker"></i> </div> ) : null ))}/> <code className="answer-area"> Ответ: &nbsp; <div className="input-number-wrap"> <input type="number" data-original={this.state.output} onBlur={e => this.check(e)}/> <i className="checker"></i> </div> </code> <div className="button-wrap"> <button onClick={e => this.refreshExample()}>Обновить</button> </div> </div> : null } </div> ) } }
mifarse/discrete-eltech
public/components/algorithms/ConversionTrainer.js
JavaScript
mit
2,480
(function($){ $(function(){ $('.button-collapse').sideNav(); $('.parallax').parallax(); $(".dropdown-button").dropdown(); $('.carousel').carousel(); $('.carousel.carousel-slider').carousel({full_width: true}); }); // end of document ready })(jQuery); // end of jQuery name space
CUC2016/Restaurante
js/init.js
JavaScript
mit
305
export function isDefined (value) { return typeof value !== 'undefined' }
carnesen/satoshi-tv
src/server/util/checks.js
JavaScript
mit
76
var eyes = require('eyes'); var async = require('async'); var utils = require('../lib/utils'); var express = require('express'); var engines = require('consolidate'); var socketio = require('socket.io'); var http = require('http'); var RedisStore = require('../lib/webserver/tools/redisstore')(express); var httpProxy = require('http-proxy'); var app = express(); var server = http.createServer(app); app.use(express.query()); app.use(express.responseTime()); /* POST */ app.use(express.bodyParser()); app.engine('ejs', engines.ejs); app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); var cookieSecret = 'rodneybatman'; var cookieParser = express.cookieParser(cookieSecret); var sessionStore = new RedisStore({ host:'127.0.0.1', port:6379 }) /* Session */ app.use(cookieParser); app.use(express.session({ store:sessionStore, secret:cookieSecret })) var io = socketio.listen(server); if(process.env.NODE_ENV=='production'){ io.enable('browser client minification'); io.enable('browser client etag'); io.enable('browser client gzip'); } io.set('log level', 1); io.set('transports', [ 'websocket' , 'flashsocket' , 'htmlfile' , 'xhr-polling' , 'jsonp-polling' ]) app.use(app.router); app.get('/', function(req, res, next){ res.render('test'); }) io.sockets.on('connection', function(socket){ socket.on('test', function(val){ eyes.inspect('ok: ' + val); }) }) server.listen(8080, function(){ console.log('web on port 8080'); }) var proxy = new httpProxy.RoutingProxy(); var router = http.createServer(function(req, res){ // // Proxy normal HTTP requests // proxy.proxyRequest(req, res, { host: 'localhost', port: 8080 }) }) router.on('upgrade', function(req, socket, head) { // // Proxy websocket requests too // proxy.proxyWebSocketRequest(req, socket, head, { host: 'localhost', port: 8080 }) }); router.listen(80, function(){ console.log('router on port 80'); })
binocarlos/quarry.io
examples/testsocketrouting.js
JavaScript
mit
1,981
'use strict'; var path = require('path'); var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var nsp = require('gulp-nsp'); var plumber = require('gulp-plumber'); var coveralls = require('gulp-coveralls'); var ghPages = require('gulp-gh-pages'); gulp.task('deploy', function() { return gulp.src('./dist/**/*') .pipe(ghPages()); }); gulp.task('static', function () { return gulp.src('**/*.js') .pipe(excludeGitignore()); }); gulp.task('nsp', function (cb) { nsp({package: path.resolve('package.json')}, cb); }); gulp.task('pre-test', function () { return gulp.src('generators/**/*.js') .pipe(excludeGitignore()) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()); }); gulp.task('test', ['pre-test'], function (cb) { var mochaErr; gulp.src('test/**/*.js') .pipe(plumber()) .pipe(mocha({reporter: 'spec'})) .on('error', function (err) { mochaErr = err; }) .pipe(istanbul.writeReports()) .on('end', function () { cb(mochaErr); }); }); gulp.task('watch', function () { gulp.watch(['generators/**/*.js', 'test/**'], ['test']); }); gulp.task('coveralls', ['test'], function () { if (!process.env.CI) { return; } return gulp.src(path.join(__dirname, 'coverage/lcov.info')) .pipe(coveralls()); }); gulp.task('prepublish', ['nsp']); gulp.task('default', ['static', 'test', 'coveralls']);
anasbihi/generator-ionic-app
gulpfile.js
JavaScript
mit
1,556
/** *@author Raul Benitez *@email raulbeni@gmail.com * * Super Class of object model */ function NetworkHardware (){ var thiz = this; var _connections_objects_list = {}; var _connections_objects_length = 0; var _packagesAddedForSource = {}; var _packageAddedForDestination = {}; var _packageIds = ""; var _attr_tooltip = []; DiagramObject.call(this); /* getters and setters */ this.getConnectionList = function () { return _controllerConnections.getConnectionsCollectionByObj(this.getIndex()); }; this.setConnectionLimit = function (connections_limit){ this.setAttrParam('connections_limit', connections_limit); }; this.getConnectionsLimit = function () { return this.getAttrParam('connections_limit'); }; this.getAttrTooltip = function () { var attr = {}; for(var i = 0; i < _attr_tooltip.length; i++){ var key = _attr_tooltip[i]; attr[key]= thiz.getAttrParam(key); } return attr; }; this.setAttrTooltip = function (attr_tooltip) { _attr_tooltip = attr_tooltip; }; /* METHODS UTILS*/ this.addAttrTooltip = function (key){ _attr_tooltip.push(key); } this.createConnectionFromMenuContext = function (){ var firewall = _controllerNetwork.getFirewallAdded(); if (firewall != null ){ firewall.showEthPositions() } var connectionPoint = []; var svg = $('.main-plain'); var elem_to_connect = $('.'+FOR_CONNECTING_CLASS); var r = thiz.getRaphael(); // var controlFactory; svg.css('cursor','pointer'); elem_to_connect.css('cursor','crosshair'); var x = thiz.getPosX(); var y = thiz.getPosY(); var path = [["M", x, y], ["L", x, y]]; var elem = thiz.getShape().node; // controlFactory = r.path(path).attr({stroke: "", "stroke-dasharray": ""}); elem.classList.add("point-adding"); connectionPoint.push(elem); svg.mousemove(function (ev) { var left = ev.pageX - DELTA_LEFT; var top = ev.pageY; path[1][1] = left; path[1][2] = top; // controlFactory.attr({path: path}); }); elem_to_connect.on('click',function(){ var elem2 = this; var isAdding = elem2.classList.contains('point-adding'); if(!isAdding){ svg.off('mousemove'); var pointB = elem2; var pointA = elem; pointA.classList.remove('point-adding'); // controlFactory.remove(); _controllerNetwork.createGraphicConnections(pointA, pointB); svg.css('cursor','cell'); elem_to_connect.css('cursor','cell').off('click'); elem_to_connect.css('cursor', 'move'); if (firewall != null ){ firewall.hideEthPositions() } } }); svg.bind("contextmenu",function(e) { e.preventDefault(); svg.css('cursor','cell'); elem_to_connect.css('cursor','cell').off('click'); elem_to_connect.css('cursor', 'move'); svg.off(); if (firewall != null ){ firewall.hideEthPositions() } }); } /* ========================== CONNECTIONS METHODS ====================================*/ this.existConnectionWithObj = function(obj){ return _controllerConnections.checkExistConnection(this.getIndex(), obj.getIndex()); }; this.getConnectionsSize = function (){ return this.getConnectionList().length; }; this.deleteConnections = function () { _controllerConnections.removeAllConnectionOf(this.getIndex()); }; this.checkConnection = function(netObject){ if(netObject instanceof NetworkHardware){ var length1 = this.getConnectionsSize(); var length2 = netObject.getConnectionsSize(); if(this.existConnectionWithObj(netObject) == true){ return false; }else if(this.getConnectionsLimit() > length1 && netObject.getConnectionsLimit() > length2){ return true; }else{ /* add a logger*/ console.log('This length = ' + length1 + ' and this limit is ' + this.getConnectionsLimit() ); console.log('netObject length = ' + length2 + ' and netObject limit is ' + netObject.getConnectionsLimit() ); return false; } }else { return false; } }; /* =========================== ADD PACKAGES ========================= */ this.addPackageToHashDestination = function (index, elem){ _packageAddedForDestination[index] = elem; } this.addPackageIds = function (index){ _packageIds += '#'+index+', '; } this.addPackageToHashSource = function (index, elem){ _packagesAddedForSource[index] = elem; } this.getPackagesListForDestination = function () { return _packageAddedForDestination; } this.getPackagesList = function () { return _packagesAddedForSource; } this.updatePackagesPosition = function (x,y) { for(var key in _packagesAddedForSource){ var package = _packagesAddedForSource[key]; var x = parseFloat(x+ 20); var y = parseFloat(y - 15); var att = {x: x , y: y }; package.getShape().attr(att); package.setPositions(x,y); package.updateNumberPosition(x,y) } } /* ========================== TOOLTIPS METHODS ====================================*/ this.destroyTooltip = function () { var shape = thiz.getShape(); $(shape.node).diagramTooltip({destroy: true}); } this.addTooltipEvent = function (update) { var shape = thiz.getShape(); var index = thiz.getIndex(); $(shape.node).diagramTooltip({ posX: thiz.getPosX(), posY: thiz.getPosY(), index: index, attrs: thiz.getAttrTooltip(), update: update }); }; }; NetworkHardware.prototype = new DiagramObject(); /*re implement methods*/ NetworkHardware.prototype.init = function (raphael, type, attr_params, klass) { klass += ' '+ FOR_CONNECTING_CLASS; var index = DiagramObject.prototype.init.call(this, raphael, type, attr_params, klass); var thiz = this; this.addItemForContextMenu({label: i8n_label('com.menucontext.create_connection'), icon:'/assets/context-menu-icons/network-ip-local.png', action: function() { $('.contextMenuPlugin').remove(); thiz.createConnectionFromMenuContext(); } }); this.addItemForContextMenu({label: i8n_label('com.menucontext.delete_connections'), icon:'/assets/context-menu-icons/cross-button.png', action: function() { $('.contextMenuPlugin').remove(); thiz.deleteConnections(); } }); this.setConnectionLimit(attr_params['connections_limit']); this.addTooltipEvent(false); return index; }; NetworkHardware.prototype.afterSubmitModalEvent = function (obj){ DiagramObject.prototype.afterSubmitModalEvent.call(this,obj); /*update tooltip*/ this.addTooltipEvent(true); /*update data on package sources*/ var packages = this.getPackagesList(); for(var k in packages){ var pack = packages[k]; pack.setSource(this); } /* update data package for destination*/ var packages_destination = this.getPackagesListForDestination(); for(var k in packages_destination){ var pack = packages_destination[k]; pack.setDestination(this); } }; NetworkHardware.prototype.afterRemoveEvent = function () { DiagramObject.prototype.afterRemoveEvent.call(this); }; NetworkHardware.prototype.afterMoveEvent = function (x, y, index) { DiagramObject.prototype.afterMoveEvent.call(this,x, y, index); //update tooltip this.addTooltipEvent(true); //update connection wire var r = this.getRaphael(); var connections_shapes = _controllerConnections.getConnectionsShapesCollectionByObj(this.getIndex()); for (var i = connections_shapes.length; i--;) { r.connection(connections_shapes[i]); } //update package position this.updatePackagesPosition(x,y); }; NetworkHardware.prototype.remove = function () { this.deleteConnections(); this.destroyTooltip(); var listPackages = this.getPackagesList(); for(var l in listPackages){ var p = listPackages[l]; _controllerNetwork.remove(p.getIndex()); } DiagramObject.prototype.remove.call(this); delete this; }; /* new methods to be overridden by the children of this class */ NetworkHardware.prototype.createConnection = function(objB){ var objA = this; var ready; if(objA === null || objB === null) return false; if(objA.checkConnection(objB)){ ready = _controllerConnections.addConnection(objA, objB); if(ready === true){ objA.afterCreateConnection(objB); objB.afterCreateConnection(objA); } return ready; } return false; }; NetworkHardware.prototype.addPackageForDestination = function (elem) { elem.setDestination(this); var index = elem.getIndex(); this.addPackageToHashDestination(index, elem); }; NetworkHardware.prototype.getIP = function () { console.log('getIP() not implemented') return null; }; NetworkHardware.prototype.setIp = function(ip){ console.log('setIP() not implemented') } NetworkHardware.prototype.afterCreateConnection = function (obj_relation ){ }; NetworkHardware.prototype.getMaskIp = function (){ console.log('getMaskIp() not implemented'); return null; }; NetworkHardware.prototype.setMaskIp = function (mask_ip){ console.log('setMaskIp() not implemented'); }; NetworkHardware.prototype.addPackageForOrigin = function (elem) { elem.setSource(this); var index = elem.getIndex(); this.addPackageToHashSource(index,elem); this.addPackageIds (index); };
HoneyJack/FirewallTool
app/assets/javascripts/object_model/network_hardware.js
JavaScript
mit
10,183
import { helper } from '@ember/component/helper'; export function pageState(params) { let page = params[0]; if(page.isPending){ return 'pending'; } else if(page.isResolved){ return 'resolved'; } else if(page.isRejected){ return 'rejected'; } else { return 'unrequested'; } } export default helper(pageState);
thefrontside/ember-impagination
tests/dummy/app/helpers/page-state.js
JavaScript
mit
339
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import path from 'path'; import gaze from 'gaze'; import replace from 'replace'; import Promise from 'bluebird'; /** * Copies static files such as robots.txt, favicon.ico to the * output (build) folder. */ async function copy({ watch } = {}) { const ncp = Promise.promisify(require('ncp')); await Promise.all([ ncp(path.join(global.cwd,'src/assets/'), path.join(global.cwd,'build/assets/')), // ncp('src/content', 'build/content'), ncp(path.join(global.cwd,'package.json'), path.join(global.cwd,'build/package.json')), ]); replace({ regex: '"start".*', replacement: '"start": "node server.js"', paths: [path.join(global.cwd,'build/package.json')], recursive: false, silent: false, }); if (watch) { const watcher = await new Promise((resolve, reject) => { gaze(path.join(global.cwd,'src/assets/**/*.*'), (err, val) => err ? reject(err) : resolve(val)); }); watcher.on('changed', async (file) => { const relPath = file.substr(path.join(global.cwd, 'src/assets/').length); await ncp(path.join(global.cwd,`src/assets/${relPath}`), path.join(global.cwd,`build/assets/${relPath}`)); }); } } export default copy;
GENGSHUANGs/hipack
tools/copy.js
JavaScript
mit
1,417
var picpik = picpik || {}; (function () { picpik.PicsRouter = Backbone.Router.extend({ routes: { '*filter': 'setFilter' }, setFilter: function (param) { picpik.picFilter = param || ''; picpik.picSet.trigger('filter'); } }); picpik.router = new picpik.PicsRouter(); Backbone.history.start(); })();
lrsjohnson/picpik
demos/backbone-structure/js/routers/router.js
JavaScript
mit
409
version https://git-lfs.github.com/spec/v1 oid sha256:09cc8f48e1dc032ae001acbba51a52f2e352ff2832758ec0323925a18697db42 size 293607
yogeshsaroya/new-cdnjs
ajax/libs/codemirror/4.0.3/codemirror.js
JavaScript
mit
131
const mongoose = require('mongoose'); const configuration = require('../server/configuration'); const Hero = require('../server/models/hero'); const source = require('../client/assets/heroes.json'); mongoose.Promise = global.Promise; mongoose.connect(configuration.mongo.uri, configuration.mongo.options); process.on('SIGTERM', () => mongoose.connection.close(() => process.exit(0))); Hero .insertMany(source) .then(docs => { console.log(`Successfully imported ${docs.length} heroes.`); mongoose.disconnect(); }) .catch(error => { console.error('An error has occured', error); mongoose.disconnect(); });
fvilers/angular2-training
tools/import.js
JavaScript
mit
632
module.exports = function (grunt, options) { return { options: { csslintrc: '.csslintrc' }, strict: { src: ['src/public/**/*.css'] } }; };
firsara/dommy
grunt/csslint.js
JavaScript
mit
170
/*! vim:set ts=2 sw=2 sts=2 expandtab */ /*! This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, curly:true, browser:true, white:true, moz:true, esnext:false, indent:2, maxerr:50, devel:true, node:true, boss:true, globalstrict:true, nomen:false, newcap:false */ "use strict"; /** * Example Usage for module: * * Usage: * ``` * Micropilot('mystudy').start().record({'a':1}).then(function(mtp){ * mtp.upload(UPLOAD_URL + mtp.studyid); * }) * ``` * * record `{a:1, ts: Date.now()}`. Then upload. * ``` * require('micropilot').Micropilot('simplestudyid').start(). * record({a:1,ts: Date.now()}).then(function(m) m.ezupload()) * // which actually uploads! * ``` * * For 1 day, record any data notified on `Observer` topics `['topic1', 'topic2']` * then upload to `<url>`, after that 24 hour `Fuse` completes. * ``` * require('micropilot').Micropilot('otherstudyid').start().watch(['topic1','topic2']). * lifetime(24 * 60 * 60 * 1000).then( * function(mtp){ mtp.upload(url); mtp.stop() }) * ``` * * How a more realistic study might look. * ``` * let monitor_tabopen = require('micropilot').Micropilot('tapopenstudy'); * var tabs = require('tabs'); * tabs.on('ready', function () { * monitor_tabopen.record({'msg:' 'tab ready', 'ts': Date.now()}) * }); * * monitor_tabopen.lifetime(86400*1000).then(function(mon){mon.ezupload()}); * // Fuse: 24 hours-ish after first start, upload * * if (user_tells_us_to_stop_snooping){ * monitor_tabopen.stop(); * } * ``` * * @module main * */ /**! Metadata about this module. */ exports.metadata = { "stability": "experimental", "engines": { "Firefox": "17", "Fennec": "17" } }; const { Cc, Ci, Cu } = require('chrome'); const xulApp = require('sdk/system/xul-app'); const { Class } = require('sdk/core/heritage'); const { Collection } = require('sdk/util/collection'); const { defer, promised, resolve } = require('sdk/core/promise'); var { indexedDB } = require('sdk/indexed-db'); exports.indexedDB = indexedDB; const observer = require('sdk/system/events'); const myprefs = require('sdk/simple-prefs').prefs; const Request = require('sdk/request').Request; const {storage} = require('sdk/simple-storage'); const timers = require('sdk/timers'); const uuid = require('sdk/util/uuid').uuid; // handle misnaming bug in idb code; let moreindexeddb = {}; Cc["@mozilla.org/dom/indexeddb/manager;1"] .getService(Ci.nsIIndexedDatabaseManager) .initWindowless(moreindexeddb); /** Random UUID as string, without braces. * * @return {string} random uuid without braces * * @memberOf main * @name uu */ let uu = exports.uu = function () { return uuid().number.slice(1, -1); }; /** Object with "passing" HTTP status codes. * * @memberOf main * @name GOODSTATUS */ const GOODSTATUS = exports.GOODSTATUS = { //"O": 0, "200": 200, "201": 201, "202": 202, "203": 203, "204": 204 }; /** Upload url * * @memberOf main * @name UPLOAD_URL */ let UPLOAD_URL = exports.UPLOAD_URL = "https://testpilot.mozillalabs.com/submit/testpilot_micropilot_"; /**!*/ // Warning: micropilot steals the simple store 'micropilot' key by name if (storage.micropilot === undefined) { storage.micropilot = {}; } /** common generic function to handle request errors * * Console errors the error code. * * @memberOf main * @name requestError */ let requestError = function (evt) console.error("ERROR", evt.target.errorCode); let requestBlocked = function (evt) console.log("BLOCKED", evt); /** log IFF `prefs.micropilot` is set. * * @return undefined * @name microlog */ myprefs.micropilotlog = true; let microlog = exports.microlog = function () { if (myprefs.micropilotlog) { console.log.apply(console, arguments); } }; /** * EventStore Constructor (Heritage) * @module EventStore */ let EventStore = exports.EventStore = Class({ /** Create an event store. * * @param {string} collection used in db and objectStore names. * @param {string} key autoincrement key, (default: "eventstoreid") * * @return EventStore instance * @memberOf EventStore * @name initialize */ initialize: function (collection, keyname) { this.collection = collection; this.keyname = keyname || "eventstoreid"; }, type: "EventStore", /** promise a indexedDB connection to `"micropilot-"+this.collection`. * * If first connection to db, creates object store: * * `createObjectStore(that.collection,{keyPath: that.keyname, autoIncrement: true }` * * Resolves on success with (`request.result`) * * @memberOf EventStore * @name db * @return promise */ db: function () { let that = this; let {promise, resolve} = defer(); // TODO each EventStore has different Db, so the createObjectStore will work. Is this gross? let req = indexedDB.open("micropilot-" + that.collection, 1); req.onerror = requestError; req.onupgradeneeded = function (/*event*/) { /*let objectStore = */ req.result.createObjectStore(that.collection, {keyPath: that.keyname, autoIncrement: true }); microlog("micropilot-object-store-made:", that.collection); }; // called after onupgradeneeded req.onsuccess = function (/*event*/) { resolve(req.result); }; req.onblocked = requestBlocked; return promise; }, /** promises to add data to the autoincrementing objectStore. * * Resolves on success with (`{id: newkey, data:data}`) * * @param {object} data jsonable data * * @memberOf EventStore * @name add * @return promise */ add: function (data) { let that = this; let {promise, resolve} = defer(); this.db().then(function (db) { let req = db.transaction([that.collection], "readwrite") .objectStore(that.collection).add(data); req.onsuccess = function (evt) { let newkey = evt.target.result; resolve({id: newkey, data: data}); }; req.onerror = requestError; req.onblocked = requestBlocked; }); return promise; }, /** promise all data from the collection (async). * * Resolves on success (`data`). * * *Note*: non-blocking, only guarantees complete list of data if all * writes have finished. * * @memberOf EventStor * @name getAll * @return promise */ getAll: function () { // using getAll() doesn't seem to work, and isn't cross-platform let {promise, resolve} = defer(); let that = this; this.db().then(function (db) { let data = []; let req = db.transaction([that.collection], "readonly").objectStore(that.collection).openCursor(); req.onsuccess = function (event) { let cursor = event.target.result; if (cursor) { data.push(cursor.value); cursor.continue(); } else { resolve(data); } }; req.onerror = requestError; req.onblocked = requestBlocked; }); return promise; }, /** promise to drop the database. * * Resolves onsuccess (`request.result`) * @memberOf EventStore * @name drop * @return promise */ drop: function () { let that = this; let {promise, resolve} = defer(); let req = indexedDB.deleteDatabase("micropilot-" + that.collection, 1); req.onsuccess = function (/*event*/) { resolve(req.result); }; req.onerror = requestError; req.onblocked = requestBlocked; return promise; }, /** promises to clear the database for re-use. * * Resolves onsuccess (`request.result`) * @memberOf EventStore * @name clear * @return promise */ clear: function () { let that = this; let { promise, resolve } = defer(); this.db().then(function (db) { let req = db.transaction([that.collection], "readwrite").objectStore(that.collection).clear(); req.onsuccess = function (/*event*/) { resolve(req.result); }; req.onerror = requestError; req.onblocked = requestBlocked; }); return promise; } }); /** gather general user data, including addons, os, etc. * * Properties: appname, location, fxVersion, os, updateChannel, addons list * @return promise promise of userdata * @name snoop * @memberOf main */ let snoop = exports.snoop = function () { let { promise, resolve } = defer(); let LOCALE_PREF = "general.useragent.locale"; let UPDATE_CHANNEL_PREF = "app.update.channel"; let xa = require('sdk/system/xul-app'); let prefs = require('sdk/preferences/service'); let u = {}; u.appname = xa.name; u.location = prefs.get(LOCALE_PREF); u.fxVersion = xa.version; u.os = require('sdk/system/runtime').os; u.updateChannel = prefs.get(UPDATE_CHANNEL_PREF); let { AddonManager } = Cu.import("resource://gre/modules/AddonManager.jsm"); u.addons = []; AddonManager.getAllAddons(function (addonList) { Array.forEach(addonList, function (a) { let o = {}; ['id', 'name', 'appDisabled', 'isActive', 'type', 'userDisabled'].forEach(function (k) { o[k] = a[k]; }); u.addons.push(o); }); resolve(u); }); return promise; }; /** Fuse Heritage Class * * @module Fuse */ let Fuse = exports.Fuse = Class({ /** * Fuses trigger (resolve their promise) no sooner than `duration + start` * * (like a dynamite fuse) * * Options: * * - `start`: start time for the fuse * - `duration`: how long to run. * - `pulseinterval`: if defined, use a `setInterval` timer (see below) * - `resolve_this`: the `this` passed into the `then` during resolution (default undefined) * - `pulsefn`: if `setInterval` timer, run this function during every `pulse` * * `setInterval` vs. `setTimeout`: Fuse is normally a `setTimeout`. If you * want finer control over it (including being able to modify the timers of * running Fuses), use `pulseInterval` to make a `setInterval` timer. * * Note 1: "Short Fuses": When the `duration` is very short, we don't guaranteed * millisecond accuracy! * * Note 2: Restart. If a Fuse 'should fire' while Firefox is not running, * it will fire the next time it can. * * Note 3: Blast from the Past. Fuses fire IFF * * ``` * Date.now() >= (that.start + that.duration) * ``` * * Note 4: Persist a fuse over restarts. * * ``` * let {storage} = require('sdk/simple-storage'); * if (! storage.firststart) ss.firststart = Date.now(); // tied to addon * Fuse({start: storeage.firststart,duration:86400 * 7 * 1000 }).then( * function(){ Micropilot('delayedstudy').start()} ) * ``` * * @memberOf Fuse * @param {Object} options * @returns Fuse instance * @name initialize */ initialize: function (options) { let {start,duration,pulseinterval,resolve_this,pulsefn} = options; this.pulseinterval = pulseinterval; let that = this; this.start = start; this.duration = duration; let { promise, resolve } = defer(); this.promise = promise; this.resolve = resolve; // should this be setInterval, or setTimeout? // setInterval allows one to modify the fuse while running // more easily, but setTimeout is much more precise. if (pulseinterval) { this.timerid = timers.setInterval(function () { if (that.checking) { return; // prevent races } that.checking = true; if (pulsefn) {pulsefn(that); } if (! duration) {return; } if (Date.now() >= (that.start + that.duration)) { that.resolve(resolve_this); that.stop(); } that.checking = false; }, pulseinterval); } else { // TODO, what is setTimeout on a negative? that.checking = false; let timerunningsofar = (Date.now() - this.start); if (duration <= timerunningsofar) { // really short intervals that.resolve(resolve_this); this.stop(); } else { this.timerid = timers.setTimeout(function () { that.resolve(resolve_this); that.stop(); }, duration - timerunningsofar); } } }, /** promise the promise. Resolves with `resolve_this` * * @memberOf Fuse * @name then * @return promise */ get then() this.promise.then, type: 'Fuse', /** stop the fuse (clear the timeout). * * @return {fuse} this * @memberOf Fuse * @name stop */ stop: function () { if (this.timerid) { timers.clearTimeout(this.timerid); } return this; } }); /** Self-destruct (uninstall) this addon * * @param {string} id addon id * @return promise (sdk/adddon/installer).uninstall * @memberOf main * @name killaddon */ let killaddon = exports.killaddon = function (id) { id = id === undefined ? require('sdk/self').id : id; microlog("attempting to remove addon:", id); return require('sdk/addon/installer').uninstall(id); }; /** * Micropilot Heritage Object * * Persists over multiple runs. * (Persistence achieved using `simple-store`, which ties a Micropilot into * a particular addon) * * @param {string} studyid unique key to id the study (used by dbs, prefs) * @module Micropilot * * @returns Micropilot instance */ let Micropilot = Class({ /** Initialize the Micropilot * * internals: * * * `_watched`: observed topics * * `eventstore`: an EventStore * * `_config`: simple-store configuration * * `personid`: a `uu()` (set this if you want.) * * `_startdate`: now, or then (if revived) * * `willrecord`: a brake on event recording * * @memberOf Micropilot * @name initialize * @param {String} studyid Id for persistent store, db. */ initialize: function (studyid) { // setup the indexdb this.studyid = studyid; this._watched = {}; this.eventstore = EventStore(this.studyid); if (storage.micropilot[studyid] === undefined) { storage.micropilot[studyid] = { personid: uu(), startdate: Date.now() // start now }; } this._config = storage.micropilot[studyid]; // persists this._startdate = this._config.startdate; this.willrecord = false; // won't record. }, type: 'Micropilot', /** get and set the startDate * * @memberOf Micropilot * @name startdate */ get startdate() this._startdate, // resetting the startdate kills existing lifetime / fuse set startdate(ts) { this.stop(); this._startdate = this._config.startdate = ts; }, /** promise of all recorded event data * * Resolve (`data`) * @memberOf Micropilot * @name data * @return promise */ data: function () this.eventstore.getAll(), /** promise to drop all data (by dropping the db) * * Resolve(`request.response`) // of the dropDatabse * @memberOf Micropilot * @name drop * @return promise */ drop: function () this.eventstore.drop(), /** promise to clear all data but keep the db * * Resolve(`request.response`) // of the clear * @memberOf Micropilot * @name clear * @return promise */ clear: function () this.eventstore.clear(), /** promise of `EventStore.add`, which is {id:<>,data:<>} * unless record "doesn't happen" because of non-running * * @memberOf Micropilot * @name record * @return promise */ record: function (data) { // remember, `resolve` turns values into promises, and is noop on promises if (! this.willrecord) { return resolve(undefined); } // todo, what if it's not jsonable? JSON.stringify(data); microlog("micropilot-record:", JSON.stringify(data)); return this.eventstore.add(data); }, /** promise the study (setting a Fuse) * * * Fuse set as {start: this.startdate,duration:duration} * (modify startdate to 'run from some other time') * * False or Undefined duration subls forever / never resolves * * Note: calls `stop()` and `start()` as side-effects * * Resolves when the study fuse resolves. * * example: * * `Micropilot('mystudy').lifetime(1000).then(function(mtp){mtp.stop()})` * * @param {integer} duration milliseconds to run Fuse * @memberOf Micropilot * @name lifetime * @return promise * */ lifetime: function (duration) { this.stop(); this.willrecord = true; // restart! let deferred = defer(); let that = this; this.start(); // iff! if (duration) { // should this allow / mix all fuse options? this.fuse = Fuse({start: this.startdate, duration: duration, resolve_this: that}); return this.fuse; } else { // no duration, so infinite, so nothing to resolve. return deferred.promise; } }, /** allow record (`this.willrecord` -> `true`) * * @return {micropilot} this * @memberOf Micropilot * @name start */ start: function () { this.willrecord = true; return this; }, /** stop the study (unset the fuse, `this.willrecord` -> `false`) * * (after stopping, `record` will not work, unless one `start()` or * or `willrecord` -> `true`) * * @return {micropilot} this * @memberOf Micropilot * @name stop */ stop: function () { this.willrecord = false; if (this.fuse !== undefined) { this.fuse.stop(); } delete this.fuse; return this; }, /** (internal) watch a topic, add to `observer-service`, parse json if possible * * @param {string} topic topic to watch. * @memberOf Micropilot * @name _watch * @return undefined */ _watch: function (topic) { if (this._watched[topic]) { return; } let that = this; let cb; if (this._watchfn !== undefined) { cb = function (evt) that._watchfn.call(that, evt); } else { let objstring = ({}).toString(); cb = function (evt) { // json if possible https://github.com/gregglind/micropilot/issues/21 let obj = {"msg": evt.type, ts: Date.now()}; ["subject", "data"].forEach(function (k) { obj[k] = evt[k]; try { obj[k] = JSON.parse(obj[k]); } catch (e) {} // obj[k] == objstring # true by type casting! WUT? if (typeof obj[k] === "string" && obj[k] === objstring) { throw Array.join(["Micropilot Serialization Error:", evt.type, k, "serialized as Object.toString() rather than JSON"], " "); } }); that.record(obj); }; } /*let o = */ observer.on(topic, cb); // add to global watch list this._watched[topic] = cb; }, /** add topics to watch (non-destructive) * * `watch` is a simplified wrapper around `record` with these features * * - watch the observer service * - record messages as * * - `msg`: topic * - `ts`: Date.now() * - `subject`: JSON.parse(subject) or subject * - `data`: JSON.parse(data) or data * * @param {array} watch_list list of topics * @return {micropilot} this * @memberOf Micropilot * @name watch */ watch: function (watch_list) { let that = this; watch_list.forEach(function (t) that._watch(t)); return this; }, /** (internal) stop watching topic * @memberOf Micropilot * @name _unwatch * @return undefined */ _unwatch: function (topic) { let cb = this._watched[topic]; if (cb) { observer.off(topic, cb); } delete this._watched[topic]; }, /** unwatch some topics (destructive) * if `unwatch_list` is undefined, unwatch all. * * @param {array} unwatch_list list of topics to remove. If undefined, unwatch all. * @memberOf Micropilot * @name unwatch * @return {micropilot} this */ unwatch: function (unwatch_list) { if (unwatch_list === undefined) { unwatch_list = Object.keys(this._watched); } let that = this; unwatch_list.forEach(function (t) that._unwatch(t)); return this; }, /** promise simplified upload with strong opinions and retry semantics * * Options: * * - `url`: defaults to `UPLOAD_URL + mtp.studyname` * - `maxtries`: Number of tries. (`3`) * - `interval`: How long to wait between tries (60 min - `60*60*1000`) * - `killaddon`: Should the addon delete itself on completion? (`false`) * * *Note 1*: https://github.com/gregglind/micropilot/issues/2 * * *Note 2*: `_config.completed` will will go to `true` on success or not. * * *Note 3*: Adds some keys to `_config` persistence: * * - `completed` * - `uploadcounter` * * This is Subject To Change, and just a starting point for how to talk * about study state. * * @param {Object} options Upload options. * @memberOf Micropilot * @name ezupload * @return promise */ ezupload: function (options) { let {promise, resolve} = defer(); let {url, maxtries, interval, killaddon: killpref} = options; let that = this; url = url || (UPLOAD_URL + that.studyid); microlog("micropilot-ezupload:", url); maxtries = maxtries || 3; interval = interval || 60 * 60 * 1000; // 60 minutes let mycleanup = function () { that._config.completed = true; // whatever properties you want let p = that.stop(); p = that.clear(); if (killpref) { microlog("micropilot: killpref on!"); resolve(p.then(killaddon)); // stop the study, clear the data, uninstall the addon. } else { resolve(p); } }; if (this._config.uploadcounter === undefined) { this._config.uploadcounter = 0; } let myupload = function () { if (that._config.uploadcounter >= maxtries) { mycleanup(that); return; } // give up! that._config.uploadcounter += 1; that.upload(url, options).then(function (response) { let dump_response = function (response) { return JSON.stringify({status: response.status, text: response.text}); }; if (! GOODSTATUS[response.status]) { // try again in interval ms microlog("micropilot-ezupload-fail:", dump_response(response), "retrying in:", interval); require('sdk/timers').setTimeout(function () {myupload(); }, interval); } else { microlog("micropilot-ezupload-success:", dump_response(response)); mycleanup(); } }); }; myupload(); return promise; }, /** Fuse based recurrent upload * */ uploadrecur: function (interval, url) { var that = this; if (!storage.lastupload) { storage.lastupload = Date.now(); // tied to addon } Fuse({start: storage.lastupload, duration: interval}).then(function () { microlog("mircopilot-recur-upload: fuse wants to upload"); storage.lastupload = Date.now(); that.upload(url).then(function (response) { microlog("micropilot-upload-response", response.text); }); that.uploadrecur(interval, url); // call it again. }); }, /** promise to upload the data * * Options: * - `simulate`: don't post, promise the request * - `uploadid`: an id for the upload * * Resolves * - if POST, after oncomplete (response) * - if `options.simulate` (request) * * @param {string} url url to POST. * @param {object} options some options, below. * @memberOf Micropilot * @name upload * @return promise */ upload: function (url, options) { // get all... is this tangled between getting and posting? // attempt to post options = options === undefined ? {} : options; let that = this; let simulate = options.simulate; let { promise, resolve } = defer(); let uploadid = options.uploadid || uu(); // specific to the upload this.data().then(function (data) { microlog("micropilot-willupload-data:", JSON.stringify(data)); let payload = {events: data}; payload.ts = Date.now(); payload.uploadid = uploadid; payload.personid = that._config.personid; snoop().then(function (userdata) { payload.userdata = userdata; microlog("micropilot-willupload-content:", JSON.stringify(payload)); let R = Request({ url: url, headers: { }, content: JSON.stringify(payload), contentType: "application/json", onComplete: function (response) { microlog("micropilot-upload-response:", response.status); microlog("micropilot-upload-response:", response.text); resolve(response); }, }); if (simulate) { resolve(R); } else { R.post(); } }); }); return promise; } }); exports.Micropilot = Micropilot;
bwinton/generator-prototype
app/templates/micropilot.js
JavaScript
mit
25,256
'use strict' var is = global.is || require('exam/lib/is') var Cute = require('../require') describe('Cute', function () { describe('.stringify', function () { var stringify = Cute.stringify var jsonable = function () { return 1 } jsonable.toJSON = jsonable it('handles numbers', function () { var json = stringify(0) is(json, '0') var zero = new Number() // eslint-disable-line is(stringify(zero), '0') }) it('handles strings', function () { var empty = new String() // eslint-disable-line is(stringify(empty), '""') }) it('handles functions', function () { is(stringify(isNaN), undefined) }) it('uses toJSON methods', function () { is(stringify(jsonable), '1') is(stringify([jsonable]), '[1]') }) it('handles undefined alone and in an array', function () { is(stringify([undefined]), '[null]') is(stringify(undefined), undefined) }) it('handles arrays of many types', function () { is(stringify([undefined, isNaN, null]), '[null,null,null]') }) it('handles special characters', function () { is(stringify('\0\b\n\f\r\t'), '"\\u0000\\b\\n\\f\\r\\t"') }) it('handles complex objects', function () { is(stringify({A: [jsonable, true, false, null, '\0\b\n\f\r\t']}), '{"A":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}') }) it('handles complex objects', function () { is(stringify({A: [jsonable, true, false, null, '\0\b\n\f\r\t']}), '{"A":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}') }) it('handles dates', function () { is(stringify(new Date(-8.64e15)), '"-271821-04-20T00:00:00.000Z"') is(stringify(new Date(8.64e15)), '"+275760-09-13T00:00:00.000Z"') is(stringify(new Date(-1)), '"1969-12-31T23:59:59.999Z"') }) it('handles circular references', function () { var o = {} o.o = o is(stringify(o), '{"o":"[Circular 1]"}') }) }) describe('.attrify', function () { it('outputs a value for value attributes', function () { is(Cute.attrify({ok: true}), '{&quot;ok&quot;:true}') }) }) describe('.parse', function () { it('parses JSON', function () { is.same(Cute.parse('{"ok":true}'), {ok: true}) }) it('parses non-strict JSON', function () { is.same(Cute.parse('{ok:true}'), {ok: true}) }) it('returns an alternative value in case of error', function () { is(Cute.parse('{ok:', null), null) }) }) describe('.run', function () { it('runs JavaScript', function () { Cute.run('process.CUTE_RUN=1') is(process.CUTE_RUN, 1) }) }) }) /* // The milliseconds are optional in ES 5, but required in 5.1. JSON.stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative // four-digit years instead of six-digit years. Credits: @Yaffle. JSON.stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && // Safari <= 5.1.7 and Opera >= 10.53 incorrectly serialize millisecond // values less than 1000. Credits: @Yaffle. JSON.stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; */
lighterio/cute
test/json-test.js
JavaScript
mit
3,222
var transform = require('../src/naked-objects'); var fs = require('fs'); var path = require('path'); gt.module('<> replacement'); gt.test('basics', function () { gt.func(transform, 'is a function'); gt.string(transform('something'), 'returns a string'); }); gt.test('<> -> Object.create(null)', function () { var replaced = transform('<>'); gt.equal(replaced, 'Object.create(null)'); }); gt.test('var foo <>; -> ?', function () { var replaced = transform('var foo = <>;'); gt.equal(replaced, 'var foo = Object.create(null);'); });
bahmutov/bare-objects
test/test.js
JavaScript
mit
547
var images = jQuery('body').find('img').map(function(){ return this.src; }).get(); alert(images);
zawiw/zawiw-license
frontend/license_script.js
JavaScript
mit
101
import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles'; const PlaceHolder = (props) => { let s = styles(props); if (props.useLoremIpsum) { return ( <p style={{padding: '10%'}}> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi a augue ex. Donec tortor erat, placerat non dolor quis, porta vestibulum massa. Suspendisse potenti. Etiam bibendum vel magna ac molestie. In lacinia dui vitae sem suscipit, ut fermentum nulla scelerisque. In sollicitudin placerat purus sit amet porttitor. Aenean id quam augue. In maximus ultrices pretium. Aliquam erat volutpat. </p> ); } return ( <div style={ s.wrapper }> <div>{props.label}</div> </div> ); } PlaceHolder.propTypes = { wrapperStyle: PropTypes.object, label: PropTypes.string, useLoremIpsum: PropTypes.bool } PlaceHolder.defaultProps = { label: 'content placeholder', useLoremIpsum: false }; export default PlaceHolder;
line64/landricks-components
src/components/PlaceHolder/index.js
JavaScript
mit
987
var b = require('..'); describe("utils", function() { before(function() { b.utils.modelName = function(model) { return model._name; } }); describe("extractOptions()", function() { var extractOptions = b.utils.extractOptions; it("removes the specified options from an object that is a mix of options and other keys into a separate object", function() { var o = { a:1, b:2, c:3 }; expect( extractOptions(o, { a:2, b:3, d:4 }) ).to.deep.equal({ a:1, b:2, d:4 }); expect(o).to.deep.equal({ c:3 }); }); it("handles empty and invalid objects", function() { var d = {}; expect(extractOptions({}, d)).to.deep.equal(d); expect(extractOptions(null, d)).to.deep.equal(d); }); it("handles false and null values", function() { var o = { a:null, b:false, c:false }; expect( extractOptions(o, { a:1, b:2, d:4 }) ).to.deep.equal({ a:null, b:false, d:4 }); expect(o).to.deep.equal({ c:false }); }); }); describe("errorMessages", function() { var errorMessages = b.utils.errorMessages; it("returns an array of error messages from an an errors object for a specific field", function() { expect( errorMessages('field', { field: [ "error #1", "error #2" ] }) ).to.deep.equal([ "error #1", "error #2" ]); }); it("handles invalid errors", function() { expect(errorMessages('field')).not.to.be.ok; }); it("returns arrays even when the error is a single string", function() { expect( errorMessages('field', { field: "error #1" }) ).to.deep.equal([ "error #1" ]); }); }); describe("domId()", function() { var domId = b.utils.domId; it("generates a dom id for a model based on the pattern <spinal-cased model name>-<spinal-cased field name>-<spinal-cased value>", function() { expect( domId({ _name: 'ModelName'}, 'fieldName', 'can_haz value?') ).to.equal('model-name-field-name-can-haz-value'); }); it("supports skipping the value", function() { expect( domId({ _name: 'ModelName'}, 'fieldName') ).to.equal('model-name-field-name'); }); it("supports non-string values", function() { expect( domId({ _name: 'ModelName'}, 'fieldName', 1) ).to.equal('model-name-field-name-1'); expect( domId({ _name: 'ModelName'}, 'fieldName', true) ).to.equal('model-name-field-name-true'); expect( domId({ _name: 'ModelName'}, 'fieldName', undefined) ).to.equal('model-name-field-name'); expect( domId({ _name: 'ModelName'}, 'fieldName', false) ).to.equal('model-name-field-name-false'); }); }); describe("inputName()", function() { var inputName = b.utils.inputName; it("generates a querystring (qs) compatible name", function() { expect( inputName({ _name: 'ModelName' }, 'fieldName') ).to.equal('modelName[fieldName]'); }); }); });
ndreas/form-fields-builder
test/utils-test.js
JavaScript
mit
3,376
module.exports = function() { function foobar(x) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(x === void 0 || x === null) { throw new TypeError("'x' is not nullable"); } if(Number.isNaN(x)) { } } };
kaoscript/kaoscript
test/fixtures/compile/comparison/comparison.eq.nan.js
JavaScript
mit
292
'use strict'; var assert = require('assert'); var metadata = require('./helpers/metadata'); function set(name, fn) { assert(name, 'Task name must be specified'); assert(typeof name === 'string', 'Task name must be a string'); assert(typeof fn === 'function', 'Task function must be specified'); function taskWrapper() { return fn.apply(this, arguments); } taskWrapper.displayName = name; var meta = metadata.get(fn) || {}; var nodes = []; if (meta.branch) { nodes.push(meta.tree); } var task = this._registry.set(name, taskWrapper) || taskWrapper; metadata.set(task, { name: name, orig: fn, tree: { label: name, type: 'task', nodes: nodes, }, }); } module.exports = set;
kaguillera/newspipeline
node_modules/gulp/node_modules/undertaker/lib/set-task.js
JavaScript
mit
748
'use strict' exports.EVENT = { FAIL: 'fail', PASS: 'pass', TEST_START: 'test', TEST_END: 'test end', SUITE_START: 'suite', SUITE_END: 'suite end', HOOK_START: 'hook', HOOK_END: 'hook end', RUNNER_START: 'start', RUNNER_END: 'end' }
kt3k/kocha
packages/kocha/src/const.js
JavaScript
mit
253
// @flow import { compose } from 'redux'; import { connect } from 'react-redux'; import { push } from 'connected-react-router'; import { debounce } from 'lodash'; import prepare from 'app/utils/prepare'; import { autocomplete } from 'app/actions/SearchActions'; import { selectAutocompleteRedux as selectAutocomplete } from 'app/reducers/search'; import { markUsernamePresent, markUsernameConsent, } from 'app/actions/EventActions'; import Abacard from './components/EventAdministrate/Abacard'; import qs from 'qs'; import { getRegistrationGroups } from 'app/reducers/events'; const searchTypes = ['users.user']; const loadData = async (props, dispatch) => { const query = qs.parse(props.location.search, { ignoreQueryPrefix: true }).q; if (query && typeof query === 'string') { await dispatch(autocomplete(query, searchTypes)); } }; const mapStateToProps = (state, props) => { const query = qs.parse(props.location.search); const results = query ? selectAutocomplete(state) : []; const { eventId } = props; const { registered } = getRegistrationGroups(state, { eventId, }); return { location: props.location, searching: state.search.searching, results, registered, }; }; const mapDispatchToProps = (dispatch, { eventId }) => { const url = `/events/${eventId}/administrate/abacard?q=`; return { clearSearch: () => dispatch(push(url)), markUsernamePresent: (...props) => dispatch(markUsernamePresent(...props)), markUsernameConsent: (...props) => dispatch(markUsernameConsent(...props)), onQueryChanged: debounce((query) => { dispatch(push(url + query)); if (query) { dispatch(autocomplete(query, searchTypes)); } }, 100), }; }; export default compose( prepare(loadData), connect(mapStateToProps, mapDispatchToProps) )(Abacard);
webkom/lego-webapp
app/routes/events/EventAbacardRoute.js
JavaScript
mit
1,839
$.domReady(function() { function getFocus() { url = window.location.href; m = url.indexOf("key_pattern"); if (m !== -1) { focus = url.slice(url.indexOf("=", m)+1, url.indexOf("&", m)); } else { focus = false; } return focus; } function openNav(focus) { if (focus) { if (focus === '.') { items = ['.']; } else if (!focus.indexOf('.')) { items = ['ROOT',focus]; } else { items = focus.split(/\./); } namespace = []; while (it = items.shift()) { namespace.push(it); join = namespace.join('.'); it = $("#namespaces span[data-id='"+join+"']"); if (it.length > 0) { $(it.selector).siblings("ul").toggleClass("view"); } } } return; } var focus = getFocus(); openNav(focus); function filterThat(s,start) { if (start) { $("#key_type").val("starts_with"); } else { $("#key_type").val("contains"); } $("#key_pattern_value").val(s); document.forms['filter_form'].submit(); } $("#namespaces ul li").on("click", function(e) { e.preventDefault(); e.stopPropagation(); $(this).children("ul").toggleClass("view"); }); $("#namespaces ul li .display").on("click", function(e) { e.preventDefault(); e.stopPropagation(); filter = $(this).data("id"); filterThat(filter,true); }); $("#namespaces ul li.item").on("click", function(e) { e.preventDefault(); e.stopPropagation(); filter = $(this).data("id"); filterThat(filter,false); }); $(".delete").on("click", function(e) { e.preventDefault(); e.stopPropagation(); key = $(this).previous().text(); if (confirm("Are you sure you want to delete the key "+key+" from database ?")) { var newF = document.createElement("form"); newF.action = 'delete/'+key; newF.method = 'POST'; document.getElementsByTagName('body')[0].appendChild(newF); newF.submit(); } }); $(".multiline").on('click', function(e) { e.preventDefault(); input = $(this).next(); area = $.create('<textarea rows="4" id="'+input.attr("id")+'" name="'+input.attr('name')+'">'); area.text(input.val()); area.appendTo($(this).parent()); input.hide(); $(this).hide(); }); });
mose/rails-i18nterface
app/assets/javascripts/rails_i18nterface/base.js
JavaScript
mit
2,312
export default { 'en': { noResult: 'No result', pleaseInput: '{1} records, please input search criteria...' }, 'zh-CN': { noResult: '找不到结果', pleaseInput: '{1}条记录,请输入查询条件...' } };
webyom/yom-auto-complete
src/i18n.js
JavaScript
mit
224
'use strict'; var express = require('express'); var router = express.Router(); var credentials = require('../credentials'); var bucket = require('../utils/bucket'); function getLatestImage(callback) { bucket.getImagesWithinHour(function(imageNames) { imageNames.reverse(); var newest = imageNames.pop(); callback(newest); }); } /* GET home page. */ router.get('/', function(req, res) { getLatestImage(function(image) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ image : image, bucket : credentials.bucket })); }); }); module.exports = router;
jwdotjs/raspberry-pi-photo-gallery
api/stream.js
JavaScript
mit
625
define([ ], function () { "use strict"; return { screen: { fitsInto: function (mq) { return Modernizr.mq(mq); } }, isTouchable: function () { return Modernizr.touch; } }; });
arielschiavoni/wast
src/client/js/plugins/device.js
JavaScript
mit
232
$(document).ready(function(){$("#shop_bundle_filter_form").change(function(e){var p=$("#shop_bundle_filter_form").serializeArray(),u=$("#shop_bundle_product_path").val();$.ajax({url:u,type:"POST",cache:!1,data:p,success:function(e){$("#shop_bundle_products").empty(),$("#shop_bundle_products").append(e)}})});var e=$("#shop_bundle_product_path").val();$.ajax({url:e,type:"POST",cache:!1,data:null,success:function(e){$("#shop_bundle_products").empty(),$("#shop_bundle_products").append(e)}})});
seinyan/jwshop
web/assets/main/script/category.js
JavaScript
mit
494
angular.module("ImageRegionSelectionDemoControllers", []) .controller("DemoController", [ "$scope", function($scope){ $scope.data = { src: "src/img/sample.jpg", width: 512, height: 384, regions: [ { name: "Region 1", x: 200, y: 10, width: 100, height: 100, rotation: 0 }, { name: "Region 2", x: 30, y: 30, width: 50, height: 50, rotation: 45 } ] }; if ($scope.data.regions.length) { $scope.selectedRegion = $scope.data.regions[0]; } else { $scope.selectedRegion = null; } $scope.addRegion = function() { $scope.data.regions.push({ name: "New Region", x: 0, y: 0, width: 10, height: 10, rotation: 0 }); }; $scope.removeRegion = function() { $scope.data.regions.splice($scope.data.regions.indexOf($scope.selectedRegion), 1); $scope.selectedRegion = null; }; }]) .directive("regions", [ function(){ return { restrict: "E", replace: true, transclude: true, scope: { src: "=", width: "=", height: "=" }, templateUrl: "src/html/regions.html", link: function(scope, element, attrs) { element.css({ "background-image": "url(" + scope.src + ")", "background-size": "100% 100%", "background-repeat": "no-repeat", "position": "relative", "width": scope.width + "px", "height": scope.height + "px" }); } }; }]) .directive("region", [ function(){ return { replace: true, restrict: "E", templateUrl: "src/html/region.html", transclude: true, scope: { x: "=", y: "=", width: "=", height: "=", rotation: "=" }, link: function(scope, element, attrs) { var render = function() { element.css({ "position": "absolute", "top": scope.y + "px", "left": scope.x + "px", "transform": "rotate(" + scope.rotation + "deg)", "width": scope.width + "px", "height": scope.height + "px" }); }; scope.$watch("x", function(x){ scope.x = parseInt(x); render(); }); scope.$watch("y", function(y){ scope.y = parseInt(y); render(); }); scope.$watch("width", function(width){ scope.width = parseInt(width); render(); }); scope.$watch("height", function(height){ scope.height = parseInt(height); render(); }); scope.$watch("rotation", function(rotation){ scope.rotation = parseInt(rotation); render(); }); } }; }]); angular.module("ImageRegionSelectionDemo", [ "vr.directives.slider", "ImageRegionSelectionDemoControllers" ]);
seancoyne/ImageRegionSelection.js
src/js/demo.js
JavaScript
mit
2,677
var searchData= [ ['year',['Year',['../classapp_1_1Year_1_1Year.html',1,'app::Year']]] ];
SLongofono/448_Project1
app/documentation/html/search/classes_4.js
JavaScript
mit
92
'use strict'; module.exports = function(sequelize, DataTypes) { var Rating = sequelize.define('Rating', { rating: DataTypes.INTEGER }, { classMethods: { associate: function(models) { Rating.hasMany(models.UserRating, {as: 'UserRatings', foreignkey: 'fk_user_rating', targetKey: 'ratingId'}); Rating.hasMany(models.UserDanceSessionRating, {as: 'UserDanceSessionRatings', foreignkey: 'fk_session_rating', targetKey: 'ratingId'}); } } }); return Rating; };
JamieWohletz/groove-central
models/rating.js
JavaScript
mit
502
const express = require('express'); const router = express.Router(); const baseUrl = 'https://jodom.ngrok.io/'; const songUrl = 'https://upload.wikimedia.org/wikipedia/commons/transcoded/4/49/National_Anthem_of_Kenya.ogg/National_Anthem_of_Kenya.ogg.mp3'; let session = 'menu'; // voice route router.post('/', (req, res) => { const { isActive, callerNumber, dtmfDigits, recordingUrl } = req.body; let responseActions = ''; // Prep state let state = isActive === '1' ? session : ''; switch (state) { case 'menu': session = 'process'; responseActions = `<Say>Hello bot ${callerNumber ? callerNumber : 'There'}</Say> <GetDigits timeout="1" finishOnKey="#"> <Say>Press 1 to listen to some song. Press 2 to tell me your name. Press 3 to talk to a human. Press 4 to hangup and quit</Say> </GetDigits>`; break; case 'process': switch(dtmfDigits) { case '1': session = 'menu'; responseActions = `<Play url="${songUrl}"/> <Redirect>${baseUrl}voice</Redirect>`; break; case '2': session = 'name'; responseActions = `<Record finishOnKey="#" maxLength="30" trimSilence="true" playBeep="true"> <Say>Please say your full name after the beep</Say> </Record>`; break; case '3': session = undefined; responseActions = `<Say>We are getting our resident human on the line for you, please wait while enjoying this nice tune. You have 30 seconds to enjoy a conversation with them</Say> <Dial phoneNumbers="+254724821003" maxDuration="30" record="true" sequential="true"/>`; break; case '4': session = undefined; responseActions = `<Say>Bye Bye, Long Live Our Machine Overlords!</Say><Reject/>`; break; default: session = 'menu'; responseActions = `<Say> Invalid choice, try again and you will be exterminated!</Say> <Redirect>${baseUrl}voice</Redirect>`; } break; case 'name': session = 'menu'; responseActions = `<Say>Your human name is</Say> <Play url="${recordingUrl}"/> <Say>Now forget it. Your new name is bot ${callerNumber} </Say> <Redirect>${baseUrl}voice</Redirect>`; break; default: responseActions = `<Say>Well, this is unexpected! Bye Bye, Long Live Our Machine Overlords</Say><Reject/>`; } let response = `<?xml version="1.0" encoding="UTF-8"?><Response>${responseActions}</Response>`; res.send(response); }); module.exports = router;
AfricasTalkingLtd/africastalking-node.js
example/routes/voice.js
JavaScript
mit
3,007
var JsSearch; (function (JsSearch) { ; })(JsSearch || (JsSearch = {})); ; //# sourceMappingURL=tokenizer.js.map
cesarandreu/js-search
source/tokenizer/tokenizer.js
JavaScript
mit
115
/** * @file init.js * @brief Accession module init entry point * @author Frédéric SCHERMA (INRA UMR1095) * @date 2016-05-26 * @copyright Copyright (c) 2016 INRA/CIRAD * @license MIT (see LICENSE file) * @details */ let Backbone = require('backbone'); // style require('./css/accession.css'); let AccessionModule = function () { this.name = "accession"; }; AccessionModule.prototype = { initialize: function (app, options) { this.models = {}; this.collections = {}; this.views = {}; this.routers = {}; this.controllers = {}; try { window.i18next.default.addResources( window.session.language, 'default', require('./locale/' + window.session.language + '/default.json')); } catch (e) { console.warn("No translation found for the current language. Fallback to english language"); } // // register the layout type of descriptors // let layoutTypes = [ 'accession', 'batch' ]; for (let i = 0; i < layoutTypes.length; ++i) { let moduleName = layoutTypes[i].replace(/_/g, '').toLowerCase(); app.descriptor.layoutTypes.registerElement(layoutTypes[i], require('./layouttypes/' + moduleName)); } // // action format types // let ActionFormatTypeManager = require('./actionstep/actionstepformatmanager'); this.actions = new ActionFormatTypeManager(); // register the standard format type of descriptors let actions = [ 'accession_list', 'accession_refinement', 'accessionconsumer_batchproducer', 'accessionconsumer_batchproducer_it', 'batchconsumer_batchmodifier', 'batchconsumer_batchproducer', 'batch_weighting' ]; for (let i = 0; i < actions.length; ++i) { let moduleName = actions[i].replace(/_/g, '').toLowerCase(); this.actions.registerElement(actions[i], require('./actionstep/' + moduleName)); } // // cache // app.main.cache.register('accession'); // // main collections // let SelectOption = require('../main/renderers/selectoption'); // cached and countable collection let ActionTypeCollection = require('./collections/actiontype'); this.collections.actionTypes = new ActionTypeCollection([], {cacheable: true}); this.views.actionTypes = new SelectOption({ className: 'action-type', collection: this.collections.actionTypes }); // global collection, not cached, static by server this.collections.conditionList = new Backbone.Collection(); // global collection, not cached, static by server let ActionStepFormatCollection = require('./collections/actionstepformat'); this.collections.actionStepFormats = new ActionStepFormatCollection(); this.views.actionStepFormats = new SelectOption({ // sync: true, className: 'action-step-format', collection: this.collections.actionStepFormats, }); // // controllers // let AccessionController = require('./controllers/accession'); let BatchController = require('./controllers/batch'); let AccessionPanelController = require('./controllers/accessionpanel'); let BatchPanelController = require('./controllers/batchpanel'); let ActionTypeController = require('./controllers/actiontype'); let ActionController = require('./controllers/action'); let StorageLocationController = require('./controllers/storagelocation'); this.controllers.accession = new AccessionController(); this.controllers.batch = new BatchController(); this.controllers.accessionpanel = new AccessionPanelController(); this.controllers.batchpanel = new BatchPanelController(); this.controllers.actiontype = new ActionTypeController(); this.controllers.action = new ActionController(); this.controllers.storagelocation = new StorageLocationController(); // // routers // let AccessionRouter = require('./routers/accession'); this.routers.accession = new AccessionRouter(); let BatchRouter = require('./routers/batch'); this.routers.batch = new BatchRouter(); let AccessionPanelRouter = require('./routers/accessionpanel'); this.routers.accessionpanel = new AccessionPanelRouter(); let BatchPanelRouter = require('./routers/batchpanel'); this.routers.batchpanel = new BatchPanelRouter(); let ActionTypeRouter = require('./routers/actiontype'); this.routers.actiontype = new ActionTypeRouter(); let ActionRouter = require('./routers/action'); this.routers.action = new ActionRouter(); let StorageLocationRouter = require('./routers/storagelocation'); this.routers.storagelocation = new StorageLocationRouter(); }, start: function (app, options) { // nothing to do }, stop: function (app, options) { } }; module.exports = AccessionModule;
coll-gate/collgate
client/apps/accession/init.js
JavaScript
mit
5,311
// This file is generated. Do not edit! Edit gherkin-javascript.razor instead. var Errors = require('./errors'); module.exports = function Parser(astBuilder) { var RULE_TYPES = [ 'None', '_EOF', // #EOF '_Empty', // #Empty '_Comment', // #Comment '_TagLine', // #TagLine '_FeatureLine', // #FeatureLine '_BackgroundLine', // #BackgroundLine '_ScenarioLine', // #ScenarioLine '_ScenarioOutlineLine', // #ScenarioOutlineLine '_ExamplesLine', // #ExamplesLine '_StepLine', // #StepLine '_DocStringSeparator', // #DocStringSeparator '_TableRow', // #TableRow '_Language', // #Language '_Other', // #Other 'Feature', // Feature! := Feature_Header Background? Scenario_Definition* 'Feature_Header', // Feature_Header! := #Language? Tags? #FeatureLine Feature_Description 'Background', // Background! := #BackgroundLine Background_Description Scenario_Step* 'Scenario_Definition', // Scenario_Definition! := Tags? (Scenario | ScenarioOutline) 'Scenario', // Scenario! := #ScenarioLine Scenario_Description Scenario_Step* 'ScenarioOutline', // ScenarioOutline! := #ScenarioOutlineLine ScenarioOutline_Description ScenarioOutline_Step* Examples_Definition+ 'Examples_Definition', // Examples_Definition! [#Empty|#Comment|#TagLine-&gt;#ExamplesLine] := Tags? Examples 'Examples', // Examples! := #ExamplesLine Examples_Description #TableRow #TableRow+ 'Scenario_Step', // Scenario_Step := Step 'ScenarioOutline_Step', // ScenarioOutline_Step := Step 'Step', // Step! := #StepLine Step_Arg? 'Step_Arg', // Step_Arg := (DataTable | DocString) 'DataTable', // DataTable! := #TableRow+ 'DocString', // DocString! := #DocStringSeparator #Other* #DocStringSeparator 'Tags', // Tags! := #TagLine+ 'Feature_Description', // Feature_Description := Description_Helper 'Background_Description', // Background_Description := Description_Helper 'Scenario_Description', // Scenario_Description := Description_Helper 'ScenarioOutline_Description', // ScenarioOutline_Description := Description_Helper 'Examples_Description', // Examples_Description := Description_Helper 'Description_Helper', // Description_Helper := #Empty* Description? #Comment* 'Description', // Description! := #Other+ ] var astBuilder = astBuilder; var context = {}; this.parse = function(tokenScanner, tokenMatcher) { astBuilder.reset(); tokenMatcher.reset(); context.tokenScanner = tokenScanner; context.tokenMatcher = tokenMatcher; context.tokenQueue = []; context.errors = []; startRule(context, 'Feature'); var state = 0; var token = null; while(true) { token = readToken(context); state = matchToken(state, token, context); if(token.isEof) break; } endRule(context, 'Feature'); if(context.errors.length > 0) { throw Errors.CompositeParserException.create(context.errors); } return getResult(); }; function addError(context, error) { context.errors.push(error); if (context.errors.length > 10) throw Errors.CompositeParserException.create(context.errors); } function startRule(context, ruleType) { handleAstError(context, function () { astBuilder.startRule(ruleType); }); } function endRule(context, ruleType) { handleAstError(context, function () { astBuilder.endRule(ruleType); }); } function build(context, token) { handleAstError(context, function () { astBuilder.build(token); }); } function getResult() { return astBuilder.getResult(); } function handleAstError(context, action) { handleExternalError(context, true, action) } function handleExternalError(context, defaultValue, action) { if(this.stopAtFirstError) return action(); try { return action(); } catch (e) { if(e instanceof Errors.CompositeParserException) { e.errors.forEach(function (error) { addError(context, error); }); } else if( e instanceof Errors.ParserException || e instanceof Errors.AstBuilderException || e instanceof Errors.UnexpectedTokenException || e instanceof Errors.NoSuchLanguageException ) { addError(context, e); } else { throw e; } } return defaultValue; } function readToken(context) { return context.tokenQueue.length > 0 ? context.tokenQueue.shift() : context.tokenScanner.read(); } function matchToken(state, token, context) { switch(state) { case 0: return matchTokenAt_0(token, context); case 1: return matchTokenAt_1(token, context); case 2: return matchTokenAt_2(token, context); case 3: return matchTokenAt_3(token, context); case 4: return matchTokenAt_4(token, context); case 5: return matchTokenAt_5(token, context); case 6: return matchTokenAt_6(token, context); case 7: return matchTokenAt_7(token, context); case 8: return matchTokenAt_8(token, context); case 9: return matchTokenAt_9(token, context); case 10: return matchTokenAt_10(token, context); case 11: return matchTokenAt_11(token, context); case 12: return matchTokenAt_12(token, context); case 13: return matchTokenAt_13(token, context); case 14: return matchTokenAt_14(token, context); case 15: return matchTokenAt_15(token, context); case 16: return matchTokenAt_16(token, context); case 17: return matchTokenAt_17(token, context); case 18: return matchTokenAt_18(token, context); case 19: return matchTokenAt_19(token, context); case 20: return matchTokenAt_20(token, context); case 21: return matchTokenAt_21(token, context); case 22: return matchTokenAt_22(token, context); case 23: return matchTokenAt_23(token, context); case 24: return matchTokenAt_24(token, context); case 25: return matchTokenAt_25(token, context); case 26: return matchTokenAt_26(token, context); case 27: return matchTokenAt_27(token, context); case 29: return matchTokenAt_29(token, context); case 30: return matchTokenAt_30(token, context); case 31: return matchTokenAt_31(token, context); case 32: return matchTokenAt_32(token, context); case 33: return matchTokenAt_33(token, context); case 34: return matchTokenAt_34(token, context); default: throw new Error("Unknown state: " + state); } } // Start function matchTokenAt_0(token, context) { if(match_Language(context, token)) { startRule(context, 'Feature_Header'); build(context, token); return 1; } if(match_TagLine(context, token)) { startRule(context, 'Feature_Header'); startRule(context, 'Tags'); build(context, token); return 2; } if(match_FeatureLine(context, token)) { startRule(context, 'Feature_Header'); build(context, token); return 3; } if(match_Comment(context, token)) { build(context, token); return 0; } if(match_Empty(context, token)) { build(context, token); return 0; } var stateComment = "State: 0 - Start"; token.detach(); var expectedTokens = ["#Language", "#TagLine", "#FeatureLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 0; } // Feature:0>Feature_Header:0>#Language:0 function matchTokenAt_1(token, context) { if(match_TagLine(context, token)) { startRule(context, 'Tags'); build(context, token); return 2; } if(match_FeatureLine(context, token)) { build(context, token); return 3; } if(match_Comment(context, token)) { build(context, token); return 1; } if(match_Empty(context, token)) { build(context, token); return 1; } var stateComment = "State: 1 - Feature:0>Feature_Header:0>#Language:0"; token.detach(); var expectedTokens = ["#TagLine", "#FeatureLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 1; } // Feature:0>Feature_Header:1>Tags:0>#TagLine:0 function matchTokenAt_2(token, context) { if(match_TagLine(context, token)) { build(context, token); return 2; } if(match_FeatureLine(context, token)) { endRule(context, 'Tags'); build(context, token); return 3; } if(match_Comment(context, token)) { build(context, token); return 2; } if(match_Empty(context, token)) { build(context, token); return 2; } var stateComment = "State: 2 - Feature:0>Feature_Header:1>Tags:0>#TagLine:0"; token.detach(); var expectedTokens = ["#TagLine", "#FeatureLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 2; } // Feature:0>Feature_Header:2>#FeatureLine:0 function matchTokenAt_3(token, context) { if(match_EOF(context, token)) { endRule(context, 'Feature_Header'); build(context, token); return 28; } if(match_Empty(context, token)) { build(context, token); return 3; } if(match_Comment(context, token)) { build(context, token); return 5; } if(match_BackgroundLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Background'); build(context, token); return 6; } if(match_TagLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Other(context, token)) { startRule(context, 'Description'); build(context, token); return 4; } var stateComment = "State: 3 - Feature:0>Feature_Header:2>#FeatureLine:0"; token.detach(); var expectedTokens = ["#EOF", "#Empty", "#Comment", "#BackgroundLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 3; } // Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:1>Description:0>#Other:0 function matchTokenAt_4(token, context) { if(match_EOF(context, token)) { endRule(context, 'Description'); endRule(context, 'Feature_Header'); build(context, token); return 28; } if(match_Comment(context, token)) { endRule(context, 'Description'); build(context, token); return 5; } if(match_BackgroundLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Feature_Header'); startRule(context, 'Background'); build(context, token); return 6; } if(match_TagLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Other(context, token)) { build(context, token); return 4; } var stateComment = "State: 4 - Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:1>Description:0>#Other:0"; token.detach(); var expectedTokens = ["#EOF", "#Comment", "#BackgroundLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 4; } // Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:2>#Comment:0 function matchTokenAt_5(token, context) { if(match_EOF(context, token)) { endRule(context, 'Feature_Header'); build(context, token); return 28; } if(match_Comment(context, token)) { build(context, token); return 5; } if(match_BackgroundLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Background'); build(context, token); return 6; } if(match_TagLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Feature_Header'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Empty(context, token)) { build(context, token); return 5; } var stateComment = "State: 5 - Feature:0>Feature_Header:3>Feature_Description:0>Description_Helper:2>#Comment:0"; token.detach(); var expectedTokens = ["#EOF", "#Comment", "#BackgroundLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 5; } // Feature:1>Background:0>#BackgroundLine:0 function matchTokenAt_6(token, context) { if(match_EOF(context, token)) { endRule(context, 'Background'); build(context, token); return 28; } if(match_Empty(context, token)) { build(context, token); return 6; } if(match_Comment(context, token)) { build(context, token); return 8; } if(match_StepLine(context, token)) { startRule(context, 'Step'); build(context, token); return 9; } if(match_TagLine(context, token)) { endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Other(context, token)) { startRule(context, 'Description'); build(context, token); return 7; } var stateComment = "State: 6 - Feature:1>Background:0>#BackgroundLine:0"; token.detach(); var expectedTokens = ["#EOF", "#Empty", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 6; } // Feature:1>Background:1>Background_Description:0>Description_Helper:1>Description:0>#Other:0 function matchTokenAt_7(token, context) { if(match_EOF(context, token)) { endRule(context, 'Description'); endRule(context, 'Background'); build(context, token); return 28; } if(match_Comment(context, token)) { endRule(context, 'Description'); build(context, token); return 8; } if(match_StepLine(context, token)) { endRule(context, 'Description'); startRule(context, 'Step'); build(context, token); return 9; } if(match_TagLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Other(context, token)) { build(context, token); return 7; } var stateComment = "State: 7 - Feature:1>Background:1>Background_Description:0>Description_Helper:1>Description:0>#Other:0"; token.detach(); var expectedTokens = ["#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 7; } // Feature:1>Background:1>Background_Description:0>Description_Helper:2>#Comment:0 function matchTokenAt_8(token, context) { if(match_EOF(context, token)) { endRule(context, 'Background'); build(context, token); return 28; } if(match_Comment(context, token)) { build(context, token); return 8; } if(match_StepLine(context, token)) { startRule(context, 'Step'); build(context, token); return 9; } if(match_TagLine(context, token)) { endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Empty(context, token)) { build(context, token); return 8; } var stateComment = "State: 8 - Feature:1>Background:1>Background_Description:0>Description_Helper:2>#Comment:0"; token.detach(); var expectedTokens = ["#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 8; } // Feature:1>Background:2>Scenario_Step:0>Step:0>#StepLine:0 function matchTokenAt_9(token, context) { if(match_EOF(context, token)) { endRule(context, 'Step'); endRule(context, 'Background'); build(context, token); return 28; } if(match_TableRow(context, token)) { startRule(context, 'DataTable'); build(context, token); return 10; } if(match_DocStringSeparator(context, token)) { startRule(context, 'DocString'); build(context, token); return 33; } if(match_StepLine(context, token)) { endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 9; } if(match_TagLine(context, token)) { endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 9; } if(match_Empty(context, token)) { build(context, token); return 9; } var stateComment = "State: 9 - Feature:1>Background:2>Scenario_Step:0>Step:0>#StepLine:0"; token.detach(); var expectedTokens = ["#EOF", "#TableRow", "#DocStringSeparator", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 9; } // Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0 function matchTokenAt_10(token, context) { if(match_EOF(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Background'); build(context, token); return 28; } if(match_TableRow(context, token)) { build(context, token); return 10; } if(match_StepLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 9; } if(match_TagLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 10; } if(match_Empty(context, token)) { build(context, token); return 10; } var stateComment = "State: 10 - Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0"; token.detach(); var expectedTokens = ["#EOF", "#TableRow", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 10; } // Feature:2>Scenario_Definition:0>Tags:0>#TagLine:0 function matchTokenAt_11(token, context) { if(match_TagLine(context, token)) { build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Tags'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Tags'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 11; } if(match_Empty(context, token)) { build(context, token); return 11; } var stateComment = "State: 11 - Feature:2>Scenario_Definition:0>Tags:0>#TagLine:0"; token.detach(); var expectedTokens = ["#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 11; } // Feature:2>Scenario_Definition:1>__alt0:0>Scenario:0>#ScenarioLine:0 function matchTokenAt_12(token, context) { if(match_EOF(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); build(context, token); return 28; } if(match_Empty(context, token)) { build(context, token); return 12; } if(match_Comment(context, token)) { build(context, token); return 14; } if(match_StepLine(context, token)) { startRule(context, 'Step'); build(context, token); return 15; } if(match_TagLine(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Other(context, token)) { startRule(context, 'Description'); build(context, token); return 13; } var stateComment = "State: 12 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:0>#ScenarioLine:0"; token.detach(); var expectedTokens = ["#EOF", "#Empty", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 12; } // Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:1>Description:0>#Other:0 function matchTokenAt_13(token, context) { if(match_EOF(context, token)) { endRule(context, 'Description'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); build(context, token); return 28; } if(match_Comment(context, token)) { endRule(context, 'Description'); build(context, token); return 14; } if(match_StepLine(context, token)) { endRule(context, 'Description'); startRule(context, 'Step'); build(context, token); return 15; } if(match_TagLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Description'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Other(context, token)) { build(context, token); return 13; } var stateComment = "State: 13 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:1>Description:0>#Other:0"; token.detach(); var expectedTokens = ["#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 13; } // Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:2>#Comment:0 function matchTokenAt_14(token, context) { if(match_EOF(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); build(context, token); return 28; } if(match_Comment(context, token)) { build(context, token); return 14; } if(match_StepLine(context, token)) { startRule(context, 'Step'); build(context, token); return 15; } if(match_TagLine(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Empty(context, token)) { build(context, token); return 14; } var stateComment = "State: 14 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:1>Scenario_Description:0>Description_Helper:2>#Comment:0"; token.detach(); var expectedTokens = ["#EOF", "#Comment", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 14; } // Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:0>#StepLine:0 function matchTokenAt_15(token, context) { if(match_EOF(context, token)) { endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); build(context, token); return 28; } if(match_TableRow(context, token)) { startRule(context, 'DataTable'); build(context, token); return 16; } if(match_DocStringSeparator(context, token)) { startRule(context, 'DocString'); build(context, token); return 31; } if(match_StepLine(context, token)) { endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 15; } if(match_TagLine(context, token)) { endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 15; } if(match_Empty(context, token)) { build(context, token); return 15; } var stateComment = "State: 15 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:0>#StepLine:0"; token.detach(); var expectedTokens = ["#EOF", "#TableRow", "#DocStringSeparator", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 15; } // Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0 function matchTokenAt_16(token, context) { if(match_EOF(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); build(context, token); return 28; } if(match_TableRow(context, token)) { build(context, token); return 16; } if(match_StepLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 15; } if(match_TagLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 16; } if(match_Empty(context, token)) { build(context, token); return 16; } var stateComment = "State: 16 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0"; token.detach(); var expectedTokens = ["#EOF", "#TableRow", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 16; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:0>#ScenarioOutlineLine:0 function matchTokenAt_17(token, context) { if(match_Empty(context, token)) { build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 19; } if(match_StepLine(context, token)) { startRule(context, 'Step'); build(context, token); return 20; } if(match_TagLine(context, token)) { startRule(context, 'Examples_Definition'); startRule(context, 'Tags'); build(context, token); return 22; } if(match_ExamplesLine(context, token)) { startRule(context, 'Examples_Definition'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_Other(context, token)) { startRule(context, 'Description'); build(context, token); return 18; } var stateComment = "State: 17 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:0>#ScenarioOutlineLine:0"; token.detach(); var expectedTokens = ["#Empty", "#Comment", "#StepLine", "#TagLine", "#ExamplesLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 17; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:1>Description:0>#Other:0 function matchTokenAt_18(token, context) { if(match_Comment(context, token)) { endRule(context, 'Description'); build(context, token); return 19; } if(match_StepLine(context, token)) { endRule(context, 'Description'); startRule(context, 'Step'); build(context, token); return 20; } if(match_TagLine(context, token)) { endRule(context, 'Description'); startRule(context, 'Examples_Definition'); startRule(context, 'Tags'); build(context, token); return 22; } if(match_ExamplesLine(context, token)) { endRule(context, 'Description'); startRule(context, 'Examples_Definition'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_Other(context, token)) { build(context, token); return 18; } var stateComment = "State: 18 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:1>Description:0>#Other:0"; token.detach(); var expectedTokens = ["#Comment", "#StepLine", "#TagLine", "#ExamplesLine", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 18; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:2>#Comment:0 function matchTokenAt_19(token, context) { if(match_Comment(context, token)) { build(context, token); return 19; } if(match_StepLine(context, token)) { startRule(context, 'Step'); build(context, token); return 20; } if(match_TagLine(context, token)) { startRule(context, 'Examples_Definition'); startRule(context, 'Tags'); build(context, token); return 22; } if(match_ExamplesLine(context, token)) { startRule(context, 'Examples_Definition'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_Empty(context, token)) { build(context, token); return 19; } var stateComment = "State: 19 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:1>ScenarioOutline_Description:0>Description_Helper:2>#Comment:0"; token.detach(); var expectedTokens = ["#Comment", "#StepLine", "#TagLine", "#ExamplesLine", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 19; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:0>#StepLine:0 function matchTokenAt_20(token, context) { if(match_TableRow(context, token)) { startRule(context, 'DataTable'); build(context, token); return 21; } if(match_DocStringSeparator(context, token)) { startRule(context, 'DocString'); build(context, token); return 29; } if(match_StepLine(context, token)) { endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 20; } if(match_TagLine(context, token)) { endRule(context, 'Step'); startRule(context, 'Examples_Definition'); startRule(context, 'Tags'); build(context, token); return 22; } if(match_ExamplesLine(context, token)) { endRule(context, 'Step'); startRule(context, 'Examples_Definition'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_Comment(context, token)) { build(context, token); return 20; } if(match_Empty(context, token)) { build(context, token); return 20; } var stateComment = "State: 20 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:0>#StepLine:0"; token.detach(); var expectedTokens = ["#TableRow", "#DocStringSeparator", "#StepLine", "#TagLine", "#ExamplesLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 20; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0 function matchTokenAt_21(token, context) { if(match_TableRow(context, token)) { build(context, token); return 21; } if(match_StepLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 20; } if(match_TagLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); startRule(context, 'Examples_Definition'); startRule(context, 'Tags'); build(context, token); return 22; } if(match_ExamplesLine(context, token)) { endRule(context, 'DataTable'); endRule(context, 'Step'); startRule(context, 'Examples_Definition'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_Comment(context, token)) { build(context, token); return 21; } if(match_Empty(context, token)) { build(context, token); return 21; } var stateComment = "State: 21 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:0>DataTable:0>#TableRow:0"; token.detach(); var expectedTokens = ["#TableRow", "#StepLine", "#TagLine", "#ExamplesLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 21; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:0>Tags:0>#TagLine:0 function matchTokenAt_22(token, context) { if(match_TagLine(context, token)) { build(context, token); return 22; } if(match_ExamplesLine(context, token)) { endRule(context, 'Tags'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_Comment(context, token)) { build(context, token); return 22; } if(match_Empty(context, token)) { build(context, token); return 22; } var stateComment = "State: 22 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:0>Tags:0>#TagLine:0"; token.detach(); var expectedTokens = ["#TagLine", "#ExamplesLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 22; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:0>#ExamplesLine:0 function matchTokenAt_23(token, context) { if(match_Empty(context, token)) { build(context, token); return 23; } if(match_Comment(context, token)) { build(context, token); return 25; } if(match_TableRow(context, token)) { build(context, token); return 26; } if(match_Other(context, token)) { startRule(context, 'Description'); build(context, token); return 24; } var stateComment = "State: 23 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:0>#ExamplesLine:0"; token.detach(); var expectedTokens = ["#Empty", "#Comment", "#TableRow", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 23; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:1>Description:0>#Other:0 function matchTokenAt_24(token, context) { if(match_Comment(context, token)) { endRule(context, 'Description'); build(context, token); return 25; } if(match_TableRow(context, token)) { endRule(context, 'Description'); build(context, token); return 26; } if(match_Other(context, token)) { build(context, token); return 24; } var stateComment = "State: 24 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:1>Description:0>#Other:0"; token.detach(); var expectedTokens = ["#Comment", "#TableRow", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 24; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:2>#Comment:0 function matchTokenAt_25(token, context) { if(match_Comment(context, token)) { build(context, token); return 25; } if(match_TableRow(context, token)) { build(context, token); return 26; } if(match_Empty(context, token)) { build(context, token); return 25; } var stateComment = "State: 25 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:1>Examples_Description:0>Description_Helper:2>#Comment:0"; token.detach(); var expectedTokens = ["#Comment", "#TableRow", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 25; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:2>#TableRow:0 function matchTokenAt_26(token, context) { if(match_TableRow(context, token)) { build(context, token); return 27; } if(match_Comment(context, token)) { build(context, token); return 26; } if(match_Empty(context, token)) { build(context, token); return 26; } var stateComment = "State: 26 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:2>#TableRow:0"; token.detach(); var expectedTokens = ["#TableRow", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 26; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:3>#TableRow:0 function matchTokenAt_27(token, context) { if(match_EOF(context, token)) { endRule(context, 'Examples'); endRule(context, 'Examples_Definition'); endRule(context, 'ScenarioOutline'); endRule(context, 'Scenario_Definition'); build(context, token); return 28; } if(match_TableRow(context, token)) { build(context, token); return 27; } if(match_TagLine(context, token)) { if(lookahead_0(context, token)) { endRule(context, 'Examples'); endRule(context, 'Examples_Definition'); startRule(context, 'Examples_Definition'); startRule(context, 'Tags'); build(context, token); return 22; } } if(match_TagLine(context, token)) { endRule(context, 'Examples'); endRule(context, 'Examples_Definition'); endRule(context, 'ScenarioOutline'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ExamplesLine(context, token)) { endRule(context, 'Examples'); endRule(context, 'Examples_Definition'); startRule(context, 'Examples_Definition'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_ScenarioLine(context, token)) { endRule(context, 'Examples'); endRule(context, 'Examples_Definition'); endRule(context, 'ScenarioOutline'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'Examples'); endRule(context, 'Examples_Definition'); endRule(context, 'ScenarioOutline'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 27; } if(match_Empty(context, token)) { build(context, token); return 27; } var stateComment = "State: 27 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:3>Examples_Definition:1>Examples:3>#TableRow:0"; token.detach(); var expectedTokens = ["#EOF", "#TableRow", "#TagLine", "#ExamplesLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 27; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0 function matchTokenAt_29(token, context) { if(match_DocStringSeparator(context, token)) { build(context, token); return 30; } if(match_Other(context, token)) { build(context, token); return 29; } var stateComment = "State: 29 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0"; token.detach(); var expectedTokens = ["#DocStringSeparator", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 29; } // Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0 function matchTokenAt_30(token, context) { if(match_StepLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 20; } if(match_TagLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); startRule(context, 'Examples_Definition'); startRule(context, 'Tags'); build(context, token); return 22; } if(match_ExamplesLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); startRule(context, 'Examples_Definition'); startRule(context, 'Examples'); build(context, token); return 23; } if(match_Comment(context, token)) { build(context, token); return 30; } if(match_Empty(context, token)) { build(context, token); return 30; } var stateComment = "State: 30 - Feature:2>Scenario_Definition:1>__alt0:1>ScenarioOutline:2>ScenarioOutline_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0"; token.detach(); var expectedTokens = ["#StepLine", "#TagLine", "#ExamplesLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 30; } // Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0 function matchTokenAt_31(token, context) { if(match_DocStringSeparator(context, token)) { build(context, token); return 32; } if(match_Other(context, token)) { build(context, token); return 31; } var stateComment = "State: 31 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0"; token.detach(); var expectedTokens = ["#DocStringSeparator", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 31; } // Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0 function matchTokenAt_32(token, context) { if(match_EOF(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); build(context, token); return 28; } if(match_StepLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 15; } if(match_TagLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Scenario'); endRule(context, 'Scenario_Definition'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 32; } if(match_Empty(context, token)) { build(context, token); return 32; } var stateComment = "State: 32 - Feature:2>Scenario_Definition:1>__alt0:0>Scenario:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0"; token.detach(); var expectedTokens = ["#EOF", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 32; } // Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0 function matchTokenAt_33(token, context) { if(match_DocStringSeparator(context, token)) { build(context, token); return 34; } if(match_Other(context, token)) { build(context, token); return 33; } var stateComment = "State: 33 - Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:0>#DocStringSeparator:0"; token.detach(); var expectedTokens = ["#DocStringSeparator", "#Other"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 33; } // Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0 function matchTokenAt_34(token, context) { if(match_EOF(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Background'); build(context, token); return 28; } if(match_StepLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); startRule(context, 'Step'); build(context, token); return 9; } if(match_TagLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Tags'); build(context, token); return 11; } if(match_ScenarioLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'Scenario'); build(context, token); return 12; } if(match_ScenarioOutlineLine(context, token)) { endRule(context, 'DocString'); endRule(context, 'Step'); endRule(context, 'Background'); startRule(context, 'Scenario_Definition'); startRule(context, 'ScenarioOutline'); build(context, token); return 17; } if(match_Comment(context, token)) { build(context, token); return 34; } if(match_Empty(context, token)) { build(context, token); return 34; } var stateComment = "State: 34 - Feature:1>Background:2>Scenario_Step:0>Step:1>Step_Arg:0>__alt1:1>DocString:2>#DocStringSeparator:0"; token.detach(); var expectedTokens = ["#EOF", "#StepLine", "#TagLine", "#ScenarioLine", "#ScenarioOutlineLine", "#Comment", "#Empty"]; var error = token.isEof ? Errors.UnexpectedEOFException.create(token, expectedTokens, stateComment) : Errors.UnexpectedTokenException.create(token, expectedTokens, stateComment); if (this.stopAtFirstError) throw error; addError(context, error); return 34; } function match_EOF(context, token) { return handleExternalError(context, false, function () { return context.tokenMatcher.match_EOF(token); }); } function match_Empty(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_Empty(token); }); } function match_Comment(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_Comment(token); }); } function match_TagLine(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_TagLine(token); }); } function match_FeatureLine(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_FeatureLine(token); }); } function match_BackgroundLine(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_BackgroundLine(token); }); } function match_ScenarioLine(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_ScenarioLine(token); }); } function match_ScenarioOutlineLine(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_ScenarioOutlineLine(token); }); } function match_ExamplesLine(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_ExamplesLine(token); }); } function match_StepLine(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_StepLine(token); }); } function match_DocStringSeparator(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_DocStringSeparator(token); }); } function match_TableRow(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_TableRow(token); }); } function match_Language(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_Language(token); }); } function match_Other(context, token) { if(token.isEof) return false; return handleExternalError(context, false, function () { return context.tokenMatcher.match_Other(token); }); } function lookahead_0(context, currentToken) { currentToken.detach(); var token; var queue = []; var match = false; do { token = readToken(context); token.detach(); queue.push(token); if (false || match_ExamplesLine(context, token)) { match = true; break; } } while(false || match_Empty(context, token) || match_Comment(context, token) || match_TagLine(context, token)); context.tokenQueue = context.tokenQueue.concat(queue); return match; } }
thetutlage/gherkin3
javascript/lib/gherkin/parser.js
JavaScript
mit
67,038
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.copyLabelsFromRepo = exports.updateLabels = exports.listLabels = undefined; /** * Export `listLabels`. */ let listLabels = exports.listLabels = (() => { var _ref = _asyncToGenerator(function* (options) { const { repository, token } = options; // Instantiate client. const client = new _client2.default({ token }); // Get source labels. const labels = yield client.getLabels(repository); // Parsed labels. return labels.map(function ({ color, name }) { return { color, name }; }); }); return function listLabels(_x) { return _ref.apply(this, arguments); }; })(); /** * Export `updateLabels`. */ let updateLabels = exports.updateLabels = (() => { var _ref2 = _asyncToGenerator(function* (options) { const { repository, token, labels } = options; // Instantiate client. const client = new _client2.default({ token }); // Set the repository labels using the labels in the configuration file. yield client.setLabels(repository, labels); }); return function updateLabels(_x2) { return _ref2.apply(this, arguments); }; })(); /** * Export `copyLabelsFromRepo`. */ let copyLabelsFromRepo = exports.copyLabelsFromRepo = (() => { var _ref3 = _asyncToGenerator(function* (options) { const { source, target, token } = options; // Instantiate clients. const client = new _client2.default({ token }); // Get source labels. const rawLabels = yield client.getLabels(source); // Parsed labels. const labels = rawLabels.map(function ({ color, name }) { return { color, name }; }); // Set the repository labels using the labels in the source repository. yield client.setLabels(target, labels); }); return function copyLabelsFromRepo(_x3) { return _ref3.apply(this, arguments); }; })(); var _client = require('./client'); var _client2 = _interopRequireDefault(_client); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /** * Module dependencies. */
seegno/github-labels
dist/index.js
JavaScript
mit
2,591
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('project-list', 'Integration | Component | project list', { integration: true }); test('it renders', function(assert) { assert.expect(2); // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{project-list}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#project-list}} template block text {{/project-list}} `); assert.equal(this.$().text().trim(), 'template block text'); });
JamieWohletz/katana
tests/integration/components/project-list-test.js
JavaScript
mit
676
const chalk = require('chalk'); // The equivalent of <code>, for embedding a cmd // eg: Please run ${cmd(woot)} module.exports = cmd => `${chalk.gray('`')}${chalk.cyan(cmd)}${chalk.gray('`')}`;
southpolesteve/now-cli
lib/utils/output/cmd.js
JavaScript
mit
198
var expect = require('expect.js'); var request = require('supertest'); var healthcheck = require('../source'); var express = require('express'); describe('server', function() { it('should use default urn', function(done) { request(express().use(healthcheck())) .get('/api/health-check') .expect(200, done); }); it('should use specified urn', function(done) { request(express().use(healthcheck({urn: '/coucou'}))) .get('/coucou') .expect(200, done); }); it('should return 200 when calling health-check-vip', function(done) { request(express().use(healthcheck())) .get('/api/health-check-vip') .expect(200, done); }); it('should return 200 when calling health-check-vip with specified urn', function(done) { request(express().use(healthcheck({urn: '/coucou'}))) .get('/coucou-vip') .expect(200, done); }); });
FastIT/health-check
test/server.js
JavaScript
mit
894
'use strict'; // Regression test for https://github.com/nodejs/node/issues/13237 const common = require('../common'); const assert = require('assert'); const async_hooks = require('async_hooks'); const seenEvents = []; common.crashOnUnhandledRejection(); const p = new Promise((resolve) => resolve(1)); p.then(() => seenEvents.push('then')); const hooks = async_hooks.createHook({ init: common.mustNotCall(), before: common.mustCall((id) => { assert.ok(id > 1); seenEvents.push('before'); }), after: common.mustCall((id) => { assert.ok(id > 1); seenEvents.push('after'); hooks.disable(); }) }); setImmediate(() => { assert.deepStrictEqual(seenEvents, ['before', 'then', 'after']); }); hooks.enable(); // After `setImmediate` in order to not catch its init event.
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-async-wrap-promise-after-enabled.js
JavaScript
mit
806
import React, { Component } from 'react' import { XmlEntities as Entities } from 'html-entities' const entities = new Entities() class FluidIframe extends Component { constructor (props) { super(props) this.state = { width: 0 } this.ratio = props.height / props.width this.onResize = this.onResize.bind(this) this.onRootRef = this.onRootRef.bind(this) } componentDidMount () { window.addEventListener('resize', this.onResize) } componentWillUnmount () { window.removeEventListener('resize', this.onResize) } onResize () { const { width } = this.root.getBoundingClientRect() this.setState({ width }) } onRootRef (e) { if (e) { this.root = e const { width } = e.getBoundingClientRect() this.setState({ width }) } } render () { const isReady = this.props.width !== 0 let content if (isReady) { let unescaped = entities.decode(this.props.content) const width = this.state.width const height = width * this.ratio unescaped = unescaped .split(`width="${this.props.width}"`) .join(`width="${width}"`) .split(`height="${this.props.height}"`) .join(`height="${height}"`) content = unescaped } return ( <div ref={this.onRootRef} > {this.state.width !== 0 && ( <div dangerouslySetInnerHTML={{ __html: content }} /> )} </div> ) } } export default FluidIframe
antoinechalifour/Reddix
src/components/FluidIframe/index.js
JavaScript
mit
1,506
requirejs.config({ baseUrl: '../../', paths: { lib: 'lib' } }); define(['jquery', 'lib/zz', 'lib/zzUtil', 'lib/zzInteraction', 'lib/zzDebug', 'lib/colorLab', 'lib/kindof'], function ($, zz, zzUtil, zzInteraction, zzDebug, colorLab, kindof) { var settings = { speed:4, dirX: 0, yForce: -5, yForceInitial : -5, arrVals: [-2.5,-2, 0, 2,2.5], arrAcc : [-0.1,0,0.05,0,-0.1], maxAcc : 0.1, maxVal : 2.5, currentSpeedIndex : 2, origo : window.innerWidth / 2, mouseX:0, setDirectionXFloating: function(x){ this.mouseX = x; var pVal = this.maxVal / this.origo; var deltaVal = (x - this.origo) * pVal; this.dirX = deltaVal; zz.world.gravity.x = -this.dirX * 0.6; var forcedPositive = this.dirX < 0 ? this.dirX * -1 : this.dirX; //this.yForce = this.yForceInitial + (forcedPositive * 0.8); }, setDirectionX: function (v) { if (v === 'left' && this.currentSpeedIndex > 0) { this.currentSpeedIndex--; } else if (v === 'right' && this.currentSpeedIndex < 4) { this.currentSpeedIndex++; } this.dirX = this.arrVals[this.currentSpeedIndex]; zz.world.gravity.x = -this.dirX; var forcedPositive = this.dirX < 0 ? this.dirX * -1 : this.dirX; this.yForce = this.yForceInitial + (forcedPositive * 0.8); }, getAcc: function(){ return -0.6; var pMAx = this.maxAcc / this.origo; //0.1 / 1240 var delta = (this.mouseX - this.origo) * pMAx; return delta < 0 ? delta * -1 : delta; // return this.arrAcc[this.currentSpeedIndex]; } }; window.settings = settings; Array.prototype.randItem = function () { return this[Math.floor(Math.random() * this.length)]; } window.skiApp = { run: runApp }; function runApp(){ // $("document").ready(function () { zz.init($("#canvas1")[0], function (a) { }); zz.spriteEngine.spriteImageSrc = 'img/trees.png'; // var testItem = new zz.item(); var noSquare = [10, 10, 100, 10, 110, 40, 10, 50], testCloud = [0, 5, 20, 0, 20, 20, 0, 20, 0, 10], skier = [0, 0, 10, 0, 10, 20, 0, 20]; bgArea = [0,0,zz.world.w,0,zz.world.w,zz.world.h,0,zz.world.h]; var treeSpritePositions = [[10, 10, 28, 24], [68, 8, 90, 54],[34,52,61,115], [98,16,121,54]]; zz.definitions.shapes.push(noSquare); function getSpriteMeasure(coords) { return { w: coords[2] - coords[0], h: coords[3] - coords[1] }; } function handleAcceleration(itemForce){ itemForce.y = settings.getAcc(); } function seedSpriteTree(x, y, forceX) { var randTree = treeSpritePositions.randItem(); var mess = getSpriteMeasure(randTree); var sprite = new zz.sprite(x, y, mess.w, mess.h, randTree[0],randTree[1]); sprite.onRenderEnd = function (item) { handleAcceleration(item.attachedForce); if (zz.isCollide(item, you)) { /* you.fillColor = "#ff0000"; zz.world.gravity.x = 0; settings.yForce = 0; settings.dirX = 0;*/ } else { //you.fillColor = "#000000"; } }; //should check collision with other figures, that could be a floor for instance... return sprite; } function seedTrees() { var maxy = 500; var startOffsetY = 600; var deltaH = 70; for (var i = 0; i < maxy; i++) { var randW = (Math.random() * zz.world.w); zz.world.items.push(seedSpriteTree(randW, (i * deltaH)+startOffsetY, 0)); } } function seedSkier(x,y) { var s= new zz.stickFigure(x, y, 20, 20, "#333333", "#444444", skier, 1, { x: 0, y: 0 }); s.pathType = 'square'; s.onRenderEnd = function renderEnd(renderedItem) { renderedItem.attachedForce.x = settings.dirX; bg.attachedForce.x = settings.dirX; // must follow } return s; } var ss= setTimeout(function(){seedTrees()},2000) ; var you = seedSkier(300, 300); var bg = new zz.stickFigure(0, 0, zz.world.w, zz.world.h, "#ccaa33", "#df0000", bgArea, 1, { x: 0, y: 0 }); var inter=""; zzInteraction.bind(bg, "mouseover", function (ev, zzItem) { if(inter !=""){ clearInterval(inter); } inter = setInterval(function(){ settings.setDirectionXFloating(ev.pageX); },200); }); zz.world.items.push(bg); zz.world.items.push(you); // zz.world.items.push(seedCloud(310, 10, 0)); zz.world.gravity.y = 0; zz.world.gravity.x = 0; //for (var i = 0; i < 100; i++) { // zz.world.items.push(seedRandomPopcorn()); //} var c = 0; zz.run(function (ctx) { //render callback som parameter. Anropas från animate. c++; zz.world.items.forEach(function (stickFig) { // if(stickFig) stickFig.render(stickFig.onRenderEnd); }); }); $("body").on("keydown", function (evt) { if (evt.which === 37) { settings.setDirectionX('left'); } if (evt.which === 39) { settings.setDirectionX('right'); } }); }; });
frankfurillo/zz
deathski/js/js.js
JavaScript
mit
6,120
import './meteo.css'; import $ from '../jQuery-globals'; import i18n from '../i18n'; import SensorWidget from '../SensorWidget'; import ld from '../locale-date'; import 'bootstrap'; ld.utc(false); ld.locale('es'); i18n.setLang('ca'); const defs = { service() { return window.sosUrl ? window.sosUrl : '/52n-sos/service'; }, offering(p) { return `http://sensors.portdebarcelona.cat/def/weather/offerings#${p}`; }, feature(p) { return `http://sensors.portdebarcelona.cat/def/weather/features#${p}`; }, property(p) { return `http://sensors.portdebarcelona.cat/def/weather/properties#${p}`; }, }; const now = new Date(); const twoHoursAgo = new Date(now.getTime() - 1000 * 60 * 60 * 2); const threeHoursAgo = new Date(now.getTime() - 1000 * 60 * 60 * 3); const back33Samples = new Date(now.getTime() - 1000 * 60 * 60 * 17); const aDayAgo = new Date(now.getTime() - 1000 * 60 * 60 * 24); const section = $('.active a').text(); switch (section) { case 'Sirena': SensorWidget('compass', { service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('02'), property: defs.property('31'), refresh_interval: 15, }, document.querySelector('.sirena .compass')); SensorWidget('thermometer', { service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('02'), property: defs.property('32'), refresh_interval: 15, }, document.querySelector('.sirena .meteo-thermometer')); SensorWidget('timechart', { title: 'Velocitat Vent', service: defs.service(), offering: defs.offering('10M'), features: [defs.feature('02')], properties: [defs.property('30M'), defs.property('30')], time_start: `${aDayAgo.toISOString().substring(0, 19)}Z`, time_end: `${now.toISOString().substring(0, 19)}Z`, }, document.querySelector('.sirena .timechart')); SensorWidget('windrose', { title: 'Rosa vents últimes 3h', subtitle: 'Sirena, mostres minutals', service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('02'), properties: [defs.property('30'), defs.property('31')], time_start: `${threeHoursAgo.toISOString().substring(0, 19)}Z`, time_end: `${now.toISOString().substring(0, 19)}Z`, refresh_interval: 120, }, document.querySelector('.sirena .windrose')); SensorWidget('table', { title: 'Taula de dades', service: defs.service(), offering: defs.offering('30M'), feature: defs.feature('02'), properties: [defs.property('30'), defs.property('30M'), defs.property('31'), defs.property('32'), defs.property('33'), defs.property('35'), defs.property('36'), defs.property('34')], time_start: `${back33Samples.toISOString().substring(0, 19)}Z`, time_end: `${now.toISOString().substring(0, 19)}Z`, }, document.querySelector('.sirena .tablex')); break; case 'XMVQA': { SensorWidget('compass', { title: 'Sirena', service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('02'), property: defs.property('31'), refresh_interval: 15, }, document.querySelector('.xmvqa .left .compass')); SensorWidget('panel', { title: 'Dades minutals', service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('02'), properties: [defs.property('30'), defs.property('31'), defs.property('32'), defs.property('33'), defs.property('34'), defs.property('35'), defs.property('36')], refresh_interval: 15, }, document.querySelector('.xmvqa .left .panel-10M')); SensorWidget('timechart', { title: 'Velocitat Vent', service: defs.service(), offering: defs.offering('10M'), features: [defs.feature('02')], properties: [defs.property('30')], time_start: `${twoHoursAgo.toISOString().substring(0, 19)}Z`, time_end: `${now.toISOString().substring(0, 19)}Z`, }, document.querySelector('.xmvqa .left .timechart')); SensorWidget('panel', { title: 'Darrers valors 30-minutals', service: defs.service(), offering: defs.offering('30M'), feature: defs.feature('02'), properties: [defs.property('30'), defs.property('31'), defs.property('32'), defs.property('33'), defs.property('34'), defs.property('35'), defs.property('36')], refresh_interval: 120, }, document.querySelector('.xmvqa .left .panel-30M')); const stations = { '01': 'Dispensari', P4: 'Dic Sud', '03': 'Adossat', P6: 'Contradic', P3: 'Unitat Mobil', P5: 'Dàrsena Sud B', 10: 'ZAL2', }; Object.keys(stations).forEach((station) => { SensorWidget('compass', { title: stations[station], service: defs.service(), offering: defs.offering('1M'), feature: defs.feature(station), property: defs.property('31'), refresh_interval: 15, }, document.querySelector(`.xmvqa .x${station} .compass`)); SensorWidget('panel', { title: 'Dades minutals', service: defs.service(), offering: defs.offering('1M'), feature: defs.feature(station), properties: [defs.property('30'), defs.property('31'), defs.property('32'), defs.property('33'), defs.property('34'), defs.property('35'), defs.property('36')], refresh_interval: 15, }, document.querySelector(`.xmvqa .x${station} .panel`)); }); } break; case 'Torre Control': SensorWidget('map', { service: defs.service(), offering: defs.offering('30M'), features: [defs.feature('P4')], properties: [], permanent_tooltips: true, swap_axis: true, max_initial_zoom: 12, }, document.querySelector('.torrecontrol .p4 .map')); SensorWidget('compass', { service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('P4'), property: defs.property('31'), refresh_interval: 15, }, document.querySelector('.torrecontrol .p4 .compass')); SensorWidget('panel', { title: 'Dades minutals', service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('P4'), properties: [defs.property('31'), defs.property('30')], refresh_interval: 15, }, document.querySelector('.torrecontrol .p4 .panel-10M')); SensorWidget('panel', { title: 'Dades 30-minutals', service: defs.service(), offering: defs.offering('30M'), feature: defs.feature('P4'), properties: [defs.property('31'), defs.property('30')], refresh_interval: 120, }, document.querySelector('.torrecontrol .p4 .panel-30M')); SensorWidget('map', { service: defs.service(), offering: defs.offering('30M'), features: [defs.feature('02')], properties: [], permanent_tooltips: true, swap_axis: true, max_initial_zoom: 12, }, document.querySelector('.torrecontrol .x02 .map')); SensorWidget('compass', { service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('02'), property: defs.property('31'), refresh_interval: 120, }, document.querySelector('.torrecontrol .x02 .compass')); SensorWidget('panel', { title: 'Dades minutals', service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('02'), properties: [defs.property('31'), defs.property('30')], refresh_interval: 15, }, document.querySelector('.torrecontrol .x02 .panel-10M')); SensorWidget('panel', { title: 'Dades 30-minutals', service: defs.service(), offering: defs.offering('30M'), feature: defs.feature('02'), properties: [defs.property('31'), defs.property('30')], refresh_interval: 120, }, document.querySelector('.torrecontrol .x02 .panel-30M')); SensorWidget('map', { service: defs.service(), offering: defs.offering('30M'), features: [defs.feature('03')], properties: [], permanent_tooltips: true, swap_axis: true, max_initial_zoom: 12, }, document.querySelector('.torrecontrol .x03 .map')); SensorWidget('compass', { service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('03'), property: defs.property('31'), refresh_interval: 15, }, document.querySelector('.torrecontrol .x03 .compass')); SensorWidget('panel', { title: 'Dades minutals', service: defs.service(), offering: defs.offering('1M'), feature: defs.feature('03'), properties: [defs.property('31'), defs.property('30')], refresh_interval: 15, }, document.querySelector('.torrecontrol .x03 .panel-10M')); SensorWidget('panel', { title: 'Dades 30-minutals', service: defs.service(), offering: defs.offering('30M'), feature: defs.feature('03'), properties: [defs.property('31'), defs.property('30')], refresh_interval: 120, }, document.querySelector('.torrecontrol .x03 .panel-30M')); break; case 'Data Browser': { const features = ['01', '02', '03', '10', '11', '12', 'P5']; const featureNames = ['01 - Dispensari', '02 - Sirena', '03 - Adossat', '10 - ZAL Prat', '11 - Bocana Sud', '12 - BEST', 'P5 - Dàrsena Sud']; const offerings = ['1M', '10M', '30M']; const offeringNames = ['Minutals', '10 minutals', '30 minutals']; const tpl = $('#item-template').html(); let html = ''; Object.keys(features).forEach((f) => { let res = tpl.replace(/\{\{id}}/g, features[f]); res = res.replace(/\{\{title}}/g, featureNames[f]); html += res; }); $('.databrowser').html(html); $('.panel-collapse').on('show.bs.collapse', function onPanelShow() { $(this).parent().removeClass('panel-default').addClass('panel-primary'); Object.keys(offerings).forEach((o) => { const feature = this.id; const offering = offerings[o]; const title = offeringNames[o]; const element = $(this).find(`.x${offering}`)[0]; if (!element.children.length) { SensorWidget('panel', { title, service: defs.service(), offering: defs.offering(offering), feature: defs.feature(feature), properties: [], refresh_interval: 60, }, element); } }); }); $('.panel-collapse').on('hide.bs.collapse', function onPanelHide() { $(this).parent().removeClass('panel-primary').addClass('panel-default'); }); $('.panel').hover( function setPanelPrimary() { $(this).removeClass('panel-default').addClass('panel-primary'); }, function setPanelDefault() { if (!$(this).find('.in').length && !$(this).find('.collapsing').length) { $(this).removeClass('panel-primary').addClass('panel-default'); } }, ); } break; default: break; }
oscarfonts/sensor-widgets
src/js/pages/meteo.apb.es.js
JavaScript
mit
11,260
define([ 'matreshka_dir/core/var/core', 'matreshka_dir/core/var/sym', 'matreshka_dir/core/initmk', 'matreshka_dir/core/util/common' ], function(core, sym, initMK, util) { "use strict"; var defaultBinders, lookForBinder; defaultBinders = core.defaultBinders = [function(node) { var tagName = node.tagName, binders = core.binders, b; if (tagName == 'INPUT') { b = binders.input(node.type); } else if (tagName == 'TEXTAREA') { b = binders.textarea(); } else if (tagName == 'SELECT') { b = binders.select(node.multiple); } else if (tagName == 'PROGRESS') { b = binders.progress(); } return b; }]; lookForBinder = core.lookForBinder = function(node) { var result, ep = defaultBinders, i; for (i = 0; i < ep.length; i++) { if (result = ep[i].call(node, node)) { return result; } } }; core.bindOptionalNode = function(object, key, node, binder, evt) { if (typeof key == 'object') { /* * this.bindNode({ key: $() }, { on: 'evt' }, { silent: true }); */ bindNode(object, key, node, binder, true); } else { bindNode(object, key, node, binder, evt, true); } return object; }; var bindNode = core.bindNode = function(object, key, node, binder, evt, optional) { if (!object || typeof object != 'object') return object; initMK(object); var isUndefined, $nodes, keys, i, j, special, indexOfDot, path, listenKey, changeHandler, domEvt, _binder, options, _options, mkHandler, foundBinder, _evt; /* * this.bindNode([['key', $(), {on:'evt'}], [{key: $(), {on: 'evt'}}]], { silent: true }); */ if (key instanceof Array) { for (i = 0; i < key.length; i++) { bindNode(object, key[i][0], key[i][1], key[i][2] || evt, node); } return object; } /* * this.bindNode('key1 key2', node, binder, { silent: true }); */ if (typeof key == 'string') { keys = key.split(/\s+/); if (keys.length > 1) { for (i = 0; i < keys.length; i++) { bindNode(object, keys[i], node, binder, evt, optional); } return object; } } /* * this.bindNode({ key: $() }, { on: 'evt' }, { silent: true }); */ if (typeof key == 'object') { for (i in key) { if (key.hasOwnProperty(i)) { bindNode(object, i, key[i], node, binder, evt); } } return object; } /* * this.bindNode('key', [ node, binder ], { silent: true }); */ if (node && node.length == 2 && !node[1].nodeName && (node[1].setValue || node[1].getValue || node[1].on)) { return bindNode(object, key, node[0], node[1], binder, evt); } indexOfDot = key.indexOf('.'); if (~indexOfDot) { path = key.split('.'); changeHandler = function(evt) { var target = evt && evt.value; if (!target) { target = object; for (var i = 0; i < path.length - 1; i++) { target = target[path[i]]; } } bindNode(target, path[path.length - 1], node, binder, evt, optional); if (evt && evt.previousValue) { core.unbindNode(evt.previousValue, path[path.length - 1], node); } }; core._delegateListener(object, path.slice(0, path.length - 2).join('.'), 'change:' + path[path.length - 2], changeHandler); changeHandler(); return object; } $nodes = core._getNodes(object, node); if (!$nodes.length) { if (optional) { return object; } else { throw Error('Binding error: node is missing for key "' + key + '".' + (typeof node == 'string' ? ' The selector is "' + node + '"' : '')); } } evt = evt || {}; special = core._defineSpecial(object, key); isUndefined = typeof special.value == 'undefined'; special.$nodes = special.$nodes.length ? special.$nodes.add($nodes) : $nodes; if (object.isMK) { if (key == 'sandbox') { object.$sandbox = $nodes; object.sandbox = $nodes[0]; } object.$nodes[key] = special.$nodes; object.nodes[key] = special.$nodes[0]; } if (key != 'sandbox') { for (i = 0; i < $nodes.length; i++) { initBinding($nodes[i]); } } if (!evt.silent) { _evt = { key: key, $nodes: $nodes, node: $nodes[0] || null }; for (i in evt) { _evt[i] = evt[i]; } core._fastTrigger(object, 'bind:' + key, _evt); core._fastTrigger(object, 'bind', _evt); } function initBinding(node) { var _binder, options = { self: object, key: key, $nodes: $nodes, node: node }; if (binder === null) { _binder = {}; } else { foundBinder = lookForBinder(node); if (foundBinder) { if (binder) { for (j in binder) { foundBinder[j] = binder[j]; } } _binder = foundBinder; } else { _binder = binder || {}; } } if (_binder.initialize) { _options = { value: special.value }; for (j in options) { _options[j] = options[j]; } _binder.initialize.call(node, _options); } if (_binder.setValue) { mkHandler = function(evt) { var v = object[sym].special[key].value; if (evt && evt.changedNode == node && evt.onChangeValue == v) return; _options = { value: v }; for (j in options) { _options[j] = options[j]; } _binder.setValue.call(node, v, _options); }; core._fastAddListener(object, '_runbindings:' + key, mkHandler); !isUndefined && mkHandler(); } if (_binder.getValue && (isUndefined && evt.assignDefaultValue !== false || evt.assignDefaultValue === true)) { _evt = { fromNode: true }; for (j in evt) { _evt[j] = evt[j]; } core.set(object, key, _binder.getValue.call(node, options), _evt); } if (_binder.getValue && _binder.on) { domEvt = { node: node, on: _binder.on, instance: object, key: key, mkHandler: mkHandler, handler: function(evt) { if (domEvt.removed) return; var oldvalue = object[key], value, j, _options = { value: oldvalue, domEvent: evt, originalEvent: evt.originalEvent || evt, preventDefault: function() { evt.preventDefault(); }, stopPropagation: function() { evt.stopPropagation(); }, which: evt.which, target: evt.target }; // hasOwnProperty is not required there for (j in options) { _options[j] = options[j]; } value = _binder.getValue.call(node, _options); if (value !== oldvalue) { core.set(object, key, value, { fromNode: true, changedNode: node, onChangeValue: value }); } } }; core.domEvents.add(domEvt); } } return object; }; });
vgrish/matreshka
src/core/bindings/bindnode.js
JavaScript
mit
6,701
'use strict'; import mongoose from 'mongoose'; // load models const Movie = mongoose.model('Movie'); export function getMovie(req, res, next) { Movie.find((err, movies) => { if (err) return next(err); res.render('index', { title: 'Movies!', movies }); }); }
gokultp/Course-Predictor
src/app/controllers/movies.server.controller.js
JavaScript
mit
288
import moment from 'moment-timezone'; class TimeService { /** * Returns the date in UTC-9 where the Destiny Daily Reset is at midnight. */ getCurrentDate() { let timestamp = moment.utc().subtract(9, 'hours'); return { month: timestamp.format('MMM'), day: timestamp.format('D'), year: timestamp.format('YYYY') }; } /** * Returns the current time in UTC and either PST or PDT. */ getCurrentTime() { const utc = moment.utc(); const pacific = moment.utc().tz('America/Los_Angeles'); return { utc: this.toDHM(utc), pacific: this.toDHM(pacific) }; } /** * Converts a UTC day, hour and minute to Pacific */ toPacific(utcDHM) { // parse UTC time const start = moment.utc().startOf('week'); start.add(utcDHM.day, 'days'); start.add(utcDHM.hour, 'hours'); start.add(utcDHM.minute, 'minutes'); // convert to Pacific return this.toDHM( start.tz('America/Los_Angeles')); } toDHM(moment) { return { day: moment.days(), hour: moment.hours(), minute: moment.minutes() }; } getCurrentDestinyWeek() { // calculate time in UTC-9 (where reset is at midnight) let timestamp = moment.utc().subtract(9, 'hours'); // ensure we are within the same week as the Sunday before the Weekly Reset if (timestamp.day() < 2) { timestamp.subtract(7, 'days'); } // get start and end of week timestamp.startOf('week').add(2, 'days'); return { tuesday: timestamp.format('MMM D'), wednesday: timestamp.add(1, 'days').format('MMM D'), thursday: timestamp.add(1, 'days').format('MMM D'), friday: timestamp.add(1, 'days').format('MMM D'), saturday: timestamp.add(1, 'days').format('MMM D'), sunday: timestamp.add(1, 'days').format('MMM D'), monday: timestamp.add(1, 'days').format('MMM D'), }; } now() { return moment.utc().format(); } since(utcTime) { let now = moment.utc(); let past = moment.utc(utcTime); return now.diff(past); } until(utcTime) { let now = moment.utc(); let future = moment.utc(utcTime); return future.diff(now); } formatDuration(totalMs) { let duration = moment.duration(totalMs); if (duration.days() > 0) { return `${duration.days()}d ${duration.hours()}h`; } return `${duration.hours()}h ${duration.minutes()}m`; } asDuration(utcTime) { let epoch = moment.unix(0); let timestamp = moment.utc(utcTime); let duration = moment.duration(timestamp.diff(epoch)); return { totalHours: Math.floor(duration.asHours()), minutes: duration.minutes() }; } }; export default new TimeService();
vivekhnz/today-in-destiny
src/services/time.js
JavaScript
mit
3,067
"use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError(CIRCULAR_RESOLUTION_ERROR); }; var reflect = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; var ASSERT = require("./assert.js"); var util = require("./util.js"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var UNDEFINED_BINDING = {}; var async = require("./async.js"); var errors = require("./errors.js"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {e: null}; var tryConvertToPromise = require("./thenables.js")(Promise, INTERNAL); var PromiseArray = require("./promise_array.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); var CapturedTrace = require("./captured_trace.js")(); var isDebugging = require("./debuggability.js")(Promise, CapturedTrace); /*jshint unused:false*/ var createContext = require("./context.js")(Promise, CapturedTrace, isDebugging); var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); var PromiseResolver = require("./promise_resolver.js"); var nodebackForPromise = PromiseResolver._nodebackForPromise; var errorObj = util.errorObj; var tryCatch = util.tryCatch; function Promise(resolver) { if (typeof resolver !== "function") { throw new TypeError(CONSTRUCT_ERROR_ARG); } if (this.constructor !== Promise) { throw new TypeError(CONSTRUCT_ERROR_INVOCATION); } //see constants.js for layout this._bitField = NO_STATE; //Since most promises have exactly 1 parallel handler //store the first ones directly on the object //The rest (if needed) are stored on the object's //elements array (this[0], this[1]...etc) //which has less indirection than when using external array this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._progressHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; //reason for rejection or fulfilled value this._settledValue = undefined; if (resolver !== INTERNAL) this._resolveFromResolver(resolver); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (typeof item === "function") { catchInstances[j++] = item; } else { return Promise.reject( new TypeError(NOT_ERROR_TYPE_OR_PREDICATE)); } } catchInstances.length = j; fn = arguments[i]; var catchFilter = new CatchFilter(catchInstances, fn, this); return this._then(undefined, catchFilter.doFilter, undefined, catchFilter, undefined); } return this._then(undefined, fn, undefined, undefined, undefined); }; Promise.prototype.reflect = function () { return this._then(reflect, reflect, undefined, this, undefined); }; Promise.prototype.thru = function(fn) { if (typeof fn !== "function") return apiRejection(NOT_FUNCTION_ERROR); return fn(this); }; Promise.prototype.then = function (didFulfill, didReject, didProgress) { if (isDebugging() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, didProgress, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject, didProgress) { var promise = this._then(didFulfill, didReject, didProgress, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (didFulfill, didReject) { return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); }; Promise.prototype.isCancellable = function () { return !this.isResolved() && this._cancellable(); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = function(fn) { var ret = new Promise(INTERNAL); var result = tryCatch(fn)(nodebackForPromise(ret)); if (result === errorObj) { ret._rejectCallback(result.e, true, true); } return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.defer = Promise.pending = function () { var promise = new Promise(INTERNAL); return new PromiseResolver(promise); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { var val = ret; ret = new Promise(INTERNAL); ret._fulfillUnchecked(val); } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") throw new TypeError(NOT_FUNCTION_ERROR); var prev = async._schedule; async._schedule = fn; return prev; }; Promise.prototype._then = function ( didFulfill, didReject, didProgress, receiver, internalData ) { ASSERT(arguments.length === 5); var haveInternalData = internalData !== undefined; var ret = haveInternalData ? internalData : new Promise(INTERNAL); if (!haveInternalData) { ret._propagateFrom(this, PROPAGATE_BIND | PROPAGATE_CANCEL); ret._captureStackTrace(); } var target = this._target(); if (target !== this) { if (receiver === undefined) receiver = this._boundTo; if (!haveInternalData) ret._setIsMigrated(); } var callbackIndex = target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver, getDomain()); if (target._isResolved() && !target._isSettlePromisesQueued()) { async.invoke( target._settlePromiseAtPostResolution, target, callbackIndex); } return ret; }; Promise.prototype._settlePromiseAtPostResolution = function (index) { ASSERT(typeof index === "number"); ASSERT(index >= 0); ASSERT(this._isFulfilled() || this._isRejected()); ASSERT(this._promiseAt(index) !== undefined); if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); this._settlePromiseAt(index); }; Promise.prototype._length = function () { ASSERT(arguments.length === 0); return this._bitField & LENGTH_MASK; }; Promise.prototype._isFollowingOrFulfilledOrRejected = function () { return (this._bitField & IS_FOLLOWING_OR_REJECTED_OR_FULFILLED) > 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & IS_FOLLOWING) === IS_FOLLOWING; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & LENGTH_CLEAR_MASK) | (len & LENGTH_MASK); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | IS_FULFILLED; }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | IS_REJECTED; }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | IS_FOLLOWING; }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | IS_FINAL; }; Promise.prototype._isFinal = function () { return (this._bitField & IS_FINAL) > 0; }; Promise.prototype._cancellable = function () { return (this._bitField & IS_CANCELLABLE) > 0; }; Promise.prototype._setCancellable = function () { this._bitField = this._bitField | IS_CANCELLABLE; }; Promise.prototype._unsetCancellable = function () { this._bitField = this._bitField & (~IS_CANCELLABLE); }; Promise.prototype._setIsMigrated = function () { this._bitField = this._bitField | IS_MIGRATED; }; Promise.prototype._unsetIsMigrated = function () { this._bitField = this._bitField & (~IS_MIGRATED); }; Promise.prototype._isMigrated = function () { return (this._bitField & IS_MIGRATED) > 0; }; Promise.prototype._receiverAt = function (index) { ASSERT(!this._isFollowing()); var ret = index === 0 ? this._receiver0 : this[ index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_RECEIVER_OFFSET]; //Only use the bound value when not calling internal methods if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { ASSERT(!this._isFollowing()); return index === 0 ? this._promise0 : this[index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_PROMISE_OFFSET]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { ASSERT(!this._isFollowing()); ASSERT(!this._isCarryingStackTrace()); return index === 0 ? this._fulfillmentHandler0 : this[index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_FULFILL_OFFSET]; }; Promise.prototype._rejectionHandlerAt = function (index) { ASSERT(!this._isFollowing()); return index === 0 ? this._rejectionHandler0 : this[index * CALLBACK_SIZE - CALLBACK_SIZE + CALLBACK_REJECT_OFFSET]; }; Promise.prototype._boundValue = function() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { ASSERT(!ret.isPending()); if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; }; Promise.prototype._migrateCallbacks = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var progress = follower._progressHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (promise instanceof Promise) promise._setIsMigrated(); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, progress, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, progress, promise, receiver, domain ) { ASSERT(typeof domain === "object"); ASSERT(!this._isFollowing()); var index = this._length(); if (index >= MAX_LENGTH - CALLBACK_SIZE) { index = 0; this._setLength(0); } if (index === 0) { ASSERT(this._promise0 === undefined); ASSERT(this._receiver0 === undefined); ASSERT(this._fulfillmentHandler0 === undefined || this._isCarryingStackTrace()); ASSERT(this._rejectionHandler0 === undefined); ASSERT(this._progressHandler0 === undefined); this._promise0 = promise; if (receiver !== undefined) this._receiver0 = receiver; if (typeof fulfill === "function" && !this._isCarryingStackTrace()) { this._fulfillmentHandler0 = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : domain.bind(reject); } if (typeof progress === "function") { this._progressHandler0 = domain === null ? progress : domain.bind(progress); } } else { ASSERT(this[base + CALLBACK_PROMISE_OFFSET] === undefined); ASSERT(this[base + CALLBACK_RECEIVER_OFFSET] === undefined); ASSERT(this[base + CALLBACK_FULFILL_OFFSET] === undefined); ASSERT(this[base + CALLBACK_REJECT_OFFSET] === undefined); ASSERT(this[base + CALLBACK_PROGRESS_OFFSET] === undefined); var base = index * CALLBACK_SIZE - CALLBACK_SIZE; this[base + CALLBACK_PROMISE_OFFSET] = promise; this[base + CALLBACK_RECEIVER_OFFSET] = receiver; if (typeof fulfill === "function") { this[base + CALLBACK_FULFILL_OFFSET] = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this[base + CALLBACK_REJECT_OFFSET] = domain === null ? reject : domain.bind(reject); } if (typeof progress === "function") { this[base + CALLBACK_PROGRESS_OFFSET] = domain === null ? progress : domain.bind(progress); } } this._setLength(index + 1); return index; }; Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { ASSERT(!this._isFollowing()); var index = this._length(); if (index >= MAX_LENGTH - CALLBACK_SIZE) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promiseSlotValue; this._receiver0 = receiver; } else { var base = index * CALLBACK_SIZE - CALLBACK_SIZE; this[base + CALLBACK_PROMISE_OFFSET] = promiseSlotValue; this[base + CALLBACK_RECEIVER_OFFSET] = receiver; } this._setLength(index + 1); }; Promise.prototype._proxyPromiseArray = function (promiseArray, index) { ASSERT(!this._isFollowing()); ASSERT(!this._isResolved()); ASSERT(arguments.length === 2); ASSERT(typeof index === "number"); ASSERT((index | 0) === index); this._setProxyHandlers(promiseArray, index); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (this._isFollowingOrFulfilledOrRejected()) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false, true); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); var propagationFlags = PROPAGATE_CANCEL | (shouldBind ? PROPAGATE_BIND : 0); this._propagateFrom(maybePromise, propagationFlags); var promise = maybePromise._target(); if (promise._isPending()) { var len = this._length(); for (var i = 0; i < len; ++i) { promise._migrateCallbacks(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (promise._isFulfilled()) { this._fulfillUnchecked(promise._value()); } else { this._rejectUnchecked(promise._reason(), promise._getCarriedStackTrace()); } }; Promise.prototype._rejectCallback = function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { if (!shouldNotMarkOriginatingFromRejection) { util.markAsOriginatingFromRejection(reason); } var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason, hasStack ? undefined : trace); }; Promise.prototype._resolveFromResolver = function (resolver) { ASSERT(typeof resolver === "function"); var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = tryCatch(resolver)(function(value) { if (promise === null) return; promise._resolveCallback(value); promise = null; }, function (reason) { if (promise === null) return; promise._rejectCallback(reason, synchronous); promise = null; }); synchronous = false; this._popContext(); if (r !== undefined && r === errorObj && promise !== null) { promise._rejectCallback(r.e, true, true); promise = null; } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { if (promise._isRejected()) return; ASSERT(!promise._isFollowingOrFulfilledOrRejected()); promise._pushContext(); var x; if (receiver === APPLY && !this._isRejected()) { x = tryCatch(handler).apply(this._boundValue(), value); } else { x = tryCatch(handler).call(receiver, value); } promise._popContext(); if (x === errorObj || x === promise || x === NEXT_FILTER) { var err = x === promise ? makeSelfResolutionError() : x.e; promise._rejectCallback(err, false, true); } else { promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { ASSERT(this._isFollowing()); ASSERT(this._rejectionHandler0 instanceof Promise); return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { ASSERT(this._isFollowing()); ASSERT(!(this._rejectionHandler0 instanceof Promise)); this._rejectionHandler0 = promise; }; Promise.prototype._cleanValues = function () { ASSERT(!this._isFollowing()); if (this._cancellable()) { this._cancellationParent = undefined; } }; Promise.prototype._propagateFrom = function (parent, flags) { if ((flags & PROPAGATE_CANCEL) > 0 && parent._cancellable()) { this._setCancellable(); this._cancellationParent = parent; } if ((flags & PROPAGATE_BIND) > 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } ASSERT((flags & PROPAGATE_TRACE) === 0); }; Promise.prototype._fulfill = function (value) { if (this._isFollowingOrFulfilledOrRejected()) return; this._fulfillUnchecked(value); }; Promise.prototype._reject = function (reason, carriedStackTrace) { if (this._isFollowingOrFulfilledOrRejected()) return; this._rejectUnchecked(reason, carriedStackTrace); }; Promise.prototype._settlePromiseAt = function (index) { var promise = this._promiseAt(index); var isPromise = promise instanceof Promise; if (isPromise && promise._isMigrated()) { promise._unsetIsMigrated(); return async.invoke(this._settlePromiseAt, this, index); } ASSERT(!this._isFollowing()); var handler = this._isFulfilled() ? this._fulfillmentHandlerAt(index) : this._rejectionHandlerAt(index); ASSERT(this._isFulfilled() || this._isRejected()); var carriedStackTrace = this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; var value = this._settledValue; var receiver = this._receiverAt(index); this._clearCallbackDataAtIndex(index); if (typeof handler === "function") { //if promise is not instanceof Promise //it is internally smuggled data if (!isPromise) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof PromiseArray) { if (!receiver._isResolved()) { if (this._isFulfilled()) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (this._isFulfilled()) { promise._fulfill(value); } else { promise._reject(value, carriedStackTrace); } } // Heuristic for promises that are stashed away somewhere // and might accumulate large index over time // The modulus is so that invokeLater is not called every time index // is over 4, but every 32nd time if (index >= 4 && (index & 31) === 4) async.invokeLater(this._setLength, this, 0); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { ASSERT(!this._isFollowing()); if (index === 0) { if (!this._isCarryingStackTrace()) { this._fulfillmentHandler0 = undefined; } this._rejectionHandler0 = this._progressHandler0 = this._receiver0 = this._promise0 = undefined; } else { var base = index * CALLBACK_SIZE - CALLBACK_SIZE; this[base + CALLBACK_PROMISE_OFFSET] = this[base + CALLBACK_RECEIVER_OFFSET] = this[base + CALLBACK_FULFILL_OFFSET] = this[base + CALLBACK_REJECT_OFFSET] = this[base + CALLBACK_PROGRESS_OFFSET] = undefined; } }; Promise.prototype._isSettlePromisesQueued = function () { return (this._bitField & IS_SETTLE_PROMISES_QUEUED) === IS_SETTLE_PROMISES_QUEUED; }; Promise.prototype._setSettlePromisesQueued = function () { this._bitField = this._bitField | IS_SETTLE_PROMISES_QUEUED; }; Promise.prototype._unsetSettlePromisesQueued = function () { this._bitField = this._bitField & (~IS_SETTLE_PROMISES_QUEUED); }; Promise.prototype._queueSettlePromises = function() { ASSERT(!this._isFollowing()); ASSERT(!this._isSettlePromisesQueued()); async.settlePromises(this); this._setSettlePromisesQueued(); }; Promise.prototype._fulfillUnchecked = function (value) { ASSERT(!this._isFollowingOrFulfilledOrRejected()); if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._rejectUnchecked(err, undefined); } this._setFulfilled(); this._settledValue = value; this._cleanValues(); if (this._length() > 0) { this._queueSettlePromises(); } }; Promise.prototype._rejectUncheckedCheckError = function (reason) { var trace = util.ensureErrorObject(reason); this._rejectUnchecked(reason, trace === reason ? undefined : trace); }; Promise.prototype._rejectUnchecked = function (reason, trace) { ASSERT(!this._isFollowingOrFulfilledOrRejected()); if (reason === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._rejectUnchecked(err); } this._setRejected(); this._settledValue = reason; this._cleanValues(); if (this._isFinal()) { ASSERT(this._length() === 0); async.throwLater(function(e) { if ("stack" in e) { async.invokeFirst( CapturedTrace.unhandledRejection, undefined, e); } throw e; }, trace === undefined ? reason : trace); return; } if (trace !== undefined && trace !== reason) { this._setCarriedStackTrace(trace); } if (this._length() > 0) { this._queueSettlePromises(); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._settlePromises = function () { this._unsetSettlePromisesQueued(); var len = this._length(); for (var i = 0; i < len; i++) { this._settlePromiseAt(i); } }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); require("./progress.js")(Promise, PromiseArray); require("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); require("./bind.js")(Promise, INTERNAL, tryConvertToPromise); require("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); require("./direct_resolve.js")(Promise); require("./synchronous_inspection.js")(Promise); require("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); Promise.Promise = Promise; };
kjvalencik/bluebird
src/promise.js
JavaScript
mit
25,033
import {Observable} from 'rxjs/Observable' Observable.prototype.groupByTimeout = function(properties) { const observable = new Observable(subscriber => { const source = this; let timeout = null; let stack = []; // subscribe to the source const subscription = source.subscribe(elm => { // add the element to stack stack.push(elm); // clear the timeout clearTimeout(timeout); // set a new timeout to wait next loop to // send the elements into the stream timeout = setTimeout(() => { // send the stack downward subscriber.next(stack); // clean stack stack = []; }); }, error => subscriber.error(error), () => subscriber.complete()); // make sure we return the subscription return subscription; }); // return the observable return observable; }
Coffeekraken/sugar
src/js/utils/rxjs/operators/groupByTimeout.js
JavaScript
mit
810
var webpack = require("webpack"), WebPackAngularTranslate = require("webpack-angular-translate"); module.exports = { entry: './app.js', output: { path: "dist", filename: "[name].js" }, module: { preLoaders: [ { test: /\.js$/, loader: WebPackAngularTranslate.jsLoader() }, { test: /\.html$/, loader: WebPackAngularTranslate.htmlLoader() } ], loaders: [ { test: /\.html$/, loader: 'html?removeEmptyAttributes=false&collapseWhitespace=false' } ] }, plugins: [ new WebPackAngularTranslate.Plugin() ] };
Kroid/webpack-angular-translate
example/webpack.config.js
JavaScript
mit
751
'use strict'; import {Dispatcher} from 'flux'; import EventEmitter from 'event-emitter'; import ACTIONS from './constants.js'; const CHANGE_EVENT = 'CHANGE_EVENT'; export const dispatcher = new Dispatcher(); /** * Example of a Store */ export function Store() { this.message = ''; this.theme = 'default'; this.eventEmitter = new EventEmitter({}); this.dispatchToken = dispatcher.register(this.onAction.bind(this)); } Store.prototype = { /** * Adds func as a listener for change events. * @param {Function} func - The function to add. */ onChange(func) { // add listener this.eventEmitter.on(CHANGE_EVENT, func); } /** * Removes func as a listener for change events. * @param {Function} func - The function to remove. */ , offChange(func) { // remove listener this.eventEmitter.off(CHANGE_EVENT, func); } /** * Triggers a change event, and calls all listeners. */ , emitChange() { this.eventEmitter.emit(CHANGE_EVENT); } /** * Called by dispatcher when an action method is called. * Unlike a pub-sub, this method is called for every action, not just * the actions it cares about. */ , onAction(action) { switch(action.type) { case ACTIONS.MESSAGE.CHANGE: this.message = action.message; this.emitChange(); break; case ACTIONS.THEME.CHANGE: this.message = `Action.setTheme('${action.theme}')`; this.theme = action.theme; this.emitChange(); break; } } }; /** * Actions provide a reliable way to dispatch events. * In reality they are just a wrapper around the dispatch call. * But the dispatch call just takes an object. It is difficult to document and * reason about. Wrapping them in action functions provides a form of documentation/spec. * The wrapping function can also do validation to make sure everything is correct before * dispatching. * * Actions are designed to be Fire and Forget. So callbacks (which are used in pub-sub) * are not allowed in Actions. * */ export const Actions = { /** * Set the message. * @param {String} message - the message to set. */ setMessage(message) { dispatcher.dispatch({ type: ACTIONS.MESSAGE.CHANGE , message: `Action.setMessage('${message}')` }); } /** * Set the theme * @param {String} theme - the theme to use. (default, success, etc) */ , setTheme(theme) { dispatcher.dispatch({ type: ACTIONS.THEME.CHANGE , theme: theme }); } }; /** * Try actions in the console! * This puts Actions in the global window namespace so you can play around with it. * In a production application you shouldn't do this, but it great for debugging/learning. */ window.Actions = Actions;
bev-a-tron/Workshops
ReactJS/src/flux/store.js
JavaScript
mit
2,764
module.exports = config => { const SAUCE = Boolean(process.env.SAUCE); const TRAVIS = Boolean(process.env.TRAVIS); const SAUCE_BROWSERS = { SL_Chrome: { base: 'SauceLabs', browserName: 'chrome', version: 'latest' }, SL_Firefox: { base: 'SauceLabs', browserName: 'firefox', version: 'latest' }, SL_Safari: { base: 'SauceLabs', browserName: 'safari', version: 'latest' }, SL_Edge: { base: 'SauceLabs', browserName: 'MicrosoftEdge', version: 'latest' }, SL_IE_11: { base: 'SauceLabs', browserName: 'internet explorer', version: '11' } }; config.set({ frameworks: ['jasmine', 'karma-typescript'], files: [ 'init.spec.ts', '{forms,polyfills,styles,src,templates,util}/**/*.ts' ], preprocessors: { '**/*.ts': 'karma-typescript' }, karmaTypescriptConfig: { bundlerOptions: { entrypoints: /\.spec\.ts$/, exclude: ['@polymer/polymer/interfaces'], transforms: [require('karma-typescript-es6-transform')()] }, compilerOptions: { lib: ['dom', 'es6'], module: 'commonjs', target: 'es5' }, coverageOptions: { exclude: [/\.(d|spec|test)\.ts$/i, /public_api/], instrumentation: !SAUCE }, reports: { html: 'coverage', 'text-summary': '' }, tsconfig: './tsconfig.json' }, sauceLabs: { testName: 'Origami Karma', startConnect: TRAVIS ? false : true, tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER }, client: { clearContext: false }, reporters: ['mocha', 'kjhtml', 'karma-typescript'], reportSlowerThan: 200, browsers: ['Chrome'], browserNoActivityTimeout: 60 * 1000, browserDisconnectTimeout: 10 * 1000, browserDisconnectTolerance: 1, captureTimeout: 4 * 60 * 1000, concurrency: 5, customLaunchers: { ...SAUCE_BROWSERS } }); if (SAUCE) { config.reporters.push('saucelabs'); config.set({ browsers: Object.keys(SAUCE_BROWSERS) }); } };
hotforfeature/origami
karma.conf.js
JavaScript
mit
2,148
define({ root: ({ settingsHeader : "Set the details for the GeoLookup Widget", settingsDesc : "Geo-enrich a list of locations from a CSV file against polygon layers on the map. Selected fields from polygon layers are appended to the locations.", settingsLoadingLayers: "Please wait while layers are loading.", settingsConfigureTitle: "Configure Layer Fields", layerTable : { colEnrich : "Enrich", colLabel : "Layer", colFieldSelector : "Fields" }, fieldTable : { colAppend : "Append", colName : "Name", colAlias : "Alias", colOrder : "Actions", label : "Check the fields you want to append. Select a field to update its alias and order." }, symbolArea : { symbolLabelWithin : 'Select the symbol for locations within:', symbolLabelOutside : 'Select the symbol for locations outside:' }, advSettings : { label: "Advanced Settings", latFieldsDesc : "Possible field names for Latitude field.", longFieldsDesc : "Possible field names for Longitude field.", intersectFieldDesc : "The name of the field created to store value if lookup intersected a layer.", intersectInDesc : "Value to store when location intersected a polygon.", intersectOutDesc : "Value to store when location did not intersect a polygon.", maxRowCount : "Maximum number of rows in CSV file.", cacheNumberDesc : "Point cluster threshold for faster processing.", subTitle : "Set values for CSV file." }, noPolygonLayers : "No Polygon Layers", errorOnOk : "Please fill out all parameters before saving config", saveFields : "Save Fields", cancelFields : "Cancel Fields", saveAdv : "Save Adv. Settings", cancelAdv : "Cancel Adv. Settings", advSettingsBtn : "Advanced Settings", chooseSymbol: "Choose a Symbol", okBtn: "OK", cancelBtn: "Cancel" }), "ar": 1, "cs": 1, "da": 1, "de": 1, "el": 1, "es": 1, "et": 1, "fi": 1, "fr": 1, "he": 1, "hr": 1, "it": 1, "ja": 1, "ko": 1, "lt": 1, "lv": 1, "nb": 1, "nl": 1, "pl": 1, "pt-br": 1, "pt-pt": 1, "ro": 1, "ru": 1, "sr": 1, "sv": 1, "th": 1, "tr": 1, "vi": 1, "zh-cn": 1, "zh-hk": 1, "zh-tw": 1 });
cmccullough2/cmv-wab-widgets
wab/2.2/widgets/GeoLookup/setting/nls/strings.js
JavaScript
mit
2,274
var webpack = require('webpack'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin; var path = require('path'); var DefinePlugin = webpack.DefinePlugin; var WebpackDevServer = require("webpack-dev-server"); var NODE_ENV = process.env.NODE_ENV || 'production'; var config = { entry : { main : [path.join(__dirname, '/src/main.js')] }, output : { path : path.join(__dirname, '/dist/assets'), filename : '[name].js', publicPath : './assets/' }, devtool : ((NODE_ENV==='development') ? 'source-map' : false), plugins : [ new HtmlWebpackPlugin({ title : '', template : path.join(__dirname, '/src/index.html'), inject : true, filename : '../index.html' }), new webpack.DefinePlugin({ 'process.env' : { NODE_ENV : JSON.stringify(NODE_ENV) } }), ], resolve : { extensions : ['', '.js', '.css'], alias : { 'root' : path.join(__dirname, '/src'), 'components' : path.join(__dirname, '/src/components'), 'styles' : path.join(__dirname, '/src/styles') } }, module : { loaders : [ { test : /\.js$/, loaders : ['react-hot', 'babel-loader'], include : path.join(__dirname, '/src') }, { test : /\.css$/, loaders : ['style', 'css'] } ] } } if (NODE_ENV === 'production') { config.plugins.push(new UglifyJsPlugin({ compress : { warnings : false }, sourcemap : false, mangle : true })); } else if (NODE_ENV === 'development') { config.entry.main.unshift('webpack/hot/only-dev-server'); config.entry.main.unshift('webpack-dev-server/client?http://0.0.0.0:3000'); config.plugins.push(new webpack.HotModuleReplacementPlugin()); } const compiler = webpack(config); if (NODE_ENV === 'development') { const server = new WebpackDevServer(compiler, { contentBase : path.join(__dirname, 'dist'), noInfo: false, quiet: false, lazy: false, hot: true, publicPath: './assets/', stats: { colors: true, chunks: false } }); server.listen(3000, 'localhost', function(){ console.log('Webpack Dev Server is listening on port 3000'); }); } else if (NODE_ENV === 'production') { compiler.run(function (err, stats) { if (err) throw err; console.log(stats.toString({ colors : true, chunks : false })); }); }
eniz/react-creditcard-input
demo/build.js
JavaScript
mit
2,783
/** * Create and manage routes on the server, by redirecting messages * to the correct module for a response. * * modules should be structured as follows: * * Module.js contains: * class Module { * constructor() { * ... * } * * doAction( messageObj ) { * * } * } */ class RouteServer { constructor( app ) { let rs = this; rs._app = app; rs._app.ws( '/', function ( ws, req ) { ws.on( 'message', function ( messageString ) { rs._receiveMessage( ws, messageString ); } ); } ); } /** * Process incoming messages from the frontend. * Expected format: * { * call_id: 'unique_id', * page_id: 'my_module', * data: { * action: 'do_something', * param1: 'important data', * param2: 2, * } * } * The format of the data parameter is defined in the module being requested. * * If the module responds to client message requests, the reply to the * client should contain the call_id parameter to trigger any callbacks * that are waiting for data from this request. */ _receiveMessage( ws, messageText ) { let messageObj = JSON.parse( messageText ); if( typeof( messageObj.page_id ) == undefined ) { throw new Error( "No page_id defined for action" ); } let customModule = require( './' + messageObj.page_id ); let mod = new customModule[ messageObj.page_id ]( ws ); if( typeof( mod.doAction ) != 'function' ) { throw new Error( "No doAction function for " + messageObj.page_id ); } mod.doAction( messageObj ); } } module.exports.RouteServer = RouteServer;
iPenguin/nodejs
server/routeserver.js
JavaScript
mit
1,802
const Box = x => ({ map: f => Box(f(x)), fold: f => f(x), inspect: () => `Box(${x})` }) const nextCharForNumberString = str => Box(str) .map(s => s.trim()) .map(s => new Number(s)) .map(i => i + 1) .map(s => String.fromCharCode(s)) .fold(c => c.toLowerCase()) const result = nextCharForNumberString(' 64 ') console.log(result);
rudijs/code-examples
javascript/functional/101-container-style-types.js
JavaScript
mit
349
var domTest = require("domtest"); // overriding default globals, which are ["$", "jQuery", "_"] domTest.defaultGlobals = ["$", "MyAwesomeObject"]; module.exports = domTest.testCase({ html: "base.htm", scripts: ["js/jquery.min.js", "js/myawesome.js"], setUp: function(callback) { // optional: do some set up stuff here... callback(); }, testjQuery: function(test) { // it loaded jQuery from the script tag in the HTML var title = this.$("h1").text() test.equals(title, "LOL I HAZ A CAT"); test.done(); }, testMyLibrary: function(test) { // it pulled MyAwesomeObject from the extra scripts var result = this.MyAwesomeObject.doIHazCat(); test.ok(result); test.done(); }, tearDown: function(callback) { // optional: undo what you did in setUp callback(); } });
joshmarshall/domtest
examples/tests/test_advanced.js
JavaScript
mit
901
define(function(require) { 'use strict'; const AbstractInputWidgetView = require('oroui/js/app/views/input-widget/abstract'); const $ = require('jquery'); const _ = require('underscore'); const __ = require('orotranslation/js/translator'); const tools = require('oroui/js/tools'); // current version: http://select2.github.io/select2/ // last version: http://select2.github.io/examples.html require('jquery.select2'); const Select2InputWidgetView = AbstractInputWidgetView.extend({ initializeOptions: { containerCssClass: 'oro-select2', dropdownCssClass: 'oro-select2__dropdown', placeholder: __('Please select'), dropdownAutoWidth: !tools.isMobile(), minimumInputLength: 0, minimumResultsForSearch: 7, adaptContainerCssClass: function(className) { const containerCssClass = this.initializeOptions.containerCssClass; if (!containerCssClass) { return false; } return className.indexOf(containerCssClass) === 0; } }, events: { 'select2-opening': 'disableKeyboard' }, widgetFunctionName: 'select2', destroyOptions: 'destroy', /** * @inheritDoc */ constructor: function Select2InputWidgetView(options) { Select2InputWidgetView.__super__.constructor.call(this, options); }, /** * @inheritDoc */ initialize: function(options) { // fix select2.each2 bug, when empty string is FALSE this.$el.attr('class', $.trim(this.$el.attr('class'))); Select2InputWidgetView.__super__.initialize.call(this, options); if (this.isInitialized()) { const data = this.$el.data(this.widgetFunctionName); data.container.data('inputWidget', this); data.dropdown.data('inputWidget', this); } this.updateFixedMode(); }, resolveOptions: function(options) { Select2InputWidgetView.__super__.resolveOptions.call(this, options); if (this.initializeOptions.adaptContainerCssClass) { this.initializeOptions.adaptContainerCssClass = _.bind( this.initializeOptions.adaptContainerCssClass, this ); } }, isInitialized: function() { return Boolean(this.$el.data(this.widgetFunctionName)); }, /** * Detects if the widget has a parent with fixed position, sets Select2 prop, and updates Select2 dropdown * position if it's needed * * @param {boolean} [updatePosition] */ updateFixedMode: function(updatePosition) { const select2Inst = this.$el.data(this.widgetFunctionName); const hasFixedParent = _.some(this.$el.parents(), function(el) { return $(el).css('position') === 'fixed'; }); if (hasFixedParent !== select2Inst.dropdownFixedMode) { select2Inst.dropdownFixedMode = hasFixedParent; if (updatePosition) { // use defer to avoid blinking of dropdown _.defer(select2Inst.positionDropdown.bind(select2Inst)); } } }, disposeWidget: function() { this.close(); return Select2InputWidgetView.__super__.disposeWidget.call(this); }, findContainer: function() { return this.$el.data(this.widgetFunctionName).container; }, open: function(...args) { return this.applyWidgetFunction('open', args); }, close: function(...args) { return this.applyWidgetFunction('close', args); }, val: function(...args) { const result = this.applyWidgetFunction('val', args); if (!args.length) { return result; } return this.$el; }, data: function(...args) { return this.applyWidgetFunction('data', args); }, updatePosition: function(...args) { return this.applyWidgetFunction('positionDropdown', args); }, focus: function(...args) { return this.applyWidgetFunction('focus', args); }, search: function(...args) { return this.applyWidgetFunction('search', args); }, disable: function(disable) { return this.applyWidgetFunction('enable', [!disable]); }, disableKeyboard: function() { const select = this.$el; const selectContainer = this.getContainer(); const isSearchHidden = selectContainer.find('.select2-search-hidden').length; const minimumResultsForSearch = this.initializeOptions.minimumResultsForSearch; const optionsLength = select.find('option').length; if (tools.isMobile() && (isSearchHidden || optionsLength < minimumResultsForSearch)) { selectContainer.find('.select2-search, .select2-focusser').hide(); } } }); return Select2InputWidgetView; });
orocrm/platform
src/Oro/Bundle/UIBundle/Resources/public/js/app/views/input-widget/select2.js
JavaScript
mit
5,367
class GameState extends Phaser.State { constructor(){ super(); this.timeCheck = 0; this.flipFlag = false; this.startList = []; this.squareList = []; this.masterCounter = 0; this.squareCounter = 0; this.square1Num; this.square2Num; this.savedSquareX1; this.savedSquareY1; this.savedSquareX2; this.savedSquareY2; this.map; this.tileset; this.layer; this.marker; this.currentTile; this.currentTilePosition; this.tileBack = 25; this.timesUp = '+'; this.youWin = '+'; this.myCountdownSeconds; } preload(){ this.game.load.tilemap('matching', 'phaser_tiles.json', null, Phaser.Tilemap.TILED_JSON); this.game.load.image('tiles', '/images/phaser_tiles.png');//, 100, 100, -1, 1, 1); } create() { this.map = this.add.tilemap('matching'); this.map.addTilesetImage('Desert', 'tiles'); this.layer = this.map.createLayer('Ground');//.tilemapLayer(0, 0, 600, 600, tileset, map, 0); this.marker = this.add.graphics(); this.marker.lineStyle(2, 0x00FF00, 1); this.marker.drawRect(0, 0, 100, 100); this.randomizeTiles(); } update(){ this.countDownTimer(); if (this.layer.getTileX(this.input.activePointer.worldX) <= 5) // to prevent the marker from going out of bounds { this.marker.x = this.layer.getTileX(this.game.input.activePointer.worldX) * 100; this.marker.y = this.layer.getTileY(this.game.input.activePointer.worldY) * 100; } if (this.flipFlag == true) { if (this.time.totalElapsedSeconds() - this.timeCheck > 0.5) { this.flipBack(); } } else { this.processClick(); } } render(){ this.game.debug.text(this.timesUp, 620, 208, 'rgb(0,255,0)'); this.game.debug.text(this.youWin, 620, 240, 'rgb(0,255,0)'); this.game.debug.text('Time: ' + this.myCountdownSeconds, 620, 15, 'rgb(0,255,0)'); this.game.debug.text('squareCounter: ' + this.squareCounter, 620, 272, 'rgb(0,0,255)'); this.game.debug.text('Matched Pairs: ' + this.masterCounter, 620, 304, 'rgb(0,0,255)'); this.game.debug.text('startList: ' + this.myString1, 620, 208, 'rgb(255,0,0)'); this.game.debug.text('squareList: ' + this.myString2, 620, 240, 'rgb(255,0,0)'); this.game.debug.text('Tile:'+ this.map.getTile(this.layer.getTileX(this.marker.x), this.layer.getTileY(this.marker.y)).index, 620, 48, 'rgb(255,0,0)'); this.game.debug.text('LayerX: ' + this.layer.getTileX(this.marker.x), 620, 80, 'rgb(255,0,0)'); this.game.debug.text('LayerY: ' + this.layer.getTileY(this.marker.y), 620, 112, 'rgb(255,0,0)'); this.game.debug.text('Tile Position: ' + this.currentTilePosition, 620, 144, 'rgb(255,0,0)'); this.game.debug.text('Hidden Tile: ' + this.getHiddenTile(), 620, 176, 'rgb(255,0,0)'); } //------------------------------------------------------------------------ getHiddenTile() { this.thisTile = this.squareList[this.currentTilePosition-1]; return this.thisTile; } flipOver() { this.map.putTile(this.currentNum, this.layer.getTileX(this.marker.x), this.layer.getTileY(this.marker.y)); } flipBack() { this.flipFlag = false; this.map.putTile(this.tileBack, this.savedSquareX1, this.savedSquareY1); this.map.putTile(this.tileBack, this.savedSquareX2, this.savedSquareY2); } processClick() { this.currentTile = this.map.getTile(this.layer.getTileX(this.marker.x), this.layer.getTileY(this.marker.y)); this.currentTilePosition = ((this.layer.getTileY(this.input.activePointer.worldY)+1)*6)-(6-(this.layer.getTileX(this.input.activePointer.worldX)+1)); if (this.input.activePointer.isDown) { // check to make sure the tile is not already flipped if (this.currentTile.index == this.tileBack) { // get the corresponding item out of squareList this.currentNum = this.squareList[this.currentTilePosition-1]; this.flipOver(); this.squareCounter++; // is the second tile of pair flipped? if (this.squareCounter == 2) { // reset squareCounter this.squareCounter = 0; this.square2Num = this.currentNum; // check for match if (this.square1Num == this.square2Num) { this.masterCounter++; if (this.masterCounter == 18) { // go "win" this.youWin = 'Got them all!'; } } else { this.savedSquareX2 = this.layer.getTileX(this.marker.x); this.savedSquareY2 = this.layer.getTileY(this.marker.y); this.flipFlag = true; this.timeCheck = this.time.totalElapsedSeconds(); } } else { this.savedSquareX1 = this.layer.getTileX(this.marker.x); this.savedSquareY1 = this.layer.getTileY(this.marker.y); this.square1Num = this.currentNum; } } } } countDownTimer() { var timeLimit = 120; this.mySeconds = this.time.totalElapsedSeconds(); this.myCountdownSeconds = this.timeLimit - this.mySeconds; if (this.myCountdownSeconds <= 0) { this.timesUp = 'Time is up!'; } } randomizeTiles() { let num; for (num = 1; num <= 18; num++) { this.startList.push(num); } for (num = 1; num <= 18; num++) { this.startList.push(num); } // for debugging this.myString1 = this.startList.toString(); let i; // randomize squareList for (i = 1; i <=36; i++) { let randomPosition = this.rnd.integerInRange(0,this.startList.length - 1); let thisNumber = this.startList[ randomPosition ]; this.squareList.push(thisNumber); let a = this.startList.indexOf(thisNumber); this.startList.splice( a, 1); } this.myString2 = this.squareList.toString(); let col,row; for (col = 0; col < 6; col++) { for (row = 0; row < 6; row++) { this.map.putTile(this.tileBack, col, row); } } } } export default GameState;
eleiva/phaser-matchingpairs-es6
src/states/GameState.js
JavaScript
mit
6,228
var fs = require('fs'), http = require('http'), https = require('https'), httpProxy = require('http-proxy'); httpProxy.createServer({ target: { host: 'localhost', port: 3000 }, ssl: { key: fs.readFileSync('ssl.key', 'utf8'), cert: fs.readFileSync('ssl2.crt', 'utf8') } }).listen(443); http.createServer(function(req, res) { res.writeHead(302, {'Location': 'https://caitdestiny.com' + req.url}); res.end(); }).listen(80);
codyromano/destiny
src/proxy.js
JavaScript
mit
461
/*jslint browser: true, white: true, eqeq: true, plusplus: true, sloppy: true, vars: true*/ /*global $, console, alert, FormData, FileReader*/ function noPreview() { $('#image-preview-div').css("display", "none"); $('#preview-img').attr('src', 'noimage'); $('upload-button').attr('disabled', ''); } function selectImage(e) { $('#file').css("color", "green"); $('#image-preview-div').css("display", "block"); $('#preview-img').attr('src', e.target.result); $('#preview-img').css('max-width', '250px'); } $(document).ready(function (e) { var path = Routing.generate('upload_image_asociado', true); var maxsize = 500 * 1024; // 500 KB $('#max-size').html((maxsize/1024).toFixed(2)); $('#upload-image-form').on('submit', function(e) { e.preventDefault(); $('#message').empty(); $('#loading').show(); $.ajax({ url: path, type: "POST", data: new FormData(this), contentType: false, cache: false, processData: false, success: function(data) { $('#loading').hide(); $('#message').html(data); } }); }); $('#file').change(function() { $('#message').empty(); var file = this.files[0]; var match = ["image/jpeg", "image/png", "image/jpg"]; if ( !( (file.type == match[0]) || (file.type == match[1]) || (file.type == match[2]) ) ) { noPreview(); $('#message').html('<div class="alert alert-warning" role="alert">Unvalid image format. Allowed formats: JPG, JPEG, PNG.</div>'); return false; } if ( file.size > maxsize ) { noPreview(); $('#message').html('<div class=\"alert alert-danger\" role=\"alert\">The size of image you are attempting to upload is ' + (file.size/1024).toFixed(2) + ' KB, maximum size allowed is ' + (maxsize/1024).toFixed(2) + ' KB</div>'); return false; } $('#upload-button').removeAttr("disabled"); var reader = new FileReader(); reader.onload = selectImage; reader.readAsDataURL(this.files[0]); }); });
jotaseme/Cecofersa
web/js/upload-image.js
JavaScript
mit
2,250
import { debounce, throttle } from 'lodash'; import ConfigStorageService from "./storage/ConfigStorageService"; import SyncStorageService from "./storage/SyncStorageService"; const clrearLoadTimeHeight = function () { document.body.style.height = null; document.body.removeEventListener("mouseenter", clrearLoadTimeHeight); }; // clears the temporary height of page used to scroll before the page render document.body.addEventListener("mouseenter", clrearLoadTimeHeight); const updateScroll = debounce(() => { ConfigStorageService.getConfig().then(config => { config.scrollyoffset = window.pageYOffset || 0; // saves the current height of page to be able to scroll on load before render the page config.scrollpageheight = document.getElementById("bhroot").offsetHeight; SyncStorageService.updateData(config); }); }, 300); class ScrollService { /** * Start watching for scroll changes and saves it on config. */ static watchScrollChange() { window.addEventListener("scroll", updateScroll); window.addEventListener("resize", updateScroll); } /** * Loads saved scrollposition from storage. */ static loadScrollPosition() { return ConfigStorageService.getConfig().then(config => { const position = config.scrollyoffset || 0; const height = config.scrollpageheight || 0; // temporally sets body height to the last saved height to be able to scroll before the page render document.body.style.height = height + "px"; window.scrollTo(0, position); }); } } export default ScrollService;
emfmesquita/beyondhelp
src/services/ScrollService.js
JavaScript
mit
1,668
/** * @class Tools * DEPRECATED - this is used only on the locus page. - move locus specific functions to Locus.js * Some functions may be made generic for use with other phenome objects, such as stocks. * The individual page is deprecated, and future pages should use * CXGN.AJAX.Ontology which is more generic * Function used in phenome pages * @author Naama Menda <nm249@cornell.edu> * */ JSAN.use('CXGN.Effects'); JSAN.use('CXGN.Phenome.Locus'); JSAN.use('CXGN.AJAX.Ontology'); JSAN.use('Prototype'); JSAN.use('jquery'); JSAN.use('jqueryui'); JSAN.use('popup'); var Tools = { //Find the selected sgn users from the locus select box and call and AJAX request to find the corresponding user type getUsers: function(user_info) { if (user_info.length==0) { var select = $('user_select'); $('associate_button').disabled = true; } else { new Ajax.Request("/phenome/assign_owner.pl", { parameters: {user_info: user_info}, onSuccess: function(response) { var select = $('user_select'); //disable the button until an option is selected $('associate_button').disabled=true; var responseText = response.responseText; var responseArray = responseText.split("|"); //last element of array is empty. dont want this in select box responseArray.pop(); select.length = responseArray.length; for (i=0; i < responseArray.length; i++) { var userObject = responseArray[i].split("*"); if (typeof(userObject[1]) != "undefined"){ select[i].value = userObject[0]; select[i].text = userObject[1]; } } }, } ); } }, //Logic on when to enable a button enableButton: function(my_button) { $(my_button).disabled=false; }, //Logic on when to disable a button disableButton: function(my_button) { $(my_button).disabled=true; }, assignOwner: function(object_id, object_type) { var sp_person_id = $('user_select').value; new Ajax.Request("/phenome/assign_owner.pl", {parameters: ///move to /ajax/locus/assign_owner {sp_person_id: sp_person_id, object_id: object_id, object_type: object_type}, onSuccess: window.location.reload() } ); }, /////////////////////// reloadPage: function() { window.location.reload(); }, /////////////////////////////////////////////// getOrganisms: function() { jQuery.ajax( { type: 'GET', url: "/ajax/locus/organisms/", dataType: "json", async: false, success: function(response) { if ( response.error ) { alert(response.error) ; } var responseArray = response.html; var select = document.getElementById('organism_select'); select.length = 0; select.length = responseArray.length + 1; select[0].text = '--select--'; for (i=1; i < responseArray.length; i++) { select[i].value = responseArray[i]; select[i].text = responseArray[i]; } }, error: function(response) { alert("an error occurred"); } }); }, ///////////////////////////////////////////////////////////////////////////////////////// //DEPRECATED - still used in add_publication.pl! //Make an ajax response that obsoletes the selected ontology term-locus association obsoleteAnnot: function(type, type_dbxref_id) { var action= 'obsolete'; new Ajax.Request('/phenome/obsolete_object_dbxref.pl', {parameters: {object_dbxref_id: type_dbxref_id, type: type, action: action}, onSuccess: function(response) { var json = response.responseText; var x = eval ("("+json+")"); if (x.error) { alert(x.error); } else { window.location.reload() ; } }, onFailure: function(response) { alert("Failed obsoleting annotation for " + type) ; var json = response.responseText; //var x = jQuery.parseJSON( json ); var x = eval("("+json+")"); //alert (x); }, }); }, //Make an ajax response that unobsoletes the selected ontology term-locus association //this is also used in add_publication.pl - need to refactor. unobsoleteAnnot: function(type, type_dbxref_id) { var action = 'unobsolete'; new Ajax.Request('/phenome/obsolete_object_dbxref.pl', { method: 'get', parameters: {object_dbxref_id: type_dbxref_id, type: type, action: action}, onSuccess: function(response) { var json = response.responseText; var x = eval ("("+json+")"); if (x.error) { alert(x.error); } else { window.location.reload() ; } }, onFailure: function(response) { alert("Failed unobsoleting annotation for " + type) ; var json = response.responseText; //var x = jQuery.parseJSON( json ); var x = eval("("+json+")"); alert (x); }, }); }, ///////////////////////// //toggle function. For toggling a collapsed section + a hidden ajax form. //This function will display correctly the form and the span contents. toggleContent: function(form,span,style) { if (!style) { style = 'inline'; } var content= span + "_content"; var onswitch= span + "_onswitch"; var offswitch= span + "_offswitch"; var form_disp = document.getElementById(form).style.display; var content_disp = document.getElementById(content).style.display; Effects.showElement(content); Effects.swapElements(onswitch,offswitch); if (form_disp == 'none') { //form is hidden, display both elements and change button to '-' Effects.showElement(form); }else if (content_disp != 'none' ){ // form is visible. If content is hidden, open the span, but keep form open Effects.hideElement(form); } }, //Make an ajax response that obsoletes the selected ontology term-locus association toggleObsoleteAnnotation: function(obsolete, id, obsolete_url, ontology_url) { new Ajax.Request(obsolete_url, { method: 'post', parameters: {id: id , obsolete: obsolete }, onSuccess: function(response) { var json = response.responseText; var x =eval ("("+json+")"); //var e = $("locus_ontology").innerHTML=x.response; //this should update the locus_ontology div if ( x.error ) { alert(x.error) ; } } }); Ontology.displayOntologies("ontology" , ontology_url); }, }
solgenomics/sgn
js/source/legacy/CXGN/Phenome/Tools.js
JavaScript
mit
7,224
'use strict'; // Development specific configuration // ================================== module.exports = { // MongoDB connection options mongo: { uri: 'mongodb://localhost/awesomex-dev' }, //seedDB: true };
pinoytech/awesomex
server/config/environment/development.js
JavaScript
mit
223
const TYPE = '@type' function typeName (t) { return t && t.slice(t.lastIndexOf(':') + 1) } function suggest (type) { switch (type) { case 'Person': return ['schema:name', 'schema:address'] case 'LocalBusiness': case 'Organization': return ['schema:name', 'schema:vatID', 'schema:address', 'schema:founder'] case 'PostalAddress': return ['schema:name', 'schema:streetAddress', 'schema:addressLocality', 'schema:postalCode', 'schema:addressCountry'] case 'Invoice': return ['schema:name', 'schema:description', 'schema:dateCreated', 'schema:paymentDueDate', 'schema:paymentMethod', 'schema:provider', 'schema:customer', 'schema:referencesOrder'] } return ['schema:name', 'schema:description', 'schema:url'] } export function toStub (fragment) { const type = fragment && fragment[TYPE] ? typeName(fragment[TYPE]) : 'Thing' const keys = Object.keys(fragment) return suggest(type).filter(function (key) { return keys.indexOf(key) === -1 }) }
thgh/ld3
src/libs/stub.js
JavaScript
mit
1,005
// ################# // // Copyright (c) 2012-2013 Micha Reischuck and John Carragher // // mySongs is available under the terms of the MIT license. // The full text of the MIT license can be found in the LICENSE file included in this package. // // ################# enyo.kind({ name: "SongView", kind: "FittableRows", classes: "enyo-fit", // Properties defaultSongSecs: 200, // seconds for song songSecs: this.defaultSongSecs, scrollTimeout: 0, running: false, lyricsCurrRow: 0, perRowMSecs: 0, halfHt: 0, rowsTraversed: 0, cursorRow: 0, initTime: 0, currIntDate: 0, currTime: 0, diffTime: 0, reqPrms: 0, prevRow: 0, tapTimer: undefined, tapTimer2: undefined, tapTimer3: undefined, textIndex: 0, scroll: 0, transpose: 0, order: [], fullscreen: false, lang: undefined, finished: true, dur: ["Ab", "A", "Bb", "B", "C", "C#", "Db", "D", "D#", "Eb", "E", "F", "F#", "Gb", "G", "G#"], moll: ["Abm", "Am", "Bbm", "Bm", "Cm", "C#m", "Dbm", "Dm", "D#m", "Ebm", "Em", "Fm", "F#m", "Gbm", "Gm", "G#m"], transposeList: [], published: { file: "", data: {}, xml: undefined, first: true, // Prefs showPrefs: { sortLyrics: true, showinToolbar: "copyright", showChords: true, showComments: false, showName: true, showTransposer: true, showPrint: false, showScroll: true, showAuto: true, scrollToNext: true } }, components: [ {kind: "Signals", onkeydown: "handleKeyPress"}, // Drawer for Phone Title and Copyright !! {name: "titleDrawer", kind: "onyx.Drawer", open: false, classes: "searchbar hochk", components: [ {style: "color: #fff; padding: .5rem; background-color: rgba(0,0,0,0.6); text-align: center;", ontap: "closeTitle", components: [ {name: "titleText", classes: "title", allowHtml: true}, ]} ]}, {name: "headerToolbar", kind: "onyx.Toolbar", ondragfinish: "titleDragFinish", components: [ {name: "titlefit", kind: "FittableColumns", style: "width: 100%; margin: 0; padding: 0;", components: [ {fit: true, components: [ {name: "title", classes: "title quer", style: "line-height: 2rem;", allowHtml: true} ]}, {kind: "FittableColumns", components: [ {name: "languagegr", kind: "Group", defaultKind: "onyx.IconButton", onActivate: "toggleLang"}, {name: "trSpacer", kind: "my.Spacer", showing: false}, {name: "transposergr", kind: "FittableColumns", components: [ {name: "transminus", kind: "onyx.IconButton", src: Helper.iconPath()+"minus.png", style: "width: 1.25rem;", ontap: "transMinus", disabled: true}, {name: "transposer", kind: "onyx.Button", classes: "reintext-button", style: "width: " + (Helper.phone() ? 3.5 : 5) + "rem; margin-top: -.125rem !important", ontap: "transButton"}, {kind: "onyx.IconButton", name: "transplus", src: Helper.iconPath()+"plus.png", style: "width: 1.25rem;", ontap: "transPlus", disabled: true}, {kind: "my.Spacer"} ]}, //~ {name: "lockButton", kind: "onyx.IconButton", toggling: true, icon: "images/lock-open.png", onclick: "toggleLock"}, {name: "fontButton", kind: "onyx.IconButton", src: Helper.iconPath()+"font.png", ontap: "showFontDialog"}, {name: "prefsButton", kind: "onyx.IconButton", src: Helper.iconPath()+"prefs.png", ontap: "showMenu"} ]} ]} ]}, {name:"transposePanels", kind: "Panels", fit: true, arrangerKind: "CollapsingArranger", draggable: false, components: [ {name: "viewIncScrollBar", kind: "FittableColumns", fit: true, classes:"app-panels inner-panels", components: [ {name: "cursorScrollBar", kind: "cursorScrollBar", ontap: "cursorTapHandler", classes: "cursor"}, {name: "viewScroller", kind: "enyo.Scroller", classes: "michote-scroller", horizontal: "hidden", fit: true, components: [ {name: "lyric", ondragfinish: "songDragFinish", ontap: "onDoubleTap"} ]} ]}, {name: "transposeList", kind: "List", touch: true, count: 16, style: "height: 100%; min-width: 4rem; max-width: 4rem; visibility: hidden;", classes: "side-pane", onSetupItem: "getTranspose", components: [ {name: "transposeListItem", ontap: "transposeTab", components: [ {name: "transposeListTitle", classes: "item"} ]} ]}, ]}, {name: "footerToolbar", kind: "onyx.Toolbar", pack: "center", components: [ {kind: "FittableColumns", style: "width: 100%; margin: 0; padding: 0;", components: [ {kind: "FittableColumns", classes: "side", components: [ {kind: "my.Grabber", ontap: "grabber"}, {name: "copy", classes: "title copy quer", fit: true, content: "&copy; michote", style: "padding: .3125rem 0;", allowHtml: true} ]}, {kind: "FittableColumns", classes: "middle", components: [ {name: "backButton", kind: "onyx.IconButton", disabled: true, src: Helper.iconPath()+"back.png", ontap: "textBack"}, {style: "width: " + (Helper.phone() ? .75 : 2) + "rem;"}, {name: "forthButton", kind: "onyx.IconButton", disabled: true, src: Helper.iconPath()+"forth.png", ontap: "textForth"} ]}, {name: "buttonfit", kind: "FittableColumns", classes: "side", stlye: "text-align: right;", components: [ {name: "playButton", kind: "onyx.IconButton", toggling: true, src: Helper.iconPath()+"play.png", ontap: "togglePlay"}, {fit: true}, {name: "printButton", kind: "onyx.IconButton", src: Helper.iconPath()+"print.png", ontap: "print", showing: Helper.browser()}, {name: "editButton", kind: "onyx.IconButton", src: Helper.iconPath()+"edit.png", ontap: "openEdit"}, {name: "infoButton", kind: "onyx.IconButton", src: Helper.iconPath()+"info.png", ontap: "showInfo"} ]} ]} ]} ], create: function() { this.inherited(arguments); }, showPrefsChanged: function() { if (this.xml) { this.renderLyrics(); } else { this.buttons(); } }, buttons: function() { this.log("redraw buttons"); this.$.backButton.setShowing(this.showPrefs.showScroll); this.$.forthButton.setShowing(this.showPrefs.showScroll); this.$.transposergr.setShowing(this.showPrefs.showTransposer); this.$.playButton.setShowing(this.showPrefs.showAuto); this.$.printButton.setShowing(Helper.browser() ? this.showPrefs.showPrint : false); this.$.buttonfit.resized(); }, start: function() { this.renderLyrics(); this.initCursor(); }, renderLyrics: function() { this.xml = this.owner.owner.dataList[this.file.toLowerCase()]; this.lang = undefined; this.log("render lyrics of", this.file); this.buttons(); this.$.transposeList.applyStyle("visibility", "hidden"); var transposition = ParseXml.get_metadata(this.xml, "transposition"); if (transposition && this.first) { this.transpose = parseInt(transposition); this.first = false; } else if (this.first) { this.transpose = 0; this.first = false; } else { this.first = false; } this.data = ParseXml.parse(this.xml, this.showPrefs.showChords, this.showPrefs.showComments, this.transpose); this.log("get data"); if (this.data.titles !== undefined) { this.textIndex = 0; // reset index this.scroll = 0; // reset scroller // Languages this.$.languagegr.destroyClientControls(); this.$.trSpacer.hide(); if (this.data.haslang[0]) { this.createLangToggle(this.data.haslang); this.$.trSpacer.show(); this.$.languagegr.render(); } // render data this.metaDataSet(); this.lyricDataSet(); // Buttons this.enableTransposer(this.data.key, this.data.haschords, this.transpose); if (this.finished) { // auto-scroll not active this.$.editButton.setDisabled(false); this.$.printButton.setDisabled(false); this.$.backButton.setDisabled(true); if (this.data.verseOrder && (this.textIndex === (this.data.verseOrder.length-1))) { this.$.forthButton.setDisabled(true); } else { this.$.forthButton.setDisabled(false); } } } this.$.titlefit.resized(); }, // ### Transposer ### getTranspose: function(inSender, inEvent) { var r = this.transposeList[inEvent.index]; var isRowSelected = inSender.isSelected(inEvent.index); this.$.transposeListItem.addRemoveClass("item-selected", isRowSelected); this.$.transposeListItem.addRemoveClass("item-not-selected-trans", !isRowSelected); this.$.transposeListTitle.setContent(r); }, enableTransposer: function(key, chords, transp) { if (key && chords) { this.log("enable Transposer"); this.$.transminus.setDisabled(false); this.$.transplus.setDisabled(false); this.transposeList = (key.charAt(key.length-1) === "m") ? this.moll : this.dur; this.$.transposeList.reset(); for (i in this.transposeList) { if (this.transposeList[i] === key) { this.$.transposeList.select(i); } } this.$.transposer.setContent(transp ? Transposer.transpose(key, transp) : key); this.$.transposer.show(); } else if (!key && chords) { this.log("enable Transposer without key"); this.$.transminus.setDisabled(false); this.$.transplus.setDisabled(false); this.$.transposer.hide(); } else { this.$.transminus.setDisabled(true); this.$.transplus.setDisabled(true); this.$.transposer.hide(); } }, transButton: function() { this.$.transposeList.applyStyle("visibility", "visible"); }, transposeTab: function(inSender, inEvent) { this.setTrans(Transposer.getDelta(this.data.key, this.transposeList[inEvent.rowIndex])); this.$.transposeList.applyStyle("visibility", "hidden"); }, setTrans: function(value) { if (value > 11) { value -= 12; } else if (value < -11) { value += 12; } this.log(value); this.transpose = value; this.renderLyrics(); }, transPlus: function() { this.setTrans(this.transpose += 1); }, transMinus: function() { this.setTrans(this.transpose -= 1); }, transPick: function() { this.setTrans(Transposer.getDelta(this.data.key, this.$.transposer.getValue())); }, // ### Language Toggle ### createLangToggle: function(l) { for (i in l) { this.addLangToggle(l[i]); } this.lang ? this.lang : this.lang = l[0]; this.$[this.lang].setActive(true); }, addLangToggle: function(l) { this.log("add", l, "toggle"); this.$.languagegr.createComponent( {name: l, kind: "onyx.IconButton", src: Helper.iconPath()+"flag.png", owner: this, components: [ {content: l, classes: "flag-button"} ]} ); }, toggleLang: function(inSender, inEvent) { if (inEvent.originator.getActive()) { this.log("The \"" + inEvent.originator.name + "\" radio button is selected."); this.lang = inEvent.originator.name; this.metaDataSet(); this.lyricDataSet(); } }, // ### set Data ### metaDataSet: function() { this.log(); var d = this.data; //~ format and set title var t = ParseXml.titlesToString(d.titles, this.lang); this.$.title.setContent(t); //~ format and set copyright var y = (d.released ? d.released + ": " : ""); // add release year var copy = ""; if (d[this.showPrefs.showinToolbar]) { copy = (this.showPrefs.showinToolbar === "authors" ? y + ParseXml.authorsToString(d.authors).join(", ") : "&copy; " + y + d[this.showPrefs.showinToolbar]); } else { copy = "&copy; " + y + $L("no" + this.showPrefs.showinToolbar); } this.$.copy.setContent(copy); this.$.titleText.setContent('<big><b>' + t + '</b></big><br><small>' + copy + '</small>'); }, lyricDataSet: function() { this.order = (this.lang ? Helper.orderLanguage(this.data.verseOrder, this.lang) : this.data.verseOrder); this.$.lyric.destroyClientControls(); var d = this.data; //~ format and set lyrics if (d.lyrics) { var lyrics = ""; if (d.lyrics === "nolyrics") { lyrics = $L(d.lyrics); } else if (d.lyrics === "wrongversion") { lyrics = $L(d.lyrics); } else { if (this.showPrefs.sortLyrics) { //~ display lyrics like verseOrder var formL = Helper.orderLyrics(d.lyrics, this.order, this.lang); this.order = Helper.handleDoubles(this.order); } else { //~ display lyrics without verseOrder var formL = d.lyrics; } // Create lyric divs for (var i in formL) { this.log("create element ", i); if (this.showPrefs.showName) { var t = $L(formL[i][0].charAt(0)).charAt(0) + formL[i][0].substring(1, formL[i][0].length) + ":"; this.$.lyric.createComponent({ name: i, kind: "FittableColumns", fit: true, classes: Helper.phone() ? "lyric lyricmar-phone" : "lyric lyricmar", components: [ {content: t, classes: "element", style: "width: 2em;"}, {content: formL[i][1], fit: true, allowHtml: true} ]}, {owner: this}); } else { this.$.lyric.createComponent({ name: i, classes: Helper.phone() ? "lyric lyricmar-phone" : "lyric lyricmar", components: [ {content: formL[i][1], allowHtml: true} ]}, {owner: this}); } if (Helper.browser) { // needed for printing this.$.lyric.createComponent({ classes: "pageBreak" }); } } } this.$.lyric.render(); // Scroll Spacer if (this.$.lyric.node.lastChild) { var x = this.$.lyric.node.lastChild.clientHeight; var h = window.innerHeight-138-x; if (h > 0) { this.$.lyric.createComponent({ name: "scrollspacer", style: "height:" + h + "px;width:100%;", classes: "scrollspacer" }); } } } this.$.lyric.render(); }, // ### Autoscroll ### togglePlay: function() { this.log(); this.tapTimer2 = undefined; // for tap handler if (this.$.playButton.src === Helper.iconPath()+"play.png") { // play if (this.lyricsCurrRow !== 0) { // paused this.running = true; this.resetStartTime(); this.showLyrics(false); } else { // begining to play this.initForTextPlay(); this.$.cursorScrollBar.cursorOn(); this.running = true; this.finished = false; this.perRowMSecs = 1000*this.songSecs/this.rowsTraversed; this.log("Require to scroll a row per", this.perRowMSecs, "mSecs. duration", this.songSecs); this.resetStartTime(); this.showLyrics(true); } this.$.playButton.set("src", Helper.iconPath()+"pause.png"); this.$.forthButton.setDisabled(false); this.$.forthButton.setDisabled(true); this.$.backButton.setDisabled(true); this.$.printButton.setDisabled(true); } else { //pause this.$.playButton.set("src", Helper.iconPath()+"play.png"); this.running = false; if (this.finished) { this.initCursor(); if (this.showPrefs.scrollToNext) { this.nextSong(); } } } }, movingLyrics: function() { //this.log(); if ((this.lyricsCurrRow > this.halfHt) && (this.lyricsCurrRow < (this.rowsTraversed - this.halfHt))) { return true; } else { return false; } }, cursorTapHandler: function(inSender, inEvent) { if (this.tapTimer2 === undefined) { //this.log("single tap"); this.tapTimer2 = window.setTimeout(enyo.bind(this, this.togglePlay), 300); } else if (this.running && this.tapTimer3 === undefined) { // double tap //this.log("double tap"); window.clearTimeout(this.tapTimer2); this.tapTimer2 = undefined; this.tapTimer3 = window.setTimeout(enyo.bind(this, this.undefTimer3), 200); // debounce double tap this.resetCursorTiming(inEvent); } return false; }, undefTimer3: function () { this.tapTimer3 = undefined; }, resetStartTime: function() { this.currIntDate = new Date(); this.currTime = this.currIntDate.getTime(); this.initTime = this.currTime - this.diffTime; this.prevRow = this.lyricsCurrRow - 1; }, resetCursorTiming: function(inEvent) { // adjust the position of the cursor var yAdj = inEvent.clientY - this.$.headerToolbar.getBounds().height - this.cursorRow; var lyricsPrevRow = this.lyricsCurrRow; // save for later this.lyricsCurrRow = this.lyricsCurrRow + yAdj; if (this.lyricsCurrRow < this.halfHt) { this.cursorRow = this.lyricsCurrRow; } else if (this.lyricsCurrRow > (this.rowsTraversed - this.halfHt)) { this.cursorRow = 2 * this.halfHt - (this.rowsTraversed - this.lyricsCurrRow); this.$.viewScroller.setScrollTop(this.lyricsCurrRow - this.cursorRow); } else { this.cursorRow = this.halfHt; } this.$.cursorScrollBar.setY(this.cursorRow); // now adjust the speed of the cursor. this.songSecs = this.songSecs * lyricsPrevRow / this.lyricsCurrRow; window.clearTimeout(this.scrollTimeout); this.perRowMSecs = 1000*this.songSecs/this.rowsTraversed; this.diffTime = this.perRowMSecs * this.lyricsCurrRow; this.resetStartTime(); // this.log("Now a row per", this.perRowMSecs, "mSecs. Duration", this.songSecs); this.showLyrics(false); if (this.data.titles) { var theTitles = ParseXml.titlesToString(this.data.titles); } this.$.title.setContent(theTitles + " (" + Math.floor(this.songSecs) + " secs)"); }, showLyrics: function(init) { if (this.running) { if (this.lyricsCurrRow === 0 && init) { var initDate = new Date(); this.initTime = initDate.getTime(); this.prevRow = 0; this.diffTime = 0; } this.currIntDate = new Date(); this.currTime = this.currIntDate.getTime() ; this.lyricsCurrRow = this.rowsTraversed * (this.currTime - this.initTime)/(this.songSecs*1000); if (this.prevRow !== this.lyricsCurrRow) { if (this.movingLyrics()) { this.$.viewScroller.setScrollTop(this.lyricsCurrRow - this.cursorRow); } else { this.cursorRow = (this.lyricsCurrRow < this.halfHt) ? this.lyricsCurrRow : 2*this.halfHt - this.rowsTraversed + this.lyricsCurrRow; this.$.cursorScrollBar.setY(this.cursorRow); } } this.prevRow = this.lyricsCurrRow; if (this.lyricsCurrRow > this.rowsTraversed) { // finished window.clearTimeout(this.scrollTimeout); this.$.cursorScrollBar.cursorOff(); this.finished = true; this.running = false; this.log("duration ",(new Date().getTime()-this.initTime)/1000, "secs"); } else { var _this = this; this.scrollTimeout = window.setTimeout(function() {enyo.requestAnimationFrame(enyo.bind(_this, "showLyrics", false));}, this.perRowMSecs); } } else { this.diffTime = this.currTime - this.initTime; } }, initCursor: function() { this.log(); this.cursorRow = 0; this.lyricsCurrRow = 0; this.$.viewScroller.setScrollTop(this.lyricsCurrRow); this.$.cursorScrollBar.setY(this.cursorRow); this.$.cursorScrollBar.cursorOff(); window.clearTimeout(this.scrollTimeout); this.$.playButton.setProperty("src", Helper.iconPath()+"play.png"); this.running = false; this.finished = false; this.$.editButton.setDisabled(false); this.$.fontButton.setDisabled(false); this.$.forthButton.setDisabled(false); this.$.backButton.setDisabled(false); this.$.printButton.setDisabled(false); this.resizeLyrics(); }, resizeLyrics: function() { this.log(); var moBoxes = document.getElementsByClassName('mochordbox'); if (moBoxes) { for (i=0; i<moBoxes.length; i++) { moBoxes[i].style.width = 'auto'; // remove fixed width } } if (this.$.lyric.node !== null && this.owner.owner.$.sidePane.css.autoResize === true) { var iFS = 100; this.$.lyric.applyStyle("font-size", iFS + "%"); this.$.lyric.applyStyle("display", "inline-block"); var newFS = (iFS * (this.$.lyric.owner.width-108)/(this.$.lyric.node.clientWidth-72)); var cmpFS = this.owner.owner.$.sidePane.css.fMin * 10 * Helper.ratio() + 80; newFS = newFS < cmpFS ? cmpFS : newFS; cmpFS = this.owner.owner.$.sidePane.css.fMax * 10 * Helper.ratio() + 80; newFS = newFS > cmpFS ? cmpFS : newFS; this.$.lyric.applyStyle("font-size", Math.floor(newFS) + "%"); this.$.lyric.applyStyle("display", "block"); // adjust width of chordboxes for music only verses } if (moBoxes) { var max=0; for (i=0; i<moBoxes.length; i++) { if (moBoxes[i].clientWidth > max) { max = moBoxes[i].clientWidth; } } for (i=0; i<moBoxes.length; i++) { moBoxes[i].style.width = max + 'px'; } } }, initForTextPlay: function() { this.log(); var ctrls = this.$.lyric.getControls(); this.resizeLyrics(); // in case screen size/orientation changed this.rowsTraversed = this.$.lyric.node.clientHeight; for (i = 0; i < ctrls.length; i++) { if (ctrls[i].name === "scrollspacer") { this.rowsTraversed = this.rowsTraversed - this.$.lyric.node.lastChild.clientHeight + 20; } } this.halfHt = this.$.viewScroller.node.clientHeight / 2; this.$.viewScroller.setScrollTop(this.lyricsCurrRow); this.$.cursorScrollBar.$.canvas.setAttribute("height", this.$.viewScroller.node.clientHeight); this.songSecs = (this.data.duration) ? this.data.duration : this.defaultSongSecs; this.$.cursorScrollBar.cursorOff(); this.$.cursorScrollBar.hasNode().height = this.$.viewScroller.node.clientHeight; this.$.editButton.setDisabled(true); this.$.fontButton.setDisabled(true); }, // ### Scrolling Button/Keypress ### scrollHelper: function() { var x = this.$[this.order[this.textIndex]].hasNode(); var ePos = Helper.calcNodeOffset(x).top - 74; // element offset - Toolbar and margin this.scroll = this.$.viewScroller.getScrollTop(); // scroll position this.$.viewScroller.scrollTo(0, (this.scroll + ePos)); }, textForth: function() { this.textIndex += 1; if (this.textIndex === 1) { this.$.backButton.setDisabled(false); } else if (this.textIndex === (this.data.verseOrder.length-1)) { this.$.forthButton.setDisabled(true); } if (this.textIndex === (this.data.verseOrder.length+1)) { this.nextSong(); } if (this.textIndex <= (this.data.verseOrder.length-1)) { this.scrollHelper(); } }, textBack: function() { this.textIndex -= 1; if (this.textIndex === 0) { this.$.backButton.setDisabled(true); } else if (this.textIndex === (this.data.verseOrder.length-2)) { this.$.forthButton.setDisabled(false); } if (this.textIndex === -2) { this.prevSong(); } if (this.textIndex >= 0) { this.scrollHelper(); } }, handleKeyPress: function(inSender, inEvent) { if (!this.running) { k = inEvent.keyCode; this.log(k); if ((k===33 || k===38 || k===37 || k===32) && this.textIndex > -2) { // PageUp this.textBack(); } else if ((k===34 || k===40 || k===39 || k===13) && this.textIndex < this.data.verseOrder.length+1) { // PageDown this.textForth(); } } }, // Go to next/prev song nextSong: function() { var o = this.owner.owner; if (o.currentIndex >= 0 && o.currentIndex < o[o.currentList].content.length-1) { this.log("next Song"); o.setCurrentIndex(o.currentIndex+1); } }, prevSong: function() { var o = this.owner.owner; if (o.currentIndex > 0) { this.log("prev Song"); o.setCurrentIndex(o.currentIndex-1); } }, // Swipe left and right songDragFinish: function(inSender, inEvent) { this.log(); if (+inEvent.dx > 120) { this.nextSong(); } if (+inEvent.dx < -120) { this.prevSong(); } }, // Swipe down in Titlebar on Phone titleDragFinish: function(inSender, inEvent) { if (Helper.phone && !this.running) { if (+inEvent.dy > 50) { this.$.titleDrawer.setOpen(true); } if (+inEvent.dy < -50) { this.$.titleDrawer.setOpen(false); } } }, closeTitle: function() { if (!this.running) { this.$.titleDrawer.setOpen(false); } }, // Maximize view on doubletap onDoubleTap: function() { if (this.tapTimer === undefined) { this.tapTimer = window.setTimeout(enyo.bind(this, this.undefTimer), 500); } else { // double tap this.log("double tap: set fullscreen: ", !this.fullscreen); window.clearTimeout(this.tapTimer); this.tapTimer = undefined; this.fullscreen = !this.fullscreen; if (this.fullscreen === true) { this.$.headerToolbar.hide(); this.$.footerToolbar.hide(); this.$.titleDrawer.setOpen(false); this.owner.owner.$.mainPanels.setIndex(1); } else { this.$.headerToolbar.show(); this.$.footerToolbar.show(); if (Helper.phone()) { this.owner.owner.$.mainPanels.setIndex(1); } else { this.owner.owner.$.mainPanels.setIndex(0); } } if (window.PalmSystem) { enyo.setFullScreen(this.fullscreen); } this.log("mainPanels index", this.owner.owner.$.mainPanels.index) return true; } }, // timing out does no undefine variable undefTimer: function() { this.tapTimer = undefined; }, // ### Button ### grabber: function() { this.owner.owner.$.mainPanels.setIndex(this.owner.owner.$.mainPanels.index ? 0 : 1); }, showMenu: function() { this.log("show menu"); this.owner.owner.$.infoPanels.setIndex(1); this.owner.owner.$.sidePane.showMenu(); }, openEdit: function() { this.log("open editmode for: ", this.file); this.owner.$.viewPanels.setIndex(3); this.owner.$.editToaster.setXml(this.xml); this.owner.$.editToaster.setFile(this.file); this.owner.$.editToaster.populate(); }, showInfo: function() { this.owner.owner.$.infoPanels.setIndex(1); this.owner.owner.$.sidePane.showInfo(this.data); }, showFontDialog: function() { this.owner.owner.$.infoPanels.setIndex(1); this.owner.owner.$.sidePane.showFont(); }, //~ toggleLock: function() { //~ if (this.$.lockButton.getIcon() === "assets/images/lock-open.png") { //~ this.$.lockButton.setIcon("assets/images/lock.png"); //~ if (window.PalmSystem) { //~ enyo.windows.setWindowProperties(enyo.windows.getActiveWindow(), {"blockScreenTimeout" : true}); //~ } //~ } else { //~ this.$.lockButton.setIcon("assets/images/lock-open.png"); //~ if (window.PalmSystem) { //~ enyo.windows.setWindowProperties(enyo.windows.getActiveWindow(), {"blockScreenTimeout" : false}); //~ } //~ } //~ }, // ### Print ### print: function() { var docURL = document.URL; docURL = docURL.slice(0, docURL.lastIndexOf('/')+1); var printWindow = window.open(docURL, 'Print Popup', 'width=800, height=600'); var printCopy = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; printCopy += '<html><head><title>Print Popup</title>'; printCopy += '<link href="build/app.css" rel="stylesheet" />'; printCopy += '</head><body>'; printCopy += this.printHeader(); printCopy += this.$.lyric.node.innerHTML; printCopy += this.printFooter(); printCopy += '</body></html>'; printWindow.document.write(printCopy); var maxWidth = 0; var thisTextEl = printWindow.document.getElementsByClassName("text"); for (i in thisTextEl) { if (thisTextEl[i].clientWidth > maxWidth) { maxWidth = thisTextEl[i].clientWidth; } } var enlarge = (thisTextEl[0].parentElement.clientWidth - 30) / maxWidth; var spacerEl = printWindow.document.getElementsByClassName("scrollspacer"); while (spacerEl.length > 0) { spacerEl[0].parentNode.removeChild(spacerEl[0]); } printWindow.document.body.style.fontSize = 20*enlarge + "px"; var _this = this; this.timer = window.setTimeout(function() {_this.printIt(printWindow);}, 500); // allow time for changes to load }, printIt: function(theWindow) { theWindow.print(); theWindow.close(); }, printHeader: function() { // add Title(s) for printing var printCopy = ""; if (this.data.titles != []) { for (i=0; i<this.data.titles.length; ++i) { var t = this.data.titles[i]; if (t.lang == this.lang || t.lang == null) { printCopy += '<div class="printTitle">' + t.title + '</div>'; } } } for (var i=0; i < this.data.comments.length; i++) { printCopy += this.data.comments[i] + '<br>';} if (this.data.key){ printCopy += 'Key : ' + this.data.key + '<br>';} if (this.data.duration){ printCopy += 'Duration : ' + this.data.duration + 'secs' + '<br>';} if (this.data.tempo){ printCopy += 'Tempo : ' + this.data.tempo + '<br>';} return printCopy; }, printFooter: function() { // add Copyright-box for printing if (this.data.authors !== []) { var a; var printCopy = '<div class="printCopy">by<br>'; for (i=0; i<this.data.authors.length; ++i) { var a = this.data.authors[i]; if (a.lang == this.lang || a.lang == undefined || a.lang == "") { printCopy += "&nbsp;&nbsp;" + a.author; if (a.type !== null) { printCopy += " ("+ a.lang +" "+ a.type +")"; } printCopy += "<br>"; } } } if (this.data.released) { printCopy += this.data.released + ' ';} if (this.data.copyright) { printCopy += '&copy; ' + this.data.copyright + '<br>';} if (this.data.publisher) { printCopy += this.data.publisher + '<br>';} printCopy += '<br><br><center>Printed with mySongs</center></div>' return printCopy; } });
michote/mySongs
source/SongView.js
JavaScript
mit
30,634
(function () { "use strict"; var app_routes = angular.module("app.routes", [ "ui.router", "ncy-angular-breadcrumb" ] ); app_routes.config( [ "$stateProvider", "$urlRouterProvider", "$locationProvider", function ($stateProvider, $urlRouterProvider, $locationProvider) { //Unfortunately laravel router makes this unable to work /* $locationProvider.html5Mode({ enabled: true, requireBase: false }); */ //Hashbang $locationProvider.hashPrefix("!"); $urlRouterProvider.otherwise("/stats"); $stateProvider //Ping .state("ping", { url: "/ping", templateUrl: "app/views/sampleView.html", controller: "SampleController as vm", ncyBreadcrumb: { label: 'Ping' } } ) .state("stats", { url: "/stats", templateUrl: "app/views/dashboard/dash.html", controller: "StatsController as vm", ncyBreadcrumb: { label: 'Stats' } } ) .state("teams", { url: "/teams", templateUrl: "app/views/teams/teamsListView.html", controller: "TeamsController as vm", ncyBreadcrumb: { label: 'Teams' } } ) .state("teamOne", { url: "/teams/:teamId", templateUrl: "app/views/teams/teamDetails.html", controller: "TeamDetailsController as vm", ncyBreadcrumb: { parent: 'teams', label: 'Team Details' } } ) .state("playerOneFromTeam", { url: "/teams/:teamId/players/:playerId", templateUrl: "app/views/players/playerDetails.html", controller: "PlayerOneFromTeamController as vm", ncyBreadcrumb: { parent: 'teamOne', label: 'Player Details' } } ) .state("coachOneFromTeam", { url: "/teams/:teamId/coach/:coachId", templateUrl: "app/views/coaches/coachDetails.html", controller: "CoachFromTeamController as vm", ncyBreadcrumb: { parent: 'teamOne', label: 'Coach Details' } } ) .state("leagues", { url: "/leagues", templateUrl: "app/views/leagues/leaguesListView.html", controller: "LeaguesController as vm", ncyBreadcrumb: { label: 'Leagues' } } ) .state("leagueOne", { url: "/leagues/:leagueId", templateUrl: "app/views/leagues/leagueDetails.html", controller: "LeagueDetailsController as vm", ncyBreadcrumb: { parent: 'leagues', label: 'League Details' } } ) .state("roundOne", { url: "/leagues/:leagueId/rounds/:roundId", templateUrl: "app/views/leagues/leagueRoundDetails.html", controller: "LeagueRoundDetailsController as vm", ncyBreadcrumb: { parent: 'leagueOne', label: 'Round Details' } } ) .state("simulateRound", { url: "/leagues/:leagueId/rounds/:roundId/simulated", templateUrl: "app/views/leagues/leagueRoundDetails.html", controller: "SimulateLeagueRoundController as vm", ncyBreadcrumb: { parent: 'leagueOne', label: 'Round Details' } } ) .state("matches", { url: "/matches", templateUrl: "app/views/matches/matchesListView.html", controller: "MatchesController as vm", ncyBreadcrumb: { label: 'Matches' } } ) .state("matchOne", { url: "/matches/:matchId", templateUrl: "app/views/matches/matchDetails.html", controller: "MatchDetailsController as vm", ncyBreadcrumb: { parent: 'matches', label: 'Match Result' } } ) .state("simulateMatch", { url: "/matches/:matchId/simulated", templateUrl: "app/views/matches/matchDetails.html", controller: "SimulateMatchController as vm", ncyBreadcrumb: { parent: 'matches', label: 'Match Result' } } ) .state("createMatch", { url: "/add/match", templateUrl: "app/views/matches/newMatch.html", controller: "NewMatchController as vm", ncyBreadcrumb: { parent: 'matches', label: 'New Match' } } ) .state("addMatch", { url: "/new/matches", params: {homeId: null, awayId: null}, templateUrl: "app/views/matches/matchesListView.html", controller: "AddMatchController as vm", ncyBreadcrumb: { label: 'Matches' } } ) ; }] ); })();
vikkio88/dsManager-php
app/modules/app.routes.js
JavaScript
mit
8,143
exports.hostname = function () { return location.hostname }
substack/decode-prompt
lib/os.js
JavaScript
mit
60
module.exports = function(app) { var baseDir = app.get('baseDir'); var env = app.get('env'); return { storage: baseDir + '/sqlite/'+env+'.sqlite', dialect: 'sqlite' }; };
AlexBrandes/tictactoe
config/db.js
JavaScript
mit
178
var rollup = require('rollup') var memory = require('rollup-plugin-memory') var rollup = require('rollup'); var through = require('through2'); var denodeify = require('denodeify'); var fs = require('fs'); var writeFile = denodeify(fs.writeFile); var unlink = denodeify(fs.unlink); var path = require('path'); module.exports = function () { var cb = this.async(); var rollupConfig = { //entry: __dirname + '/src.js', plugins: [ memory({ contents: source }) ] }; this.cacheable(); rollup .rollup(rollupConfig) .then(function (bundle) { var result = bundle.generate({ format: 'cjs' }); cb(null, result.code, result.map); }) .catch(cb); this.cacheable(); var callback = this.async(); var resource = this.resourcePath; var source = ''; return through(function (chunk, enc, cb) { source += chunk.toString('utf8'); cb(); }, function (cb) { var self = this; // Write a temp file just in case we are preceded by // another browserify transform var tmpfile = path.resolve(path.dirname(filename), path.basename(filename) + '.tmp'); var doSourceMap = opts.sourceMaps !== false; writeFile(tmpfile, source, 'utf8').then(function () { var config = {}; if (opts.config) { var configPath = /^\//.test(opts.config) ? opts.config : process.cwd() + '/' + opts.config; config = require(configPath); } return rollup.rollup(Object.assign(config, { entry: tmpfile, sourceMap: doSourceMap ? 'inline' : false })); }).then(function (bundle) { var generated = bundle.generate({format: 'cjs'}); self.push(generated.code); self.push(null); bundle.modules.forEach(function(module) { var file = module.id; if (!/\.tmp$/.test(file)) { self.emit('file', file) } }); return unlink(tmpfile); }).then(function () { cb(); }).catch(cb); }); var params = Object.assign({}, parseUrl(this.query), parseUrl(this.resourceQuery)); var path = params.root + params.url; if (!coordsPromise[path]) { coordsPromise[path] = new Promise((resolve, reject) => { dd.push(() => { log('resolving', path); makeSprites(FILELIST[path], path).then(resolve, reject); }); }); } coordsPromise[path].then( coordinates => { log('done:', resource); if (resource in coordinates) { callback(null, g(coordinates[resource])); } else { throw JSON.stringify({resource, coordinates, mes: 'no resource found'}); } }, err => console.error('makeSprites failed!', err) ); log('setting new timeout', path); clearTimeout(timeOut); timeOut = setTimeout(doAllSprites, 2000); }; module.exports.pitch = function (remainingRequest) { log('pitch'); this.cacheable(); var params = Object.assign({}, parseUrl(this.query), parseUrl(this.resourceQuery)); var filename = remainingRequest.split('?')[0]; var path = params.root + params.url; FILELIST[path] = FILELIST[path] || []; if (FILELIST[path].indexOf(filename) === -1) { FILELIST[path].push(filename); } };
QiV/misc
rollup-loader.js
JavaScript
mit
3,227
#!/usr/bin/env node // // マニュアル) // http://selenium.googlecode.com/git/docs/api/javascript/class_webdriver_promise_Deferred.html // var assert = require('assert'); var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.chrome()) .build(); var d = webdriver.promise.defer(); setTimeout(function(){ console.log('A'); d.fulfill(); }, 1000); // BrowserStack がラップしてる deferred オブジェクトの場合、 // この then 内が実行されなかったので調べた。これだとちゃんと動く。 d.then(function(){ console.log('B'); driver.get('http://example.com'); driver.wait(function(){ console.log('C'); return driver.getTitle().then(function(title){ console.log('title =', title); return title === 'Example Domain'; }); }, 5000).then(function(){ console.log('D'); }).then(function(){ driver.quit(); }); });
kjirou/nodejs-codes
examples/selenium-webdriver/deferred/index.js
JavaScript
mit
968
import React, { Component } from 'react' import renderer from 'react-test-renderer' import { DatePicker } from './index' class CustomInput extends Component { render() { return <input type="text" autoComplete="off" {...this.props} /> } } describe('<DatePicker />', () => { let component describe('by default', () => { beforeEach(() => { component = renderer.create(<DatePicker />).toJSON() }) it('matches with snapshot', () => { expect(component).toMatchSnapshot() }) }) describe('with custom input', () => { beforeEach(() => { component = renderer .create(<DatePicker>{CustomInput}</DatePicker>) .toJSON() }) it('matches with snapshot', () => { expect(component).toMatchSnapshot() }) }) })
KissKissBankBank/kitten
assets/javascripts/kitten/components/form/date-picker/test.js
JavaScript
mit
787
/* cycle.js 2013-02-19 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. */ /*jslint evil: true, regexp: true */ /*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push, retrocycle, stringify, test, toString */ if (typeof JSON.decycle !== 'function') { JSON.decycle = function decycle(object) { 'use strict'; // Make a deep copy of an object or array, assuring that there is at most // one instance of each object or array in the resulting structure. The // duplicate references (which might be forming cycles) are replaced with // an object of the form // {$ref: PATH} // where the PATH is a JSONPath string that locates the first occurrence. // So, // var a = []; // a[0] = a; // return JSON.stringify(JSON.decycle(a)); // produces the string '[{"$ref":"$"}]'. // JSONPath is used to locate the unique object. $ indicates the top level of // the object or array. [NUMBER] or [STRING] indicates a child member or // property. var objects = [], // Keep a reference to each unique object or array paths = []; // Keep the path to each unique object or array return (function derez(value, path) { // The derez recurses through the object, producing the deep copy. var i, // The loop counter name, // Property name nu; // The new object or array // typeof null === 'object', so go on if this value is really an object but not // one of the weird builtin objects. if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { // If the value is an object or array, look to see if we have already // encountered it. If so, return a $ref/path object. This is a hard way, // linear search that will get slower as the number of unique objects grows. for (i = 0; i < objects.length; i += 1) { if (objects[i] === value) { return {$ref: paths[i]}; } } // Otherwise, accumulate the unique value and its path. objects.push(value); paths.push(path); // If it is an array, replicate the array. if (Object.prototype.toString.apply(value) === '[object Array]') { nu = []; for (i = 0; i < value.length; i += 1) { nu[i] = derez(value[i], path + '[' + i + ']'); } } else { // If it is an object, replicate the object. nu = {}; for (name in value) { if (Object.prototype.hasOwnProperty.call(value, name)) { nu[name] = derez(value[name], path + '[' + JSON.stringify(name) + ']'); } } } return nu; } return value; }(object, '$')); }; } if (typeof JSON.retrocycle !== 'function') { JSON.retrocycle = function retrocycle($) { 'use strict'; // Restore an object that was reduced by decycle. Members whose values are // objects of the form // {$ref: PATH} // are replaced with references to the value found by the PATH. This will // restore cycles. The object will be mutated. // The eval function is used to locate the values described by a PATH. The // root object is kept in a $ variable. A regular expression is used to // assure that the PATH is extremely well formed. The regexp contains nested // * quantifiers. That has been known to have extremely bad performance // problems on some browsers for very long strings. A PATH is expected to be // reasonably short. A PATH is allowed to belong to a very restricted subset of // Goessner's JSONPath. // So, // var s = '[{"$ref":"$"}]'; // return JSON.retrocycle(JSON.parse(s)); // produces an array containing a single element which is the array itself. var px = /^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/; (function rez(value) { // The rez function walks recursively through the object looking for $ref // properties. When it finds one that has a value that is a path, then it // replaces the $ref object with a reference to the value that is found by // the path. var i, item, name, path; if (value && typeof value === 'object') { if (Object.prototype.toString.apply(value) === '[object Array]') { for (i = 0; i < value.length; i += 1) { item = value[i]; if (item && typeof item === 'object') { path = item.$ref; if (typeof path === 'string' && px.test(path)) { value[i] = eval(path); } else { rez(item); } } } } else { for (name in value) { if (typeof value[name] === 'object') { item = value[name]; if (item) { path = item.$ref; if (typeof path === 'string' && px.test(path)) { value[name] = eval(path); } else { rez(item); } } } } } } }($)); return $; }; }
FineUploader/fine-uploader
test/static/third-party/json2/cycle.js
JavaScript
mit
6,214
IntlMessageFormat.__addLocaleData({locale:"lu",pluralRuleFunction:function(a,l){return"other"}});
vladimirbrasil/testghpagepolymer
bower_components/intl-messageformat/dist/locale-data/lu.js
JavaScript
mit
97
/** * Created by mac on 15/11/24. */ 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactRedux = require('react-redux'); var _redux = require('redux'); var _reduxThunk = require('redux-thunk'); var _reduxThunk2 = _interopRequireDefault(_reduxThunk); var _fetch = require('./fetch'); var _fetching = require('./fetching'); var _LoadingBar = require('./LoadingBar'); var _LoadingBar2 = _interopRequireDefault(_LoadingBar); var BindReact = (function (_Component) { _inherits(BindReact, _Component); function BindReact() { _classCallCheck(this, BindReact); _Component.apply(this, arguments); } BindReact.prototype.render = function render() { var reducers = this.props.reducers; // 并返回一个包含兼容 API 的函数。 var createStoreWithMiddleware = _redux.applyMiddleware(_reduxThunk2['default'], _fetch.middleware)(_redux.createStore); // 像使用 createStore() 一样使用它。 var app = _redux.combineReducers(_extends({}, reducers, { fetching: _fetching.fetching })); var store = createStoreWithMiddleware(app); return _react2['default'].createElement( _reactRedux.Provider, { store: store }, this.show() ); }; BindReact.prototype.show = function show() { var Module = this.props.Module; return _react2['default'].createElement( 'div', null, _react2['default'].createElement(Module, null), _react2['default'].createElement(_LoadingBar2['default'], null) ); }; return BindReact; })(_react.Component); exports['default'] = BindReact; module.exports = exports['default'];
xiaoking/eagle
lib/BindReact.js
JavaScript
mit
2,810
'use strict'; const electron = require('electron'); const app = electron.app; // Module to control application life. const BrowserWindow = electron.BrowserWindow; // Module to create native browser window. const storage = require('electron-json-storage'); var Menu = electron.Menu; var menu = new Menu(); var dialog = electron.dialog; var fs = require('fs'); var shell = electron.shell; var monode = require('monode')(); var draggedFilePath = []; //path of any file that was dragged onto the app icon var openFileAlias; global.monome_device = null; global.shared_object = {}; global.window_id = 0; // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. var mainWindow = null, crackedWindows = {}, currentId = 0, shuttingDown=false; // Quit when all windows are closed. app.on('window-all-closed', function() { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('before-quit',function(e){ e.preventDefault(); shuttingDown=true; closeWindows(); }); global.flipShutdownFlag = function () { if(shuttingDown) { shuttingDown = false; } }; function closeWindows() { if(BrowserWindow.getAllWindows().length) { if(BrowserWindow.getAllWindows()[0]) { BrowserWindow.getAllWindows()[0].close(); } } else { app.exit(0); } } monode.on('device', function(device) { if(device) { global.monome_device = device; console.log("monome device connected:", device); //tbd-make this configurable device.rotation = 180; } }); monode.on('disconnect', function(device){ global.monome_device = null; console.log('A device was disconnected:', device); }); app.on("open-file", function(event, path) { event.preventDefault(); if(!app.isReady()){ draggedFilePath.push(path); } else { openFileAlias([path]); } }); // This method will be called when Electron has finished // initialization and is ready to create browser windows. app.on('ready', function() { // Create the Application's main menu var template = [{ label: "Application", submenu: [ { label: "About Application", selector: "orderFrontStandardAboutPanel:" }, { type: "separator" }, { label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); }} ]}, { label: "File", submenu: [ { label: "New", accelerator: "CmdOrCtrl+N", click: function() { mainWindow = openCrackedWindow(); } }, { label: "Open", accelerator: "CmdOrCtrl+O", click: function() { openFile(dialog.showOpenDialogSync(mainWindow,{ filters: [ { name: 'Javascript', extensions: ['js'] } ], title:"Open a file", properties:["multiSelections","openFile"] })) } }, { label: "Save", accelerator: "CmdOrCtrl+S", click: function() { saveFile(); } }, { label: "Close", accelerator: "CmdOrCtrl+W", click: function() { if(mainWindow) { mainWindow.close(); } else if(BrowserWindow.getAllWindows()[0]) { BrowserWindow.getAllWindows()[0].close(); } } } ]}, { label: "Edit", submenu: [ { label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" }, { label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" }, { type: "separator" }, { label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" }, { label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" }, { label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" }, { label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" } ]}, { label: "Window", submenu: [ { label: "Toggle Audio", accelerator: "CmdOrCtrl+M", click:muteWindow}, { label: "Toggle Read-Only", accelerator: "CmdOrCtrl+L", click:toggleReadOnly}, { label: "Reload Window", accelerator: "CmdOrCtrl+R", click:reloadWindow}, { label: 'Toggle Developer Tools', accelerator: (function () { if (process.platform === 'darwin') return 'Alt+Command+I'; else return 'Ctrl+Shift+I'; })(), click: function (item, mainWindow) { if (mainWindow) mainWindow.toggleDevTools(); } } ]}, { label: "Themes", submenu: getThemesMenu() },{ label: "Help ", submenu: [{ label:'Examples', submenu:getExamples() }, { label:'Demos', submenu:getDemos() }, { label:'API Docs', click:function(){ shell.openExternal('http://billorcutt.github.io/i_dropped_my_phone_the_screen_cracked/'); } }, { label:'Website', click:function(){ shell.openExternal('https://github.com/billorcutt/i_dropped_my_phone_the_screen_cracked'); } } ]} ]; Menu.setApplicationMenu(Menu.buildFromTemplate(template)); //are we opening bc a file was dragged onto the icon? if(!draggedFilePath.length) { mainWindow = openCrackedWindow(); } else { openFile(draggedFilePath); draggedFilePath = []; } //it opens a window function openCrackedWindow() { var options = {width: 800, height: 600, webPreferences:{webSecurity:false, nodeIntegration: true, enableRemoteModule: true, contextIsolation:false}}; //offset from current window if(mainWindow) { options.x = mainWindow.getBounds().x + 10; options.y = mainWindow.getBounds().y + 10; } // Create the browser window. var win = new BrowserWindow(options); //get the current theme storage.get("theme",function(error,data){ if(!error && data && data.name) { win.webContents.executeJavaScript("crackedEditor.setOption(\"theme\", \""+data.name+"\");"); } }); // and load the index.html of the app. win.loadURL('file://' + __dirname + '/index.html'); // Open the DevTools. //win.webContents.openDevTools(); //focus win.on('focus',function(e){ mainWindow = this; currentId = this.id; }); //keep the window from closing before we can save win.on('close',function(e){ e.preventDefault(); return false; }); // Emitted when the window is closed. win.on('closed', function(e) { delete crackedWindows[currentId]; mainWindow = BrowserWindow.getFocusedWindow() || null; currentId = mainWindow ? mainWindow.id : 0; if(shuttingDown) { app.quit(); } }); crackedWindows[win.id]=win; global.window_id = win.id; return win; } //start menu //get an array of theme css from the theme directory //to build the menu function getThemesMenu() { var path = app.getAppPath(); var themes = fs.readdirSync(path+'/lib/editor/theme/'); var result = []; if(themes && themes.length) { themes.map(function(item){ var name = item.replace(/\.css/,''); result.push({ label:name, click:function(){ if(mainWindow && storage) { mainWindow.webContents.executeJavaScript("crackedEditor.setOption(\"theme\", \""+name+"\");"); storage.set("theme",{"name":name}); } } }); }); } result.push({ type: "separator" }); result.push({ label:"Make Text Bigger", click:makeFontBigger, accelerator: 'Command+=' }); result.push({ label:"Make Text Smaller", click:makeFontSmaller, accelerator: "Command+-" }); return result; } function makeFontBigger() { if(mainWindow) { mainWindow.webContents.executeJavaScript("changeFontSize(1)"); } } function makeFontSmaller() { if(mainWindow) { mainWindow.webContents.executeJavaScript("changeFontSize(0)"); } } //scan the demo folder and create a menu function getDemos() { var path = app.getAppPath(); var demos = fs.readdirSync(path+'/Cracked/Demos/'); var result = []; if(demos && demos.length) { demos.map(function(name){ result.push({ label:name, click:function(){ openFile([path+'/Cracked/Demos/'+name]); } }); }); } return result; } //scan the examples folder and create a menu function getExamples() { var path = app.getAppPath(); var examplesDirectories = fs.readdirSync(path+'/Cracked/Examples/'); var result = []; if(examplesDirectories && examplesDirectories.length) { examplesDirectories.map(function(categoryDirectory){ if(fs.lstatSync(path+'/Cracked/Examples/'+categoryDirectory).isDirectory()) { result.push({ label:categoryDirectory, submenu:[] }); var examples = fs.readdirSync(path+'/Cracked/Examples/'+categoryDirectory); if(examples && examples.length) { examples.map(function(item){ result[result.length-1].submenu.push({ label:item, click:function(){ openFile([path+'/Cracked/Examples/'+categoryDirectory+'/'+item]); } }) }); } } }); } return result; } //define some methods for opening & saving function openFile(path) { if(path && path.length) { for(var i=0;i<path.length;i++) { mainWindow = openCrackedWindow(); mainWindow.webContents.executeJavaScript("openFile('"+path[i]+"')"); } } } //make an alias for the openFile method we can use outside the onReady handler openFileAlias = (function(){return openFile})(); function saveFile() { if(mainWindow) { mainWindow.webContents.executeJavaScript("saveFile()"); } } function reloadWindow() { if(mainWindow) { mainWindow.webContents.executeJavaScript("evalEditor()"); } } function toggleTitleTag(tag) { var title = mainWindow.webContents.getTitle(); if(title.indexOf(tag)!==-1) { title = title.replace("["+tag+"]", ""); } else { title = title + " ["+tag+"]"; } mainWindow.webContents.executeJavaScript("document.title='"+title+"'"); } function toggleReadOnly() { if(mainWindow) { mainWindow.webContents.executeJavaScript("crackedEditor.setOption(\"readOnly\", !crackedEditor.getOption(\"readOnly\"))"); var title = mainWindow.webContents.getTitle(); toggleTitleTag("Read-Only"); } } function muteWindow() { if(mainWindow) { mainWindow.webContents.setAudioMuted(!mainWindow.webContents.isAudioMuted()); var title = mainWindow.webContents.getTitle(); toggleTitleTag("Muted"); } } });
billorcutt/Cracked
main.js
JavaScript
mit
12,506
"use strict"; exports.__esModule = true; exports.default = lruCache; function lruCache(limit, equals) { var entries = []; function get(key) { var cacheIndex = entries.findIndex(function (entry) { return equals(key, entry.key); }); // We found a cached entry if (cacheIndex > -1) { var entry = entries[cacheIndex]; // Cached entry not at top of cache, move it to the top if (cacheIndex > 0) { entries.slice(cacheIndex, 1); entries.unshift(entry); } return entry.value; } // No entry found in cache, return null return undefined; } function put(key, value) { if (!get(key)) { entries.unshift({ key: key, value: value }); if (entries.length > limit) { entries.pop(); } } } return { get: get, put: put }; }
geng890518/editor-ui
node_modules/lru-memoize/lib/lruCache.js
JavaScript
mit
836
$(document).ready(function() { $('#maintable').DataTable( { iDisplayLength: 20, aaData: data, columns: [ { title: "Name" }, { title: "Position" }, { title: "Office" }, { title: "Extn." }, { title: "Start date" }, { title: "Salary" } ], ordering:true, //scrollY:'100%', //scrollX: true, //scrollCollapse:true, stateSave:true }); $('#table').DataTable( { iDisplayLength: 20, aaData: data, columns: [ { title: "Name" }, { title: "Position" }, { title: "Office" }, { title: "Extn." }, { title: "Start date" }, { title: "Salary" } ], ordering:true, scrollY:'100%', scrollX: true, scrollCollapse:true, stateSave:true, multiSelect:{ multiSelectOptions:[ {selector:".name", col:0}, {selector:".office", col:2} ] } }); } );
omarcho/dataTables.multiSelect
examples/js/example1.js
JavaScript
mit
936
/*! jQuery UI - v1.10.4 - 2014-05-23 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.ka={closeText:"დახურვა",prevText:"&#x3c; წინა",nextText:"შემდეგი &#x3e;",currentText:"დღეს",monthNames:["იანვარი","თებერვალი","მარტი","აპრილი","მაისი","ივნისი","ივლისი","აგვისტო","სექტემბერი","ოქტომბერი","ნოემბერი","დეკემბერი"],monthNamesShort:["იან","თებ","მარ","აპრ","მაი","ივნ","ივლ","აგვ","სექ","ოქტ","ნოე","დეკ"],dayNames:["კვირა","ორშაბათი","სამშაბათი","ოთხშაბათი","ხუთშაბათი","პარასკევი","შაბათი"],dayNamesShort:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],dayNamesMin:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],weekHeader:"კვირა",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.ka)});
Checo1983/petfriends
js/jquery-ui-1.10.4.custom/development-bundle/ui/minified/i18n/jquery.ui.datepicker-ka.min.js
JavaScript
mit
1,334
var utils = require('../lib/utils'); var database = require('../lib/database'); /** * 检查参数 * * @param {any} req * @param {any} res * @param {any} next */ exports.checkAuthorizeParams = function(req, res, next) { if (!req.query.client_id) { return next(utils.missingParameterError('client_id')); } if (!req.query.redirect_uri) { return next(utils.missingParameterError('redirect_uri')); } database.getAppInfo(req.query.client_id, function(err, ret) { if (err) return next(err); req.appInfo = ret; database.verifyAppRedirectUri( req.query.client_id, req.query.redirect_uri, function(err, ok) { if (err) { return next(err); } if (!ok) { return next(utils.redirectUriNotMatchError(req.query.redirect_uri)); } next(); }); }); }; /** * 显示确认页面 * * @param {any} req * @param {any} res * @param {any} next */ exports.showAppInfo = function(req, res, next) { res.locals.loginUserId = req.loginUserId; res.locals.appInfo = req.appInfo; res.render('index'); }; /** * 确认授权 * * @param {any} req * @param {any} res * @param {any} next */ exports.confirmApp = function(req, res, next) { database.generateAuthorizationCode( req.loginUserId, req.query.client_id, req.query.redirect_uri, function(err, ret) { if (err) return next(err); console.log(ret); res.redirect(utils.addQueryParamsToUrl(req.query.redirect_uri, { code: ret })); }); }; /** * 获取access_token * * @param {any} req * @param {any} res * @param {any} next */ exports.getAccessToken = function(req, res, next) { var client_id = req.body.client_id || req.query.client_id; var client_secret = req.body.client_secret || req.query.client_secret; var redirect_uri = req.body.redirect_uri || req.query.redirect_uri; var code = req.body.code || req.query.code; if (!client_id) return next(utils.missingParameterError('client_id')); if (!client_secret) return next(utils.missingParameterError('client_secret')); if (!redirect_uri) return next(utils.missingParameterError('redirect_uri')); if (!code) return next(utils.missingParameterError('code')); database.verifyAuthorizationCode(code, client_id, client_secret, redirect_uri, function(err, userId) { if (err) return next(err); database.generateAccessToken(userId, client_id, function(err, accessToken) { if (err) return next(err); database.deleteAuthorizationCode(code, function(err) { if (err) console.error(err); }); res.apiSuccess({ access_token: accessToken, expires_in: 3600 * 24 }); }); }); };
Cheng-Bin/oauth2-node
api-server/routes/authorize.js
JavaScript
mit
3,006
var config = require('../config') if(!config.tasks.html) return var browserSync = require('browser-sync') var gulp = require('gulp') var gulpif = require('gulp-if') var handleErrors = require('../lib/handleErrors') var htmlmin = require('gulp-htmlmin') var path = require('path') var render = require('gulp-nunjucks-render') var fs = require('fs') var exclude = path.normalize('!**/{' + config.tasks.html.excludeFolders.join(',') + '}/**') var paths = { src: [path.join(config.root.src, config.tasks.html.src, '/**/*.html'), exclude], dest: path.join(config.root.dest, config.tasks.html.dest), } var getData = function(file) { var dataPath = path.resolve(config.root.src, config.tasks.html.src, config.tasks.html.dataFile) return JSON.parse(fs.readFileSync(dataPath, 'utf8')) } var htmlTask = function() { render.nunjucks.configure([path.join(config.root.src, config.tasks.html.src)], {watch: false }) return gulp.src(paths.src) .on('error', handleErrors) .pipe(render()) .on('error', handleErrors) .pipe(gulpif(process.env.NODE_ENV == 'production', htmlmin(config.tasks.html.htmlmin))) .pipe(gulp.dest(paths.dest)) .pipe(browserSync.stream()) } gulp.task('html', htmlTask) module.exports = htmlTask
haymez/mithril-routing
gulpfile.js/tasks/html.js
JavaScript
mit
1,293
import React from "react"; import { render, screen, createMockUser } from "../../utilities/tests/test-utils"; import userEvent from "@testing-library/user-event"; import UsersList from "./UsersList"; import { user } from "../../utilities/tests/mockData"; const admin = createMockUser("admin@test.com", true, true, "ADMIN"); const props = { active: [], suspended: [], loading: false, params: {}, rootPath: "test", routes: [], loggedInUser: admin, loadUsers: jest.fn(), }; describe("UserList", () => { it("renders empty list with message if no users found", () => { render(<UsersList {...props} />); expect(screen.getByRole("link", { name: "Back" })).toBeInTheDocument(); expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent(/Users/i); expect(screen.getByRole("link", { name: "Create new user" })).toBeInTheDocument(); expect(screen.getByText(/Nothing to show/i)).toBeInTheDocument(); }); it("fetches users on load", async () => { render(<UsersList {...props} />); expect(props.loadUsers).toBeCalled(); }); it("shows loader when fetching users", () => { const newProps = { ...props, loading: true, }; render(<UsersList {...newProps} />); expect(screen.getByTestId("loader")).toBeInTheDocument(); }); it("lists active users by default", () => { const newProps = { ...props, active: [user], }; render(<UsersList {...newProps} />); const items = screen.getAllByRole("listitem"); expect(screen.getByPlaceholderText(/Search users by name/i)).toBeInTheDocument(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent("test.user-1498@ons.gov.uk"); }); it("renders list of active users by default", () => { const newProps = { ...props, active: [user], }; render(<UsersList {...newProps} />); const items = screen.getAllByRole("listitem"); expect(screen.getByPlaceholderText(/Search users by name/i)).toBeInTheDocument(); expect(items).toHaveLength(1); expect(items[0]).toHaveTextContent("test.user-1498@ons.gov.uk"); screen.getByLabelText("Show active users", { pressed: true }); }); it("renders list of inactive users when show suspended is active", () => { const newProps = { ...props, active: [user], }; render(<UsersList {...newProps} />); expect(screen.getByLabelText("Show active users", { pressed: true })).toBeInTheDocument(); expect(screen.getByLabelText("Show suspended users", { pressed: false })).toBeInTheDocument(); userEvent.click(screen.getByRole("button", { name: /suspended/i })); expect(screen.getByLabelText("Show active users", { pressed: false })).toBeInTheDocument(); expect(screen.getByLabelText("Show suspended users", { pressed: true })).toBeInTheDocument(); expect(screen.getByText(/nothing to show/i)).toBeInTheDocument(); }); });
ONSdigital/florence
src/app/views/users/UsersList.test.js
JavaScript
mit
3,148
import { setupApplicationTest as defaultSetup } from 'ember-qunit'; import startPretender from '../helpers/start-pretender'; function setupPretender(hooks) { hooks.beforeEach(function () { this.pretender = startPretender(); }); hooks.afterEach(function () { this.pretender.shutdown(); }); } export function setupApplicationTest(hooks) { defaultSetup(hooks); setupPretender(hooks); }
bgentry/ember-apollo-client
tests/helpers/setup.js
JavaScript
mit
406
import Printer from "../lib/printer"; import generate, { CodeGenerator } from "../lib"; import { parse } from "@babel/parser"; import * as t from "@babel/types"; import fs from "fs"; import path from "path"; import fixtures from "@babel/helper-fixtures"; describe("generation", function() { it("completeness", function() { Object.keys(t.VISITOR_KEYS).forEach(function(type) { expect(Printer.prototype[type]).toBeTruthy(); }); Object.keys(Printer.prototype).forEach(function(type) { if (!/[A-Z]/.test(type[0])) return; expect(t.VISITOR_KEYS[type]).toBeTruthy(); }); }); it("multiple sources", function() { const sources = { "a.js": "function hi (msg) { console.log(msg); }\n", "b.js": "hi('hello');\n", }; const parsed = Object.keys(sources).reduce(function(_parsed, filename) { _parsed[filename] = parse(sources[filename], { sourceFilename: filename, }); return _parsed; }, {}); const combinedAst = { type: "File", program: { type: "Program", sourceType: "module", body: [].concat( parsed["a.js"].program.body, parsed["b.js"].program.body, ), }, }; const generated = generate(combinedAst, { sourceMaps: true }, sources); expect(generated.map).toEqual( { version: 3, sources: ["a.js", "b.js"], mappings: "AAAA,SAASA,EAAT,CAAaC,GAAb,EAAkB;AAAEC,UAAQC,GAAR,CAAYF,GAAZ;AAAmB;;ACAvCD,GAAG,OAAH", names: ["hi", "msg", "console", "log"], sourcesContent: [ "function hi (msg) { console.log(msg); }\n", "hi('hello');\n", ], }, "sourcemap was incorrectly generated", ); expect(generated.rawMappings).toEqual( [ { name: undefined, generated: { line: 1, column: 0 }, source: "a.js", original: { line: 1, column: 0 }, }, { name: "hi", generated: { line: 1, column: 9 }, source: "a.js", original: { line: 1, column: 9 }, }, { name: undefined, generated: { line: 1, column: 11 }, source: "a.js", original: { line: 1, column: 0 }, }, { name: "msg", generated: { line: 1, column: 12 }, source: "a.js", original: { line: 1, column: 13 }, }, { name: undefined, generated: { line: 1, column: 15 }, source: "a.js", original: { line: 1, column: 0 }, }, { name: undefined, generated: { line: 1, column: 17 }, source: "a.js", original: { line: 1, column: 18 }, }, { name: "console", generated: { line: 2, column: 0 }, source: "a.js", original: { line: 1, column: 20 }, }, { name: "log", generated: { line: 2, column: 10 }, source: "a.js", original: { line: 1, column: 28 }, }, { name: undefined, generated: { line: 2, column: 13 }, source: "a.js", original: { line: 1, column: 20 }, }, { name: "msg", generated: { line: 2, column: 14 }, source: "a.js", original: { line: 1, column: 32 }, }, { name: undefined, generated: { line: 2, column: 17 }, source: "a.js", original: { line: 1, column: 20 }, }, { name: undefined, generated: { line: 3, column: 0 }, source: "a.js", original: { line: 1, column: 39 }, }, { name: "hi", generated: { line: 5, column: 0 }, source: "b.js", original: { line: 1, column: 0 }, }, { name: undefined, generated: { line: 5, column: 3 }, source: "b.js", original: { line: 1, column: 3 }, }, { name: undefined, generated: { line: 5, column: 10 }, source: "b.js", original: { line: 1, column: 0 }, }, ], "raw mappings were incorrectly generated", ); expect(generated.code).toBe( "function hi(msg) {\n console.log(msg);\n}\n\nhi('hello');", ); }); it("identifierName", function() { const code = "function foo() { bar; }\n"; const ast = parse(code, { filename: "inline" }).program; const fn = ast.body[0]; const id = fn.id; id.name += "2"; id.loc.identifierName = "foo"; const id2 = fn.body.body[0].expression; id2.name += "2"; id2.loc.identiferName = "bar"; const generated = generate( ast, { filename: "inline", sourceFileName: "inline", sourceMaps: true, }, code, ); expect(generated.map).toEqual( { version: 3, sources: ["inline"], names: ["foo", "bar"], mappings: "AAAA,SAASA,IAAT,GAAe;AAAEC;AAAM", sourcesContent: ["function foo() { bar; }\n"], }, "sourcemap was incorrectly generated", ); expect(generated.rawMappings).toEqual( [ { name: undefined, generated: { line: 1, column: 0 }, source: "inline", original: { line: 1, column: 0 }, }, { name: "foo", generated: { line: 1, column: 9 }, source: "inline", original: { line: 1, column: 9 }, }, { name: undefined, generated: { line: 1, column: 13 }, source: "inline", original: { line: 1, column: 0 }, }, { name: undefined, generated: { line: 1, column: 16 }, source: "inline", original: { line: 1, column: 15 }, }, { name: "bar", generated: { line: 2, column: 0 }, source: "inline", original: { line: 1, column: 17 }, }, { name: undefined, generated: { line: 3, column: 0 }, source: "inline", original: { line: 1, column: 23 }, }, ], "raw mappings were incorrectly generated", ); expect(generated.code).toBe("function foo2() {\n bar2;\n}"); }); it("lazy source map generation", function() { const code = "function hi (msg) { console.log(msg); }\n"; const ast = parse(code, { filename: "a.js" }).program; const generated = generate(ast, { sourceFileName: "a.js", sourceMaps: true, }); expect(Array.isArray(generated.rawMappings)).toBe(true); expect( Object.getOwnPropertyDescriptor(generated, "map"), ).not.toHaveProperty("value"); expect(generated).toHaveProperty("map"); expect(typeof generated.map).toBe("object"); }); }); describe("programmatic generation", function() { it("numeric member expression", function() { // Should not generate `0.foo` const mem = t.memberExpression( t.numericLiteral(60702), t.identifier("foo"), ); new Function(generate(mem).code); }); it("nested if statements needs block", function() { const ifStatement = t.ifStatement( t.stringLiteral("top cond"), t.whileStatement( t.stringLiteral("while cond"), t.ifStatement( t.stringLiteral("nested"), t.expressionStatement(t.numericLiteral(1)), ), ), t.expressionStatement(t.stringLiteral("alt")), ); const ast = parse(generate(ifStatement).code); expect(ast.program.body[0].consequent.type).toBe("BlockStatement"); }); it("prints directives in block with empty body", function() { const blockStatement = t.blockStatement( [], [t.directive(t.directiveLiteral("use strict"))], ); const output = generate(blockStatement).code; expect(output).toBe(`{ "use strict"; }`); }); it("flow object indentation", function() { const objectStatement = t.objectTypeAnnotation( [t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())], null, null, null, ); const output = generate(objectStatement).code; expect(output).toBe(`{ bar: string }`); }); it("flow object exact", function() { const objectStatement = t.objectTypeAnnotation( [t.objectTypeProperty(t.identifier("bar"), t.stringTypeAnnotation())], null, null, null, true, ); const output = generate(objectStatement).code; expect(output).toBe(`{| bar: string |}`); }); it("flow object indentation with empty leading ObjectTypeProperty", function() { const objectStatement = t.objectTypeAnnotation( [], [ t.objectTypeIndexer( t.identifier("key"), t.anyTypeAnnotation(), t.numberTypeAnnotation(), ), ], null, ); const output = generate(objectStatement).code; expect(output).toBe(`{ [key: any]: number }`); }); }); describe("CodeGenerator", function() { it("generate", function() { const codeGen = new CodeGenerator(t.numericLiteral(123)); const code = codeGen.generate().code; expect(parse(code).program.body[0].expression.value).toBe(123); }); }); const suites = fixtures(`${__dirname}/fixtures`); suites.forEach(function(testSuite) { describe("generation/" + testSuite.title, function() { testSuite.tests.forEach(function(task) { const testFn = task.disabled ? it.skip : it; testFn( task.title, function() { const expected = task.expect; const actual = task.actual; const actualCode = actual.code; if (actualCode) { const actualAst = parse(actualCode, { filename: actual.loc, plugins: task.options.plugins || [], strictMode: false, sourceType: "module", }); const result = generate(actualAst, task.options, actualCode); if ( !expected.code && result.code && fs.statSync(path.dirname(expected.loc)).isDirectory() && !process.env.CI ) { console.log(`New test file created: ${expected.loc}`); fs.writeFileSync(expected.loc, result.code); } else { expect(result.code).toBe(expected.code); } } }, ); }); }); });
hulkish/babel
packages/babel-generator/test/index.js
JavaScript
mit
10,581
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: "\n\n" }, dist: { src: [ 'src/_intro.js', 'src/main.js', 'src/_outro.js' ], dest: 'dist/<%= pkg.name.replace(".js", "") %>.js' } }, uglify: { options: { banner: '/*! <%= pkg.name.replace(".js", "") %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' }, dist: { files: { 'dist/<%= pkg.name.replace(".js", "") %>.min.js': ['<%= concat.dist.dest %>'] } } }, qunit: { files: ['test/*.html'] }, jshint: { files: ['dist/modelo.js'], options: { globals: { console: true, module: true, document: true }, jshintrc: '.jshintrc' } }, watch: { files: ['<%= jshint.files %>'], tasks: ['concat', 'jshint', 'qunit'] } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('test', ['jshint', 'qunit']); grunt.registerTask('default', ['concat', 'jshint', 'qunit', 'uglify']); };
colevoss/modelo
Gruntfile.js
JavaScript
mit
1,383
/** * @file EmbeddedValidator * @author Gabriel Roy <gab@uon.io> * @ignore */ "use strict"; const uon = require('uon.core'); const ValidationError = require('../ValidationError'); const TypeManager = require('../TypeManager'); /** * Embedded Type */ TypeManager.register('uon.db.Embedded', { set: function (field, value, oldValue) { // ensure field type and value type are same type // FIXME try to avoid using instanceof as node_modules caching scheme might screw us up if (!(value instanceof field.type)) { throw new ValidationError(field.key + " must of type " + field.type.name); } if (value !== oldValue) { if (oldValue !== undefined) { oldValue.removeListener(this); } value.addListener(this, field.key); } return value; }, unset: function (field, oldValue) { if (oldValue !== undefined) { oldValue.removeListener(this); } }, serialize: function (field, value, options) { return value.toObject(options && options.recursive); }, deserialize: function (field, value) { if(!value) { return undefined; } if (value instanceof field.type) { return value; } return new field.type(value); } });
uon-team/uon.db
src/types/Embedded.js
JavaScript
mit
1,396
const equalityCheckOptions = { Fail: 0, Success: 1, idle: 2 }; const gameStatusOptions = { inProgress: 0, Lost: 1, Won: 2 } const Header = (props) => ( <div> <h3>Play Nine</h3> <hr/> </div> ); class NumberBox extends React.Component { handleNumberClick = () => { this.props.handleNumberClick(this.props.number); } render() { const { number, selectedNumbers, usedNumbers, handleNumberClick } = this.props; const isSelected = selectedNumbers.includes(number); const isUsed = usedNumbers.includes(number); const numberBoxColor = isUsed ? 'lightgreen' : isSelected ? 'lightgrey' : 'grey'; return ( <div className={`numberBox ${numberBoxColor}`} onClick={this.handleNumberClick}> {number} </div> ) } } ; const NumberBoxList = (props) => { const { numbers, selectedNumbers, usedNumbers, handleNumberClick } = props; return ( <div className="numberBoxList"> {numbers && numbers.map(number => <NumberBox number={number} handleNumberClick={handleNumberClick} selectedNumbers={selectedNumbers} usedNumbers={usedNumbers} /> )} </div> ) }; const Star = (props) => ( <span className="star"> <i className="fa fa-star"/> </span> ); const StarReset = ({handleStarReset, starResetCount}) => ( <button onClick={handleStarReset} className="btn reset"> {starResetCount} <i className="fa fa-refresh"/> </button> ); const SelectedNumbers = ({selectedNumbers, handleNumberClick}) => ( <NumberBoxList numbers={selectedNumbers} selectedNumbers={selectedNumbers} usedNumbers={[]} handleNumberClick={handleNumberClick} /> ); const Dashboard = (props) => { const { starCount, selectedNumbers, handleNumberClick, handleStarReset, handleEqualityCheck, equalityCheckStatus, starResetCount } = props; const StarsNode = [...Array(starCount)].map((i) => <Star key={i}/>); return ( <div className="dashboard"> <div className="dashboard-item"> {StarsNode} </div> <div className="dashboard-item"> <EqualityChecker handleEqualityCheck={handleEqualityCheck} equalityCheckStatus={equalityCheckStatus} selectedNumbers={selectedNumbers} /> <StarReset handleStarReset={handleStarReset} starResetCount={starResetCount} /> </div> <div className="dashboard-item"> <SelectedNumbers handleNumberClick={handleNumberClick} selectedNumbers={selectedNumbers} /> </div> </div> ) }; const EqualityChecker = (props) => { const {handleEqualityCheck, equalityCheckStatus, selectedNumbers} = props; const {idle, Success} = equalityCheckOptions; const statusClass = equalityCheckStatus === idle ? "" : equalityCheckStatus === Success ? "lightgreen" : "red"; return ( <div> <button onClick={handleEqualityCheck} disabled={selectedNumbers.length === 0} className={`btn ${statusClass}`} > <i className="fa fa-check"/> </button> </div> ) }; const GameStatusBoard = ({status, handleGameReset}) => { const heading = (status === gameStatusOptions.Lost ? "Game Lost!" : "Game Won!"); return ( <div className="game-status"> <h2>{heading}</h2> <div> <button onClick={handleGameReset} className="btn"> Try again </button> </div> </div> ) }; class App extends React.Component { state = { selectedNumbers: [], usedNumbers: [], starResetCount: 10, starCount: Math.ceil(Math.random(1, 9) * 9), equalityCheckStatus: equalityCheckOptions.idle } handleNumberSelect = (number) => { const {selectedNumbers, usedNumbers, equalityCheckStatus} = this.state; const isAlreadyActivated = usedNumbers.includes(number) || selectedNumbers.includes(number) if (isAlreadyActivated) return; this.setState((prevState) => ({ equalityCheckStatus: equalityCheckOptions.idle, selectedNumbers: [...prevState.selectedNumbers, number] })); } handleNumberUnselect = (number) => { this.setState({ equalityCheckStatus: equalityCheckOptions.idle, selectedNumbers: this.state.selectedNumbers.filter((sn) => sn !== number) }); } handleNumberClick = (number) => { this.state.selectedNumbers.includes(number) ? this.handleNumberUnselect(number) : this.handleNumberSelect(number); } handleStarReset = () => { if (this.state.starResetCount === 0) return; this.setState((prevState) => ({ starResetCount: prevState.starResetCount - 1, starCount: this.generateRandomNumber(), selectedNumbers: [] })) } handleGameReset = () => { this.setState({ selectedNumbers: [], usedNumbers: [], starResetCount: 5, starCount: this.generateRandomNumber(), equalityCheckStatus: equalityCheckOptions.idle }) } handleEqualityCheck = () => { const {selectedNumbers, starResetCount, starCount, usedNumbers} = this.state; const sumOfSelected = selectedNumbers.reduce((a, b) => a + b); if (sumOfSelected === starCount) { this.setState((prevState) => ({ usedNumbers: [...prevState.usedNumbers, ...selectedNumbers], selectedNumbers: [], starCount: this.generateRandomNumber(prevState.starCount), equalityCheckStatus: equalityCheckOptions.Success }) ); } else { this.setState({equalityCheckStatus: equalityCheckOptions.Fail}); } }; calculateGameStatus = () => { const {starResetCount, usedNumbers, equalityCheckStatus, starCount} = this.state; const lastCheckFailed = starResetCount === 0 && equalityCheckStatus === equalityCheckOptions.Fail; const lastStarCountNumberAlreadyUsed = starResetCount === 0 && usedNumbers.includes(starCount); const allNumbersUsed = usedNumbers.length === 9; if (allNumbersUsed) return gameStatusOptions.Won; if (lastCheckFailed || lastStarCountNumberAlreadyUsed) return gameStatusOptions.Lost; return gameStatusOptions.InProgress; }; generateRandomNumber = (oldNumber = 0) => { let rn; //making sure that new random number doesn't repeat the old one do rn = Math.ceil(Math.random(1, 9) * 9) while (rn === oldNumber); return rn; } render() { const { starCount, selectedNumbers, usedNumbers, equalityCheckStatus, starResetCount } = this.state; const numbers = (Array(10).fill().map((n, i) => i)).slice(1); const gameStatus = this.calculateGameStatus(); return ( <div style={{minWidth: "400px"}}> <Header /> <Dashboard starCount={starCount} selectedNumbers={selectedNumbers} handleNumberClick={this.handleNumberClick} handleStarReset={this.handleStarReset} handleEqualityCheck={this.handleEqualityCheck} equalityCheckStatus={equalityCheckStatus} starResetCount={starResetCount} /> <NumberBoxList handleNumberClick={this.handleNumberClick} numbers={numbers} selectedNumbers={selectedNumbers} usedNumbers={usedNumbers} /> { gameStatus !== gameStatusOptions.InProgress && <GameStatusBoard status={gameStatus} handleGameReset={this.handleGameReset} /> } </div> ) } } ReactDOM.render( <App />, mountNode );
narekg/Play-Nine
source.js
JavaScript
mit
8,973
const { getIn, addToArray, removeFromArray, replacePath, lastIndex, isEmpty, lastItem, } = require('../../utils/functionalHelpers') module.exports = ({ licence, path, allowEmpty = false } = {}) => { const records = getIn(licence, path) if (!allowEmpty && isEmpty(records)) { throw new Error(`No records at path: ${path}`) } if (records && !Array.isArray(records)) { throw new Error(`No list at path: ${path}`) } return { add: modify(addRecord), remove: modify(removeRecord), records, last, } function last() { return records ? lastItem(records) : undefined } function addRecord({ record }) { return addToArray(record, records) } function removeRecord({ index = 0 } = {}) { const selector = !isEmpty(index) ? index : lastIndex(records) return removeFromArray(selector, 1, records) } function modify(updateMethod) { return ({ record = null, index = null } = {}) => { const newRecords = updateMethod({ record, records, index }) return replacePath(path, newRecords, licence) } } }
noms-digital-studio/licences
server/services/utils/recordList.js
JavaScript
mit
1,089
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/license */ CKEDITOR.plugins.setLang("specialchar","cs",{euro:"Znak eura",lsquo:"Počáteční uvozovka jednoduchá",rsquo:"Koncová uvozovka jednoduchá",ldquo:"Počáteční uvozovka dvojitá",rdquo:"Koncová uvozovka dvojitá",ndash:"En pomlčka",mdash:"Em pomlčka",iexcl:"Obrácený vykřičník",cent:"Znak centu",pound:"Znak libry",curren:"Znak měny",yen:"Znak jenu",brvbar:"Přerušená svislá čára",sect:"Znak oddílu",uml:"Přehláska",copy:"Znak copyrightu",ordf:"Ženský indikátor rodu",laquo:"Znak dvojitých lomených uvozovek vlevo", not:"Logistický zápor",reg:"Znak registrace",macr:"Pomlčka nad",deg:"Znak stupně",sup2:"Dvojka jako horní index",sup3:"Trojka jako horní index",acute:"Čárka nad vpravo",micro:"Znak mikro",para:"Znak odstavce",middot:"Tečka uprostřed",cedil:"Ocásek vlevo",sup1:"Jednička jako horní index",ordm:"Mužský indikátor rodu",raquo:"Znak dvojitých lomených uvozovek vpravo",frac14:"Obyčejný zlomek jedna čtvrtina",frac12:"Obyčejný zlomek jedna polovina",frac34:"Obyčejný zlomek tři čtvrtiny",iquest:"Znak obráceného otazníku", Agrave:"Velké písmeno latinky A s čárkou nad vlevo",Aacute:"Velké písmeno latinky A s čárkou nad vpravo",Acirc:"Velké písmeno latinky A s vokáněm",Atilde:"Velké písmeno latinky A s tildou",Auml:"Velké písmeno latinky A s dvěma tečkami",Aring:"Velké písmeno latinky A s kroužkem nad",AElig:"Velké písmeno latinky Æ",Ccedil:"Velké písmeno latinky C s ocáskem vlevo",Egrave:"Velké písmeno latinky E s čárkou nad vlevo",Eacute:"Velké písmeno latinky E s čárkou nad vpravo",Ecirc:"Velké písmeno latinky E s vokáněm", Euml:"Velké písmeno latinky E s dvěma tečkami",Igrave:"Velké písmeno latinky I s čárkou nad vlevo",Iacute:"Velké písmeno latinky I s čárkou nad vpravo",Icirc:"Velké písmeno latinky I s vokáněm",Iuml:"Velké písmeno latinky I s dvěma tečkami",ETH:"Velké písmeno latinky Eth",Ntilde:"Velké písmeno latinky N s tildou",Ograve:"Velké písmeno latinky O s čárkou nad vlevo",Oacute:"Velké písmeno latinky O s čárkou nad vpravo",Ocirc:"Velké písmeno latinky O s vokáněm",Otilde:"Velké písmeno latinky O s tildou", Ouml:"Velké písmeno latinky O s dvěma tečkami",times:"Znak násobení",Oslash:"Velké písmeno latinky O přeškrtnuté",Ugrave:"Velké písmeno latinky U s čárkou nad vlevo",Uacute:"Velké písmeno latinky U s čárkou nad vpravo",Ucirc:"Velké písmeno latinky U s vokáněm",Uuml:"Velké písmeno latinky U s dvěma tečkami",Yacute:"Velké písmeno latinky Y s čárkou nad vpravo",THORN:"Velké písmeno latinky Thorn",szlig:"Malé písmeno latinky ostré s",agrave:"Malé písmeno latinky a s čárkou nad vlevo",aacute:"Malé písmeno latinky a s čárkou nad vpravo", acirc:"Malé písmeno latinky a s vokáněm",atilde:"Malé písmeno latinky a s tildou",auml:"Malé písmeno latinky a s dvěma tečkami",aring:"Malé písmeno latinky a s kroužkem nad",aelig:"Malé písmeno latinky ae",ccedil:"Malé písmeno latinky c s ocáskem vlevo",egrave:"Malé písmeno latinky e s čárkou nad vlevo",eacute:"Malé písmeno latinky e s čárkou nad vpravo",ecirc:"Malé písmeno latinky e s vokáněm",euml:"Malé písmeno latinky e s dvěma tečkami",igrave:"Malé písmeno latinky i s čárkou nad vlevo",iacute:"Malé písmeno latinky i s čárkou nad vpravo", icirc:"Malé písmeno latinky i s vokáněm",iuml:"Malé písmeno latinky i s dvěma tečkami",eth:"Malé písmeno latinky eth",ntilde:"Malé písmeno latinky n s tildou",ograve:"Malé písmeno latinky o s čárkou nad vlevo",oacute:"Malé písmeno latinky o s čárkou nad vpravo",ocirc:"Malé písmeno latinky o s vokáněm",otilde:"Malé písmeno latinky o s tildou",ouml:"Malé písmeno latinky o s dvěma tečkami",divide:"Znak dělení",oslash:"Malé písmeno latinky o přeškrtnuté",ugrave:"Malé písmeno latinky u s čárkou nad vlevo", uacute:"Malé písmeno latinky u s čárkou nad vpravo",ucirc:"Malé písmeno latinky u s vokáněm",uuml:"Malé písmeno latinky u s dvěma tečkami",yacute:"Malé písmeno latinky y s čárkou nad vpravo",thorn:"Malé písmeno latinky thorn",yuml:"Malé písmeno latinky y s dvěma tečkami",OElig:"Velká ligatura latinky OE",oelig:"Malá ligatura latinky OE",372:"Velké písmeno latinky W s vokáněm",374:"Velké písmeno latinky Y s vokáněm",373:"Malé písmeno latinky w s vokáněm",375:"Malé písmeno latinky y s vokáněm",sbquo:"Dolní 9 uvozovka jednoduchá", 8219:"Horní obrácená 9 uvozovka jednoduchá",bdquo:"Dolní 9 uvozovka dvojitá",hellip:"Trojtečkový úvod",trade:"Obchodní značka",9658:"Černý ukazatel směřující vpravo",bull:"Kolečko",rarr:"Šipka vpravo",rArr:"Dvojitá šipka vpravo",hArr:"Dvojitá šipka vlevo a vpravo",diams:"Černé piky",asymp:"Téměř se rovná"});
maukoese/jabali
app/assets/js/ckeditor/plugins/specialchar/dialogs/lang/cs.js
JavaScript
mit
4,968
var m = require('mongodb'), _ = require('underscore'), Q = require('q'), db_defer = Q.defer(); //new m.Db( 'node-mongo-meetings', //new m.Server("127.0.0.1", 27017, {auto_reconnect: true})); //db.open(function () { //}); var mongostr = process.env.MONGOHQ_URL || 'mongodb://127.0.0.1:27017/node-mongo-meetings'; function connectIt() { m.connect(mongostr, {auto_reconnect: true}, function(error, db) { console.log('connected to db'); db.addListener("error", function (error) { console.log("Error connecting to MongoHQ"); }); db_defer.resolve(db); }); } connectIt(); exports.db = function (callback) { db_defer.promise.then(callback); };
wheeyls/meetingVis
models/db.js
JavaScript
mit
701
import show from './show' import update from './update' import photo from './photo' import password from './password' export default [ show, update, photo, password ]
ccetc/platform
src/admin/middleware/account/index.js
JavaScript
mit
176
'use strict'; const JDLRelationship = require('./jdl_relationship'), buildException = require('../exceptions/exception_factory').buildException, exceptions = require('../exceptions/exception_factory').exceptions; class JDLRelationships { constructor() { this.relationships = { OneToOne: {}, OneToMany: {}, ManyToOne: {}, ManyToMany: {} }; this.size = 0; } add(relationship) { if (!relationship) { throw new buildException(exceptions.NullPointer, 'A relationship must be passed.'); } if (!JDLRelationship.isValid(relationship)) { throw new buildException(exceptions.InvalidObject, 'A valid relationship must be passed.'); } this.relationships[relationship.type][relationship.getId()] = relationship; this.size++; } toArray() { let relationships = []; for (let type in this.relationships) { if (this.relationships.hasOwnProperty(type)) { for (let relationshipId in this.relationships[type]) { if (this.relationships[type].hasOwnProperty(relationshipId)) { relationships.push(this.relationships[type][relationshipId]); } } } } return relationships; } toString() { var string = ''; for (let type in this.relationships) { if (this.relationships.hasOwnProperty(type) && Object.keys(this.relationships[type]).length !== 0) { let result = relationshipTypeToString(this.relationships[type], type); string += `${result}\n`; } } return string.slice(0, string.length - 1); } } module.exports = JDLRelationships; function relationshipTypeToString(relationships, type) { let relationship = `relationship ${type} {\n`; for (let internalRelationship in relationships) { if (relationships.hasOwnProperty(internalRelationship)) { let lines = relationships[internalRelationship].toString().split('\n'); lines = lines.slice(1, lines.length - 1); relationship += `${lines.join('')},\n`; } } relationship = `${relationship.slice(0, relationship.length - 2)}\n}`; return relationship; }
axel-halin/Thesis-JHipster
FML-brute/node_modules/jhipster-core/lib/core/jdl_relationships.js
JavaScript
mit
2,123
/* Search item per level */ FILTER.prototype.SelectCraftable = function(ev) { var selected = ev.target.dataset.slot.replace(/[0-9]/g, ""); var target = ev.target; // Remove the element if (target.classList.contains('selected')) { target.classList.remove('selected'); } // Add the element else { target.classList.add('selected'); } this.filter.slotHat = []; for (let i = 10, len = this.classesAndSlot.length; i < len; i++) { if (!this.classesAndSlot[i].classList.contains('selected')) { this.filter.slotHat.push(this.classesAndSlot[i].dataset.slot); } } // Apply changes this.ApplyFilter(); }; console.log('FILTER Craftables');
tag9724/Scrap.tf-stylizer
src/js/inject/filters/craftable.js
JavaScript
mit
757
/* global describe, it, beforeEach */ const SuperCLI = require('../lib/super-cli') let cli describe('# cli.run', () => { beforeEach(() => { cli = new SuperCLI({ autoRun: false }) }) it('Should trigger a command', done => { cli.on('command', done) cli.run('command') }) it('Should catch all commands if there isn\'t found a registered command', done => { cli.on('*', () => done()) cli.run('other-command') }) })
kvartborg/super-cli
test/super-cli.run.js
JavaScript
mit
457
'use strict'; System.register(['./busyconfiguration', './busy'], function (_export, _context) { "use strict"; var BusyConfiguration, Busy; function configure(aurelia, callback) { var config = new BusyConfiguration(); if (typeof callback === 'function') { callback(config); } } _export('configure', configure); return { setters: [function (_busyconfiguration) { BusyConfiguration = _busyconfiguration.BusyConfiguration; }, function (_busy) { Busy = _busy.Busy; }], execute: function () { _export('Busy', Busy); } }; });
drivesoftware/aurelia-busy-indicator
dist/system/index.js
JavaScript
mit
594
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, Image, ListView, Dimensions, Navigator, NavigatorIOS, ScrollView, ActivityIndicator, Platform, TouchableOpacity, View } from 'react-native'; // import ArticleList from './ArticleList'; import ArticleDetail from './ArticleDetail'; let {height,width} = Dimensions.get('window'); let HostApi = // 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'; 'http://172.16.101.202/'; //http://172.16.101.202/play/circle/getBannerList4C let BannerListApi = HostApi+'play/circle/getBannerList4C'; //http://172.16.101.202/play/circle/getPostList4C let ArticleListApi = HostApi+'play/circle/getPostList4C'; class CustomLabel extends Component{ render(){ return( <Text style = {this.props.style}>{this.props.content}</Text> ); } } class ScrollViewContent extends Component{ render(){ let bannerTitle = this.props.bannerInfo.title; let bannerImage = this.props.bannerInfo.bannerImgUrl; let image = { uri:HostApi+bannerImage } // require('../Images/blue.png'); return ( <View> <Image source = {image} style = {{flex:1,flexDirection:'column-reverse',width:width-20,margin:10}}> <Text style= {{fontSize:16,color:'white',marginBottom:10,marginLeft:10,backgroundColor:'rgba(100, 100, 100, 0.00001)'}}>{bannerTitle}</Text> </Image> </View> ); } } class ListViewCell extends Component{ constructor(props){ super(props); // console.warn('cell---->selection:'+this.props.selectionID+' row:'+this.props.rowID); } _ListViewCellClicked(){ // console.warn('clicked rowID:'+this.props.rowID); // console.warn('navigator:'+this.props.navigator); this.props.navigator.push({ // leftButtonTitle:'back', leftButtonIcon:require('../Images/nav_back.png'), onLeftButtonPress:()=>this.props.navigator.pop(), component:ArticleDetail, title:'帖子详情', // barTintColor: '#996699', translucent:true, passProps:{ text:'这是从帖子界面获取到的文本', }, }); } render(){ let rowData = this.props.currentRowData; let tagListArray = rowData.tagList; let image = { uri:HostApi+rowData.coverImgURL }; let postTime = new Date(); postTime.setTime(rowData.postTime); // console.warn(postTime); //如果图片资源地址不可用时,显示默认占位图 let headImage = require('../Images/默认头像灰.png'); if(rowData.authorInfo.photoURL){ headImage = { uri:HostApi+rowData.authorInfo.photoURL } } return( <TouchableOpacity onPress = {()=>this._ListViewCellClicked()}> <View style = {styles.cellContainer}> <Image source = {image} style = {styles.imageStyle}></Image> {/* 标签 */} <CustomLabel style ={{fontSize:15,color: 'gray',textAlign:'left',marginLeft:10}} content = {tagListArray[0].tagName}/> {/* 标题 */} <Text numberOfLines ={2} style = {{fontSize:18,color:'brown',marginVertical:5,marginLeft:10}}>{rowData.title}</Text> <View style = {{flexDirection:'row',justifyContent:'space-between'}}> {/* 头像 */} <Image source = {headImage} style = {{marginBottom:5,marginLeft:10,alignSelf:'center',width:10,height:10}}/> {/* 用户名 */} <Text style={styles.userNanme}>{rowData.authorInfo.nickName}</Text> {/* 发送时间 */} <Text style={styles.updateTime}>{postTime.toLocaleString()}</Text> {/* 点赞数 */} <Text style={styles.loveCont}>{rowData.thumbNumber}</Text> </View> </View> </TouchableOpacity> ); } } class ArticleList extends Component { constructor(props){ super(props); // let ArticleListJSON = require('./ArticleList.json'); // let ArticleListArray = ArticleListJSON.postListPerPage.postList; // let BannerListJSON = require('./ArticleBannerList.json'); // let BannerListArray = BannerListJSON.bannerList; // console.warn('数组长度:'+ArticleListArray.length); const ds = new ListView.DataSource({rowHasChanged:(r1,r2)=> r1 !== r2}); this.state = { dataSource: ds, // ds.cloneWithRows(ArticleListArray), scrollViewIndex:0, bannerDataSource:null, // bannerDataSource:BannerListArray, }; // console.warn(height); // console.warn(ArticleListApi); setInterval(()=>{ if(null !=this.state.bannerDataSource){ let i = (++this.state.scrollViewIndex)%this.state.bannerDataSource.length; // console.warn(i); this.setState({scrollViewIndex:i}); //滚动到指定的x, y偏移处 _scrollView.scrollTo({x:width*i,y:0,animated:true}); // _scrollView.scrollToEnd({animated:false}); } },3000); // 在ES6中,如果在自定义的函数里使用了this关键字,则需要对其进行“绑定”操作,否则this的指向不对 // 像下面这行代码一样,在constructor中使用bind是其中一种做法(还有一些其他做法,如使用箭头函数等) this._requestBannerListData = this._requestBannerListData.bind(this); } _requestBannerListData(){ fetch(BannerListApi,{ method:'POST', header:{ 'Content-Type':'application/x-www-form-urlencoded', }, body:'', }) .then((response)=>response.json()) .then((responseJson)=>{ // console.warn(responseJson.bannerList[0].title); // 注意,这里使用了this关键字,为了保证this在调用时仍然指向当前组件,我们需要对其进行“绑定”操作 this.setState({bannerDataSource:responseJson.bannerList}); }) .catch((error)=>{ console.error(error); }) .done(); } _requestArticleListData(){ fetch(ArticleListApi,{ method:'POST', header:{ 'Content-Type':'application/x-www-form-urlencoded', }, body:'boardId=1&pageNumber=0', }) .then(response=>response.json()) .then(responseJson=>{ // FIXME: 为什么每次请求的数据都只有一条,且还是占位脏数据 // console.warn('文章条数:'+responseJson.postListPerPage.postList.length); // console.warn('文章标题:'+responseJson.postListPerPage.postList[0].title); let ArticleListJSON = require('./ArticleList.json'); let ArticleListArray = ArticleListJSON.postListPerPage.postList; // console.warn(ArticleListArray.length); // console.warn(ArticleListArray[0].title); this.setState({ dataSource:this.state.dataSource.cloneWithRows(ArticleListArray), }); }) .catch(error=>{ console.error(error); }) .done(); } componentDidMount(){ this._requestBannerListData(); this._requestArticleListData(); } componentWillUnmoont(){ clearInterval(); } render() { // console.warn('title:'+this.props.navigator); //设置state时,会重新渲染一次组件 if(!this.state.bannerDataSource || !this.state.dataSource || this.state.dataSource.length <1){ return ( <View style = {{flex:1,'justifyContent':'center'}}> <ActivityIndicator animating = {true} size = 'large'/> <Text style = {{textAlign:'center',color:'gray'}}>Loading...</Text> </View> // {/* <View style = {{backgroundColor:'red',alignSelf:'center',width:100,height:100}}> // <Text>loading message</Text> // </View> */} ); } return ( <View style ={styles.container}> <ScrollView // QUESTION: ref相关,_scrollView怎么不用定义 ref ={(scrollView)=>{ _scrollView = scrollView;}} style = {styles.scrollViewContainer} // contentContainerStyle = horizontal = {true} showsHorizontalScrollIndicator = {false} pagingEnabled = {true} // scrollEnabled = {true} automaticallyAdjustContentInsets = {true} onScroll = {()=>{ // console.warn('hha '); }} onContentSizeChange = {(contentWidth,contentHeight)=>{ // console.warn(contentWidth+','+contentHeight); }} > { // 遍历数组,设置控件 // console.warn(this.state.bannerDataSource); this.state.bannerDataSource.map((bannerInfo,i)=> // console.warn(bannerInfo.title); <ScrollViewContent key={i} bannerInfo = {bannerInfo} /> ) } {/* //普通的设置方法 <ScrollViewContent bannerInfo = {BannerListArray[0]}/> <ScrollViewContent bannerInfo = {BannerListArray[1]}/> <ScrollViewContent bannerInfo = {BannerListArray[2]}/> <ScrollViewContent bannerInfo = {BannerListArray[3]}/> */} </ScrollView> <ListView dataSource = {this.state.dataSource} renderRow = {(rowData,selection,row)=> { // console.warn('selection:'+selection+' row:'+row); return <ListViewCell currentRowData = {rowData} selectionID = {selection} rowID ={row} navigator = {this.props.navigator}/>}} //可使用borderBottomWidth实现 renderSeparator = {(selection,row) => <View key= {`${selection} -${row}`} style = {styles.cellSeparator} />} /> </View> // <Navigator // initialRoute = {{title:'圈子',index:0}} // renderScene = {(route, navigator)=> // <Text>hah {route.title}!</Text> // } // style={{padding: 100}} // /> // <View style={styles.container}> // <ListView // dataSource = {this.state.dataSource} // renderRow = {(rowData)=> <ListViewCell currentRowData = {rowData}/>} // renderScrollComponent = {()=>} // //可使用borderBottomWidth实现 // renderSeparator = {(selection,row) => <View key= {`${selection} -${row}`} style = {styles.cellSeparator} />} // /> // {/* <View style = {styles.cellContainer}> // <Image source = {imageName} style = {styles.imageStyle}></Image> // <CustomLabel style ={{fontSize:15,color: 'white',textAlign:'left',marginLeft:10}} content = '投资策略'/> // <Text style = {{fontSize:20,color:'brown',marginVertical:5,marginLeft:10}}>文章标题</Text> // <View style = {{flexDirection:'row',justifyContent:'space-between'}}> // <Text style={styles.userNanme}>用户名</Text> // <Text style={styles.updateTime}>更新时间</Text> // <Text style={styles.loveCont}>100</Text> // </View> // </View> */} // </View> ); } } export default class Article extends Component { constructor(props){ super(props); this.state = { }; } componentDidMount(){ } componentWillUnmoont(){ clearInterval(); } _GoToArticleDetail(){ // console.warn('帖子详情'); // TODO: 隐藏tabbar this.refs.nav.push({ // leftButtonTitle:'back', leftButtonIcon:require('../Images/nav_back.png'), onLeftButtonPress:()=>this.refs.nav.pop(), component:ArticleDetail, title:'帖子详情', // barTintColor: '#996699', translucent:true, passProps:{ text:'这是从帖子界面获取到的文本', }, }); } render() { let defaultComponent = ArticleList; let defaultName = 'ArticleList'; return ( // <Navigator // initialRoute = {{component:ArticleList,name:defaultName,index:0}} // renderScene = {(route,navigator)=>{ // let Component = route.component; // if(Component){ // return <Component {...route.params} navigator = {navigator} /> // } // }} // configureScene = {()=>{ return Navigator.SceneConfigs.VerticalDownSwipeJump;}} // /> <NavigatorIOS ref = 'nav' initialRoute = {{ component:defaultComponent, title:'投资圈', rightButtonTitle:'详情', translucent:true, onRightButtonPress:()=>this._GoToArticleDetail(), }} style = {{flex:1}} ></NavigatorIOS> // < ArticleList /> // <View> // <ScrollView // // QUESTION: ref相关,_scrollView怎么不用定义 // ref ={(scrollView)=>{ _scrollView = scrollView;}} // style = {styles.scrollViewContainer} // // contentContainerStyle = // horizontal = {true} // showsHorizontalScrollIndicator = {false} // pagingEnabled = {true} // // scrollEnabled = {true} // automaticallyAdjustContentInsets = {true} // onScroll = {()=>{ // // console.warn('hha '); // }} // onContentSizeChange = {(contentWidth,contentHeight)=>{ // // console.warn(contentWidth+','+contentHeight); // }} // > // { // // 遍历数组,设置控件 // // console.warn(this.state.bannerDataSource); // this.state.bannerDataSource.map((bannerInfo,i)=> // // console.warn(bannerInfo.title); // <ScrollViewContent key={i} bannerInfo = {bannerInfo} /> // ) // } // {/* //普通的设置方法 // <ScrollViewContent bannerInfo = {BannerListArray[0]}/> // <ScrollViewContent bannerInfo = {BannerListArray[1]}/> // <ScrollViewContent bannerInfo = {BannerListArray[2]}/> // <ScrollViewContent bannerInfo = {BannerListArray[3]}/> */} // </ScrollView> // <ListView // dataSource = {this.state.dataSource} // renderRow = {(rowData)=> <ListViewCell currentRowData = {rowData}/>} // //可使用borderBottomWidth实现 // renderSeparator = {(selection,row) => <View key= {`${selection} -${row}`} style = {styles.cellSeparator} />} // /> // </View> // <Navigator // initialRoute = {{title:'圈子',index:0}} // renderScene = {(route, navigator)=> // <Text>hah {route.title}!</Text> // } // style={{padding: 100}} // /> // <View style={styles.container}> // <ListView // dataSource = {this.state.dataSource} // renderRow = {(rowData)=> <ListViewCell currentRowData = {rowData}/>} // renderScrollComponent = {()=>} // //可使用borderBottomWidth实现 // renderSeparator = {(selection,row) => <View key= {`${selection} -${row}`} style = {styles.cellSeparator} />} // /> // {/* <View style = {styles.cellContainer}> // <Image source = {imageName} style = {styles.imageStyle}></Image> // <CustomLabel style ={{fontSize:15,color: 'white',textAlign:'left',marginLeft:10}} content = '投资策略'/> // <Text style = {{fontSize:20,color:'brown',marginVertical:5,marginLeft:10}}>文章标题</Text> // <View style = {{flexDirection:'row',justifyContent:'space-between'}}> // <Text style={styles.userNanme}>用户名</Text> // <Text style={styles.updateTime}>更新时间</Text> // <Text style={styles.loveCont}>100</Text> // </View> // </View> */} // </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, //子元素沿主轴的对齐方式 justifyContent: 'center', //子元素沿着次轴的对齐方式 // alignItems: 'center', backgroundColor: '#FFFFFF', // '#FFFFFF', overflow:'hidden', paddingTop:64, }, scrollViewContainer:{ // marginTop:Platform.OS === 'android'?0:20, height:280, backgroundColor:'lightgray', }, cellContainer:{ // flex:1, // justifyContent:'center', // alignItems:'center', // height:100, // backgroundColor: `#F5FCFF`, // borderColor:'black', // borderBottomWidth:1, }, cellSeparator:{ backgroundColor: 'black', height: 0.5, }, imageStyle:{ alignSelf:'center', margin:10, width:width - 20, height:200, }, userNanme: { fontSize: 13, textAlign: 'center', // backgroundColor:'red', marginHorizontal:10, marginBottom: 5, }, updateTime: { fontSize:13, textAlign: 'left', flex:1, color: '#333333', // backgroundColor:'yellow', marginBottom: 5, }, loveCont:{ fontSize:13, color: '#666666', textAlign:'right', // backgroundColor:'red', marginRight:10, marginBottom: 5, }, }); // AppRegistry.registerComponent('Demo4', () => Demo4);
Quxiaolei/Study_RN
Demo4/Container/Article.js
JavaScript
mit
16,790
import { test, moduleFor } from 'ember-qunit'; import LtiAppsRoute from 'appkit/routes/lti-apps'; moduleFor('route:lti-apps', 'Unit: routes/lti-apps'); test('it exists', function() { ok(this.subject() instanceof LtiAppsRoute); });
instructure/lti-public-resources-eak
tests/unit/routes/lti-apps-test.js
JavaScript
mit
235
module.exports = diff function diff(o,o2,report,fragment){ fragment = fragment||[] if(!report) throw new TypeError("missing report! must be an array.") if(Array.isArray(o)) { // check length if(!Array.isArray(o2)){ report.push({path:fragment,reason:'the other side is not an array',code:'ANARRAY'}) } else { if(o.length != o2.length){ if(o.length < o2.length){ report.push({path:fragment,reason:'array has fewer items.',values:{a:o.length,b:o2.length},code:'ALESS'}) } else { report.push({path:fragment,reason:'array has more items.',values:{a:o.length,b:o2.length},code:'AMORE'}) } } //? if i have a length error every item could be off by one //? i check that each item is anywhere in the array then if the array is sorted //? check each item // assumed sort will generate a bunch of errors on length mismatch for(var i=0; i < o.length;++i){ diff(o[i],o2[i],report,fkey(fragment,i)) } } } else if(!o) { if(o !== o2) { report.push({path:fragment,reason:'falsey value is not equal ',values:{a:o,b:o2},code:'VFALSEY'}) } } else if(typeof o === 'object') { if(!o2) { // missing object for o2 value // i do not include the a side object because that would bloat logs. report.push({path:fragment,reason:'object missing on other side.',values:{a:o},code:'ONEW'}) } else { var keys = Object.keys(o); var keys2 = Object.keys(o2) if(keys.length < keys2.length) { report.push({path:fragment,reason:'object has more items. ',values:{a:keys.length,b:keys2.length},code:'OMORE'}) } else if(keys.length < keys.length) { report.push({path:fragment,reason:'object has fewer items.',values:{a:keys.length,b:keys2.length},code:'OLESS'}) } // key length check for(var i=0;i<keys.length;++i){ diff(o[keys[i]],o2[keys[i]],report,fkey(fragment,keys[i])) } } } else { // plain value if(o != o2) { report.push({path:fragment,reason:'values are not equal',value:{a:o,b:o2},code:'VNEQUAL'}) } } } function fkey(f,v){ var n = f.slice.apply(f) n.push(v) return n }
soldair/changes-feed-diff
lib/diff.js
JavaScript
mit
2,248
module.exports = { parser: 'babel-eslint', env: { browser: true, es6: true, node: true, }, plugins: ['react'], rules: { 'no-unused-vars': [ 'error', { args: 'after-used', argsIgnorePattern: '^event$', ignoreRestSiblings: true, vars: 'all', }, ], curly: [2, 'multi-line'], 'jsx-quotes': 1, 'no-shadow': 1, 'no-trailing-spaces': 1, 'no-underscore-dangle': 1, 'no-unused-expressions': 1, 'object-curly-spacing': [1, 'always'], quotes: [2, 'single', 'avoid-escape'], 'react/jsx-boolean-value': 1, 'react/jsx-no-undef': 1, 'react/jsx-uses-react': 1, 'react/jsx-uses-vars': 1, 'react/jsx-wrap-multilines': 1, 'react/no-did-mount-set-state': 1, 'react/no-did-update-set-state': 1, 'react/no-unknown-property': 1, 'react/react-in-jsx-scope': 1, 'react/self-closing-comp': 1, 'react/sort-prop-types': 1, semi: 2, strict: 0, }, };
jossmac/react-scrolllock
.eslintrc.js
JavaScript
mit
987
version https://git-lfs.github.com/spec/v1 oid sha256:895b2329b667b4f730407acd1cfd6994bf53fb6c987e524b7e13c8ba203c8bb2 size 1611
yogeshsaroya/new-cdnjs
ajax/libs/knockout-validation/2.0.2/localization/ro-RO.js
JavaScript
mit
129
import React from "react"; import Avatar from "material-ui/Avatar"; import ReplacedDividerText from "../components/ReplacedDividerText"; import "./AboutPage.css"; export default ({ picture, about }) => ( <div className="about"> <Avatar src={picture || "https://www.gravatar.com/avatar?d=mp&s=1000"} size={200} /> <p className="about-text"> <ReplacedDividerText text={about} divider="." replacement={ <span> .<br /> </span> } /> </p> </div> );
lehaSVV2009/resume
src/containers/AboutPage.js
JavaScript
mit
553