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
'use strict' const Sequelize = require('sequelize') const db = require('APP/db') const House = db.define('houses', { name: Sequelize.STRING }) module.exports = House
arinova/Expelliarmus
db/models/house.js
JavaScript
mit
170
const elasticsearch = require('elasticsearch'); const async = require('async'); const IndexStore = require('./indexstore.js'); const Mapping = require('./mappings.js'); class Store { constructor(config) { let mapping = new Mapping(config); // https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/configuration.html let client = new elasticsearch.Client({ host: config.elastic.host + ':' + config.elastic.port, keepAlive: false, requestTimeout: 1000 * 60 * 60 * 3, log: [{ type: 'stdio', levels: config.elastic.log || ['error'] }] }); this.Tender = new IndexStore(mapping.TENDER, client); this.Buyer = new IndexStore(mapping.BUYER, client); this.Supplier = new IndexStore(mapping.SUPPLIER, client); this.client = client; } init(cb) { console.log('Open connection to elasticsearch'); this.client.ping({ requestTimeout: 1000 // ping usually has a 100ms timeout }, (error) => { if (error) { console.log('elasticsearch could not be reached'); return cb(error); } async.forEachSeries( [this.Tender, this.Buyer, this.Supplier], (index, next) => { index.checkIndex(next); }, () => { console.log('Connection open'); cb(); }); }); } close(cb) { this.client.close(); cb(); } } module.exports = Store;
digiwhist/opentender-backend
lib/store.js
JavaScript
mit
1,340
{ return { grid: gridData }; }
stas-vilchik/bdd-ml
data/7838.js
JavaScript
mit
39
/* Script: Selectors.js Adds advanced CSS Querying capabilities for targeting elements. Also includes pseudoselectors support. License: MIT-style license. */ Native.implement([Document, Element], { getElements: function(expression, nocash){ expression = expression.split(','); var items, local = {}; for (var i = 0, l = expression.length; i < l; i++){ var selector = expression[i], elements = Selectors.Utils.search(this, selector, local); if (i != 0 && elements.item) elements = $A(elements); items = (i == 0) ? elements : (items.item) ? $A(items).concat(elements) : items.concat(elements); } return new Elements(items, {ddup: (expression.length > 1), cash: !nocash}); } }); Element.implement({ match: function(selector){ if (!selector || (selector == this)) return true; var tagid = Selectors.Utils.parseTagAndID(selector); var tag = tagid[0], id = tagid[1]; if (!Selectors.Filters.byID(this, id) || !Selectors.Filters.byTag(this, tag)) return false; var parsed = Selectors.Utils.parseSelector(selector); return (parsed) ? Selectors.Utils.filter(this, parsed, {}) : true; } }); var Selectors = {Cache: {nth: {}, parsed: {}}}; Selectors.RegExps = { id: (/#([\w-]+)/), tag: (/^(\w+|\*)/), quick: (/^(\w+|\*)$/), splitter: (/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g), combined: (/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g) }; Selectors.Utils = { chk: function(item, uniques){ if (!uniques) return true; var uid = $uid(item); if (!uniques[uid]) return uniques[uid] = true; return false; }, parseNthArgument: function(argument){ if (Selectors.Cache.nth[argument]) return Selectors.Cache.nth[argument]; var parsed = argument.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/); if (!parsed) return false; var inta = parseInt(parsed[1]); var a = (inta || inta === 0) ? inta : 1; var special = parsed[2] || false; var b = parseInt(parsed[3]) || 0; if (a != 0){ b--; while (b < 1) b += a; while (b >= a) b -= a; } else { a = b; special = 'index'; } switch (special){ case 'n': parsed = {a: a, b: b, special: 'n'}; break; case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break; case 'even': parsed = {a: 2, b: 1, special: 'n'}; break; case 'first': parsed = {a: 0, special: 'index'}; break; case 'last': parsed = {special: 'last-child'}; break; case 'only': parsed = {special: 'only-child'}; break; default: parsed = {a: (a - 1), special: 'index'}; } return Selectors.Cache.nth[argument] = parsed; }, parseSelector: function(selector){ if (Selectors.Cache.parsed[selector]) return Selectors.Cache.parsed[selector]; var m, parsed = {classes: [], pseudos: [], attributes: []}; while ((m = Selectors.RegExps.combined.exec(selector))){ var cn = m[1], an = m[2], ao = m[3], av = m[5], pn = m[6], pa = m[7]; if (cn){ parsed.classes.push(cn); } else if (pn){ var parser = Selectors.Pseudo.get(pn); if (parser) parsed.pseudos.push({parser: parser, argument: pa}); else parsed.attributes.push({name: pn, operator: '=', value: pa}); } else if (an){ parsed.attributes.push({name: an, operator: ao, value: av}); } } if (!parsed.classes.length) delete parsed.classes; if (!parsed.attributes.length) delete parsed.attributes; if (!parsed.pseudos.length) delete parsed.pseudos; if (!parsed.classes && !parsed.attributes && !parsed.pseudos) parsed = null; return Selectors.Cache.parsed[selector] = parsed; }, parseTagAndID: function(selector){ var tag = selector.match(Selectors.RegExps.tag); var id = selector.match(Selectors.RegExps.id); return [(tag) ? tag[1] : '*', (id) ? id[1] : false]; }, filter: function(item, parsed, local){ var i; if (parsed.classes){ for (i = parsed.classes.length; i--; i){ var cn = parsed.classes[i]; if (!Selectors.Filters.byClass(item, cn)) return false; } } if (parsed.attributes){ for (i = parsed.attributes.length; i--; i){ var att = parsed.attributes[i]; if (!Selectors.Filters.byAttribute(item, att.name, att.operator, att.value)) return false; } } if (parsed.pseudos){ for (i = parsed.pseudos.length; i--; i){ var psd = parsed.pseudos[i]; if (!Selectors.Filters.byPseudo(item, psd.parser, psd.argument, local)) return false; } } return true; }, getByTagAndID: function(ctx, tag, id){ if (id){ var item = (ctx.getElementById) ? ctx.getElementById(id, true) : Element.getElementById(ctx, id, true); return (item && Selectors.Filters.byTag(item, tag)) ? [item] : []; } else { return ctx.getElementsByTagName(tag); } }, search: function(self, expression, local){ var splitters = []; var selectors = expression.trim().replace(Selectors.RegExps.splitter, function(m0, m1, m2){ splitters.push(m1); return ':)' + m2; }).split(':)'); var items, filtered, item; for (var i = 0, l = selectors.length; i < l; i++){ var selector = selectors[i]; if (i == 0 && Selectors.RegExps.quick.test(selector)){ items = self.getElementsByTagName(selector); continue; } var splitter = splitters[i - 1]; var tagid = Selectors.Utils.parseTagAndID(selector); var tag = tagid[0], id = tagid[1]; if (i == 0){ items = Selectors.Utils.getByTagAndID(self, tag, id); } else { var uniques = {}, found = []; for (var j = 0, k = items.length; j < k; j++) found = Selectors.Getters[splitter](found, items[j], tag, id, uniques); items = found; } var parsed = Selectors.Utils.parseSelector(selector); if (parsed){ filtered = []; for (var m = 0, n = items.length; m < n; m++){ item = items[m]; if (Selectors.Utils.filter(item, parsed, local)) filtered.push(item); } items = filtered; } } return items; } }; Selectors.Getters = { ' ': function(found, self, tag, id, uniques){ var items = Selectors.Utils.getByTagAndID(self, tag, id); for (var i = 0, l = items.length; i < l; i++){ var item = items[i]; if (Selectors.Utils.chk(item, uniques)) found.push(item); } return found; }, '>': function(found, self, tag, id, uniques){ var children = Selectors.Utils.getByTagAndID(self, tag, id); for (var i = 0, l = children.length; i < l; i++){ var child = children[i]; if (child.parentNode == self && Selectors.Utils.chk(child, uniques)) found.push(child); } return found; }, '+': function(found, self, tag, id, uniques){ while ((self = self.nextSibling)){ if (self.nodeType == 1){ if (Selectors.Utils.chk(self, uniques) && Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); break; } } return found; }, '~': function(found, self, tag, id, uniques){ while ((self = self.nextSibling)){ if (self.nodeType == 1){ if (!Selectors.Utils.chk(self, uniques)) break; if (Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self); } } return found; } }; Selectors.Filters = { byTag: function(self, tag){ return (tag == '*' || (self.tagName && self.tagName.toLowerCase() == tag)); }, byID: function(self, id){ return (!id || (self.id && self.id == id)); }, byClass: function(self, klass){ return (self.className && self.className.contains(klass, ' ')); }, byPseudo: function(self, parser, argument, local){ return parser.call(self, argument, local); }, byAttribute: function(self, name, operator, value){ var result = Element.prototype.getProperty.call(self, name); if (!result) return (operator == '!='); if (!operator || value == undefined) return true; switch (operator){ case '=': return (result == value); case '*=': return (result.contains(value)); case '^=': return (result.substr(0, value.length) == value); case '$=': return (result.substr(result.length - value.length) == value); case '!=': return (result != value); case '~=': return result.contains(value, ' '); case '|=': return result.contains(value, '-'); } return false; } }; Selectors.Pseudo = new Hash({ // w3c pseudo selectors checked: function(){ return this.checked; }, empty: function(){ return !(this.innerText || this.textContent || '').length; }, not: function(selector){ return !Element.match(this, selector); }, contains: function(text){ return (this.innerText || this.textContent || '').contains(text); }, 'first-child': function(){ return Selectors.Pseudo.index.call(this, 0); }, 'last-child': function(){ var element = this; while ((element = element.nextSibling)){ if (element.nodeType == 1) return false; } return true; }, 'only-child': function(){ var prev = this; while ((prev = prev.previousSibling)){ if (prev.nodeType == 1) return false; } var next = this; while ((next = next.nextSibling)){ if (next.nodeType == 1) return false; } return true; }, 'nth-child': function(argument, local){ argument = (argument == undefined) ? 'n' : argument; var parsed = Selectors.Utils.parseNthArgument(argument); if (parsed.special != 'n') return Selectors.Pseudo[parsed.special].call(this, parsed.a, local); var count = 0; local.positions = local.positions || {}; var uid = $uid(this); if (!local.positions[uid]){ var self = this; while ((self = self.previousSibling)){ if (self.nodeType != 1) continue; count ++; var position = local.positions[$uid(self)]; if (position != undefined){ count = position + count; break; } } local.positions[uid] = count; } return (local.positions[uid] % parsed.a == parsed.b); }, // custom pseudo selectors index: function(index){ var element = this, count = 0; while ((element = element.previousSibling)){ if (element.nodeType == 1 && ++count > index) return false; } return (count == index); }, even: function(argument, local){ return Selectors.Pseudo['nth-child'].call(this, '2n+1', local); }, odd: function(argument, local){ return Selectors.Pseudo['nth-child'].call(this, '2n', local); } });
fpupor/jsall
demo/js/Mootools/classes/Selectors/class.js
JavaScript
mit
10,050
/* * Parser Whitespace Helper tests */ var assert = require('assert') var atokParser = require('..') var options = {} describe('helpers.whitespace()', function () { describe('with false', function () { function myParser () { atok.whitespace(false) } var Parser = atokParser.createParser(myParser, 'options') var p = new Parser(options) it('should ignore it', function (done) { function handler (token, idx, type) { done( new Error('Should not trigger') ) } p.on('error', done) p.on('data', handler) p.write(' ') done() }) }) describe('with default options', function () { var Parser = atokParser.createParserFromFile('./parsers/whitespaceHelperParser.js', 'options') var p = new Parser it('should parse the input data', function (done) { p.on('error', done) p.write(' \t\n\r\n') assert.equal(p.atok.length, 0) done() }) }) describe('with specified whitespaces', function () { function wsParser () { atok.whitespace(['\n','\r','\t'], 'whitespace') } var Parser = atokParser.createParser(wsParser) var p = new Parser it('should parse the input data except spaces', function (done) { p.on('error', done) p.write('\t\n\r\n ') assert.equal(p.atok.length, 1) done() }) }) describe('with a handler', function () { function wsParser (handler) { atok.whitespace(handler) } var Parser = atokParser.createParser(wsParser, 'handler') it('should parse the input and call the handler', function (done) { var match = 0 function handler () { match++ } var p = new Parser(handler) p.on('error', done) p.write('\t\n\r\n ') assert.equal(match, 5) done() }) }) describe('with specified whitespaces and a handler', function () { function wsParser (ws, handler) { atok.whitespace(ws, handler) } var Parser = atokParser.createParser(wsParser, 'ws,handler') it('should parse the input and call the handler', function (done) { var match = 0 function handler () { match++ } var p = new Parser(['\n','\r','\t'], handler) p.on('error', done) p.write('\t\n\r\n ') assert.equal(match, 4) done() }) }) })
pierrec/node-atok-parser
test/helper-whitespace-test.js
JavaScript
mit
2,371
'use strict'; var express = require('express') , router = express.Router(); var home = require('./home/routes'); var news = require('./news/routes') export default function(io) { router.use('/', home); router.use('/news', news(io)); return router; };
calebgregory/newscraper_app
app/routes.js
JavaScript
mit
272
/** * @fileoverview Defines a storage for rules. * @author Nicholas C. Zakas */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const lodash = require("lodash"); const ruleReplacements = require("../conf/replacements").rules; const builtInRules = require("./built-in-rules-index"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Creates a stub rule that gets used when a rule with a given ID is not found. * @param {string} ruleId The ID of the missing rule * @returns {{create: function(RuleContext): Object}} A rule that reports an error at the first location * in the program. The report has the message `Definition for rule '${ruleId}' was not found` if the rule is unknown, * or `Rule '${ruleId}' was removed and replaced by: ${replacements.join(", ")}` if the rule is known to have been * replaced. */ const createMissingRule = lodash.memoize(ruleId => { const message = Object.prototype.hasOwnProperty.call(ruleReplacements, ruleId) ? `Rule '${ruleId}' was removed and replaced by: ${ruleReplacements[ruleId].join(", ")}` : `Definition for rule '${ruleId}' was not found`; return { create: context => ({ Program() { context.report({ loc: { line: 1, column: 0 }, message }); } }) }; }); /** * Normalizes a rule module to the new-style API * @param {(Function|{create: Function})} rule A rule object, which can either be a function * ("old-style") or an object with a `create` method ("new-style") * @returns {{create: Function}} A new-style rule. */ function normalizeRule(rule) { return typeof rule === "function" ? Object.assign({ create: rule }, rule) : rule; } //------------------------------------------------------------------------------ // Public Interface //------------------------------------------------------------------------------ class Rules { constructor() { this._rules = Object.create(null); } /** * Registers a rule module for rule id in storage. * @param {string} ruleId Rule id (file name). * @param {Function} ruleModule Rule handler. * @returns {void} */ define(ruleId, ruleModule) { this._rules[ruleId] = normalizeRule(ruleModule); } /** * Access rule handler by id (file name). * @param {string} ruleId Rule id (file name). * @returns {{create: Function, schema: JsonSchema[]}} * A rule. This is normalized to always have the new-style shape with a `create` method. */ get(ruleId) { if (typeof this._rules[ruleId] === "string") { this.define(ruleId, require(this._rules[ruleId])); } if (this._rules[ruleId]) { return this._rules[ruleId]; } if (builtInRules.has(ruleId)) { return builtInRules.get(ruleId); } return createMissingRule(ruleId); } *[Symbol.iterator]() { yield* builtInRules; for (const ruleId of Object.keys(this._rules)) { yield [ruleId, this.get(ruleId)]; } } } module.exports = Rules;
BenoitZugmeyer/eslint
lib/rules.js
JavaScript
mit
3,417
const { Either } = require('monet') Either.Left() // Failure Either.Right() // Success const eitherTest = fnReturningEither() eitherTest.isLeft() eitherTest.isRight()
bachstatter/fn-presentation
assets/code-examples/eitherIntro.js
JavaScript
mit
170
var PORT = 443; var HOST = 'localhost'; var tls = require('tls'); var fs = require('fs'); var options = { ca: [ fs.readFileSync('./peek-example-cert.pem') ] }; var client = tls.connect(PORT, HOST, options, function() { if (client.authorized) { console.log('CONNECTED AND AUTHORIZED\n'); client.on('close', function() { console.log('SOCKET CLOSED\n'); process.exit(); }); // Time to make some request to the server client.write('GET /hey HTTP/1.1\r\n'); client.write('\r\n'); } else { console.log('AUTH FAILED\n'); process.exit(); } }); client.setEncoding('utf8'); client.on('data', function(data) { console.log('-------------'); console.log(data); });
amitkanfer/node-peek
examples/peek_client_example.js
JavaScript
mit
774
export const SET_COORDS = 'Map/SET_COORDS'; export const SET_VISIBILITY = 'Map/SET_VISIBILITY';
MatthewKosloski/lugar
src/components/Map/constants/actionTypes.js
JavaScript
mit
95
/* oRequire An "object" version of require that returns the requested directory's contents as properties on an object. Detects .js, .coffee, .litcoffee, and .json file extensions. Ideal for loading Express routes, data models, controllers, etc. Note that this module is synchronous. */ var _ = require('lodash') var path = require('path') var fs = require('fs') module.exports = function(directory) { var getObject = function(relative) { var object = {} var absolute = path.join(__dirname, relative) var ignore = [ '.DS_Store' ] _.map(fs.readdirSync(absolute), function(filename) { if (ignore.indexOf(filename) === -1) { var absoluteFileName = path.join(absolute, filename) var isDir = fs.lstatSync(absoluteFileName).isDirectory() if (isDir) { relativeFileName = path.join(relative, filename) object[filename] = getObject(relativeFileName) } else { filename = filename.replace(/(.js|.coffee|.litcoffee|.json)/, '') relativeFileName = path.join(relative, filename) object[filename] = require(relativeFileName) } } }) return object } return getObject(path.join('../../../', directory)) }
merciba/orequire
src/orequire.js
JavaScript
mit
1,192
function notification(data) { var st = data.status, isStick = (data.status == 'success'), title = st !== undefined && (st.charAt(0).toUpperCase() + st.slice(1)), notice = new PNotify({ title: title, text: data.msg, type: data.status, delay: 2000, shadow: false, hide: isStick, buttons: { closer: true, sticker: false } }); notice.get().click(function () { notice.remove(); }); }
Karapet94/agat-777
public/js/common/functions.js
JavaScript
mit
634
import React from 'react'; import styled from 'react-emotion'; import { ViewPlayer, ViewControls } from '../features'; import MenuContainer from '../features/ViewMenuContainer'; import { Dimensions, Neighbors, Rule, Shape, States, Style, Viewer, } from '../features/ViewMenuItems'; import { Dimensions as DimensionsPopup, Viewer as ViewerPopup, Shape as ShapePopup, States as StatesPopup, } from '../features/ViewMenuPopups'; import { PopupArea, PopupManager } from '../libs/popup'; const Container = styled('div')` position: relative; background-color: olivedrab; height: 100vh; width: 100vw; z-index: 0; `; export default props => ( <Container> <PopupArea id="popup-area" /> <ViewPlayer {...props} /> <MenuContainer {...props}> <PopupManager popupName="dimensions" component={DimensionsPopup}> <Dimensions /> </PopupManager> <PopupManager popupName="viewer" component={ViewerPopup}> <Viewer /> </PopupManager> <PopupManager popupName="states" component={StatesPopup}> <States /> </PopupManager> <PopupManager popupName="shape" component={ShapePopup}> <Shape /> </PopupManager> <Neighbors /> <Rule /> <Style /> </MenuContainer> <ViewControls {...props} /> </Container> );
erhathaway/cellular_automata
src/scenes/View.js
JavaScript
mit
1,339
let Twitter = require('twitter') let FB = require('fb') let Promise = require('promise') require('songbird') module.exports = (app) => { let twitterConfig = app.config.auth.twitter return async (req, res) => { let status = req.body.reply let networkType = req.body.networkType if (!networkType) { return req.flash('error', 'Invalid network type') } if (!status) { return req.flash('error', 'Status cannot be empty') } if (networkType === 'twitter') { if(status.length > 140) { return req.flash('error', 'Status is over 140 characters') } let config = { consumer_key: twitterConfig.consumerKey, consumer_secret: twitterConfig.consumerSecret, access_token_key: req.user.twitter.token, access_token_secret: req.user.twitter.secret } console.log(config) let twitterClient = new Twitter(config) await twitterClient.promise.post('statuses/update', {status}) } else if(networkType === 'facebook') { FB.setAccessToken(req.user.facebook.token); let response = await new Promise((resolve, reject) => FB.api('me/feed', 'post', { message: status}, resolve)) console.log(response) } res.redirect('/timeline') } }
umkatakam/socialfeed
app/routes/compose.js
JavaScript
mit
1,277
import { ADD_NOVEL_COMMENT } from '../constants/actionTypes'; export function addNovelCommentSuccess(novelId, replyToCommentId) { return { type: ADD_NOVEL_COMMENT.ADD_SUCCESS, payload: { novelId, replyToCommentId, timestamp: Date.now(), }, }; } export function addNovelCommentFailure(novelId, replyToCommentId) { return { type: ADD_NOVEL_COMMENT.ADD_FAILURE, payload: { novelId, replyToCommentId, }, }; } export function addNovelComment(novelId, comment, replyToCommentId) { return { type: ADD_NOVEL_COMMENT.ADD, payload: { novelId, comment, replyToCommentId, }, }; }
alphasp/pxview
src/common/actions/addNovelComment.js
JavaScript
mit
667
var test = require('tape'); var objectToImage = require('./'); var Sharp = require('sharp'); var parse = require('thumbor-url').parse; var toImage = function(url) { return objectToImage(parse(url + 'http://example.com/image.jpg')); }; test('no options', function(t) { t.throws(function() { objectToImage(); }); t.end(); }); test('empty string', function(t) { t.ok(toImage('')); t.ok(toImage('') instanceof Sharp); t.end(); }); test('crop/extract', function(t) { var parsed = parse('/10x20:110x220/http://example.com/image.jpg'); // this is a real use case parsed.crop.method = 'faces'; var image = objectToImage(parsed); t.equal(image.options.leftOffsetPre, 10); t.equal(image.options.topOffsetPre, 20); t.equal(image.options.widthPre, 100); t.equal(image.options.heightPre, 200); t.end(); }); test('trim', function(t) { t.throws(function() { toImage('/trim/'); }); t.end(); }); test('width & height', function(t) { var image = toImage('/10x20/'); t.equal(image.options.width, 10); t.equal(image.options.height, 20); t.end(); }); test('filters not supported', function(t) { var filters = [ 'brightness', 'contrast', 'colorize', 'equalize', 'fill', 'format', 'grayscale', 'max_bytes', 'noise', 'no_upscale', 'rgb', 'round_corner', 'rotate', 'saturation', 'sharpen', 'strip_icc', 'watermark', 'convolution', 'blur', 'extract_focal', 'gifv' ]; filters.forEach(function(filter) { t.throws(function() { toImage('/filters:' + filter + '()/'); }); }); t.end(); }); test('supported filters', function(t) { t.equal(toImage('/filters:quality(30)/').options.quality, 30); t.end(); });
kesla/thumbor-to-sharp-image
test.js
JavaScript
mit
1,751
'use strict'; /** * Maintains all stubs for an imposter * @module */ var predicates = require('./predicates'), Q = require('q'); /** * Creates the repository * @param {module:models/responseResolver} resolver - The response resolver * @param {boolean} recordMatches - Whether to record matches (the --debug command line flag) * @param {string} encoding - utf8 or base64 * @returns {Object} */ function create (resolver, recordMatches, encoding) { /** * The list of stubs within this repository * @memberOf module:models/stubRepository# * @type {Array} */ var stubs = []; function trueForAll (list, predicate) { // we call map before calling every so we make sure to call every // predicate during dry run validation rather than short-circuiting return list.map(predicate).every(function (result) { return result; }); } function findFirstMatch (request, logger) { if (stubs.length === 0) { return undefined; } var matches = stubs.filter(function (stub) { var stubPredicates = stub.predicates || []; return trueForAll(stubPredicates, function (predicate) { return predicates.resolve(predicate, request, encoding, logger); }); }); if (matches.length === 0) { logger.debug('no predicate match'); return undefined; } else { logger.debug('using predicate match: ' + JSON.stringify(matches[0].predicates || {})); return matches[0]; } } /** * Adds a stub to the repository * @memberOf module:models/stubRepository# * @param {Object} stub - The stub to add */ function addStub (stub) { stubs.push(stub); } /** * Finds the right stub for a request and generates a response * @memberOf module:models/stubRepository# * @param {Object} request - The protocol request * @param {Object} logger - The logger * @returns {Object} - Promise resolving to the response */ function resolve (request, logger) { var stub = findFirstMatch(request, logger) || { responses: [{ is: {} }] }, responseConfig = stub.responses.shift(), deferred = Q.defer(); logger.debug('generating response from ' + JSON.stringify(responseConfig)); stub.responses.push(responseConfig); resolver.resolve(responseConfig, request, logger, stubs).done(function (response) { var match = { timestamp: new Date().toJSON(), request: request, response: response }; if (recordMatches) { stub.matches = stub.matches || []; stub.matches.push(match); } deferred.resolve(response); }, deferred.reject); return deferred.promise; } return { stubs: stubs, addStub: addStub, resolve: resolve }; } module.exports = { create: create };
p-equis/mountebank
src/models/stubRepository.js
JavaScript
mit
3,069
'use strict'; let [gulp, $] = [require('gulp'), require('gulp-load-plugins')()]; /** Add Plugins as Property to $ */ $.browserSync = require('browser-sync'); $.argv = require('yargs').argv; $.del = require('del'); $.h2j = require('gulp-html2jade'); /** * Task Files List * @type {Array} */ const conf = require('./gulpconf')($); const tsk = {}; const tasks = ['utilities', 'frontend', 'server', 'listen', 'media', 'help', 'transfer']; for (let n of tasks) tsk[n] = require(conf.path.root.tasks + n)(gulp, $, conf, tsk); /** * REGISTER TASKS * Total: 13 */ /** Utilities */ gulp.task('cache', tsk.utilities.cache); gulp.task('clean', tsk.utilities.clean); gulp.task('h2j', tsk.utilities.h2j); gulp.task('zip', tsk.utilities.zip); /** Transfer */ gulp.task('transfer', gulp.parallel(tsk.transfer.libs, gulp.parallel(tsk.transfer.fonts, tsk.transfer.extras))); /** Frontend */ gulp.task('styles', tsk.frontend.styles); gulp.task('scripts', tsk.frontend.scripts); gulp.task('templates', tsk.frontend.templates); /** Media */ gulp.task('images', tsk.media.images); /** Build */ gulp.task('build', gulp.series('clean', ['styles', 'scripts', 'templates', 'images', 'transfer'])); /** Listen */ gulp.task('watch', gulp.series('build', gulp.parallel(tsk.listen.watch, tsk.listen.reload))); /** Server */ gulp.task('server', gulp.parallel(tsk.server.web, 'watch')); /** Help */ gulp.task('test', tsk.help.test); gulp.task('help', tsk.help.help); /** Default */ gulp.task('default', gulp.series('help'));
wallenweel/gulp4-es2015
gulpfile.babel.js
JavaScript
mit
1,518
var UIManager = (function(){ function UIManager(sceneManager){ this.sceneManager = sceneManager; this.xyInput = []; this.taskbar = []; this.viewControls = []; this.playBackControls = []; this.shapeProperties = []; // density, friction, restitution, isSensor, edit this.bodyProperties = []; // name, userdata, type, isBullet, edit, tex_file, tex_width, tex_height this.jointProperties = []; // name, userdata, type, collideConnected, joint_specific_parameters this.jointPropertyRows = []; } UIManager.prototype.initialize = function(inputHandler){ var sceneManager = this.sceneManager; // hide separators var elementsToHide = document.getElementsByClassName("separator"); for (var i = 0; i < elementsToHide.length; i++){ elementsToHide[i].style.visibility = "hidden"; } // hide alert dialog box var alertDialog = $("#alert_dialog"); alertDialog.hide(); var alertButtons = alertDialog.find("button"); alertButtons[0].addEventListener("click", function(){ alertDialog.hide(); var data = new Blob([JSON.stringify(sceneManager.saveScene(), null, 4)], {type:'text/plain'}); var textFile = window.URL.createObjectURL(data); window.open(textFile); sceneManager.newScene(); }); alertButtons[1].addEventListener("click", function(){ alertDialog.hide(); sceneManager.newScene(); }); alertButtons[2].addEventListener("click", function(){ alertDialog.hide(); }); // hide auto shape option view var autoShape = $("#auto_shape"); autoShape.hide(); var shapeButtons = autoShape.find("button"); shapeButtons[0].addEventListener("click", function(){ $('#loadBitmap')[0].value = null; $("#loadBitmap").trigger('click'); autoShape.hide(); }); shapeButtons[1].addEventListener("click", function(){ autoShape.hide(); }); $('#loadBitmap').change(function(e){ if (e.target.files.length < 0){ return; } if(e.target.files[0].name && e.target.files[0].type == "image/bmp"){ var reader = new FileReader(); reader.readAsBinaryString(e.target.files[0]); reader.onload = function(e){ var loader = new BMPImageLoader(); var image = loader.loadBMP(e.target.result); // default settings var xSpace = Editor.autoTrace.xSpace, ySpace = Editor.autoTrace.ySpace, dataWidth = parseInt(image.width / xSpace), dataHeight = parseInt(image.height / ySpace), alphaThreshold = 127, concavity = Editor.autoTrace.concavity; var points = []; for (var i = 0; i < dataHeight; i++){ for (var j = 0; j < dataWidth; j++){ var pixel = image.getPixelAt(j * xSpace, i * ySpace); if ((pixel[0]) >= alphaThreshold){ points.push([j * xSpace - image.width / 2 , i * ySpace - image.height / 2]); } } } // create concave hull from points var concaveHull = hull(points, concavity); delete points; // create shape sceneManager.createShapeFromPoints(concaveHull); delete concaveHull; // release image image.dispose(); delete image; } } }); // initialize transform tool buttons $("#transformTools").find("button").each(function(index){ var action = $(this).data("event"); mixin(this, inputHandler, action); this.addEventListener("click", function(e){ e.preventDefault(); e.target[action](); }); }); // initialize pivot tool buttons $("#pivotTools").find("button").each(function(index){ var action = $(this).data("event"); mixin(this, inputHandler, action); this.addEventListener("click", function(e){ e.preventDefault(); e.target[action](); }); }); this.xyInput = [$("#input_x")[0], $("#input_y")[0]]; this.xyInput[0].addEventListener("keypress", function(e){ if (e.which == 13){ // enter pressed if (!isNaN(parseFloat(this.value))){ if (inputHandler.transformTool == 5){ sceneManager.setScaleOfSelectedObjects(parseFloat(this.value), null, 0, inputHandler); } else if (inputHandler.transformTool == 7){ sceneManager.setPositionOfSelectedObjects(parseFloat(this.value), null, 0, inputHandler); } else if (inputHandler.transformTool == 6){ sceneManager.setRotationOfSelectedObjects(parseFloat(this.value), 0, inputHandler); } } } }); this.xyInput[1].addEventListener("keypress", function(e){ if (e.which == 13){ // enter pressed if (!isNaN(parseFloat(this.value))){ if (inputHandler.transformTool == 5){ sceneManager.setScaleOfSelectedObjects(null, parseFloat(this.value), 0, inputHandler); } else if (inputHandler.transformTool == 7){ sceneManager.setPositionOfSelectedObjects(null, parseFloat(this.value), 0, inputHandler); } } } }); $("#loadScene").hide(); $("#fileMenu").find("a").each(function(index){ var action = $(this).data("event"); // mixin(this, sceneManager, action); this.addEventListener("click", function(e){ e.preventDefault(); if (action == 'newScene'){ alertDialog.show(); return; } else if (action == 'loadScene'){ $('#loadScene')[0].value = null; $("#loadScene").trigger('click'); return; } else if (action == 'saveScene'){ var data = new Blob([JSON.stringify(sceneManager.saveScene(), null, 4)], {type:'text/plain'}); var textFile = window.URL.createObjectURL(data); window.open(textFile); return; } else if (action == 'exportWorld'){ var data = new Blob([JSON.stringify(sceneManager.exportWorld(), null, 4)], {type:'text/plain'}); var textFile = window.URL.createObjectURL(data); window.open(textFile); return; } else if (action == 'exportSelection'){ var data = new Blob([JSON.stringify(sceneManager.exportSelection(), null, 4)], {type:'text/plain'}); var textFile = window.URL.createObjectURL(data); window.open(textFile); return; } }); }); $('#loadScene').change(function(e){ if (e.target.files.length < 0){ return; } if(e.target.files[0].name){ var reader = new FileReader(); reader.readAsText(e.target.files[0]); reader.onload = function(e){ sceneManager.newScene(); sceneManager.loadScene(JSON.parse(e.target.result)); } } }); $('#editMenu').find("a")[0].addEventListener("click", function(e){ sceneManager.deleteSelectedObjects(); }); $("#addToScene").find("a").each(function(index){ mixin(this, sceneManager, "createBody"); var params = parseInt($(this).data("shape")); this.addEventListener("click", function(e){ e.preventDefault(); var shapeType = parseInt(params / 10); if (shapeType == 0){ e.target["createBody"](shapeType); } else { e.target["createBody"](shapeType, params % 10); } }); }); $("#addToBody").find("a").each(function(index){ mixin(this, sceneManager, "createShape"); var params = parseInt($(this).data("shape")); this.addEventListener("click", function(e){ e.preventDefault(); var shapeType = parseInt(params / 10); if (shapeType == 0){ e.target["createShape"](shapeType); } else { if (params % 10 != 2){ e.target["createShape"](shapeType, params % 10); } else { autoShape.show(); } } }); }); $("#createJoint").find("a").each(function(index){ mixin(this, sceneManager, "createJoint"); var type = parseInt($(this).data("type")); this.addEventListener("click", function(e){ e.preventDefault(); e.target["createJoint"](type); }); }); // properties of selected shape(s) this.shapeProperties = $("#shape_properties").find("input"); for (var i = 0; i < 6; i++){ this.shapeProperties[i].addEventListener('keypress', function(e){ if (e.which == 13){ var property = $(this).data('property'); for (var i = 0; i < sceneManager.selectedShapes.length; i++){ if (parseFloat(this.value) != NaN) sceneManager.selectedShapes[i][property] = parseFloat(this.value); } } }); } $(this.shapeProperties[6]).change(function(){ for (var i = 0; i < sceneManager.selectedShapes.length; i++){ var property = $(this).data('property'); sceneManager.selectedShapes[i][property] = $(this).is(":checked"); } }); var ref = this; this.shapeProperties[7].addEventListener('click', function(){ if (sceneManager.state == sceneManager.STATE_BODY_EDIT_MODE){ sceneManager.enterShapeEditMode(); this.value = "Done"; ref.updateShapePropertyView(); ref.updateBodyPropertyView(); } else if (sceneManager.state == sceneManager.STATE_SHAPE_EDIT_MODE){ sceneManager.enterBodyEditMode(); this.value = "Edit"; ref.updateShapePropertyView(); ref.updateBodyPropertyView(); } }); // properties of selected body(s) this.bodyProperties = $("#body_properties").find("input"); this.bodyProperties.push($("#body_properties").find("select")[0]); for (var i = 0; i < 2; i++){ this.bodyProperties[i].addEventListener('keypress', function(e){ if (e.which == 13){ var property = $(this).data('property'); for (var i = 0; i < sceneManager.selectedBodies.length; i++){ sceneManager.selectedBodies[i][property] = this.value; } } }); } for (var i = 4; i < 6; i++){ this.bodyProperties[i].addEventListener('keypress', function(e){ if (e.which == 13){ var property = $(this).data('property'); for (var i = 0; i < sceneManager.selectedBodies.length; i++){ if (parseFloat(this.value) != NaN) sceneManager.selectedBodies[i][property] = parseFloat(this.value); } } }); } $(this.bodyProperties[2]).change(function(){ for (var i = 0; i < sceneManager.selectedBodies.length; i++){ var property = $(this).data('property'); sceneManager.selectedBodies[i][property] = $(this).is(":checked"); } }); $(this.bodyProperties[3]).change(function(){ for (var i = 0; i < sceneManager.selectedBodies.length; i++){ var property = $(this).data('property'); sceneManager.selectedBodies[i][property] = $(this).is(":checked"); } }); this.bodyProperties[6].addEventListener('click', function(){ if (sceneManager.state == sceneManager.STATE_DEFAULT_MODE){ sceneManager.enterBodyEditMode(); this.value = "Done"; ref.updateShapePropertyView(); ref.updateBodyPropertyView(); ref.updateJointPropertyView(); } else if (sceneManager.state == sceneManager.STATE_BODY_EDIT_MODE) { sceneManager.enterDefaultMode(); this.value = "Edit"; ref.updateShapePropertyView(); ref.updateBodyPropertyView(); ref.updateJointPropertyView(); } }); $(this.bodyProperties[14]).change(function(){ for (var i = 0; i < sceneManager.selectedBodies.length; i++){ var property = $(this).data('property'); sceneManager.selectedBodies[i][property] = parseInt(this.value); } }); this.bodyProperties[7].addEventListener("click", function(e){ this.value = null; }); $(this.bodyProperties[7]).change(function(e){ // console.log(e.target.files[0].type); if (e.target.files == null && e.target.files.length < 0){ return; } if(e.target.files[0].name && (e.target.files[0].type == "image/png" || e.target.files[0].type == "image/jpeg" || e.target.files[0].type == "image/bmp")){ for (var i = 0; i < sceneManager.selectedBodies.length; i++){ sceneManager.selectedBodies[i].setSprite(Editor.resourceDirectory + e.target.files[0].name); } } }); for (var i = 8; i < 14; i++){ this.bodyProperties[i].addEventListener('keypress', function(e){ if (e.which == 13){ for (var i = 0; i < sceneManager.selectedBodies.length; i++){ if (parseFloat(this.value) != NaN){ var action = $(this).data('action'); sceneManager.selectedBodies[i][action](parseFloat(this.value)); } } } }); } // properties of selected joint(s) this.jointProperties = $("#joint_properties").find("input"); this.jointPropertyRows = $("#joint_properties").find("tr"); for (var i = 0; i < 8; i++){ if (i == 2 || i == 5){ continue; } this.jointProperties[i].addEventListener('keypress', function(e){ if (e.which == 13){ for (var j = 0; j < sceneManager.selectedJoints.length; j++){ var property = $(this).data('property'); if (i < 2){ sceneManager.selectedJoints[j][property] = this.value; } else { if (parseFloat(this.value) != null){ sceneManager.selectedJoints[j][property] = parseFloat(this.value); } } } } }); } $(this.jointProperties[2]).change(function(){ var property = $(this).data('property'); for (var i = 0; i < sceneManager.selectedJoints.length; i++){ sceneManager.selectedJoints[i][property] = $(this).is(":checked"); } }); $(this.jointProperties[5]).change(function(){ var property = $(this).data('property'); for (var i = 0; i < sceneManager.selectedJoints.length; i++){ sceneManager.selectedJoints[i][property] = $(this).is(":checked"); } }); $(this.jointProperties[8]).change(function(){ var property = $(this).data('property'); for (var i = 0; i < sceneManager.selectedJoints.length; i++){ sceneManager.selectedJoints[i][property] = $(this).is(":checked"); } }); this.jointProperties[9].addEventListener('click', function(){ if (sceneManager.selectedJoints[0].inEditMode){ sceneManager.selectedJoints[0].inEditMode = false; this.value = "Edit"; } else { sceneManager.selectedJoints[0].inEditMode = true; this.value = "Done" } }); this.updateShapePropertyView(); this.updateBodyPropertyView(); this.updateJointPropertyView(); }; UIManager.prototype.onMouseDown = function(inputHandler){ this.updateShapePropertyView(); this.updateBodyPropertyView(); this.updateJointPropertyView(); // update input-xy if (inputHandler.selection.length != 1){ this.xyInput[0].value = ""; this.xyInput[1].value = ""; return; } this.updateInputXY(inputHandler); }; UIManager.prototype.onMouseMove = function(inputHandler){ this.updateShapePropertyView(); this.updateBodyPropertyView(); this.updateJointPropertyView(); // update input-xy if (inputHandler.selection.length != 1){ this.xyInput[0].value = ""; this.xyInput[1].value = ""; return; } this.updateInputXY(inputHandler); }; UIManager.prototype.onMouseUp = function(inputHandler){ this.updateShapePropertyView(); this.updateBodyPropertyView(); this.updateJointPropertyView(); if (inputHandler.selection.length != 1){ this.xyInput[0].value = ""; this.xyInput[1].value = ""; return; } this.updateInputXY(inputHandler); }; UIManager.prototype.updateShapePropertyView = function(){ var sceneManager = this.sceneManager; if ((sceneManager.state == sceneManager.STATE_BODY_EDIT_MODE || sceneManager.state == sceneManager.STATE_SHAPE_EDIT_MODE) && sceneManager.selectedShapes.length > 0){ $("#shape_properties").show(); if(sceneManager.selectedShapes.length == 1){ this.shapeProperties[0].disabled = false; this.shapeProperties[0].value = sceneManager.selectedShapes[0].density; this.shapeProperties[1].value = sceneManager.selectedShapes[0].friction; this.shapeProperties[2].value = sceneManager.selectedShapes[0].restitution; this.shapeProperties[3].value = sceneManager.selectedShapes[0].maskBits; this.shapeProperties[4].value = sceneManager.selectedShapes[0].categoryBits; this.shapeProperties[5].value = sceneManager.selectedShapes[0].groupIndex; this.shapeProperties[6].checked = sceneManager.selectedShapes[0].isSensor; this.shapeProperties[7].disabled = false; } else { this.shapeProperties[0].value = ""; // this.shapeProperties[0].disabled = true; this.shapeProperties[1].value = ""; this.shapeProperties[6].value = ""; this.shapeProperties[7].disabled = true; var allAreSensor = false; for (var i = 0; i < sceneManager.selectedShapes.length; i++){ if (allAreSensor != sceneManager.selectedShapes[i].isSensor && i != 0){ allAreSensor = false; break; } else { allAreSensor = sceneManager.selectedShapes[i].isSensor; } } this.shapeProperties[3].checked = allAreSensor; } } else { // hide this view $("#shape_properties").hide(); } }; UIManager.prototype.updateBodyPropertyView = function(){ var sceneManager = this.sceneManager; if ((sceneManager.state == sceneManager.STATE_DEFAULT_MODE || sceneManager.state == sceneManager.STATE_BODY_EDIT_MODE) && sceneManager.selectedBodies.length > 0){ $("#body_properties").show(); if(sceneManager.selectedBodies.length == 1){ var cachedBody = sceneManager.selectedBodies[0]; this.bodyProperties[0].disabled = false; this.bodyProperties[0].value = cachedBody.name; this.bodyProperties[1].value = cachedBody.userData; this.bodyProperties[2].checked = cachedBody.isBullet; this.bodyProperties[3].checked = cachedBody.isFixedRotation; this.bodyProperties[4].value = cachedBody.linearDamping; this.bodyProperties[5].value = cachedBody.angularDamping; this.bodyProperties[6].disabled = false; this.bodyProperties[14].value = cachedBody.bodyType; if (cachedBody.sprite != null){ this.bodyProperties[8].value = cachedBody.getSpriteWidth(); this.bodyProperties[9].value = cachedBody.getSpriteHeight(); this.bodyProperties[10].value = cachedBody.getSpriteSourceWidth() != null ? cachedBody.getSpriteSourceWidth() : "-"; this.bodyProperties[11].value = cachedBody.getSpriteSourceHeight() != null ? cachedBody.getSpriteSourceHeight() : "-"; this.bodyProperties[12].value = cachedBody.getSpriteOffsetX() != null ? cachedBody.getSpriteOffsetX() : "-"; this.bodyProperties[13].value = cachedBody.getSpriteOffsetY() != null ? cachedBody.getSpriteOffsetY() : "-"; } else { this.bodyProperties[8].value = ""; this.bodyProperties[9].value = ""; this.bodyProperties[10].value = ""; this.bodyProperties[11].value = ""; this.bodyProperties[12].value = ""; this.bodyProperties[13].value = ""; } } else { this.bodyProperties[0].disabled = true; this.bodyProperties[0].value = ""; this.bodyProperties[1].value = ""; this.bodyProperties[4].value = ""; this.bodyProperties[5].value = ""; this.bodyProperties[6].disabled = true; var allAreBullet = false, allHaveFixedRotation = false, allHaveSameBodyType = 0; for (var i = 0; i < sceneManager.selectedBodies.length; i++){ if (allAreBullet != sceneManager.selectedBodies[i].isBullet && i != 0){ allAreBullet = false; break; } else { allAreBullet = sceneManager.selectedBodies[i].isBullet; } } for (var i = 0; i < sceneManager.selectedBodies.length; i++){ if (allHaveFixedRotation != sceneManager.selectedBodies[i].isFixedRotation && i != 0){ allHaveFixedRotation = false; break; } else { allHaveFixedRotation = sceneManager.selectedBodies[i].isFixedRotation; } } for (var i = 0; i < sceneManager.selectedBodies.length; i++){ if (allHaveSameBodyType != sceneManager.selectedBodies[i].bodyType && i != 0){ allHaveSameBodyType = 3; break; } else { allHaveSameBodyType = sceneManager.selectedBodies[i].bodyType; } } this.bodyProperties[2].checked = allAreBullet; this.bodyProperties[3].checked = allHaveFixedRotation; this.bodyProperties[14].value = allHaveSameBodyType; this.bodyProperties[8].value = ""; this.bodyProperties[9].value = ""; this.bodyProperties[10].value = ""; this.bodyProperties[11].value = ""; } } else { // hide this view $("#body_properties").hide(); } }; UIManager.prototype.updateJointPropertyView = function(){ var sceneManager = this.sceneManager; if (sceneManager.state == sceneManager.STATE_DEFAULT_MODE && sceneManager.selectedJoints.length > 0){ $("#joint_properties").show(); var jointNames = ["Distance", "Weld", "Revolute", "Wheel", "Pulley", "Gear", "Prismatic", "Rope"]; if(sceneManager.selectedJoints.length == 1){ var cachedJoint = sceneManager.selectedJoints[0]; $(this.jointPropertyRows[2]).find("p")[1].innerHTML = jointNames[cachedJoint.jointType]; $(this.jointPropertyRows[this.jointPropertyRows.length - 1]).show(); this.jointProperties[0].disabled = false; this.jointProperties[0].value = cachedJoint.name; this.jointProperties[1].value = cachedJoint.userData; this.jointProperties[2].checked = cachedJoint.collideConnected; // distance or wheel joint if (cachedJoint.jointType == 0 || cachedJoint.jointType == 3){ $(this.jointPropertyRows[4]).find("p")[0].innerHTML = "Frequency Hz"; $(this.jointPropertyRows[4]).show(); $(this.jointPropertyRows[5]).show(); this.jointProperties[3].value = cachedJoint.frequencyHZ; this.jointProperties[4].value = cachedJoint.dampingRatio; } else { $(this.jointPropertyRows[4]).hide(); $(this.jointPropertyRows[5]).hide(); } // pulley, gear or rope joint if (cachedJoint.jointType == 4 || cachedJoint.jointType == 5 || cachedJoint.jointType == 7){ if (cachedJoint.jointType == 7){ $(this.jointPropertyRows[4]).find("p")[0].innerHTML = "Max Length"; } else{ $(this.jointPropertyRows[4]).find("p")[0].innerHTML = "Ratio"; } this.jointProperties[3].value = cachedJoint.frequencyHZ.toFixed(3); $(this.jointPropertyRows[4]).show(); } // revolute, wheel joint or prismatic joint if (cachedJoint.jointType == 2 || cachedJoint.jointType == 3 || cachedJoint.jointType == 6){ $(this.jointPropertyRows[6]).show(); $(this.jointPropertyRows[7]).show(); $(this.jointPropertyRows[8]).show(); if (cachedJoint.jointType == 6){ $(this.jointPropertyRows[8]).find("p")[0].innerHTML = "Max Motor Force" } else { $(this.jointPropertyRows[8]).find("p")[0].innerHTML = "Max Motor Torque" } this.jointProperties[5].checked = cachedJoint.enableMotor; this.jointProperties[6].value = cachedJoint.motorSpeed; this.jointProperties[7].value = cachedJoint.maxMotorTorque; } else { $(this.jointPropertyRows[6]).hide(); $(this.jointPropertyRows[7]).hide(); $(this.jointPropertyRows[8]).hide(); } // revolute joint if (cachedJoint.jointType == 2 || cachedJoint.jointType == 6){ this.jointProperties[8].checked = cachedJoint.enableLimit; if (cachedJoint.jointType == 2){ $(this.jointPropertyRows[10]).find("p")[0].innerHTML = "Lower Angle"; $(this.jointPropertyRows[11]).find("p")[0].innerHTML = "Upper Angle"; $(this.jointPropertyRows[10]).find("p")[1].innerHTML = cachedJoint.lowerAngle.toFixed(3); $(this.jointPropertyRows[11]).find("p")[1].innerHTML = cachedJoint.upperAngle.toFixed(3); } else { $(this.jointPropertyRows[10]).find("p")[0].innerHTML = "Lower Translation"; $(this.jointPropertyRows[11]).find("p")[0].innerHTML = "Upper Translation"; $(this.jointPropertyRows[10]).find("p")[1].innerHTML = cachedJoint.lowerTranslation.toFixed(3); $(this.jointPropertyRows[11]).find("p")[1].innerHTML = cachedJoint.upperTranslation.toFixed(3); } $(this.jointPropertyRows[9]).show(); $(this.jointPropertyRows[10]).show(); $(this.jointPropertyRows[11]).show(); } else { $(this.jointPropertyRows[9]).hide(); $(this.jointPropertyRows[10]).hide(); $(this.jointPropertyRows[11]).hide(); } } else { this.jointProperties[0].disabled = true; this.jointProperties[0].value = ""; this.jointProperties[1].value = ""; $(this.jointPropertyRows[2]).find("p")[1].innerHTML = ""; for (var i = 4; i < this.jointPropertyRows.length; i++){ $(this.jointPropertyRows[i]).hide(); } } } else { // hide this view $("#joint_properties").hide(); } }; // update input-xy whenever an object is selected / moved UIManager.prototype.updateInputXY = function(inputHandler){ if (inputHandler.transformTool == 5){ if (this.sceneManager.state != this.sceneManager.STATE_SHAPE_EDIT_MODE){ this.xyInput[0].value = inputHandler.selection[0].scaleXY[0].toFixed(2); this.xyInput[1].value = inputHandler.selection[0].scaleXY[1].toFixed(2); } else { this.xyInput[0].value = ""; this.xyInput[1].value = ""; } } else if (inputHandler.transformTool == 7){ if (this.sceneManager.state == this.sceneManager.STATE_SHAPE_EDIT_MODE){ if (inputHandler.selection.length == 1 && inputHandler.selection[0].x){ this.xyInput[0].value = inputHandler.selection[0].x.toFixed(2); this.xyInput[1].value = inputHandler.selection[0].y.toFixed(2); } } else { if (inputHandler.selection[0].position){ this.xyInput[0].value = inputHandler.selection[0].position[0].toFixed(2); this.xyInput[1].value = inputHandler.selection[0].position[1].toFixed(2); } } } else if (inputHandler.transformTool == 6){ if (this.sceneManager.state != this.sceneManager.STATE_SHAPE_EDIT_MODE && inputHandler.selection[0].rotation){ this.xyInput[0].value = inputHandler.selection[0].rotation.toFixed(2); this.xyInput[1].value = ""; } else { this.xyInput[0].value = ""; this.xyInput[1].value = ""; } } }; // binds custom object methods to dom events function mixin(target, source, methods){ for (var ii = 2, ll = arguments.length; ii < ll; ii++){ var method = arguments[ii]; target[method] = source[method].bind(source); } } var instance; return{ getInstance: function(sceneManager){ if (instance == null){ instance = new UIManager(sceneManager); instance.constructor = null; } return instance; } }; })();
amuTBKT/Physics-Editor
js/UIManager.js
JavaScript
mit
26,024
'use strict'; angular.module('quakeStatsApp') .controller('FlagsCtrl', ['$scope', '$routeParams', 'Constants', 'qconsoleLog', 'FlagsService', function ($scope, $routeParams, Constants, qconsoleLog, FlagsService) { $scope.gameId = $routeParams.gameId; $scope.stats = {}; if (qconsoleLog.success === false) { console.log('Cannot load qconsole - you wil not be able to see Flag stats'); } else { $scope.stats = FlagsService.getFlagsStats(qconsoleLog.result, $scope.gameId); } $scope.objectToArray = function(items) { var result = []; angular.forEach(items, function(value) { result.push(value); }); return result; }; }]);
mbarzeev/quake-stats
app/scripts/controllers/flags-ctrl.js
JavaScript
mit
745
'use strict'; 'use strict'; import path from 'path'; import fs from 'fs'; const _root = path.resolve(__dirname, '..'); export function root(args) { args = Array.prototype.slice.call(arguments, 0); return path.join.apply(path, [_root].concat(args)); } /** * Remove extension from string * @param {string} str - line of string * @returns {string} - string without extension */ export const removeExtension = (str) => str.match(/[^.]*/i)[0]; /** * Get subdirectories names */ // export const getFolders = (src) => fs.readdirSync(src).filter(file => fs.statSync(path.join(src, file)).isDirectory()); // const srcPages = './src/app/pages'; // const src = 'src'; /** * Get Obj with pages * TODO: refactor */ // export const getEntries = () => { // const folders = getFolders(srcPages), // pages = {}; // folders.map((v) => { // pages[v] = `${ srcPages }/${ v }/${ v }.js`; // }); // pages.main = './src/main.js'; // console.log(pages); // return pages; // };
mahcr/mahcr.github.io
config/scripts/helpers.js
JavaScript
mit
1,000
// // MP4 - A Pure Javascript Mp4 Container Parser Based On ISO_IEC_14496-12 // LICENSE: MIT // COPYRIGHT: 2015 Active 9 LLC. // /* * * Synopsis: * The MP4 or Motion Picture v4 is a fully adaptive formated losely * based on the mpeg / mp3 containers. The origins of the mp4 date back * to the year 2000 on IRC. The MPEG group graciously adopted said format * and many codecs based on the mp4 container and motion vector technology * began to emerge. This paved the way for high quality low bitrate real-time * audio/video streaming and recording. Over 15 years later the mp4 container * is now the defacto standard installed on billions of devices and in billions * of homes world-wide. It has paved the way to future HD audio/video streaming * as well as 3d VR technologies. * * This library implements the ISO_IEC_14496-12 mp4 container as a parser for * nodejs. This is a low-level library designed to work with mp4v1 / mp4v2 codecs. * */ // // WARNING - This implementation is unfinished. // TODO - mp4 file stream loading // - mp4 file stream offset // - mp4 json data output // - udta meta data parsing // - make readChunk.sync efficient! var fs = require('fs'); var path = require('path'); var util = require('util'); var readChunk = require('read-chunk'); var buffer= new Buffer(512000000); module.exports = function(mp4file) { mp4file = path.resolve(mp4file); console.log("Parsing ", mp4file); var mp4data = fs.openSync(mp4file,'r+'); var mp4stats = fs.statSync(mp4file); var file_size = mp4stats.size; console.log("Filesize ", file_size, ' bytes'); var offset = 0; var atom_size = 16; // Boldy Guess The Atom_Size var atom_type = "ftyp"; // Default Atom/Box Type var mp4 = { ftyp: {} }; while(offset<=file_size) { //console.log("OFFSET:", offset); // Forget The Yellow Pages (aka Brands) if (atom_type=="ftyp") { mp4.atom_size = readChunk.sync(mp4file, offset+0, 4)[3]; atom_size = mp4.atom_size; atom_type = bufferToChar(readChunk.sync(mp4file, offset+4, 4)); mp4.major_brand = bufferToChar(readChunk.sync(mp4file, offset+8, 4)); mp4.minor_version = bufferToChar(readChunk.sync(mp4file, offset+12, 4)); mp4.compatible_brands = bufferToChar(readChunk.sync(mp4file, offset+16, atom_size-16)); // seek offset offset += atom_size; atom_type = 'moov'; // Motion Object Oriented Vector (aka Moov) } if (atom_type=="moov") { parse_moov(mp4data, buffer, offset); // seek offset offset += atom_size; } } console.log("Mp4:", mp4); fs.closeSync(mp4data); return mp4; } var bufferToChar = function(buffer) { var output = ''; var i = buffer.length; var o = 0; while (o<i) { output += ''+ String.fromCharCode(buffer[o]) +''; o++; } return output; } var parse_moov = function(mp4data, buffer, offset) { var moov_size = fs.readSync(mp4data, buffer, offset, 4, 0); // read 4 bytes unpacked N var moov_type = fs.readSync(mp4data, buffer, offset, 4, 4); // read 4 bytes moov_size = offset + moov_size; offset += 8; //console.log("SIZING ::", offset, moov_size, offset); while (offset<moov_size) { var size = fs.readSync(mp4data, buffer, offset, 4, 0); // read 4 bytes unpacked N var type = fs.readSync(mp4data, buffer, offset, 4, 4); // read 4 bytes //console.log("MOOVE::", size, type); // Motion Vector High Definition (aka MVHD) if (type=="mvhd") { parse_mvhd(mp4data, buffer, offset); // Trak (Aka Track) } else if (type=="trak") { parse_track(mp4data, buffer, offset); // User Data Space (aka UDTA) } else if (type=="udta") { parse_udta(mp4data, buffer, offset); } offset += size; // seek offset } } var parse_track = function(mp4data, buffer, offset) { console.log("TRACK"); var track_size = fs.readSync(mp4data, buffer, offset, 4, 0);; //read 4 bytes unpacked N var track_type = fs.readSync(mp4data, buffer, offset, 4, 4);; //read 4 bytes track_offset = offset + track_size; offset += 8; while(offset<track_size) { var size = fs.readSync(mp4data, buffer, offset, 4, 0); // read 4 bytes unpacked N var type = fs.readSync(mp4data, buffer, offset, 4, 4); //read 4 bytes if (type=="tkhd") { parse_tkhd(offset); } offset += size; // seek offset } } var parse_tkhd = function(mp4data, buffer, offset) { console.log("TKHD"); offset += 8 //seek offset var version = fs.readSync(mp4data, buffer, offset, 1, 0); // read 1 bytes 8bit unpacked C var flags = fs.readSync(mp4data, buffer, offset, 3, 1); // read 3 bytes var ctime = 0; var mtime = 0; var track_id = 0; var reserved = 0; var duration = 0; if (version==0) { ctime = fs.readSync(mp4data, buffer, offset, 4, 4); // read 4 bytes unpacked N mtime = fs.readSync(mp4data, buffer, offset, 4, 8); // read 4 bytes unpacked N track_id = fs.readSync(mp4data, buffer, offset, 4, 12); // read 4 bytes unpacked N reserved = fs.readSync(mp4data, buffer, offset, 4, 16); // read 4 bytes duration = fs.readSync(mp4data, buffer, offset, 4, 20); // read 4 bytes unpacked N } else if (version==1) { ctime = fs.readSync(mp4data, buffer, offset, 8, 4); // read 8 bytes unpacked Q mtime = fs.readSync(mp4data, buffer, offset, 8, 12); // read 8 bytes unpacked Q track_id = fs.readSync(mp4data, buffer, offset, 4, 20); // read 4 bytes unpacked N reserved = fs.readSync(mp4data, buffer, offset, 4, 24); // read 4 bytes duration = fs.readSync(mp4data, buffer, offset, 4, 28); // read 4 bytes unpacked Q } reserved = 0; // read 8 bytes var layer = 0; // read 2 bytes unpacked N var alternate_group = 0; // read 2 bytes unpacked N var volume = 0; // read 2 bytes unpacked N reserved = 0; // read 2 bytes var matrix = 0; //read 36 bytes var width = 0; //read 4 bytes unpacked N var height = 0; //read 4 bytes unpacked N return { "ctime": ctime, "mtime": mtime, "track_id": track_id, "duration": duration, "layer": layer, "alternate_group": alternate_group, "volume": volume, "width": width, "height": height } } var parse_mvhd = function(mp4data, buffer, offset) { console.log("MVHD"); offset += 8; // seek offset var version = 0; // read 1 bytes 8bit unpacked C var flags = 0; // read 3 bytes var ctime = 0; var mtime = 0; var scale = 0; var duration = 0; if (version==0) { ctime = 0; // read 4 bytes unpacked N mtime = 0; // read 4 bytes unpacked N scale = 0; // read 4 bytes unpacked N duration = 0; // read 4 bytes unpacked N } else if (version=-1) { ctime = 0; // read 8 bytes unpacked Q mtime = 0; // read 8 bytes unpacked Q scale = 0; // read 4 bytes unpacked N duration = 0; // read 8 bytes unpacked Q } return { "ctime": ctime, "mtime": mtime, "scale": scale, "duration": duration } } var parse_udta = function(mp4data, buffer, offset) { }
active9/mp4
index.js
JavaScript
mit
6,765
'use strict'; import {getNiceTime} from './util'; let ppq, bpm, factor, nominator, denominator, playbackSpeed, bar, beat, sixteenth, tick, ticks, millis, millisPerTick, secondsPerTick, ticksPerBeat, ticksPerBar, ticksPerSixteenth, numSixteenth, diffTicks; function setTickDuration(){ secondsPerTick = (1/playbackSpeed * 60)/bpm/ppq; millisPerTick = secondsPerTick * 1000; //console.log(millisPerTick, bpm, ppq, playbackSpeed, (ppq * millisPerTick)); //console.log(ppq); } function setTicksPerBeat(){ factor = (4/denominator); numSixteenth = factor * 4; ticksPerBeat = ppq * factor; ticksPerBar = ticksPerBeat * nominator; ticksPerSixteenth = ppq/4; //console.log(denominator, factor, numSixteenth, ticksPerBeat, ticksPerBar, ticksPerSixteenth); } function updatePosition(event){ diffTicks = event.ticks - ticks; tick += diffTicks; ticks = event.ticks; //console.log(diffTicks, millisPerTick); millis += diffTicks * millisPerTick; while(tick >= ticksPerSixteenth){ sixteenth++; tick -= ticksPerSixteenth; while(sixteenth > numSixteenth){ sixteenth -= numSixteenth; beat++; while(beat > nominator){ beat -= nominator; bar++; } } } } export function parseTimeEvents(song){ //console.time('parse time events ' + song.name); let timeEvents = song._timeEvents; let type; let event; ppq = song.ppq; bpm = song.bpm; nominator = song.nominator; denominator = song.denominator; playbackSpeed = song.playbackSpeed; bar = 1; beat = 1; sixteenth = 1; tick = 0; ticks = 0; millis = 0; setTickDuration(); setTicksPerBeat(); timeEvents.sort((a, b) => (a.ticks <= b.ticks) ? -1 : 1); for(event of timeEvents){ event.song = song; type = event.type; updatePosition(event); switch(type){ case 0x51: bpm = event.bpm; setTickDuration(); break; case 0x58: nominator = event.nominator; denominator = event.denominator; setTicksPerBeat(); break; default: continue; } //time data of time event is valid from (and included) the position of the time event updateEvent(event); //console.log(event.barsAsString); } song.lastEventTmp = event; //console.log(event); //console.log(timeEvents); } export function parseEvents(song, evts){ //console.log(events) let event; let startEvent = 0; let lastEventTick = 0; let events = [].concat(evts, song._timeEvents); let numEvents = events.length; //console.log(events) events.sort(function(a, b){ return a._sortIndex - b._sortIndex; }); event = events[0]; bpm = event.bpm; factor = event.factor; nominator = event.nominator; denominator = event.denominator; ticksPerBar = event.ticksPerBar; ticksPerBeat = event.ticksPerBeat; ticksPerSixteenth = event.ticksPerSixteenth; numSixteenth = event.numSixteenth; millisPerTick = event.millisPerTick; secondsPerTick = event.secondsPerTick; millis = event.millis; bar = event.bar; beat = event.beat; sixteenth = event.sixteenth; tick = event.tick; for(let i = startEvent; i < numEvents; i++){ event = events[i]; //console.log(event.ticks, event.type) switch(event.type){ case 0x51: bpm = event.bpm; millis = event.millis; millisPerTick = event.millisPerTick; secondsPerTick = event.secondsPerTick; //console.log(millisPerTick,event.millisPerTick); //console.log(event); break; case 0x58: factor = event.factor; nominator = event.nominator; denominator = event.denominator; numSixteenth = event.numSixteenth; ticksPerBar = event.ticksPerBar; ticksPerBeat = event.ticksPerBeat; ticksPerSixteenth = event.ticksPerSixteenth; millis = event.millis; //console.log(nominator,numSixteenth,ticksPerSixteenth); //console.log(event); break; default: updatePosition(event); updateEvent(event); } lastEventTick = event.ticks; } song.lastEventTmp = event; } function updateEvent(event){ //console.log(bar, beat, ticks) //console.log(event, bpm, millisPerTick, ticks, millis); event.bpm = bpm; event.nominator = nominator; event.denominator = denominator; event.ticksPerBar = ticksPerBar; event.ticksPerBeat = ticksPerBeat; event.ticksPerSixteenth = ticksPerSixteenth; event.factor = factor; event.numSixteenth = numSixteenth; event.secondsPerTick = secondsPerTick; event.millisPerTick = millisPerTick; event.ticks = ticks; event.millis = millis; event.seconds = millis/1000; event.bar = bar; event.beat = beat; event.sixteenth = sixteenth; event.tick = tick; //event.barsAsString = (bar + 1) + ':' + (beat + 1) + ':' + (sixteenth + 1) + ':' + tick; var tickAsString = tick === 0 ? '000' : tick < 10 ? '00' + tick : tick < 100 ? '0' + tick : tick; event.barsAsString = bar + ':' + beat + ':' + sixteenth + ':' + tickAsString; event.barsAsArray = [bar, beat, sixteenth, tick]; var timeData = getNiceTime(millis); event.hour = timeData.hour; event.minute = timeData.minute; event.second = timeData.second; event.millisecond = timeData.millisecond; event.timeAsString = timeData.timeAsString; event.timeAsArray = timeData.timeAsArray; }
abudaan/qambi
stuff/legacy/parse_events.js
JavaScript
mit
5,434
'use strict'; var expect = require('expect.js'); var mockery = require('mockery'); var configUnreachable = { view: 'kokoko', port: '1234' // unreachable port }; var configBadPort = { view: 'kokoko', port: '-' // bad port formar }; var configDemoMode = { view: 'kokoko', demoMode: true }; describe('JenkinsGrabber', function () { it('should return configuration error', function () { expect(require('../modules/jenkinsGrabber')).to.throwException('view config missed'); }); it('should have public methods and static values', function () { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configUnreachable); expect(jenkinsGrabber.getStatus).to.be.a('function'); expect(jenkinsGrabber.setLogger).to.be.a('function'); expect(jenkinsGrabber.STATUS).to.be.an('object'); }); describe('setLogger()', function () { it('custom logger function should be called', function () { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configUnreachable); var log = false; jenkinsGrabber.setLogger({ info: function () { log = true; } }); expect(jenkinsGrabber.getStatus).to.throwException('callback parameter missed'); expect(log).to.be.ok(); }); }); describe('getStatus()', function () { describe('demo mode', function () { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configDemoMode); it('OK', function (done) { jenkinsGrabber.getStatus(function (err, value) { expect(value).to.be(jenkinsGrabber.STATUS.OK); done(); }); }); it('RUN', function (done) { jenkinsGrabber.getStatus(function (err, value) { expect(value).to.be(jenkinsGrabber.STATUS.RUN); done(); }); }); it('FAIL', function (done) { jenkinsGrabber.getStatus(function (err, value) { expect(value).to.be(jenkinsGrabber.STATUS.FAIL); done(); }); }); it('UNDEFINED', function (done) { jenkinsGrabber.getStatus(function (err, value) { expect(value).to.be(jenkinsGrabber.STATUS.UNDEFINED); done(); }); }); }); describe('prodution mode [bad jenkins config]', function () { it('wrong format port request failed', function () { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configBadPort); expect(jenkinsGrabber.getStatus).withArgs(function () {}).to.throwException('port should be'); }); it('unreachable port request failed', function (done) { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configUnreachable); jenkinsGrabber.getStatus(function (err) { expect(err).to.contain('ECONNREFUSED'); done(); }); }); }); describe('prodution mode [fake jenkins response]', function () { var returnValuesIndex = 0; var returnValues = ['blue', 'red_anime', 'red']; beforeEach(function () { mockery.enable({ warnOnReplace: false, warnOnUnregistered: false, useCleanCache: true }); mockery.registerMock('http', { get: function (value, callback) { var res = function () { var self = this; self.setEncoding = function () { //-- }; self.on = function (event, eventCallback) { if (event === 'data') { eventCallback(JSON.stringify({ jobs: [{ color: returnValues[returnValuesIndex++] }] })); } else if (event === 'end') { eventCallback(); } return self; }; return self; }; callback(new res()); return { on: function () { // --- } }; } }); }); afterEach(function () { mockery.disable(); }); it('should return "ok" if color is "blue"', function (done) { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configUnreachable); jenkinsGrabber.getStatus(function (err, value) { expect(err).to.be(null); expect(value).to.be('ok'); done(); }); }); it('should return "run" if color is "red_anime"', function (done) { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configUnreachable); jenkinsGrabber.getStatus(function (err, value) { expect(err).to.be(null); expect(value).to.be('run'); done(); }); }); it('should return "fail" if color is "red"', function (done) { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configUnreachable); jenkinsGrabber.getStatus(function (err, value) { expect(err).to.be(null); expect(value).to.be('fail'); done(); }); }); it('should skip jenkins error', function (done) { var jenkinsGrabber = require('../modules/jenkinsGrabber')(configUnreachable); jenkinsGrabber.getStatus(function (err, value) { expect(err).to.be(null); expect(value).to.be('undefined'); done(); }); }); }); }); });
antonfisher/rpi-jenkins-light
tests/jenkinsGrabber.test.js
JavaScript
mit
6,643
import h from '../h'; export default ({style, ...rest,}) => h('div', { ...rest, style: { display: 'flex', width: '100%', boxSizing: 'border-box', ...style, }, });
ChenH0ng/blog
client/src/Components/Container.js
JavaScript
mit
207
import React from 'react'; import { getDOMNode } from '@test/testUtils'; import IconStack from '../IconStack'; describe('IconStack', () => { it('Should render a span', () => { const instance = getDOMNode(<IconStack />); assert.equal(instance.tagName, 'SPAN'); }); it('Should have a custom className', () => { const instance = getDOMNode( <IconStack className="custom"> <span /> </IconStack> ); assert.include(instance.className, 'custom'); }); it('Should have a custom style', () => { const fontSize = '12px'; const instance = getDOMNode( <IconStack style={{ fontSize }}> <span /> </IconStack> ); assert.equal(instance.style.fontSize, fontSize); }); it('Should have a custom className prefix', () => { const instance = getDOMNode(<IconStack classPrefix="custom-prefix" />); assert.ok(instance.className.match(/\bcustom-prefix\b/)); }); });
suitejs/suite
src/IconStack/test/IconStackSpec.js
JavaScript
mit
944
import { ProjectType } from '../types'; import ProjectQueries from './ProjectQueriesQL'; import ProjectMutations from './ProjectMutationsQL'; export { ProjectType, ProjectQueries, ProjectMutations };
NikaBuligini/whistleblower-server
app/graph/models/project/ProjectQL.js
JavaScript
mit
201
import React from 'react' import { Text, Form, Field, } from 'react-ui-core/src' export default ( <Form> <Text>Generic Form</Text> <Field label="Name" placeholder="Enter name" /> <Field type="select" label="Priority" options={[ { label: 'Low', value: 'low' }, { label: 'High', value: 'high' }, ]} /> <Field type="textarea" label="Comments" /> <Field type="checkbox" label="Option" /> </Form> )
rentpath/react-ui
stories/core/Form.js
JavaScript
mit
517
$(function () { // 全站通用重新載入列表 $("body") .on("reload-table", function (data) { var $lists = $("[data-table-url]"); $lists.each(function (i, el) { var $container = $(el), url = $container.data("table-url"); $.get(url, null, function (result, status, xhr) { $container.html(result); }); }); }); });
dinowang/MvcTrig
Hexon.MvcTrig.Sample/Scripts/site.event.js
JavaScript
mit
470
version https://git-lfs.github.com/spec/v1 oid sha256:fa484aa90da0ca0e92e95c5e9d4d0024f568cc81f5c4c33ef7acc2b025afd360 size 5962
yogeshsaroya/new-cdnjs
ajax/libs/globalize/1.0.0-alpha.7/globalize/number.min.js
JavaScript
mit
129
const _ = require('lodash'); module.exports = function errorToString(err) { const hasMessage = err != null && _.isString(err.msg); if (_.isString(err)) { return err; } else if (hasMessage) { return err.msg; } return err + ''; };
opentable/oc
src/utils/error-to-string.js
JavaScript
mit
249
var fs = require('fs'); var path = require('path'); var api = JSON.parse( fs.readFileSync(path.resolve(__dirname, 'inspector.json'), 'utf8') ); var doc = require('./generate-doc.js'); doc(api); var lib = require('./generate-lib.js'); lib(api);
admazely/inspector
build/generate.js
JavaScript
mit
256
var config = require('./config'); /*======================================== = Requiring stuffs = ========================================*/ var sh = require('shelljs'); var gulp = require('gulp'), replace = require('gulp-replace'); seq = require('run-sequence'), jade = require('gulp-jade'), mobilizer = require('gulp-mobilizer'), uglify = require('gulp-uglify'), sourcemaps = require('gulp-sourcemaps'), less = require('gulp-less'), cssmin = require('gulp-cssmin'), order = require('gulp-order'), concat = require('gulp-concat'), rename = require('gulp-rename'), zip = require('gulp-zip'), ignore = require('gulp-ignore'), path = require('path'), fs = require('fs'); /*========================================= = Report Errors to Console = ==========================================*/ gulp.on('err', function(e) { console.log(e.err.stack); }); /*========================================= = Clean dest folder = =========================================*/ gulp.task('clean:server', function(done){ sh.rm('-rf',path.join(__dirname,'_dest/server')); done(); }); gulp.task('clean:desktop', function(done){ sh.rm('-rf',path.join(__dirname,'_dest/desktop')); done(); }); gulp.task('clean:mobile',function(done){ sh.rm('-rf',path.join(__dirname,'_dest/mobile')); done(); }); gulp.task('clean', function(done) { seq('clean:server','clean:desktop','clean:mobile',done); }); /*================================== = prepare for server built = ==================================*/ gulp.task('server:prepare', function(done){ var dirs = [ path.join(__dirname,'_dest'), path.join(__dirname,'_dest','server','public','downloads'), path.join(__dirname,'_dest','server','public','upload'), path.join(__dirname,'_dest','server','public','updates'), path.join(__dirname,'_dest','server','public','thirds'), path.join(__dirname,'_dest','server','public','images') ]; for(var i in dirs){ if(!sh.test('-d', dirs[i])){ sh.mkdir('-p', dirs[i]); } } done(); }); /*================================== = build js for server = ==================================*/ gulp.task('server:js', function(done){ gulp.src([ '**/*.js', '!_*/**/*', '!app/**/*', '!build/**/*', '!config/**/*', '!test/**/*', '!commands/**/*', '!gulpfile.js', '!public/_tmp/**/**', '!public/upload/**/*', ]) .pipe(uglify()) .pipe(gulp.dest('_dest/server')); //特殊情况 gulp.src([ 'commands/**/*.js', ]) .pipe(gulp.dest('_dest/server/commands')); done(); }); /*================================== = Copy server related = ==================================*/ gulp.task('server:copy', function(done){ gulp.src([ '**/*.jade', '**/*.@(html|htm)', '**/*.@(json|txt)', '**/*.css', '**/*.@(eot|svg|ttf|woff|woff2|otf)', '**/*.@(png|jpg|gif)', '**/*.wsdl', '!_*/**/*', '!app/**/*', '!build/**/*', '!test/**/*', '!config/**/*', '!public/_*/**/*', '!public/upload/**/*', ]) .pipe(gulp.dest(path.join(__dirname,'_dest','server'))); done(); }); /*=========================================== = build node-webkit clients(APP): = = win32,win64,osx32,osx64,linux32,linux64 = ============================================*/ gulp.task('node-webkit:prepare', function(done){ var www_dir = path.join(__dirname,'_dest/desktop/www'); if(!sh.test(www_dir)){ sh.mkdir('-p',www_dir); } sh.cp('-rf', path.join(__dirname,'_app/*'), www_dir); sh.cp('-f', path.join(__dirname,'build/node-webkit','package.json'), www_dir); done(); }); gulp.task('node-webkit:builder', function(done){ var NwBuilder = require('node-webkit-builder'); var nw = new NwBuilder({ files: path.join(__dirname,'_dest/desktop/www','**/**'), platforms: ['win','osx','linux'], version: '0.12.2',//download node-webkit version appName: 'platforms', buildDir: path.join(__dirname,'./_dest/desktop'), cacheDir: path.join(__dirname,'../_cache'), buildType: 'default', forceDownload: false, macCredits: false, macIcns: false, macZip: true, macPlist: false, winIco: null, }); // nw.on('log', console.log); nw.build() .then(function(){ done(); }) .catch(function(err){ console.error(err); }); }); gulp.task('node-webkit:deploy',function(done){ //zip&copy to downloads var deploy_dir = path.join(__dirname,'_dest','server','public','downloads'); if(!sh.test('-d',deploy_dir)){ sh.mkdir('-p', deploy_dir); } gulp.src(path.join(__dirname,'_dest/desktop/platforms','linux32')) .pipe(zip(config.project.name + '-linux32.zip')) .pipe(gulp.dest(deploy_dir)); gulp.src(path.join(__dirname,'_dest/desktop/platforms','linux64')) .pipe(zip(config.project.name + '-linux64.zip')) .pipe(gulp.dest(deploy_dir)); gulp.src(path.join(__dirname,'_dest/desktop/platforms','win32')) .pipe(zip(config.project.name + '-win32.zip')) .pipe(gulp.dest(deploy_dir)); gulp.src(path.join(__dirname,'_dest/desktop/platforms','win64')) .pipe(zip(config.project.name + '-win64.zip')) .pipe(gulp.dest(deploy_dir)); gulp.src(path.join(__dirname,'_dest/desktop/platforms','osx32')) .pipe(zip(config.project.name + '-osx32.zip')) .pipe(gulp.dest(deploy_dir)); gulp.src(path.join(__dirname,'_dest/desktop/platforms','osx64')) .pipe(zip(config.project.name + '-osx64.zip')) .pipe(gulp.dest(deploy_dir)); done(); }); gulp.task('node-webkit', function(done){ seq('node-webkit:prepare','node-webkit:builder','node-webkit:deploy',done); }); /*=========================================== = build cordova clients(APP): = = android, ios = ============================================*/ gulp.task('cordova',function(done){ //NOTE: npm install cordova-cli -g var root_dir = path.join(__dirname); var target_dir = path.join(__dirname,'_dest/mobile'); var config_file = path.join(__dirname, 'build/cordova/config.xml'); var www_dir = path.join(__dirname,'_app/*'); var res_dir = path.join(__dirname,'build/cordova/res') var platforms = ['android@' + config.platforms.android.version,'ios']; if(!sh.test('-d', target_dir)){ sh.mkdir(target_dir); } sh.cp(config_file,target_dir); sh.cp('-r',www_dir, path.join(__dirname,'_dest/mobile/www')); sh.cp('-r',res_dir, target_dir); sh.cd(target_dir); for(var i in platforms){ sh.exec('cordova platform add ' + platforms[i]); } sh.exec('cordova prepare'); sh.exec('cordova build --release'); sh.cd(root_dir); //copy to downloads directory var downloads = path.join(__dirname,'_dest','server','public','downloads'); if(!sh.test('-d',downloads)){ sh.mkdir(downloads); } gulp.src(path.join(__dirname,'_dest','mobile','platforms/android/ant-build','CordovaApp-release-unsigned.apk')) .pipe(rename(config.project.name +'.apk')) .pipe(gulp.dest(path.join(__dirname,'_dest','server','public','downloads'))); gulp.src(path.join(__dirname, '_dest','mobile','platforms/ios', config.project.name,'**/*')) .pipe(zip(config.project.name + '.ipa')) .pipe(gulp.dest(path.join(__dirname,'_dest','server','public','downloads'))); done(); }); /*==================================== = sign Task = ====================================*/ gulp.task('android:sign', function(done){ //java sign var unsigned_file = path.join(__dirname,'/_dest/server/public/downloads', config.project.name + '.apk '); if(sh.test('-f', unsigned_file)){ sh.exec('jarsigner ' + ' -keystore ' + config.java_sign.keystore + ' -storepass ' + config.java_sign.keystore_password + ' -digestalg SHA1 -sigalg MD5withRSA ' + ' ./_dest/server/public/downloads/'+ config.project.name + '.apk ' + config.java_sign.keystore_username); }else{ console.log('WARNING: unsigned .apk file does not found, so unsigned.'); } done(); }); /*==================================== = Build Task = ====================================*/ gulp.task('build:server', function(done){ seq('clean:server','server:prepare','server:js','server:copy', done); }); gulp.task('build:mobile', function(done){ seq('clean:mobile','cordova','android:sign',done); }); gulp.task('build:desktop', function(done){ seq('clean:desktop','node-webkit',done); }); gulp.task('build:client', function(done){ seq('build:mobile','build:desktop', done); }); gulp.task('build', function(done){ seq('build:server','build:client', done); }); /*==================================== = Default Task = ====================================*/ gulp.task('default', function(){ console.log("\nUsage:\n"); console.error("WARNING!!! "); console.error("****This build will overwrite './_dest/' directory.****\n"); console.log("|- command: gulp build"); console.log(" |- description: to deploy application's server and clients.\n"); console.log("|- command: gulp build:server"); console.log(" |- description: to deploy application's server.\n"); console.log("|- command: gulp build:client"); console.log(" |- description: to deploy cordova and node-webkit clients.\n"); console.log("|- command: gulp build:mobile"); console.log(" |- description: to deploy cordova clients only.\n"); console.log("|- command: gulp build:desktop"); console.log(" |- description: to deploy node-webkit clients only.\n"); });
williambai/beyond-webapp
lottery/gulpfile.js
JavaScript
mit
10,313
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = function () { function Message(recipient, text) { _classCallCheck(this, Message); this.rec = recipient; this.txt = text; } _createClass(Message, [{ key: 'getData', value: function getData() { var data = { recipient: { id: this.rec }, message: { text: this.txt } }; return data; } }]); return Message; }();
Voronchuk/fb-bot-api
app/messages/Message.js
JavaScript
mit
1,270
/** * Created by admin on 15-5-12. */ (function () { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame']; } var blacklisted = /iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent); if (!window.requestAnimationFrame || blacklisted) { window.requestAnimationFrame = function (callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame || blacklisted) { window.cancelAnimationFrame = function (id) { clearTimeout(id); }; } }()); window.onload = function () { this.canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; // canvas.width = 300; canvas.height = window.innerHeight; // canvas.height = 300; this.ctx = canvas.getContext("2d"); this.Game = {}; Game.step = 3; Game.rand = function rand(m, n) { return Math.round(Math.random() * (n - m) + m); }; var road = new Road(); var car = new Car(); var frame = 0; function loop() { ctx.clearRect(-1000, -1000, 3000, 3000); road.update(); road.render(); // ctx.strokeStyle = "white"; // drawCircle(road.allPoints[road.currIdx], 5); car.update(road.allPoints[road.currIdx].x,road.allPoints[road.currIdx].y,road.allPoints[road.currIdx].rad); //测试Sprite向量角. // car.update(road.allPoints[road.currIdx].x,road.allPoints[road.currIdx].y,(80 * Math.PI)/180); car.render(); centerMe({ x: car.x, y: car.y }); // tick = setTimeout(loop, 1000); requestAnimationFrame(loop); frame++; } loop(); var $wrapper = document.querySelector("#wrapper"); function mousedown(e){ Game.step = 7; e.preventDefault(); e.stopPropagation(); } function mouseup(e){ Game.step = 2; e.preventDefault(); e.stopPropagation(); } $wrapper.addEventListener("mousedown",mousedown,false); $wrapper.addEventListener("touchstart",mousedown,false); $wrapper.addEventListener("mouseup",mouseup,false); $wrapper.addEventListener("touchend",mouseup,false); }
picacure/_sandBox
recognition/cubic/BezierSimple/runway/js/setup.js
JavaScript
mit
2,487
import Ember from 'ember'; import wskCard from 'ember-material/components/wsk-card'; export default wskCard;
bbaaxx/ember-material
app/components/wsk-card.js
JavaScript
mit
111
'use strict'; /** * * @param {Number} value The number. * @param {Boolean} mod * @returns {number} */ module.exports = (value, mod) => { var useMod = mod === true; var sign = useMod && Math.sign(value) || 1; var val = useMod && Math.abs(value) || value; var centValue = val * 100; //100 represents 0.00 var integerValue = (centValue > 0) && Math.floor(centValue) || Math.ceil(centValue); if (Math.round(Math.round((centValue - integerValue) * 100) / 10) > 5) { ++integerValue; } return (integerValue / 100) * sign; };
evertonamorim/tax-round-br
lib/tax-round-br.js
JavaScript
mit
570
/** * interface.js * Andrea Tino - 2015 */ /** * Describes a ScriptSharp interface for TypeScript rendering. * This module implements interface: [TSRenderer]. */ module.exports = function() { var interfaceFQName = null; // [string] return { /** * Initializes the interface with initial information. * rm: [RegexMatches] */ initialize: function(rm) { if (!rm) { throw 'Error: A [RegexMatches] is needed to initialize the interface!'; } }, /** * Renders the TypeScript interface. */ render: function() { } }; };
andry-tino/sankaku
lib/interface.js
JavaScript
mit
607
const bcrypt = require('bcrypt-nodejs'); const crypto = require('crypto'); const mongoose = require('mongoose'); const mongooseHidden = require('mongoose-hidden')() const userSchema = new mongoose.Schema({ email: { type: String, unique: true }, password: { type: String, hide: true }, passwordResetToken: { type: String, hide: true }, passwordResetExpires: { type: Date, hide: true }, facebook: { type: String, hide: true }, twitter: { type: String, hide: true }, tokens: { type: Array, hide: true }, profile: { name: String, picture: String, theme: { type: Number, default: 1 }, } }, { timestamps: true }); /** * Password hash middleware. */ userSchema.pre('save', function save(next) { const user = this; if (!user.isModified('password')) { return next(); } bcrypt.genSalt(10, (err, salt) => { if (err) { return next(err); } bcrypt.hash(user.password, salt, null, (err, hash) => { if (err) { return next(err); } user.password = hash; next(); }); }); }); /** * Helper method for validating user's password. */ userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { cb(err, isMatch); }); }; /** * Helper method for getting user's gravatar. */ userSchema.methods.gravatar = function gravatar(size) { if (!size) { size = 200; } if (!this.email) { return `https://gravatar.com/avatar/?s=${size}&d=retro`; } const md5 = crypto.createHash('md5').update(this.email).digest('hex'); return `https://gravatar.com/avatar/${md5}?s=${size}&d=retro`; }; const User = mongoose.model('User', userSchema); module.exports = User;
marreo/moocherv2
models/User.js
JavaScript
mit
1,724
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var Subject = window.Rx ? Rx.Subject : require('rxjs/Subject').Subject; exports.default = Subject;
davidkpiano/RxCSS
lib/subject.js
JavaScript
mit
179
'use strict' import Hackfridays from './src/Hackfridays' Hackfridays('android')
Cloudoki/react-native-boilerplate
index.android.js
JavaScript
mit
83
import { combineReducers } from 'redux'; import LibTableReducer from './reducer_libtable'; import FeaturesReducer from './reducer_features'; import FetchReducer from './reducer_status'; const rootReducer = combineReducers({ features: FeaturesReducer, fetchstatus: FetchReducer, tabledata: LibTableReducer, }); export default rootReducer;
txwkx/RDFJS4U
src/js/reducers/index.js
JavaScript
mit
346
(function () { 'use strict'; /** Registers the 'snippet' filter, which returns the first sentence of a * blog of text. * * - snippet(text) will return a substring of the given string up until, * and including, the first punctuation mark contained in the following * list of punctuation: . ! ? 。(note the last is a period in Chinese). * Moreover, if the text begins with either a <p> or a <blockquote> HTML * tag, the appropriate closing tag is appended to the end of the returned * text, so that the returned snippet is ready to be used in HTML. */ angular.module('core.articleIndex').filter('snippet', function () { return function snippet (text) { const snip = new RegExp('^([^.!?。]+.)').exec(text)[0]; // If the first sentence is contained in an html tag, complete that // tag in the snippet for valid syntax. return snip + (snip.indexOf('<p>') === 0 ? '</p>' : '') + (snip.indexOf('<blockquote>') === 0 ? '</blockquote>' : ''); }; }); })();
Ahlkanvorez/Blog
public/angularJS/blog-app/core/article-index/article-index.snippet.filter.js
JavaScript
mit
1,101
//Write an expression that calculates rectangle’s area by given width and height. var width = 2.5, height = 3; console.log('Rectangle Area: '+CalcArea(width,height)); function CalcArea(width, height) { return width * height; }
zvet80/TelerikAcademyHomework
06.JS/02.OperatorsAndExpressions/OperatorsAndExpressions/03.RectangleArea.js
JavaScript
mit
236
// The code in this file is executed using app.runtime.loadFile(); var app = protos.app; app.RUNTIME_SUCCESS = true;
derdesign/protos
test/fixtures/test.skeleton/runtime.js
JavaScript
mit
120
/*global describe, it, beforeEach*/ 'use strict'; var assert = require('assert'); var esformatter = require('esformatter'); var fs = require('fs'); var plugin = require('..'); describe('esformatter-add-trailing-commas', function() { beforeEach(function() { esformatter.register(plugin); }); it('should add trailing commas on object', function(done) { var output = esformatter.format(readfile('fixtures/object.js')); assert.equal(output, readfile('expected/object.js')); done(); }); it('should add trailing commas on array', function(done) { var output = esformatter.format(readfile('fixtures/array.js')); assert.equal(output, readfile('expected/array.js')); done(); }); }); function readfile(name) { return fs.readFileSync('test/' + name).toString(); }
deoxxa/esformatter-add-trailing-commas
test/index.js
JavaScript
mit
800
chrome.app.runtime.onLaunched.addListener(function () { chrome.app.window.create('index.html', { 'id': "indexWindow", 'outerBounds': { 'width': 400, 'height': 500 } }); });
jtooker/BatchFileRenamer
background.js
JavaScript
mit
228
/* ========================================================================== Content Slider ========================================================================== */ /**** Variables & Arrays ****/ /* var templify = { header:"Templify", subHead:"// Identity, User Interface, Front End", content:"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries.", actionLink:"#portfolio", action:"Read More", img:'<img src="images/workTemplify.jpg" alt="Templify" />' };*/ var $proj1=$('#templify'); var $proj2=$('#logowork'); var $proj3=$('#webbbuilders'); var $proj4=$('#amdocs'); var projects = [$proj1, $proj2, $proj3, $proj4]; var i = 0; /**** Functions ****/ /* var emptyIt = function (){ $('.workInfo h2').empty(); $('.workInfo h3').empty(); $('.workInfo p').empty(); $('.workInfo a').empty().removeAttr("href").removeAttr("class"); $('.slideImage img').remove(); }; var insertIt = function (){ $('.workInfo h2').append(templify.header); $('.workInfo h3').append(templify.subHead); $('.workInfo p').append(templify.content); $('.workInfo a').addClass("slideLink").attr("href", templify.actionLink).stop().append(templify.action); $('.slideImage').append(templify.img); }; */ /**** Arrows ****/ /* var goRight = function () { if (i==3) { i=0; } else { i++; }; $(current).removeClass('InToLeft'); setTimeout(function(){$(current).addClass('OutToLeft');}, 0.1); setTimeout(function(){ $(current).addClass('hideThis'); }, 1800); setTimeout(function(){$(next).addClass('InToLeft');}, 0.1); setTimeout(function(){ $(next).removeClass('hideThis'); }, 1400); } var goLeft = function () { if (i==0) { i=3; } else { i=i-1; }; $(current).removeClass('InToLeft'); setTimeout(function(){$(current).addClass('OutToLeft');}, 0.1); setTimeout(function(){ $(current).addClass('hideThis'); }, 1800); setTimeout(function(){$(previous).addClass('InToLeft');}, 0.1); setTimeout(function(){ $(previous).removeClass('hideThis'); }, 1400); }; */ $('.arrow-right').click(function(){ stop(); var current = projects[i]; if (i===(projects.length-1)) { var current = projects[projects.length-1]; var next = projects[0]; i=-1; } else { var next = projects[i+1]; }; $(current).removeClass('InToLeft'); setTimeout(function(){$(current).addClass('OutToLeft');}, 0.1); setTimeout(function(){ $(current).addClass('hideThis'); }, 1850); setTimeout(function(){$(next).addClass('InToLeft');}, 0.1); setTimeout(function(){ $(next).removeClass('hideThis'); }, 1850); i++; console.log('switch'); }); $('.arrow-left').click(function(){ stop(); var current = projects[i]; if (i==0) { var current = projects[0]; var previous = projects[projects.length-1]; i=projects.length; } else { var previous = projects[i-1]; }; $(current).removeClass('InToLeft'); setTimeout(function(){$(current).addClass('OutToLeft');}, 0.1); setTimeout(function(){ $(current).addClass('hideThis'); }, 1850); setTimeout(function(){$(previous).addClass('InToLeft');}, 0.1); setTimeout(function(){ $(previous).removeClass('hideThis'); }, 1850); i=i-1; console.log('switch'); }); /* $('.right').click(function(){ i++; $('#templify').removeClass('InToLeft'); setTimeout(function(){$('#templify').addClass('OutToLeft');}, 0.1); setTimeout(function(){ $('#templify').addClass('hideThis'); }, 1800); setTimeout(function(){$('#templify2').addClass('InToLeft');}, 0.1); setTimeout(function(){ $('#templify2').removeClass('hideThis'); }, 1400); }); $('.left').click(function(){ i=i-1; $('#templify2').removeClass('InToLeft'); setTimeout(function(){$('#templify2').addClass('OutToLeft');}, 0.1); setTimeout(function(){ $('#templify2').addClass('hideThis'); }, 1900); setTimeout(function(){$('#templify').addClass('InToLeft');}, 0.1); setTimeout(function(){ $('#templify').removeClass('hideThis'); }, 1600); }); */ /* ========================================================================== Smooth Scroll ========================================================================== */ //When you click on an <a> that has a '#' $('a[href^="#"]').bind('click.smoothscroll',function (e) { //prevent from default action to intitiate e.preventDefault(); //'hash' targets the part of the address that comes after the '#' var target = this.hash; $target = $(target); $('html, body').stop().animate({ //The .offset() method allows us to retrieve the current position of an element relative to the document. //Here we are using it to find the position of the target, which we defined earlier as the section of the address that will come after the '#' 'scrollTop': $target.offset().top }, 500, 'swing', function () { window.location.hash = target; }); }); /* ========================================================================== Waypoints ========================================================================== */ $('#home').waypoint(function() { $('*').removeClass('active'); $('#toHome').addClass('active'); }, { offset: -100 }); $('#portfolio').waypoint(function() { $('*').removeClass('active'); $('#toPortfolio').addClass('active'); }, { offset: -50 }); $('#portfolio').waypoint(function() { $('*').removeClass('active'); $('#toPortfolio').addClass('active'); }, { offset: 50 }); $('#about').waypoint(function() { $('*').removeClass('active'); $('#toAbout').addClass('active'); }, { offset: 50 }); /* ========================================================================== Social Nav ========================================================================== */ $('#socialNav').click(function(){ $('#socialNav ul li').toggleClass('open'); });
davo/BA-Apps
.refs/nirbenita.me/js/script.js
JavaScript
mit
6,175
var needle = document.getElementById('needle'); var direction = 0; window.addEventListener('deviceorientation', orientationHandler, true); function orientationHandler(event) { direction = event.alpha || 0; } var needleDirector = setInterval(directNeedle, 50); function directNeedle() { needle.setAttribute('transform','translate(50 50) rotate('+direction+') translate(-50 -50)'); } var container = document.documentElement; container.addEventListener('click',toggleFullscreen); container.requestFullscreen = container.requestFullscreen || container.mozRequestFullscreen || container.webkitRequestFullscreen || container.msRequestFullscreen; function toggleFullscreen() { container.requestFullscreen(); }
scottmmjackson/scottmmjackson.github.io
compass/index.js
JavaScript
mit
736
'use strict'; const common = require('../common.js'); const URL = require('url').URL; const inputs = require('../fixtures/url-inputs.js').urls; const bench = common.createBenchmark(main, { input: Object.keys(inputs), prop: ['href', 'origin', 'protocol', 'username', 'password', 'host', 'hostname', 'port', 'pathname', 'search', 'searchParams', 'hash'], n: [3e5] }); function setAndGet(n, url, prop, alternative) { const old = url[prop]; bench.start(); for (var i = 0; i < n; i += 1) { url[prop] = n % 2 === 0 ? alternative : old; // set url[prop]; // get } bench.end(n); } function get(n, url, prop) { bench.start(); for (var i = 0; i < n; i += 1) { url[prop]; // get } bench.end(n); } const alternatives = { href: 'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test', protocol: 'https:', username: 'user2', password: 'pass2', host: 'foo.bar.net:22', hostname: 'foo.bar.org', port: '23', pathname: '/aaa/bbb', search: '?k=99', hash: '#abcd' }; function getAlternative(prop) { return alternatives[prop]; } function main({ n, input, prop }) { const value = inputs[input]; const url = new URL(value); switch (prop) { case 'protocol': case 'username': case 'password': case 'host': case 'hostname': case 'port': case 'pathname': case 'search': case 'hash': case 'href': setAndGet(n, url, prop, getAlternative(prop)); break; case 'origin': case 'searchParams': get(n, url, prop); break; default: throw new Error('Unknown prop'); } }
MTASZTAKI/ApertusVR
plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/benchmark/url/whatwg-url-properties.js
JavaScript
mit
1,603
/* AngularJS v1.5.0-local+sha.798fb18 (c) 2010-2015 Google, Inc. http://angularjs.org License: MIT */ (function(N,e,E){'use strict';function F(t,b){b=b||{};e.forEach(b,function(e,g){delete b[g]});for(var g in t)!t.hasOwnProperty(g)||"$"===g.charAt(0)&&"$"===g.charAt(1)||(b[g]=t[g]);return b}var y=e.$$minErr("$resource"),K=/^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;e.module("ngResource",["ng"]).provider("$resource",function(){var t=/^https?:\/\/[^\/]*/,b=this;this.defaults={stripTrailingSlashes:!0,actions:{get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"},"delete":{method:"DELETE"}}}; this.$get=["$http","$log","$q",function(g,J,G){function z(e,f){return encodeURIComponent(e).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,f?"%20":"+")}function A(e,f){this.template=e;this.defaults=r({},b.defaults,f);this.urlParams={}}function H(u,f,m,h){function d(a,c){var d={};c=r({},f,c);v(c,function(c,k){x(c)&&(c=c());var q;if(c&&c.charAt&&"@"==c.charAt(0)){q=a;var n=c.substr(1);if(null==n||""===n||"hasOwnProperty"===n||!K.test("."+n))throw y("badmember", n);for(var n=n.split("."),f=0,l=n.length;f<l&&e.isDefined(q);f++){var h=n[f];q=null!==q?q[h]:E}}else q=c;d[k]=q});return d}function L(a){return a.resource}function l(a){F(a||{},this)}var t=new A(u,h);m=r({},b.defaults.actions,m);l.prototype.toJSON=function(){var a=r({},this);delete a.$promise;delete a.$resolved;return a};v(m,function(a,c){var f=/^(POST|PUT|PATCH)$/i.test(a.method),u=!1;e.isNumber(a.timeout)||(a.timeout&&(J.debug("ngResource:\n Only numeric values are allowed as `timeout`.\n Promises are not supported in $resource, because the same value would be used for multiple requests. If you are looking for a way to cancel requests, you should use the `cancellable` option."), delete a.timeout),u=e.isDefined(a.cancellable)?a.cancellable:h&&e.isDefined(h.cancellable)?h.cancellable:b.defaults.cancellable);l[c]=function(k,q,n,h){var b={},m,w,B;switch(arguments.length){case 4:B=h,w=n;case 3:case 2:if(x(q)){if(x(k)){w=k;B=q;break}w=q;B=n}else{b=k;m=q;w=n;break}case 1:x(k)?w=k:f?m=k:b=k;break;case 0:break;default:throw y("badargs",arguments.length);}var C=this instanceof l,p=C?m:a.isArray?[]:new l(m),s={},z=a.interceptor&&a.interceptor.response||L,A=a.interceptor&&a.interceptor.responseError|| E,D;v(a,function(a,c){switch(c){default:s[c]=M(a);case "params":case "isArray":case "interceptor":case "cancellable":}});!C&&u&&(D=G.defer(),s.timeout=D.promise);f&&(s.data=m);t.setUrlParams(s,r({},d(m,a.params||{}),b),a.url);b=g(s).then(function(d){var k=d.data;if(k){if(e.isArray(k)!==!!a.isArray)throw y("badcfg",c,a.isArray?"array":"object",e.isArray(k)?"array":"object",s.method,s.url);if(a.isArray)p.length=0,v(k,function(a){"object"===typeof a?p.push(new l(a)):p.push(a)});else{var b=p.$promise; F(k,p);p.$promise=b}}d.resource=p;return d},function(a){(B||I)(a);return G.reject(a)});b.finally(function(){p.$resolved=!0;!C&&u&&(p.$cancelRequest=e.noop,D=s.timeout=null)});b=b.then(function(a){var c=z(a);(w||I)(c,a.headers);return c},A);return C?b:(p.$promise=b,p.$resolved=!1,u&&(p.$cancelRequest=D.resolve),p)};l.prototype["$"+c]=function(a,d,b){x(a)&&(b=d,d=a,a={});a=l[c].call(this,a,this,d,b);return a.$promise||a}});l.bind=function(a){return H(u,r({},f,a),m)};return l}var I=e.noop,v=e.forEach, r=e.extend,M=e.copy,x=e.isFunction;A.prototype={setUrlParams:function(b,f,m){var h=this,d=m||h.template,g,l,r="",a=h.urlParams={};v(d.split(/\W/),function(c){if("hasOwnProperty"===c)throw y("badname");!/^\d+$/.test(c)&&c&&(new RegExp("(^|[^\\\\]):"+c+"(\\W|$)")).test(d)&&(a[c]={isQueryParamValue:(new RegExp("\\?.*=:"+c+"(?:\\W|$)")).test(d)})});d=d.replace(/\\:/g,":");d=d.replace(t,function(a){r=a;return""});f=f||{};v(h.urlParams,function(a,b){g=f.hasOwnProperty(b)?f[b]:h.defaults[b];e.isDefined(g)&& null!==g?(l=a.isQueryParamValue?z(g,!0):z(g,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+"),d=d.replace(new RegExp(":"+b+"(\\W|$)","g"),function(a,b){return l+b})):d=d.replace(new RegExp("(/?):"+b+"(\\W|$)","g"),function(a,b,c){return"/"==c.charAt(0)?c:b+c})});h.defaults.stripTrailingSlashes&&(d=d.replace(/\/+$/,"")||"/");d=d.replace(/\/\.(?=\w+($|\?))/,".");b.url=r+d.replace(/\/\\\./,"/.");v(f,function(a,d){h.urlParams[d]||(b.params=b.params||{},b.params[d]=a)})}};return H}]})})(window, window.angular); //# sourceMappingURL=angular-resource.min.js.map
tianlmn/AngularJS
build/angular-resource.min.js
JavaScript
mit
4,453
var searchData= [ ['keyboardmapping',['KeyboardMapping',['../class_snowflake_1_1_emulator_1_1_input_1_1_keyboard_mapping.html',1,'Snowflake::Emulator::Input']]] ];
SnowflakePowered/snowflakepowered.github.io
doc/html/search/classes_9.js
JavaScript
mit
166
import React, { Component } from 'react'; import { connect } from 'react-redux'; import Select from 'react-select'; import { createGroupTransfer, fetchStudentGroupsExcept, fetchStudentsGroup } from '../../../actions/admin/adminDashboardActions'; const mapStateToProps = (state) => { return { teachers: state.adminReducer.teachers, groups: state.adminReducer.groups }; }; const mapDispatchToProps = (dispatch) => { return { fetchStudentGroupsExcept: (groupId) => dispatch(fetchStudentGroupsExcept(groupId)), fetchStudentsGroup: (groupId) => dispatch(fetchStudentsGroup(groupId)) }; }; class StudentsPicker extends Component { constructor(props) { super(props); this.state = { selectedStudents: [] }; this.handleInputChange = this.handleInputChange.bind(this); } componentDidMount() { this.fetchStudents(this.props.onlyCurrentGroup); } componentWillReceiveProps(nextProps) { if (this.props.onlyCurrentGroup !== nextProps.onlyCurrentGroup) { this.setState({ selectedStudents: [] }); this.fetchStudents(nextProps.onlyCurrentGroup); } } fetchStudents(onlyCurrentGroup) { if (onlyCurrentGroup) { this.props.fetchStudentsGroup(this.props.group.id); } else { this.props.fetchStudentGroupsExcept(this.props.group.id); } } getCurrentOptions() { if (this.props.groups) { const students = this.props.groups.filter(group => this.getPredicate(group.id, this.props.group.id)) .reduce((acc, current) => acc.concat(current.students), []) .filter(elem => elem !== undefined) .map( option => { return { value: option.id, label: option.name }; } ); return students; } return []; } getPredicate(id1, id2) { if (this.props.onlyCurrentGroup) { return id1 === id2; } return id1 !== id2; } handleInputChange(inputValue) { this.setState({ selectedStudents: inputValue }, () => { this.props.sendSelectedStudents(this.state.selectedStudents); }); } render() { return ( <Select className='student-picker-select' name='student-picker-select' value={this.state.selectedStudents} options={this.getCurrentOptions()} noResultsText={'No Students Found!'} onChange={this.handleInputChange} multi={true} placeholder={'Find students'} searchPromptText={'Type to Search'} /> ); } } export default connect(mapStateToProps, mapDispatchToProps)(StudentsPicker);
jrm2k6/i-heart-reading
resources/assets/js/components/admin/forms/StudentsPicker.js
JavaScript
mit
2,585
var Connection = require("./database"); var db = new Connection(); function User() { } User.prototype.get = function(id, callback) { db.getUser(id, function(err, user) { callback(err, user); }); } User.prototype.current = function(req, res) { if(req.session.passport.user) { return req.session.passport.user; } else { return false; } } User.prototype.isUser = function(req, res, next) { if(!req.session.passport.user) { res.redirect("/login"); } else { next(); } } User.prototype.auth = function(req, res, next) { if(!req.session.passport.user) { res.send(403, "Access denied"); } else { next() } } module.exports = User;
luiselizondo/mariachi
lib/user.js
JavaScript
mit
656
/** * Created by Administrator on 2016/6/13. */ $(document).ready(function(){ //alert("文档加载完毕") $("p").click(function(){ $(this).hide(); }) })
wangyongtan/H5
2016/0612~15-JQuery/0612-JQuery/app.js
JavaScript
mit
178
/** * Created by mandy on 16-4-19. */ 'use strict'; (function () { function userCtrl ($scope, API_CONFIG, $uibModal, allRoleList, User) { 'ngInject'; var roleOptions = generateRoleOptions(); /** * * @type {*[]} select options used in filter of column 'locked' */ var lockedOptions = [ {value: '', label: '请选择状态'}, {value: true, label: '锁定'}, {value: false, label: '正常'} ]; /** * * @type {Array} data in table */ $scope.data = []; // table options in table $scope.options = { columns: [ {name: 'username', label: '用户名', showed: true, filter: 'filter_username', placeholder: '用户名', sort: 'order_username'}, {name: 'realname', label: '真实姓名', showed: true, filter: 'filter_realname', placeholder: '真实姓名', sort: 'order_realname'}, {name: 'role', label: '角色', showed: true, filter: 'filter_role_id', filterType: 'select', filterOptions: roleOptions, placeholder: '角色', sort: 'order_realname', html: roleHtml}, {name: 'email', label: '邮箱', showed: true, filter: 'filter_email', placeholder: '邮箱', sort: 'order_email'}, {name: 'telephone', label: '电话', showed: true, filter: 'filter_telephone', placeholder: '电话', sort: 'order_telephone'}, {name: 'description', label: '描述', showed: true, filter: false, sort: false}, {name: 'created_time', label: '创建时间', showed: true, filter: 'filter_created_time', placeholder: '创建时间', sort: 'order_realname', html: createdTimeHtml}, {name: 'locked', label: '锁定状态', showed: true, filter: 'filter_locked', filterType: 'select', filterOptions: lockedOptions, placeholder: '锁定状态', sort: 'order_realname', html: lockedHtml}, {name: 'handler', label: '操作', showed: true, filter: false, sort: false, html: handlerHtml, handler: [openUserDetail, openUpdateUserModal, openDeleteUserModal]} ], url: API_CONFIG.USERS, tableColumnFlag: true, filterFlag: true, sortFlag: true, checkboxFlag: true, detailHtml: detailHtml, tableRowOptions: [{row: 15}, {row: 25}, {row: 50}, {row: 100}], search: { name: 'search' }, edit: { create: { html: '<a class="btn btn-primary btn-sm"><i class="fa fa-plus"></i></a>', handler: openCreateUserModal }, 'delete': { html: '<a class="btn btn-primary btn-sm"><i class="fa fa-trash-o"></i></a>', handler: openDeleteUserModal } }, page: { current: 1, rows: 15, totalPages: 1, totalRows: 1 } }; function generateRoleOptions () { var roleOptions = [{value: '', label: '请选择角色'}]; var role; for (var i in allRoleList) { role = allRoleList[i]; roleOptions.push({value: role.id, label: role.name}); } return roleOptions; } /** * Generate html in td of 'locked' column * @param {Boolean} data - value of user.locked * @returns {string} */ function lockedHtml (data) { var html = ''; html += '<span class="label '; if (data) { html += 'label-warning">锁定'; } else { html += 'label-info">正常'; } html += '</span>'; return html; } /** * Generate html in td of 'role' column * @param {Object} data - value of user.role * @returns {string} */ function roleHtml (data) { return '<span>' + data.name + '</span>'; } /** * Generate html in td of 'created_time' column * @param {Number} data * @returns {string} */ function createdTimeHtml (data) { var date = new Date(parseInt(data)); return '<span>' + date.toLocaleString() + '</span>'; } function handlerHtml (el) { var html = '<i class="fa fa-info btn-text btn-info" title="详情" ng-click="(el2.handler[0])(el)"></i>'; html += '<i class="fa fa-edit btn-text btn-primary" title="修改信息" ng-click="(el2.handler[1])(el)"></i>'; html += '<i class="fa fa-undo btn-text btn-primary" title="重置密码" ng-click="(el2.handler[1])(el)"></i>'; html += '<i ng-if="el.locked" class="fa fa-unlock btn-text btn-warning" title="解除锁定" ng-click="(el2.handler[1])(el)"></i>'; html += '<i class="fa fa-trash btn-text btn-default" title="删除" ng-click="(el2.handler[2])(el)"></i>'; return html; } function detailHtml (el) { return '<td colspan="10" class="td-detail" ng-show="el.detailOpened" ng-include="\'/app/config/user/user_detail.html\'"></td>'; } function openCreateUserModal () { var modalInstance = $uibModal.open({ animation: true, templateUrl: '/app/config/user/create-user-modal/index.html', controller: 'createUserModalCtrl', size: 'md', resolve: { roleOptions: function () { return roleOptions; } } }); modalInstance.result.then(function (result) { if (result == 'success') { $scope.options.doSearch(1); } }); } function openUpdateUserModal (el) { var modalInstance = $uibModal.open({ animation: true, templateUrl: '/app/config/user/update-user-modal/index.html', controller: 'updateUserModalCtrl', size: 'md', resolve: { selectedUser: function () { return el; }, roleOptions: function () { return roleOptions; } } }); modalInstance.result.then(function (result) { if (result == 'success') { $scope.options.doSearch(1); } }); } function openDeleteUserModal ($index) { var modalInstance = $uibModal.open({ animation: true, templateUrl: '/app/config/user/delete-user-modal/index.html', controller: 'deleteUserModalCtrl', size: 'md' }); modalInstance.result.then(function (result) { if (result == 'success') { $scope.options.doSearch(1); } }); } function openUserDetail (el) { if (el.detailOpened) { el.detailOpened = false; } else { for (var i in $scope.data) { $scope.data[i].detailOpened = false; } if (!el.hasOwnProperty('detail')) { User.getDetail(el.id).then(function (res) { el.detail = res; }); } el.detailOpened = true; } } } angular.module('app.config').controller('userCtrl', userCtrl); })();
Mandy-Tang/cs-example
client/app/config/user/userCtrl.js
JavaScript
mit
6,715
'use strict'; var http = require('http'); var express = require('express'); var config = require('./config'); var app = express(); var server = http.createServer(app); var io = require('socket.io')(server); var Robot = require('./src/lib/Robot'); var SerialPort = require('serialport').SerialPort; var serialPort = new SerialPort(config.xbee.serialPort, { baudrate: config.xbee.baudrate }); app.use(express.static(__dirname + '/build')); var robot = new Robot(serialPort); io.on('connection', function(socket) { socket.on('move', function(data) { robot.setSpeed(data.alpha, data.amplitude); robot.move(); socket.emit('moved', data); }); }); module.exports = server; if (!module.parent) { server.listen(config.server.port); }
fbentz/Porcoduino
app.js
JavaScript
mit
753
$(document).ready(function () { $(".list-group").on("click", "#transition",function(e){ e.preventDefault(); var uri= $(this).attr("href"); $("#serpent").animate({left: 0}, 3000); setTimeout(function(){ $.ajax({url: uri, type: "GET", data: {url: uri}}).done(function(response){ window.location.href = response; }) }, 3000) }) $('#ask-question').on("click", function(e){ e.preventDefault(); $(this).fadeOut(700, function(){ }) setTimeout(function(){ $('#new-question-form').fadeIn(700, function(){ }) }, 700) }) $('#main-top').on("click", "#SPAM", function(e){ e.preventDefault(); var title = $('input[name="title"]').val(); var description = $('input[name="description"]').val(); var uri = $('form').attr("action"); $.ajax({url: uri, type: "POST", context: this, data: {title, description}}).done(function(response) { var response = JSON.parse(response); $('#foot').animate({top: 0}, 1000, function(){ //animation happens here }) setTimeout(function(){ var source = $('#new-question-template').html(); var template = Handlebars.compile(source); var html = template(response); $(html).hide().prependTo('.list-group').fadeIn("slow"); $('#foot').animate({top: -397}, 1000, function(){ //animation happens here }) }, 1000) setTimeout(function(){ $('input[name="title"').val(""); $('input[name="description"').val(""); }, 1500) }) }) $('.list-group').on("click", '#up-vote', function(e){ e.preventDefault(); var uri = $(this).parent().parent().find("a").attr("href") + "/votes" $.ajax({url: uri, type: "POST", context: this}).done(function(response){ var badge = $(this).parent().parent().find("span.badge"); $(badge).css("color", "yellow"); $(badge).text(response); }) }) $('#questions-page').on("click", '.commentable', function(e){ e.preventDefault(); var source = $('#new-comment-template').html(); var template = Handlebars.compile(source); var html = template(); var showComment = $(this).next(); var uri = "../" + $(this).attr("id") + "/comments" var parentDiv = $(this).parent().parent() // console.log(div.find('#answer-comments')) $(this).fadeOut(700, function(){ }) setTimeout(function(){ $(html).hide().prependTo(showComment).fadeIn("slow"); }, 700) $('#questions-page').on("click", "#SPAM", function(e){ e.preventDefault(); var text = $('input[name="text"]').val(); $.ajax({url: uri, type: "POST", context: this, data: {text: text}}).done(function(response){ if (uri.indexOf("question") > -1){div = '#question-comments'} else if (uri.indexOf("answer") > -1) { parentDiv = parentDiv.parent().parent() div = parentDiv.find("#answer-comments") } $(response).hide().prependTo(div).fadeIn("slow"); $('input[name="text"]').val(""); }) }) }) });
sf-squirrels-2016/PythonOverflow
public/js/application.js
JavaScript
mit
3,076
export const artifactsList = [ { text: 'result.txt', url: 'bar', job_name: 'generate-artifact', job_path: 'bar', }, { text: 'foo.txt', url: 'foo', job_name: 'foo-artifact', job_path: 'foo', }, ];
mmkassem/gitlabhq
spec/frontend/vue_mr_widget/components/mock_data.js
JavaScript
mit
236
import React from 'react'; import PropTypes from 'prop-types'; import Relay from 'react-relay/classic'; import shallowCompare from 'react-addons-shallow-compare'; import AutocompleteDialog from '../../../shared/Autocomplete/Dialog'; import Button from '../../../shared/Button'; import FlashesStore from '../../../../stores/FlashesStore'; import TeamSuggestion from './team-suggestion'; import TeamPipelineCreateMutation from '../../../../mutations/TeamPipelineCreate'; class Chooser extends React.Component { static displayName = "PipelineTeamIndex.Chooser"; static propTypes = { pipeline: PropTypes.shape({ id: PropTypes.string.isRequired, slug: PropTypes.string.isRequired, organization: PropTypes.shape({ teams: PropTypes.shape({ edges: PropTypes.array.isRequired }) }) }).isRequired, relay: PropTypes.object.isRequired, onChoose: PropTypes.func.isRequired }; state = { loading: false, searching: false, removing: null, showingDialog: false }; shouldComponentUpdate(nextProps, nextState) { // Only update when a forceFetch isn't pending, and we also meet the usual // requirements to update. This avoids any re-use of old cached Team data. return !nextState.searching && shallowCompare(this, nextProps, nextState); } render() { return ( <div> <Button onClick={this.handleDialogOpen} > Add to Team </Button> <AutocompleteDialog isOpen={this.state.showingDialog} onRequestClose={this.handleDialogClose} width={400} onSearch={this.handleTeamSearch} onSelect={this.handleTeamSelect} items={this.renderAutoCompleteSuggstions(this.props.relay.variables.teamAddSearch)} placeholder="Search all teams…" selectLabel="Add" popover={false} ref={(_autoCompletor) => this._autoCompletor = _autoCompletor} /> </div> ); } renderAutoCompleteSuggstions(teamAddSearch) { const organizationTeams = this.props.pipeline.organization.teams; if (!organizationTeams || this.state.loading) { return [<AutocompleteDialog.Loader key="loading" />]; } // Filter team edges by permission to add them const relevantTeamEdges = organizationTeams.edges.filter(({ node }) => ( node.permissions.teamPipelineCreate.allowed )); // Either render the suggestions, or show a "not found" error if (relevantTeamEdges.length > 0) { return relevantTeamEdges.map(({ node }) => { return [<TeamSuggestion key={node.id} team={node} />, node]; }); } else if (teamAddSearch !== "") { return [ <AutocompleteDialog.ErrorMessage key="error"> Could not find a team with name <em>{teamAddSearch}</em> </AutocompleteDialog.ErrorMessage> ]; } return [ <AutocompleteDialog.ErrorMessage key="error"> Could not find any more teams to add </AutocompleteDialog.ErrorMessage> ]; } handleDialogOpen = () => { this.setState({ showingDialog: true }, () => { this._autoCompletor.focus(); }); }; handleDialogOpen = () => { // First switch the component into a "loading" mode and refresh the data in the chooser this.setState({ loading: true }); this.props.relay.forceFetch({ includeSearchResults: true, pipelineSelector: `!${this.props.pipeline.slug}` }, (state) => { if (state.done) { this.setState({ loading: false }); } }); // Now start showing the dialog, and when it's open, autofocus the first // result. this.setState({ showingDialog: true }, () => { this._autoCompletor.focus(); }); }; handleDialogClose = () => { this.setState({ showingDialog: false }); this._autoCompletor.clear(); this.props.relay.setVariables({ teamAddSearch: '' }); }; handleTeamSearch = (teamAddSearch) => { this.setState({ searching: true }); this.props.relay.forceFetch( { teamAddSearch }, (state) => { if (state.done) { this.setState({ searching: false }); } } ); }; handleTeamSelect = (team) => { this.setState({ showingDialog: false }); this._autoCompletor.clear(); this.props.relay.setVariables({ teamAddSearch: '' }); const mutation = new TeamPipelineCreateMutation({ team: team, pipeline: this.props.pipeline }); Relay.Store.commitUpdate(mutation, { onFailure: this.handleMutationFailure, onSuccess: this.handleMutationSuccess }); }; handleMutationSuccess = () => { this.props.onChoose(); }; handleMutationFailure = (transaction) => { FlashesStore.flash(FlashesStore.ERROR, transaction.getError()); }; } export default Relay.createContainer(Chooser, { initialVariables: { isMounted: false, includeSearchResults: false, teamAddSearch: '', pipelineSelector: null }, fragments: { pipeline: () => Relay.QL` fragment on Pipeline { ${TeamPipelineCreateMutation.getFragment('pipeline')} id slug organization { teams(search: $teamAddSearch, first: 10, order: RELEVANCE, pipeline: $pipelineSelector) @include (if: $includeSearchResults) { edges { node { id permissions { teamPipelineCreate { allowed } } ${TeamSuggestion.getFragment('team')} ${TeamPipelineCreateMutation.getFragment('team')} } } } } } ` } });
fotinakis/buildkite-frontend
app/components/pipeline/teams/Index/chooser.js
JavaScript
mit
5,687
export const MIN_PLAYERS = 6
foglerek/yn-mafia
server/config.js
JavaScript
mit
28
var chai_1 = require("chai"); var element_1 = require("../element"); describe("Class Element", function () { var testElement = new element_1.Element({ kind: "someKind", name: "someElement", elements: [{ kind: "someChild" }, { kind: "someChild" }] }); describe("element properties", function () { it("property kind", function () { chai_1.expect(testElement.kind).to.be.equal("someKind"); }); it("property name", function () { chai_1.expect(testElement.name).to.be.equal("someElement"); }); it("property elements", function () { var elements = testElement.elements; chai_1.expect(elements).length(2); elements.forEach(function (elem) { chai_1.expect(elem.kind).to.be.equal("someChild"); }); }); }); });
nitintutlani/scraper
build/test/element.spec.js
JavaScript
mit
849
/// <reference path="typings/jquery/jquery.d.ts" /> var express = require('express'), fs = require('fs'), request = require('request'), cheerio = require('cheerio'), app = express(); //Passo 1 app.get('/raspagem', function(req, res){ //passo 2 var url = 'http://www.portaldatransparencia.gov.br/PortalComprasDiretasOEOrgaoSuperior.asp?Ano=2015&Valor=86726995548647&Pagina=1'; request(url, function(error, response, html){ if(error) throw error; var $ = cheerio.load(html); //objeto que irá armazenar a tabela var resultado = []; //Passo 3 //Manipulando o selector específico para montar nossa estrutura // Escolhi não selecionar a primeira linha porque faz parte do header da tabela $("#listagem tr:not(:first-child)").each(function(i){ //obtendo as propriedades da tabela // O método .trim() garante que irá remover espaço em branco var codigo = $(this).find('td').eq(0).text().trim(), orgao = $(this).find('td').eq(1).text().trim(), valorTotal = $(this).find('td').eq(2).text().trim(); //inserindo os dados obtidos no nosso objeto resultado.push({ codigo: codigo, orgao: orgao, total: valorTotal }); }); fs.writeFile('resulta.json', JSON.stringify(resultado, null, 4), function(err){ console.log('JSON escrito com sucesso! O Arquivo está na raiz do projeto.'); }); res.send('Dados raspados com sucesso! Verifique seu node console.') }); }); app.listen('3000', function(){ console.log('Executando raspagem de dados na porta 3000...'); }); exports = module.exports = app;
phcbarros/NodeJS
webscrapper/main.js
JavaScript
mit
1,645
/*************************************************************************** * * Copyright (C) Telegraph Media Group Ltd. * All Rights Reserved. No use, copying or distribution of this work may be * made. This notice must be included on all copies, modifications and * derivatives of this work. **************************************************************************** * Author: Luke Dyson Date: 24/03/2008 * * Description: * Renders all slideshow functionality * * 11/04/2011 S Gadhiraju Used SlideShowObj to auto rotate the slideshows [DIGI-378] * 20/04/2011 S Gadhiraju Surprise! IE's setInterval implementation is different from other browsers. So used a different way of calling setInterval. * **************************************************************************** * $Id: tmglSlideShow.js,v 1.7 2009/08/13 11:06:55 dysonl Exp $ ***************************************************************************/ // Generic slideshow array to save each found slideshow var ssObj = []; // Generic slideshow object to save data for each found slideshow function SlideShowObj() { this.delay=3000; this.timeoutId=null; this.autoFunction=null; this.ssType=null; } function SlideShowObj(timeout, autoFunction) { this.delay=timeout; this.timeoutId=null; this.autoFunction=autoFunction; this.ssType=null; } function someclickReporting() { Webtrends.dcs['dcsCleanUp']; Webtrends.dcs['dcsMeta']; Webtrends.dcs['dcsMetaCustom']; } // Slideshow function to show the "next" slide function ssNext(id) { // Retrieve the currently shown slide number var indexShown = $(ssObj[id].slideshow).find(".ssImg").index($(ssObj[id].slideshow).find(".ssImg:visible").get(0)); // to refresh the ad frame on popup slideshows var nextImage = 0; // hide the currently shown slide $(ssObj[id].slideshow).find(".ssImg:eq("+indexShown+")").hide(); // If we have reached the end of the slides, start from the beginning, otherwise show the next slide (update counters if they exist) if(indexShown == $(ssObj[id].slideshow).find(".ssImg").length-1) { $(ssObj[id].slideshow).find(".ssImg:eq(0)").show(); if($(ssObj[id].slideshow).find(".tools .index").length>0) { $(ssObj[id].slideshow).find(".tools .index").html("1"); } nextImage = 0; } else { $(ssObj[id].slideshow).find(".ssImg:eq("+(indexShown+1)+")").show(); if($(ssObj[id].slideshow).find(".tools .index").length>0) { $(ssObj[id].slideshow).find(".tools .index").html((indexShown+1)+1); } nextImage = indexShown+1; } } // Slideshow function to show the "previous" slide function ssPrev(id) { // Retrieve the currently shown slide number var indexShown = $(ssObj[id].slideshow).find(".ssImg").index($(ssObj[id].slideshow).find(".ssImg:visible").get(0)); // to refresh the ad frame on popup slideshows var nextImage = 0; // hide the currently shown slide $(ssObj[id].slideshow).find(".ssImg:eq("+indexShown+")").hide(); // If we have reached the beginning of the slides, start from the end, otherwise show the previous slide (update counters if they exist) if(indexShown == 0) { $(ssObj[id].slideshow).find(".ssImg:eq("+($(ssObj[id].slideshow).find(".ssImg").length-1)+")").show(); if($(ssObj[id].slideshow).find(".tools .index").length>0) { $(ssObj[id].slideshow).find(".tools .index").html($(ssObj[id].slideshow).find(".ssImg").length); } nextImage = $(ssObj[id].slideshow).find(".ssImg").length-1; } else { $(ssObj[id].slideshow).find(".ssImg:eq("+(indexShown-1)+")").show(); if($(ssObj[id].slideshow).find(".tools .index").length>0) { $(ssObj[id].slideshow).find(".tools .index").html(indexShown); } nextImage = indexShown-1; } } // Slideshow function to so a "random" slide function randomFrame(id) { // Retrieve the currently shown slide number var indexShown = $(ssObj[id].slideshow).find(".ssImg").index($(ssObj[id].slideshow).find(".ssImg:visible").get(0)); // Choose a random slide number var randomFrameNo=Math.floor(Math.random() * $(ssObj[id].slideshow).find(".ssImg").length); // prevent showing the same frame twice in a row, otherwise show the current slide and show the randomly selected slide if(indexShown==randomFrameNo) { randomFrame(); } else { $(ssObj[id].slideshow).find(".ssImg:eq("+indexShown+")").hide(); $(ssObj[id].slideshow).find(".ssImg:eq("+randomFrameNo+")").show(); } } // Initialise all slideshows on this page function initSS() { // Get all the slideshows on the page var slideshow = $(".slideshow").get(); // For every slideshow found... for(i in slideshow) { var slideshowRotationSpeedID = $(slideshow[i]).parent().attr("id") + 'rotationSpeed'; var slideshowRotationSpeed = $("#" + slideshowRotationSpeedID).text(); var autoFunction = "nextFrame"; if( slideshowRotationSpeed == null || slideshowRotationSpeed =="" || slideshowRotationSpeed == 0) { slideshowRotationSpeed = null; autoFunction = null; } // Generate a new slideshow object for this slideshow // ssObj[i] = new SlideShowObj(); ssObj[i] = new SlideShowObj(slideshowRotationSpeed, autoFunction); // Save the slideshow for ready access ssObj[i].slideshow = slideshow[i]; // added to make sure we are dealing with a dom object and not a function if (typeof(slideshow[i]) != 'object') continue; /* Retrieve setup data from the DOM */ /* Get the functional elements from the first comment found in the rotating element, then split it. */ var ssSetup = $(ssObj[i].slideshow).comments(0) != null?$(ssObj[i].slideshow).comments(0).split(","):null; if (ssSetup != null) { // Get the time delay (if this is set), and save it to this slideshows' object (Generally only used if there is a function also set) if(ssSetup[0] != null && ssSetup[0] != ""){ ssObj[i].delay = ssSetup[0]; } // Get the function required (if this is set), and save it to this slideshows' object if(ssSetup[1] != null && ssSetup[1] != ""){ ssObj[i].autoFunction = ssSetup[1]; } } // Define the type of this slideshow if ($(ssObj[i].slideshow).is(".epic")==true) { ssObj[i].ssType = "epic"; } else { ssObj[i].ssType = "image"; } // Setup the slides ready for viewing (Remove "fail gracefully" classes and reset their states) $(ssObj[i].slideshow).find(".ssImg").removeClass("hide").hide(); $(ssObj[i].slideshow).find(".ssImg:first").removeClass("show").show(); // Find the previous button (if it exists) and bind a click event function to it... if($(ssObj[i].slideshow).find(".tools .prev, .tools .prevNoFade").get(0)!=undefined){ $(ssObj[i].slideshow).find(".tools .prev, .tools .prevNoFade").bind("click",{count:i},function(e){ // If this slideshow is currently automated, stop the automation if (ssObj[e.data.count].timeoutId!=null){ clearInterval(ssObj[e.data.count].timeoutId); ssObj[e.data.count].timeoutId=null; } // Fire off the call to show the previous slide for this slideshow ssPrev(e.data.count); // Click reporting // dcsCleanup(); // dcsMeta(); // dcsMetaCustom(); someclickReporting(); // Click report based on slideshow type if (ssObj[e.data.count].ssType == "image") { // Added WT.dl = 53 parameter to flag that page is not a reload. See DIGI-1114 dcsMultiTrack('DCSext.embeddedSlideshowImage',$(ssObj[e.data.count].slideshow).find("> .ssImg:visible > img").attr("src"),"WT.dl","53"); trackGoogle(); } else if (ssObj[e.data.count].ssType == "epic") { dcsMultiTrack('DCSext.epicSlideshow',$(ssObj[e.data.count].slideshow).find("> .ssImg:visible > iframe").attr("src").substring($(ssObj[e.data.count].slideshow).find("> .ssImg:visible > iframe").attr("src").indexOf("=")+1,$(ssObj[e.data.count].slideshow).find("> .ssImg:visible > iframe").attr("src").length)); trackGoogle(); } }); } // Find the next button (if it exists) and bind a click event function to it... if($(ssObj[i].slideshow).find(".tools .next, .tools .nextNoFade").get(0)!=undefined){ $(ssObj[i].slideshow).find(".tools .next, .tools .nextNoFade").bind("click",{count:i},function(e){ // If this slideshow is currently automated, stop the automation if (ssObj[e.data.count].timeoutId!=null){ clearInterval(ssObj[e.data.count].timeoutId); ssObj[e.data.count].timeoutId=null; } // Fire off the call to show the next slide for this slideshow ssNext(e.data.count); // Click reporting // dcsCleanup(); // dcsMeta(); // dcsMetaCustom(); someclickReporting(); // Click report based on slideshow type if (ssObj[e.data.count].ssType == "image") { // Added WT.dl = 53 parameter to flag that page is not a reload. See DIGI-1114 dcsMultiTrack('DCSext.embeddedSlideshowImage',$(ssObj[e.data.count].slideshow).find("> .ssImg:visible > img").attr("src"),"WT.dl","53"); trackGoogle(); } else if (ssObj[e.data.count].ssType == "epic") { dcsMultiTrack('DCSext.epicSlideshow',$(ssObj[e.data.count].slideshow).find("> .ssImg:visible > iframe").attr("src").substring($(ssObj[e.data.count].slideshow).find("> .ssImg:visible > iframe").attr("src").indexOf("=")+1,$(ssObj[e.data.count].slideshow).find("> .ssImg:visible > iframe").attr("src").length)); trackGoogle(); } }); } // if this slideshow shows the current slide count and a total slide count, initialise them if($(ssObj[i].slideshow).find(".index").length>0 && $(ssObj[i].slideshow).find(".total").length>0) { $(ssObj[i].slideshow).find(".index").html("1"); $(ssObj[i].slideshow).find(".total").html($(ssObj[i].slideshow).find(".ssImg").length); } // The nav area is now ready to show. $(ssObj[i].slideshow).find(".tools").removeClass("hide").show(); // from this slideshows object, decide if it is to be automated using the standard slideshow functions if(ssObj[i].autoFunction == "randomFrame"){ ssObj[i].timeoutId = setInterval('randomFrame('+i+')',Number(ssObj[i].delay)); }else if(ssObj[i].autoFunction == "nextFrame"){ ssObj[i].timeoutId = setInterval('ssNext('+i+')',Number(ssObj[i].delay)); }else if(ssObj[i].autoFunction == "prevFrame"){ ssObj[i].timeoutId = setInterval('ssPrev('+i+')',Number(ssObj[i].delay)); } } } $(function() { initSS(); });
balamurugan01/foundation6
node_modules/parker/problem sites/telegraph.co.uk/The Telegraph - Telegraph online, Daily Telegraph, Sunday Telegraph - Telegraph_files/tmglSlideShow.js
JavaScript
mit
10,214
export default function userReducer(state = [], action) { switch (action.type) { case 'GET_USERS': return [ ...action.users ]; default: return state; } }
Tierica9002/bamboilero
src/reducers/userReducer.js
JavaScript
mit
229
export {default as setEnv} from './setEnv'; export {default as watch} from './watch'; export {default as reactHotServer} from './reactHotServer'; export {default as babelLoader} from './babelLoader'; export {default as cssLoader} from './cssLoader'; export {default as stylusLoader} from './stylusLoader'; export {default as pugLoader} from './pugLoader'; export {default as imageLoader} from './imageLoader'; export {default as fontLoader} from './fontLoader';
fugr-ru/webpack-custom-blocks
src/index.js
JavaScript
mit
463
import Head from 'next/head' export default () => ( <div> <Head> <title>Dashboard tilskudd</title> <meta name='viewport' content='initial-scale=1.0, width=device-width' /> <link rel='icon' sizes='192x192' href='static/images/icons/chrome-touch-icon-192x192.png' /> <link rel='apple-touch-icon' href='static/images/icons/apple-touch-icon-precomposed.png' /> <link rel='shortcut icon' href='static/images/icons/favicon.ico' /> </Head> </div> )
telemark/tilskudd-dashboard
components/head.js
JavaScript
mit
485
 var _ = require('lodash'); var gulp = require('gulp-help')(require('gulp')); var path = require('path'); var nunit = require('gulp-nunit-runner'); var config = require('./../config'); var _description = 'Runs all e2e tests.'; function _task() { return gulp.src(_.map(config.pattern.tests.e2e, _mapPatternsToPaths), { read: false }).pipe(nunit({ // Specify the path to the runner executable. executable: config.files.exe.nunit, // Specify the path where the tests should run from. basepath: config.directory.bin.e2e, options: { // Specify a unique file name for the results so multiple test // types can be ran in parallel. result: 'TestResult.E2E.xml' } })); // Takes a pattern for a file name and joins it with a path. function _mapPatternsToPaths(pattern) { return path.join(config.directory.bin.e2e, pattern); } } gulp.task('e2e-tests-development', _description, ['build-development'], _task); gulp.task('e2e-tests-development-isolated', _description, [], _task);
JaredMathis/VagueBook
Build/tasks/e2e-tests-development.js
JavaScript
mit
1,256
module.exports = notFound function notFound() { this.res.writeHead(404, { 'Content-Type': 'application/json' }) this.res.end(JSON.stringify({ error: 'notFound', reason: 'Document not found.' })) }
hayes/unpm
lib/respond/404.js
JavaScript
mit
219
import _ from 'underscore'; import { getFirstCharacterCapitalized } from '~/lib/utils/text_utility'; export const DEFAULT_SIZE_CLASS = 's40'; export const IDENTICON_BG_COUNT = 7; export function getIdenticonBackgroundClass(entityId) { const type = (entityId % IDENTICON_BG_COUNT) + 1; return `bg${type}`; } export function getIdenticonTitle(entityName) { return getFirstCharacterCapitalized(entityName) || ' '; } export function renderIdenticon(entity, options = {}) { const { sizeClass = DEFAULT_SIZE_CLASS } = options; const bgClass = getIdenticonBackgroundClass(entity.id); const title = getIdenticonTitle(entity.name); return `<div class="avatar identicon ${_.escape(sizeClass)} ${_.escape(bgClass)}">${_.escape(title)}</div>`; } export function renderAvatar(entity, options = {}) { if (!entity.avatar_url) { return renderIdenticon(entity, options); } const { sizeClass = DEFAULT_SIZE_CLASS } = options; return `<img src="${_.escape(entity.avatar_url)}" class="avatar ${_.escape(sizeClass)}" />`; }
jirutka/gitlabhq
app/assets/javascripts/helpers/avatar_helper.js
JavaScript
mit
1,038
'use strict'; var voxel = require('voxel') , createGame = require('voxel-engine') , voxelPlayer = require('voxel-player') var game = createGame({ generate: voxel.generator['Valley'] , chunkDistance: 2 , materials: ['#fff', '#000'] , materialFlatColor: true , worldOrigin: [0, 0, 0] , controls: { discreteFire: true } }) game.appendTo('#game') var createPlayer = voxelPlayer(game) , player = createPlayer('player.png') player.possess() player.position.set(0, 0, 4) window.addEventListener('keydown', function(e) { if (e.keyCode === 'R'.charCodeAt(0)) { player.toggle() } // force exit pointer lock for node-webkit if (e.keyCode === 27) { document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock document.exitPointerLock() } })
romainberger/voxel-app
src/index.js
JavaScript
mit
870
// Regular expression that matches all symbols in the `Javanese` script as per Unicode v6.0.0: /[\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE\uA9DF]/;
mathiasbynens/unicode-data
6.0.0/scripts/Javanese-regex.js
JavaScript
mit
138
Dragon.module(['dragon/components', 'dragon/classlist', 'dragon/dom', 'dragon/event', 'dragon/components/menu', 'dragon/components/menuitem', 'dragon/components/externallogin.html'], function (WC, Class, Dom, Event, Menu, MenuItem, doc) { function createMenuItem(ctrl, menu, type, select, icon) { var menuItem = document.createElement('li'); Class.add(menuItem, 'ctrl-icon', 'icon-' + icon); menuItem._authority_type = type; menu.appendChild(menuItem); if (select) setSelected(menuItem, ctrl); } function setSelected(item, control) { control.ctrl.auth = control.ctrl.authority[item._authority_type]; Class.add(control.ctrl.selected, 'icon-' + control.ctrl.auth.icon); var auth = control.ctrl.auth; // determine user status if (window[auth.namespace]) { auth.getStatus(); } else { var asyncLoad = !auth.syncInit; // set global space init function to be called once script is loaded window[auth.asyncInit] = function () { auth.init(Dragon.config.basePath + 'dragon/components/redirect.html?'); if (asyncLoad) auth.getStatus(); }; Dragon.loadScript(auth.script, asyncLoad).then(function () { if (!asyncLoad) auth.asyncInit(); }); } } function login(evt) { var arrow = Class.contains(evt.target, 'icon-arrow-down') ? evt.target : null, control = Dom.shadowHost(evt.target), auth; if (!arrow) arrow = Dom.parent(evt.target, 'icon-arrow-down'); if (arrow) { Class.toggle(control.ctrl.menu, 'toggle'); Class.toggle(control.ctrl.inner, 'toggle'); Event.cancel(evt); return; } if (control.ctrl.menu.contains(evt.target)) { var item = evt.target; if (item.tagName.toLowerCase() != 'li') item = Dom.parent(evt.target, 'li'); if (item) setSelected(item, control); } auth = control.ctrl.auth; // in case user is logged in, gather info if not execute login if (auth.isAuthenticated) { setUserInfo(auth, control); } else { auth.login().then(function () { auth.isAuthenticated = true; setUserInfo(auth, control); }, function (error) { throwError(error, control); }); } } function setUserInfo(auth, control) { auth.getUserInfo().then(function (user) { auth.user = user || {}; auth.user.auth = auth.name; Event.raise(control, 'login_success', auth.user); }, function (error) { throwError(error, control); }); } function throwError(error, control) { Event.raise(control, 'login_error', error); } return WC.register('ctrl-externallogin', { template: doc.querySelector('template'), lifecycle: { created: function () { this.ctrl.authority = { facebook: { name: 'facebook', icon: 'facebook', namespace: 'FB', asyncInit: 'fbAsyncInit', script: '//connect.facebook.net/en_US/all.js', init: function (redirectUrl) { FB.init({ appId: this.id, channelUrl: redirectUrl + this.namespace, status: false }); }, getStatus: function () { var that = this; FB.getLoginStatus(function (response) { that.isAuthenticated = (response.status === 'connected'); }, true); }, getUserInfo: function () { return new Promise(function (resolve, reject) { FB.api('/me', function (response) { if (response.error) { reject(response.error); } else { resolve(response); } }); }); }, getUserProfile: function () { }, login: function () { return new Promise(function (resolve, reject) { FB.login(function (response) { if (response.status === 'connected') { resolve(response); } else { reject(response.status); } }); }); } }, google: { name: 'google', icon: 'googleplus', namespace: 'gapi', asyncInit: 'getGoogleStatus', scope: 'https://www.googleapis.com/auth/plus.me', script: 'https://apis.google.com/js/client.js?onload=getGoogleStatus', init: function () { }, getStatus: function () { var that = this; gapi.auth.authorize({ client_id: that.id, immediate: true, scope: that.scope }, function (token) { that.isAuthenticated = !!token; }); }, getUserInfo: function () { return new Promise(function (resolve, reject) { gapi.client.load('oauth2', 'v2', function () { gapi.client.oauth2.userinfo.get().execute(function (user) { resolve(user); }) // NOTE: how to catch exceptions here ?! }); }); }, getUserProfile: function () { }, login: function () { return new Promise(function (resolve, reject) { gapi.auth.authorize({ client_id: this.id, immediate: false, scope: this.scope }, function (token) { if (token) { resolve(token); } else { reject(token); } }); }); } }, windows: { name: 'windows', icon: 'windows8', namespace: 'WL', asyncInit: 'wlAsyncInit', scope: 'wl.signin', script: '//js.live.net/v5.0/wl.js', init: function (redirectUrl) { WL.init({ client_id: this.id, scope: this.scope, status: false, redirect_uri: redirectUrl + this.namespace }); }, getStatus: function () { var that = this; WL.getLoginStatus(function (response) { that.isAuthenticated = (response.status === 'connected'); }, true); }, getUserInfo: function () { return WL.api({ path: 'me' }); }, getUserProfile: function () { }, login: function () { return WL.login({ scope: this.scope }); } }, linkedin: { name: 'linkedin', icon: 'linkedin', namespace: 'IN', asyncInit: 'inAsyncInit', syncInit: 'inSyncInit', //scope: '"r_basicprofile', script: '//platform.linkedin.com/in.js?async=true', init: function () { var that = this window[this.syncInit] = function () { that.getStatus(); } IN.init({ api_key: this.id, onLoad: this.syncInit, authorize: true }); }, getStatus: function () { this.isAuthenticated = IN.User.isAuthorized(); }, getUserInfo: function () { return new Promise(function (resolve, reject) { IN.API.Profile('me').result(function (user) { resolve(user.values[0]); }).error(function (error) { reject(error); }); }); }, getUserProfile: function () { }, login: function () { return new Promise(function (resolve, reject) { // NOTE: LinkedIn API doesn't have a way to notify for cancel/error from login popup! IN.User.authorize(function () { resolve(); }); }); } } }; this.ctrl.menu = this.shadowRoot.querySelector('ul'); this.ctrl.selected = this.shadowRoot.querySelector('.ctrl-icon'); this.ctrl.inner = this.shadowRoot.querySelector('.ctrl-inner'); this.ctrl.text = this.shadowRoot.querySelector('.ctrl-text'); Event.add(this.shadowRoot.querySelector('.ctrl-inner'), 'click', login); if (!this.getAttribute('authority')) this.style.display = 'none'; } }, text: { attribute: {}, set: function (value) { this.ctrl.text.innerHTML = value; } }, authority: { attribute: {}, set: function () { var authorities = Dragon.getOptions(this.authority); Dom.empty(this.ctrl.menu); var keys = Object.keys(authorities); if (keys.length > 1) { this.appendChild(Dom.create('span', 'ctrl-icon icon-arrow-down')); } else if (keys.length > 0) Class.add(this, 'single'); else this.style.display = 'none'; for (var i = 0, count = keys.length; i < count; i++) { var key = keys[i]; if (!authorities.hasOwnProperty(key)) continue; this.authority[key] = authorities[key]; this.ctrl.authority[key].id = authorities[key]; createMenuItem(this, this.ctrl.menu, key, i == 0, this.ctrl.authority[key].icon); } if (keys.length == 1) setSelected(this.ctrl.menu.querySelector('.ctrl-menuitem,ctrl-menuitem'), this); } } }); }); //TODO when FB fix their js try login ad put correct riderct url and redirect.html must be included into project!!!!!!!!!
DimDragon/jschema
JSchema/scripts/dragon/components/externallogin.js
JavaScript
mit
8,577
/** * Replaces string interpolation with template strings. * * @example * * "a#{b}c" -> `a${b}c` * * @param {Object} node * @param {MagicString} patcher */ export default function patchStringInterpolation(node, patcher) { if (node.type === 'ConcatOp') { if (node.parentNode.type !== 'ConcatOp') { let cutLength = (node.raw.slice(0,3)=='"""') ? 3 : 1; patcher.overwrite(node.range[0], node.range[0] + cutLength, '`'); patcher.overwrite(node.range[1] - cutLength, node.range[1], '`'); } patchInterpolation(node.left, patcher); patchInterpolation(node.right, patcher); } } /** * Patches the interpolation surrounding a node, if it is an interpolated value. * * @param {Object} node * @param {MagicString} patcher * @private */ function patchInterpolation(node, patcher) { switch (node.type) { case 'String': case 'ConcatOp': return; } const interpolationStart = findInterpolationStart(node, patcher.original); if (interpolationStart < 0) { throw new Error( 'unable to find interpolation start, i.e. "#{", before ' + node.type + ' at line ' + node.line + ', column ' + node.column ); } patcher.overwrite(interpolationStart, interpolationStart + 1, '$'); } /** * Find the start of the interpolation that contains an expression. * * @param {Object} expression * @param {string} source * @returns {number} * @private */ function findInterpolationStart(expression, source) { var index = expression.range[0] - 2; while (index >= 0) { if (source.slice(index, index + '#{'.length) === '#{') { break; } index--; } return index; }
edi9999/decaffeinate
src/patchers/patchStringInterpolation.js
JavaScript
mit
1,662
var api = require('./api'); var pollHandler = require('./pollHandler'); module.exports = { legionStuff: function legionStuff(message) { var content = message.content.toLowerCase() if (content === '!hello') { message.channel.sendMessage('Hello there!'); } else if (content === '!git') { message.channel.sendMessage('https://github.com/LooMan/marvin'); } else if (content === '!saywaat') { message.channel.sendMessage('https://www.youtube.com/watch?v=yqyixwqiCag'); } else if (content === '!morning') { message.channel.sendMessage('Good morning to you sir!'); } else if (content === '!tableflip') { message.channel.sendMessage('(╯°□°)╯︵ ┻━┻'); } else if (content === '!daniel') { danielThings(message); } else if (content === '!tim') { message.channel.sendMessage('Doing a Tim is planning an whole evening/day to play mythic+ or likewise and then cancel you last minute because you cant play'); } else if (content === '!yeel') { message.channel.sendMessage('Doing a Yeel is pulling like 200 mil dps on everything without <:bis:252403348580466688> legs'); } else if (content === '!help') { message.channel.sendMessage('```css\n' + '| Command | Description\n----------------------------------------------------------\n| !members | Returns number of members in Venture\n| !daniel | Explains what doing a Daniel is\n| !tim | Explains what doing a Tim is\n| !yeel | Explains what doing a Yeel is\n| !gif search | Returns a random gif from giphy\n| !ilvl name | Returns ilvl of name on Frostmane\n| !ilvl name server | Returns ilvl of name on server\n| !affix | M+ affixes starting with current week\n| !poll | Creates a poll. Example: \n| | !poll Fråga?svar1/svar2' + '```'); } else if ( content.includes('!poll') ) { pollHandler.createPoll(message); } else if ( content.includes('!note') ) { pollHandler.createNote(message); } else if (content.includes('penis') || content.includes('snopp') || content.includes('kuk') || content.includes('penis') || content.includes('dick')) { console.log(message.author); //for debug if (message.author.id == '214443010820145153') { //bc var bcStrings = ['Stop beeing so immature Simon...', 'Sigh...this guy', 'Language mister!', 'Oh here I though you were older than 5...'] var rand = Math.floor(Math.random() * (bcStrings.length - 1)); message.channel.sendMessage(bcStrings[rand]) } else { message.channel.sendMessage('hihi :eggplant:'); } } else if (content.includes('cos')) { if (message.author.id != '149853728743227392') { //daniel is a buzzkill cosQuotes(message); } } if (content.includes("marvin") || (content.includes("marv"))) { marvinQuotes(message); } } } function marvinQuotes(message) { var rand = Math.floor(Math.random() * 6) + 1; if (rand == 1) { message.channel.sendMessage("I think you ought to know I’m feeling very depressed."); } else if (rand == 2) { message.channel.sendMessage("It won’t work, I have an exceptionally large mind."); } else if (rand == 3) { message.channel.sendMessage("I am at a rough estimate thirty billion times more intelligent than you."); } else if (rand == 4) { message.channel.sendMessage("Ghastly, isn’t it?"); } else if (rand == 5) { message.channel.sendMessage("I have a million ideas. They all point to certain death."); } else if (rand == 6) { message.channel.sendMessage("Funny,"); message.channel.sendMessage("How just when you think life can’t possibly get any worse it suddenly does."); } } function cosQuotes(message) { var cosQuotes = ['Thats gonna COSt ya! :wink:', 'Oh Court of Stars i love that place!', 'Well if we are going to conquer earth we might aswell start with CoS']; var rand = Math.floor(Math.random() * (cosQuotes.length - 1)); message.channel.sendMessage(cosQuotes[rand]); } function danielThings(message) { var danielHappenings = ['Doing a Daniel can be that you are playing healer in 3v3 arena and start to use solarwrath instead of healing your teamate who is dying', 'Doing a Daniel can be that you are playing Arcway on the spider boss and instead of running away from your target you are running to them, but then when u understand the strat u start running away from them so far that u are running out of the bossroom and reset the boss', 'Doing a Daniel can be that you have the "AFK Girian" text when u enter a bg and you think that writing /afk is a good idea to get it removed', 'Doing a Daniel can be that you just dinged lvl 110 and started doing dungs with your palls and suddenly you have better gear than them..']; var rand = Math.floor(Math.random() * (danielHappenings.length - 1)); message.channel.sendMessage(danielHappenings[rand]); }
LooMan/marvin
app/legionHandler.js
JavaScript
mit
5,356
import "../../../svg/emoji/vomiting.svg"; import "../../../svg/emoji/smirking.svg"; import "../../../svg/emoji/surprised.svg"; import "../../../svg/emoji/unamused.svg"; import "../../../svg/emoji/zombie.svg"; import "../../../svg/emoji/tired.svg"; import "../../../svg/emoji/tongue.svg"; import "../../../svg/emoji/wink.svg";
wuhanchu/antd-admin
src/modules/UIElement/iconfont/emoji.js
JavaScript
mit
326
/* @flow */ import type { UserInfo } from '../interfaces/admin' import { post } from 'jquery' // Action type // ------------------------------------ export const REQUEST_USERS = 'REQUEST_USERS' export const RECIEVE_USERS = 'RECIEVE_USERS' export const REQUEST_USER_PW_CH = 'REQUEST_USER_PW_CH' export const RECIEVE_USER_PW_CH = 'RECIEVE_USER_PW_CH' const initialState = { waiting : false, received : false, success : false } export function createReqUsersAction() : Action { return { type: REQUEST_USERS } } export function createRecvUsersAction(users : Array<UserInfo>) : Action { return { type: RECIEVE_USERS, users } } export function createReqChangeUserAction() : Action { return { type: REQUEST_USER_PW_CH } } export function createRecvChUsersAction() : Action { return { type: RECIEVE_USER_PW_CH } } export function requestUsers(payload) { return (dispatch: Function): Promise => { dispatch(createReqUsersAction()) return post('http://localhost:3001/graphql',{ query: `{ users{ _id, name, email } }` }).done(resp => { dispatch(createRecvUsersAction(resp.data.users)) }) } } export function requestChUsers(payload) { return (dispatch: Function): Promise => { dispatch(createReqUsersAction()) console.log(payload); let query = "mutation {"+ "updateUser(email: \""+payload.email+"\", password: \""+payload.password+"\") {"+ "email,"+ "name"+ "}"+ "}" console.log("query : "+query); return post('http://localhost:3001/graphql',{ query:query }).done(resp => { dispatch(createRecvChUsersAction()) }) } } /** * Action Handlers */ const ACTION_HANDLERS = { [REQUEST_USERS]: (state) => { return ({ ...state, waiting: true }) }, [RECIEVE_USERS]: (state, action) => { return ({ ...state, users: action.users, waiting:false }) }, [REQUEST_USER_PW_CH]: (state) => { return ({ ...state, initialState }) }, [RECIEVE_USER_PW_CH]: (state, action) => { return ({ ...state, waiting: false , success: action.success, received: true }) }, } /** * Reducers */ export default function reducer (state = initialState, action: Action) { const handler = ACTION_HANDLERS[action.type] return handler ? handler(state, action) : state }
parkgaram/solidware-mini-project
src/routes/Admin/modules/admin.js
JavaScript
mit
2,423
'use strict'; /** * Module dependencies */ var pagesPolicy = require('../policies/pages.server.policy'), pages = require('../controllers/pages.server.controller'); module.exports = function (app) { // pages collection routes app.route('/api/pages').all(pagesPolicy.isAllowed) .get(pages.list) .post(pages.create); // Single article routes app.route('/api/pages/:pageUrl').all(pagesPolicy.isAllowed) .get(pages.read) .put(pages.update) .delete(pages.delete); // Finish by binding the article middleware // app.param('pageId', pages.pageByID); app.param('pageUrl', pages.pageByUrl); };
rastemoh/mean
modules/pages/server/routes/pages.server.routes.js
JavaScript
mit
626
// templates / tplSimpleLayout export let tplSimpleLayout = ` <div class="pps__swiper-wrapper pps__swiper-wrapper-simple"> <div class="pps__swiper--nav pps__swiper--prev"> <span class="pps__btn-link prev"></span> </div> <div class="pps__swiper-container pps__swiper-container-simple">{{content}}</div> <div class="pps__swiper--nav pps__swiper--next"> <span class="pps__btn-link next"></span> </div> </div> `;
greenglobal/ppsloop
src/widget/templates/tplSimpleLayout.js
JavaScript
mit
447
'use strict'; var _ = require('underscore'); var gulp = require('gulp'); var jscs = require('gulp-jscs'); var plumber = require('gulp-plumber'); var assets = require('../assets'); module.exports = function() { var js = _.union(assets.clientJs, assets.serverJs); return gulp.src(js) .pipe(plumber({ errorHandler: require('../error.beep') })) .pipe(jscs({ preset: 'airbnb' })); }
tgolen/k2
gulp/tasks/codestyle.js
JavaScript
mit
412
var clinicaMed = angular.module('clinicaMed'); clinicaMed.controller('medicamentoListagemController', ['$scope', '$state', 'constants', 'medicamentoListagemService', function ($scope, $state, constants, medicamentoListagemService) { $scope.pesquisar = function () { if ($scope.filtro) { medicamentoListagemService.fetchAll($scope.filtro); $scope.pesquisaRealizada = true; } }; $scope.limparPesquisa = function () { $scope.filtro = ''; medicamentoListagemService.fetchAll($scope.filtro); $scope.pesquisaRealizada = false; }; $scope.editarMedicamento = function (id) { $state.go('medicamento.edicao', {id: id}); }; $scope.excluirMedicamento = function (id) { $scope.idMedicamento = id; }; $scope.confirmarExcluirMedicamento = function () { medicamentoListagemService.deleteMedicamento($scope.idMedicamento); }; $scope.$on('MEDICAMENTOS_FETCHED_SUCCESS', function (e, data) { $scope.medicamentos = data; }); $scope.$on('MEDICAMENTO_DELETE_SUCCESS', function () { medicamentoListagemService.fetchAll(); operacaoSucesso(); }); function operacaoSucesso() { $scope.mostrarAlertaSucesso = true; } function inicializarDadosTabelaListagem() { $scope.paginaAtual = 1; $scope.colunas = [ { caminhoNoObjeto: 'nomeGenerico', classeCol: 'col-md-3', nome: 'Nome Genérico' }, { caminhoNoObjeto: 'nomeFabrica', classeCol: 'col-md-4', nome: 'Nome Fábrica' }, { caminhoNoObjeto: 'fabricante', classeCol: 'col-md-3', nome: 'Fabricante' } ]; } function initizialize() { inicializarDadosTabelaListagem(); $scope.filtro = ''; medicamentoListagemService.fetchAll($scope.filtro); } initizialize(); }] );
douglasouza/clinicaMed
src/main/resources/static/app/components/medicamento/listagem/controller.js
JavaScript
mit
2,291
// Karma configuration // Generated on Sat Aug 26 2017 22:51:57 GMT+0530 (Sri Lanka Standard Time) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'tests/*.test.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) }
99xt/interns-portal
karma.conf.js
JavaScript
mit
1,698
export const ADD_CHARACTER = 'ADD_CHARACTER'; export const REMOVE_CHARACTER = 'REMOVE_CHARACTER'; export function addCharacterById(id) { const action = { type: ADD_CHARACTER, id } return action; }; export function removeCharacterById(id) { const action = { type: REMOVE_CHARACTER, id } return action; };
thiendang/React-JS---Mastering-Redux
src-SuperSquad/actions/index.js
JavaScript
mit
334
var isNullOrUndefined = require("is_null_or_undefined"), JSONAsset = require("./JSONAsset"), Shader = require("./Shader"), enums = require("../enums"); var JSONAssetPrototype = JSONAsset.prototype, MaterialPrototype; module.exports = Material; function Material() { JSONAsset.call(this); this.shader = null; this.side = null; this.blending = null; this.wireframe = null; this.wireframeLineWidth = null; this.receiveShadow = null; this.castShadow = null; this.uniforms = null; } JSONAsset.extend(Material, "odin.Material"); MaterialPrototype = Material.prototype; MaterialPrototype.construct = function(options) { JSONAssetPrototype.construct.call(this, options); options = options || {}; if (options.shader) { this.shader = options.shader; } else { if (options.vertex && options.fragment) { this.shader = Shader.create(options.vertex, options.fragment); } } this.uniforms = options.uniforms || {}; this.side = isNullOrUndefined(options.side) ? enums.side.FRONT : options.side; this.blending = isNullOrUndefined(options.blending) ? enums.blending.DEFAULT : options.blending; this.wireframe = isNullOrUndefined(options.wireframe) ? false : !!options.wireframe; this.wireframeLineWidth = isNullOrUndefined(options.wireframeLineWidth) ? 1 : options.wireframeLineWidth; this.receiveShadow = isNullOrUndefined(options.receiveShadow) ? true : !!options.receiveShadow; this.castShadow = isNullOrUndefined(options.castShadow) ? true : !!options.castShadow; return this; }; MaterialPrototype.destructor = function() { JSONAssetPrototype.destructor.call(this); this.side = null; this.blending = null; this.wireframe = null; this.wireframeLineWidth = null; this.receiveShadow = null; this.castShadow = null; this.uniforms = null; return this; }; MaterialPrototype.parse = function() { JSONAssetPrototype.parse.call(this); return this; };
nathanfaucett/odin
src/Assets/Material.js
JavaScript
mit
2,039
/** * These are all of the global variables used during accretion: */ var anum; var stellar_luminosity_ratio; var mainSeqLife; var age, r_ecosphere; var r_greenhouse; // var randomTool; function System(seed){ seed = seed || 100; randomTool = new MersenneTwister(seed); } System.prototype = Object.create({ distributePlanets: function(stellarMass) { var astro = new Astro(); var accrete = new Accrete(); var planet = {}; var planets = []; this.stellarMassRatio = stellarMass || utils.randomNumber(0.6, 1.3); stellar_luminosity_ratio = astro.luminosity(this.stellarMassRatio); planet = accrete.distributePlanetaryMasses(this.stellarMassRatio, stellar_luminosity_ratio, 0.0, accrete.stellarDustLimit(this.stellarMassRatio)); mainSeqLife = 1.0E10 * (this.stellarMassRatio / stellar_luminosity_ratio); if ((mainSeqLife >= 6.0E9)) { age = utils.randomNumber(1.0E9, 6.0E9); } else { age = utils.randomNumber(1.0E9, mainSeqLife); } r_ecosphere = Math.sqrt(stellar_luminosity_ratio); var r_greenhouse = r_ecosphere * GREENHOUSE_EFFECT_CONST; while (planet !== NULL) { planet.orbit_zone = astro.orbitalZone(planet.a); if (planet.gasGiant) { planet.density = astro.empiricalDensity(planet.mass, planet.a, planet.gasGiant); planet.radius = astro.volumeRadius(planet.mass, planet.density); } else { planet.radius = astro.kothariRadius(planet.mass, planet.a, planet.gasGiant, planet.orbit_zone); planet.density = astro.volumeDensity(planet.mass, planet.radius); } planet.orbital_period = astro.period(planet.a, planet.mass, this.stellarMassRatio); planet.day = astro.dayLength(planet.mass, planet.radius, planet.orbital_period, planet.e, planet.gasGiant); planet.resonant_period = spin_resonance; planet.axial_tilt = astro.inclination(planet.a); planet.escape_velocity = astro.escapeVel(planet.mass, planet.radius); planet.surface_accel = astro.acceleration(planet.mass, planet.radius); planet.rms_velocity = astro.rmsVel(MOLECULAR_NITROGEN, planet.a); planet.molecule_weight = astro.moleculeLimit(planet.a, planet.mass, planet.radius); if ((planet.gasGiant)) { planet.surface_grav = INCREDIBLY_LARGE_NUMBER; planet.greenhouse_effect = FALSE; planet.volatile_gas_inventory = INCREDIBLY_LARGE_NUMBER; planet.surface_pressure = INCREDIBLY_LARGE_NUMBER; planet.boil_point = INCREDIBLY_LARGE_NUMBER; planet.hydrosphere = INCREDIBLY_LARGE_NUMBER; planet.albedo = utils.about(GAS_GIANT_ALBEDO, 0.1); planet.surface_temp = INCREDIBLY_LARGE_NUMBER; } else { planet.surface_grav = astro.gravity(planet.surface_accel); planet.greenhouse_effect = astro.greenhouse(planet.orbit_zone, planet.a, r_greenhouse); planet.volatile_gas_inventory = astro.volInventory(planet.mass, planet.escape_velocity, planet.rms_velocity, this.stellarMassRatio, planet.orbit_zone, planet.greenhouse_effect); planet.surface_pressure = astro.pressure(planet.volatile_gas_inventory, planet.radius, planet.surface_grav); if ((planet.surface_pressure === 0)) { planet.boil_point = 0; } else { planet.boil_point = astro.boilingPoint(planet.surface_pressure); } astro.iterateSurfaceTemp(planet); } planets.push(planet); planet = planet.next_planet; } return this.systemToJSON(planets); }, systemToJSON: function(planets) { var jsonOut = { 'star' : { 'mass' : this.stellarMassRatio, 'luminosity' : stellar_luminosity_ratio, 'mainSequenceLifetime' : (mainSeqLife / 1.0E6), 'currentAge' : (age / 1.0E6), 'ecospherRadius' : r_ecosphere }, 'planets' : [] }; jsonOut.planets = planets.map(function(planet, counter) { return { 'number' : counter + 1, 'gasGiant' : planet.gasGiant, 'resonantPeriod' : planet.resonant_period, 'distanceFromPrimaryStar' : planet.a, 'eccentricity' : planet.e, 'mass' : planet.mass * EARTH_MASSES_PER_SOLAR_MASS, 'equatorialRadius' : planet.radius, 'density' : planet.density, 'escapeVelocity' : planet.escape_velocity / CM_PER_KM, 'smallestMolecularWeight' : getSmallestMolecularWeight(planet.molecule_weight), 'surfaceAcceleration' : planet.surface_accel, 'surfaceGravity' : planet.surface_grav, 'boilingPointOfWater' : (planet.boil_point - KELVIN_CELCIUS_DIFFERENCE), 'surfacePressure' : (planet.surface_pressure / 1000.0), 'greenhouseEffect' : planet.greenhouse_effect, 'surfaceTemperature' : (planet.surface_temp - KELVIN_CELCIUS_DIFFERENCE), 'hydrospherePercentage' : (planet.hydrosphere * 100), 'cloudCoverPercentage' : (planet.cloud_cover * 100), 'iceCoverPercentage' : (planet.ice_cover * 100), 'axialTilt' : planet.axial_tilt, 'albedo' : planet.albedo, 'lengthOfYear' : (planet.orbital_period / 365.25), 'lengthOfDay' : planet.day, }; }); return jsonOut; } });
kbingman/accrete
src/main.js
JavaScript
mit
5,874
'use strict'; /** * @constructor Queue - simple, synchronous queue of anything */ function Queue() { var queue = []; var length = 0; /** * @method drain - flush queue; when called during draining, * nothing changes * @access public * @param {function} interceptor - function that should be called for each queue element * @param {*} thisArg - context within which interceptor should be called * @returns {Queue} current instance */ this.drain = function drain(interceptor, thisArg) { var currentQueue = queue; queue = []; // values that are going to be scheduled in current queue get their own, fresh queue length = 0; for(var i = 0, len = currentQueue.length; i < len; i++) { interceptor.call(thisArg || null, currentQueue[i]); } return this; }; /** * @method drain - add element to queue; when called during draining, * value is added to new, fresh queue * @access public * @param {*} element - value that should be added to the queue * @returns {Queue} current instance */ this.add = function add(element) { queue.push(element); length++; return this; }; /** * @property length - current length of queue; when called during draining, * it's length of new queue, created before it * @access public * @readonly */ Object.defineProperty(this, 'length', { get: function() { return length; }, set: function() { throw new TypeError('Cannot assign to read only property \'length\' of ' + this.toString()); } }); } module.exports = Queue;
erykpiast/micro-next-tick
src/queue.js
JavaScript
mit
1,732
//var imageTags = document.getElementsByTagName("img"); // Returns array of <img> DOM nodes var $imageTags = $('img:visible'); //var authCode = "7bvWk1SFf2CBBn9R8c6KJ1P3ne0zre"; var authCode = "umUFgMhzz2cMpj6TexWSdmgzO6FhcY"; //random guy on github's access token: 1INOKIFjD8v6Lv1Swf2qgdOAWmBNhC var sources = []; var result; var results = {}; if(localStorage.imageTag != undefined){ result = localStorage.imageTag; //console.log("Cached result is "); //console.log(result); //console.log(Object.keys(JSON.parse(result))); }else{ getResult(finish); } function getResult(){ for (var i = 0; i < $imageTags.length; i++) { var srcURL = $imageTags[i]; srcURLWidth = srcURL.clientWidth; srcURLHeight = srcURL.clientHeight; //console.log("width: " + srcURLWidth); var src = $imageTags[i].src; var LIMITING_SIZE_MIN = 40; var LIMITING_SIZE_MAX = 3200; if (typeof(srcURLWidth) != "undefined" && srcURLWidth > LIMITING_SIZE_MIN && srcURLHeight > LIMITING_SIZE_MIN && srcURLWidth < LIMITING_SIZE_MAX && srcURLHeight < LIMITING_SIZE_MAX) { //console.log("result: " + src); sources.push(src); } } for (var i = 0; i < sources.length; i++) { query_api(sources[i], makeHashmap); make_ocr_request(sources[i], makeHashmap); } finish(); } function makeHashmap(url, hash) { //console.log(hash); for (var i = 0; i < hash.length; i++) { var hashLower = hash[i].toLowerCase(); if(results[hashLower] === undefined) results[hashLower] = []; if(results[hashLower].indexOf(url) == -1) results[hashLower].push(url); } console.log("resulting hashmap contains:"); console.log (results); } function finish(){ if(result == undefined){ result = JSON.stringify(results); localStorage.imageTag = result; } console.log("finish"); console.log(result); } function query_api(url, callback) { $.ajax({ url: "https://api.clarifai.com/v1/tag/?url="+url, 'headers': { 'Authorization': 'Bearer ' + authCode }, type: "GET", async: false, success: function (data) { var hash = data.results[0].result.tag.classes; callback(url, hash); }, error: function(data){ console.log("AJAX error: " + data); } }); } function make_ocr_request(url, callback) { $.ajax({ url: "https://api.projectoxford.ai/vision/v1.0/ocr?" + "language=unk&detectOrientation=true", beforeSend: function(xhrObj){ // Request headers xhrObj.setRequestHeader("Content-Type","application/json"); xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","c93522f717264b48924915779428dc8c"); // xhrObj.setRequestHeader("Access-Control-Allow-Origin": "http://siteA.com"); }, type: "POST", async: false, // Request body data: "{'Url': '" + url + "'}", }) .done(function(data) { console.log("the data returned from the ocr reques was"); console.log(data); if (data.regions[0] !== undefined){ //console.log(data); var parsed_JSON = data.regions[0].lines; console.log("parsed-json is this long " + parsed_JSON.length); var even_more_parsed = ""; for (var j = 0; j < parsed_JSON.length; j++) { console.log("outer loops ran"); for (var i = 0; i < parsed_JSON[j].words.length; i++) { console.log("each word processed was " + parsed_JSON[j].words[i].text); even_more_parsed += " " + parsed_JSON[j].words[i].text; } } even_more_parsed = even_more_parsed.trim(); var arr = even_more_parsed.split(' '); console.log("parsed JSON : " + even_more_parsed); console.log("arr to push to hashmap : " + arr); console.log("HTTP request for OCR worked"); callback(url, arr); } //var parsedata = data. //alert("success"); }); } result
hstall2529/Findr
url-scraper.js
JavaScript
mit
4,283
const jwt = require('jsonwebtoken'); const env = require('./../.env'); module.exports = function (req, res, next) { if (req.method === 'OPTIONS') { next(); } else { const token = req.body.token || req.query.token || req.headers['authorization']; if (!token) { return res.status(403).send({ errors: ['No token provided'] }); } jwt.verify(token, env.authSecret, function (error, decoded) { if (error) { res.status(403).send({ errors: ['Failed to authenticate token'] }); } else { next(); } }); } };
ricardorinco/MEAN-Finance
backend/config/auth.js
JavaScript
mit
639
module.exports = require('./lib/prerenderMySqlCache');
kaermorchen/prerender-mysql-cache
index.js
JavaScript
mit
55
var should = require('should'); var fs = require('fs'); var loopbackTs = require("../index"); var path = require("path"); var gutil = require('gulp-util'); require("mocha"); var createVinyl = function createVinyl(filename, contents) { var base = path.join(__dirname, 'models'); var filePath = path.join(base, filename); return new gutil.File({ 'cwd': __dirname, 'base': base, 'path': filePath, 'contents': contents || fs.readFileSync(filePath) }); }; function compileFile(inputFileName, outputFileName, done) { var simpleFile = createVinyl(inputFileName); var stream = loopbackTs(); stream.on("data", function(tsdFile) { should.exist(tsdFile); should.exist(tsdFile.path); should.exist(tsdFile.relative); should.exist(tsdFile.contents); should.equal(path.basename(tsdFile.path), outputFileName); String(tsdFile.contents).should.equal( fs.readFileSync(path.join(__dirname, 'expected/' + outputFileName), 'utf-8') ); done(); }); stream.write(simpleFile); stream.end(); } describe('gulp-loopback-ts', function() { it("should pass file when it isNull()", function(done) { var stream = loopbackTs(); var emptyFile = { 'isNull': function() { return true; } }; stream.on('data', function(data) { data.should.equal(emptyFile); done(); }); stream.write(emptyFile); stream.end(); }); it("should emit error when file isStream()", function(done) { var stream = loopbackTs(); var streamFile = { "isNull": function() { return false; }, "isStream": function() { return true; } } stream.on("error", function(err) { err.message.should.equal("Streaming not supported"); done(); }); stream.write(streamFile); stream.end(); }); it("should compile an empty model file", function(done) { compileFile("empty.json", "empty.d.ts", done); }); it("should emit error if the JSON does not have a 'name' member", function(done) { var invalidJsonFile = createVinyl("invalid.json"); var stream = loopbackTs(); stream.on("error", function(err) { err.message.should.equal("Missing model 'name' member."); done(); }); stream.write(invalidJsonFile); stream.end(); }); it("should compile a single simple file", function(done) { compileFile("simple.json", "simple.d.ts", done); }); it("should compile multiple files into a single output", function(done) { var files = [ createVinyl("primary-file-id.json"), createVinyl("primary-file-injected-id.json")]; var stream = loopbackTs("multiple.d.ts"); stream.on("data", function(tsdFile) { should.exist(tsdFile); should.exist(tsdFile.path); should.exist(tsdFile.relative); should.exist(tsdFile.contents); should.equal(path.basename(tsdFile.path), "multiple.d.ts"); String(tsdFile.contents).should.equal( fs.readFileSync(path.join(__dirname, 'expected/multiple.d.ts'), 'utf-8') ); done(); }); files.forEach(function(file) { stream.write(file); }) stream.end(); }); it("should resolve belongsTo relations", function(done) { var files = [ createVinyl("primary-file-id.json"), createVinyl("primary-file-injected-id.json"), createVinyl("belongs-to.json")]; var stream = loopbackTs("belongsTo.d.ts"); stream.on("data", function(tsdFile) { should.exist(tsdFile); should.exist(tsdFile.path); should.exist(tsdFile.relative); should.exist(tsdFile.contents); should.equal(path.basename(tsdFile.path), "belongsTo.d.ts"); String(tsdFile.contents).should.equal( fs.readFileSync(path.join(__dirname, 'expected/belongsTo.d.ts'), 'utf-8') ); done(); }); files.forEach(function(file) { stream.write(file); }) stream.end(); }); it("should resolve hasOne relations", function(done) { var files = [ createVinyl("primary-file-id.json"), createVinyl("primary-file-injected-id.json"), createVinyl("has-one.json")]; var stream = loopbackTs("hasOne.d.ts"); stream.on("data", function(tsdFile) { should.exist(tsdFile); should.exist(tsdFile.path); should.exist(tsdFile.relative); should.exist(tsdFile.contents); should.equal(path.basename(tsdFile.path), "hasOne.d.ts"); String(tsdFile.contents).should.equal( fs.readFileSync(path.join(__dirname, 'expected/hasOne.d.ts'), 'utf-8') ); done(); }); files.forEach(function(file) { stream.write(file); }) stream.end(); }); })
nseba/gulp-loopback-ts
test/main.js
JavaScript
mit
5,500
var fnToArray = require('./toArray'); var fnDelay = require('./delay'); var fnApply = require('./apply'); // fn.debounce module.exports = function (handler, msDelay) { 'use strict'; var debouncing; return function () { var args = fnToArray(arguments); if (debouncing) { clearTimeout(debouncing); } debouncing = fnDelay(function () { debouncing = false; fnApply(handler, args); }, msDelay); }; };
davidchase/fn.js
src/debounce.js
JavaScript
mit
493
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails react-core */ 'use strict'; let React = require('react'); let ReactDOM = require('react-dom'); let ReactDOMServer = require('react-dom/server'); let Scheduler = require('scheduler'); describe('ReactDOMRoot', () => { let container; beforeEach(() => { jest.resetModules(); container = document.createElement('div'); React = require('react'); ReactDOM = require('react-dom'); ReactDOMServer = require('react-dom/server'); Scheduler = require('scheduler'); }); if (!__EXPERIMENTAL__) { it('createRoot is not exposed in stable build', () => { expect(ReactDOM.createRoot).toBe(undefined); }); return; } it('renders children', () => { const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); }); it('warns if a callback parameter is provided to render', () => { const callback = jest.fn(); const root = ReactDOM.createRoot(container); expect(() => root.render(<div>Hi</div>, callback), ).toErrorDev( 'render(...): does not support the second callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().', {withoutStack: true}, ); Scheduler.unstable_flushAll(); expect(callback).not.toHaveBeenCalled(); }); it('warns if a callback parameter is provided to unmount', () => { const callback = jest.fn(); const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); expect(() => root.unmount(callback), ).toErrorDev( 'unmount(...): does not support a callback argument. ' + 'To execute a side effect after rendering, declare it in a component body with useEffect().', {withoutStack: true}, ); Scheduler.unstable_flushAll(); expect(callback).not.toHaveBeenCalled(); }); it('unmounts children', () => { const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); root.unmount(); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual(''); }); it('supports hydration', async () => { const markup = await new Promise(resolve => resolve( ReactDOMServer.renderToString( <div> <span className="extra" /> </div>, ), ), ); // Does not hydrate by default const container1 = document.createElement('div'); container1.innerHTML = markup; const root1 = ReactDOM.createRoot(container1); root1.render( <div> <span /> </div>, ); Scheduler.unstable_flushAll(); // Accepts `hydrate` option const container2 = document.createElement('div'); container2.innerHTML = markup; const root2 = ReactDOM.createRoot(container2, {hydrate: true}); root2.render( <div> <span /> </div>, ); expect(() => Scheduler.unstable_flushAll()).toErrorDev('Extra attributes'); }); it('clears existing children with legacy API', async () => { container.innerHTML = '<div>a</div><div>b</div>'; ReactDOM.render( <div> <span>c</span> <span>d</span> </div>, container, ); expect(container.textContent).toEqual('cd'); ReactDOM.render( <div> <span>d</span> <span>c</span> </div>, container, ); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('dc'); }); it('clears existing children', async () => { container.innerHTML = '<div>a</div><div>b</div>'; const root = ReactDOM.createRoot(container); root.render( <div> <span>c</span> <span>d</span> </div>, ); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('cd'); root.render( <div> <span>d</span> <span>c</span> </div>, ); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('dc'); }); it('throws a good message on invalid containers', () => { expect(() => { ReactDOM.createRoot(<div>Hi</div>); }).toThrow('createRoot(...): Target container is not a DOM element.'); }); it('warns when rendering with legacy API into createRoot() container', () => { const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); expect(() => { ReactDOM.render(<div>Bye</div>, container); }).toErrorDev( [ // We care about this warning: 'You are calling ReactDOM.render() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call root.render(element)?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: 'Replacing React-rendered children with a new root component.', ], {withoutStack: true}, ); Scheduler.unstable_flushAll(); // This works now but we could disallow it: expect(container.textContent).toEqual('Bye'); }); it('warns when hydrating with legacy API into createRoot() container', () => { const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); expect(() => { ReactDOM.hydrate(<div>Hi</div>, container); }).toErrorDev( [ // We care about this warning: 'You are calling ReactDOM.hydrate() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. ' + 'Did you mean to call createRoot(container, {hydrate: true}).render(element)?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: 'Replacing React-rendered children with a new root component.', ], {withoutStack: true}, ); }); it('warns when unmounting with legacy API (no previous content)', () => { const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); let unmounted = false; expect(() => { unmounted = ReactDOM.unmountComponentAtNode(container); }).toErrorDev( [ // We care about this warning: 'You are calling ReactDOM.unmountComponentAtNode() on a container that was previously ' + 'passed to ReactDOM.createRoot(). This is not supported. Did you mean to call root.unmount()?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: "The node you're attempting to unmount was rendered by React and is not a top-level container.", ], {withoutStack: true}, ); expect(unmounted).toBe(false); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); root.unmount(); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual(''); }); it('warns when unmounting with legacy API (has previous content)', () => { // Currently createRoot().render() doesn't clear this. container.appendChild(document.createElement('div')); // The rest is the same as test above. const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); let unmounted = false; expect(() => { unmounted = ReactDOM.unmountComponentAtNode(container); }).toErrorDev( [ 'Did you mean to call root.unmount()?', // This is more of a symptom but restructuring the code to avoid it isn't worth it: "The node you're attempting to unmount was rendered by React and is not a top-level container.", ], {withoutStack: true}, ); expect(unmounted).toBe(false); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual('Hi'); root.unmount(); Scheduler.unstable_flushAll(); expect(container.textContent).toEqual(''); }); it('warns when passing legacy container to createRoot()', () => { ReactDOM.render(<div>Hi</div>, container); expect(() => { ReactDOM.createRoot(container); }).toErrorDev( 'You are calling ReactDOM.createRoot() on a container that was previously ' + 'passed to ReactDOM.render(). This is not supported.', {withoutStack: true}, ); }); it('warns when creating two roots managing the same container', () => { ReactDOM.createRoot(container); expect(() => { ReactDOM.createRoot(container); }).toErrorDev( 'You are calling ReactDOM.createRoot() on a container that ' + 'has already been passed to createRoot() before. Instead, call ' + 'root.render() on the existing root instead if you want to update it.', {withoutStack: true}, ); }); it('does not warn when creating second root after first one is unmounted', () => { const root = ReactDOM.createRoot(container); root.unmount(); Scheduler.unstable_flushAll(); ReactDOM.createRoot(container); // No warning }); it('warns if creating a root on the document.body', async () => { expect(() => { ReactDOM.createRoot(document.body); }).toErrorDev( 'createRoot(): Creating roots directly with document.body is ' + 'discouraged, since its children are often manipulated by third-party ' + 'scripts and browser extensions. This may lead to subtle ' + 'reconciliation issues. Try using a container element created ' + 'for your app.', {withoutStack: true}, ); }); it('warns if updating a root that has had its contents removed', async () => { const root = ReactDOM.createRoot(container); root.render(<div>Hi</div>); Scheduler.unstable_flushAll(); container.innerHTML = ''; expect(() => { root.render(<div>Hi</div>); }).toErrorDev( 'render(...): It looks like the React-rendered content of the ' + 'root container was removed without using React. This is not ' + 'supported and will cause errors. Instead, call ' + "root.unmount() to empty a root's container.", {withoutStack: true}, ); }); });
chicoxyzzy/react
packages/react-dom/src/__tests__/ReactDOMRoot-test.js
JavaScript
mit
10,617
(function() { 'use strict'; angular .module('app.employee') .controller('IncreaseDialogController', IncreaseDialogController); /** @ngInject */ function IncreaseDialogController($mdDialog, $scope, selectedMail, employeeService) { $scope.newIncre = selectedMail; $scope.selectedMail = {}; angular.copy(selectedMail, $scope.selectedMail); // $scope.newIncre = {}; console.log($scope.newIncre.IncreaseInfo); //////////////////////////////////////////////////////////call service method//////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////// // $scope.increase = []; $scope.increase = { "_id": $scope.newIncre._id, "DetailIn": "", "AmountIn": "", "StartDateIn": "", "EndDateIn": "" }; console.log($scope.newIncre); $scope.addIncrease = function() { $scope.newIncre.IncreaseInfo.push($scope.increase); console.log($scope.newIncre._id); console.log($scope.newIncre.IncreaseInfo); $scope.increase = { "DetailIn": "", "AmountIn": "", "StartDateIn": "", "EndDateIn": "" } }; $scope.removeIncre = function(index) { // console.log("TEST"); $scope.newIncre.IncreaseInfo.splice(index, 1); }; $scope.saveIncrease = function() { employeeService.putIncrease($scope.newIncre).then(function(res) { $scope.closeDialog(); }, function(err) { console.log(err); }); console.log($scope.newIncre); }; // $scope.closeDialog = function() { $mdDialog.hide(); } } //end controler })();
mob35/PMS
src/app/main/apps/employee/dialogs/compose/increaseEmp.controller.js
JavaScript
mit
1,977
declare module "reselect" { declare type Selector<TState, TProps, TResult> = (state: TState, props: TProps, ...rest: any[]) => TResult; declare type SelectorCreator = { < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16 >( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, selector10: Selector<TState, TProps, T10>, selector11: Selector<TState, TProps, T11>, selector12: Selector<TState, TProps, T12>, selector13: Selector<TState, TProps, T13>, selector14: Selector<TState, TProps, T14>, selector15: Selector<TState, TProps, T15>, selector16: Selector<TState, TProps, T16>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13, arg14: T14, arg15: T15, arg16: T16 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16 >( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9>, Selector<TState, TProps, T10>, Selector<TState, TProps, T11>, Selector<TState, TProps, T12>, Selector<TState, TProps, T13>, Selector<TState, TProps, T14>, Selector<TState, TProps, T15>, Selector<TState, TProps, T16> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13, arg14: T14, arg15: T15, arg16: T16 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15 >( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, selector10: Selector<TState, TProps, T10>, selector11: Selector<TState, TProps, T11>, selector12: Selector<TState, TProps, T12>, selector13: Selector<TState, TProps, T13>, selector14: Selector<TState, TProps, T14>, selector15: Selector<TState, TProps, T15>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13, arg14: T14, arg15: T15 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15 >( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9>, Selector<TState, TProps, T10>, Selector<TState, TProps, T11>, Selector<TState, TProps, T12>, Selector<TState, TProps, T13>, Selector<TState, TProps, T14>, Selector<TState, TProps, T15> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13, arg14: T14, arg15: T15 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 >( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, selector10: Selector<TState, TProps, T10>, selector11: Selector<TState, TProps, T11>, selector12: Selector<TState, TProps, T12>, selector13: Selector<TState, TProps, T13>, selector14: Selector<TState, TProps, T14>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13, arg14: T14 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14 >( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9>, Selector<TState, TProps, T10>, Selector<TState, TProps, T11>, Selector<TState, TProps, T12>, Selector<TState, TProps, T13>, Selector<TState, TProps, T14> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13, arg14: T14 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13 >( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, selector10: Selector<TState, TProps, T10>, selector11: Selector<TState, TProps, T11>, selector12: Selector<TState, TProps, T12>, selector13: Selector<TState, TProps, T13>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13 >( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9>, Selector<TState, TProps, T10>, Selector<TState, TProps, T11>, Selector<TState, TProps, T12>, Selector<TState, TProps, T13> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12, arg13: T13 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12 >( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, selector10: Selector<TState, TProps, T10>, selector11: Selector<TState, TProps, T11>, selector12: Selector<TState, TProps, T12>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12 ) => TResult ): Selector<TState, TProps, TResult>, < TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12 >( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9>, Selector<TState, TProps, T10>, Selector<TState, TProps, T11>, Selector<TState, TProps, T12> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11, arg12: T12 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, selector10: Selector<TState, TProps, T10>, selector11: Selector<TState, TProps, T11>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9>, Selector<TState, TProps, T10>, Selector<TState, TProps, T11> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10, arg11: T11 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, selector10: Selector<TState, TProps, T10>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9>, Selector<TState, TProps, T10> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, selector9: Selector<TState, TProps, T9>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8>, Selector<TState, TProps, T9> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, selector8: Selector<TState, TProps, T8>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7, T8>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7>, Selector<TState, TProps, T8> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, selector7: Selector<TState, TProps, T7>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6, T7>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6>, Selector<TState, TProps, T7> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, selector6: Selector<TState, TProps, T6>, resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5, T6>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5>, Selector<TState, TProps, T6> ], resultFunc: ( arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6 ) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, selector5: Selector<TState, TProps, T5>, resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4, T5>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4>, Selector<TState, TProps, T5> ], resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, selector4: Selector<TState, TProps, T4>, resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3, T4>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3>, Selector<TState, TProps, T4> ], resultFunc: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, selector3: Selector<TState, TProps, T3>, resultFunc: (arg1: T1, arg2: T2, arg3: T3) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2, T3>( selectors: [ Selector<TState, TProps, T1>, Selector<TState, TProps, T2>, Selector<TState, TProps, T3> ], resultFunc: (arg1: T1, arg2: T2, arg3: T3) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2>( selector1: Selector<TState, TProps, T1>, selector2: Selector<TState, TProps, T2>, resultFunc: (arg1: T1, arg2: T2) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1, T2>( selectors: [Selector<TState, TProps, T1>, Selector<TState, TProps, T2>], resultFunc: (arg1: T1, arg2: T2) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1>( selector1: Selector<TState, TProps, T1>, resultFunc: (arg1: T1) => TResult ): Selector<TState, TProps, TResult>, <TState, TProps, TResult, T1>( selectors: [Selector<TState, TProps, T1>], resultFunc: (arg1: T1) => TResult ): Selector<TState, TProps, TResult> }; declare type Reselect = { createSelector: SelectorCreator, defaultMemoize: <TFunc: Function>( func: TFunc, equalityCheck?: (a: any, b: any) => boolean ) => TFunc, createSelectorCreator: ( memoize: Function, ...memoizeOptions: any[] ) => SelectorCreator, createStructuredSelector: <TState, TProps>( inputSelectors: { [k: string | number]: Selector<TState, TProps, any> }, selectorCreator?: SelectorCreator ) => Selector<TState, TProps, any> }; declare module.exports: Reselect; }
mwalkerwells/flow-typed
definitions/npm/reselect_v3.x.x/flow_v0.34.x-v0.46.x/reselect_v3.x.x.js
JavaScript
mit
23,266
'use strict'; import mongoose from 'mongoose'; // create new schema const schema = new mongoose.Schema({ type: { type: String }, data: { timestampInterval: Number, transaction_id: Number } }, { strict: false }); // virtual date attribute schema.virtual('date') .get(() => this._id.getTimestamp()); // assign schema to 'Sheet' mongoose.model('TimestampInterval', schema);
smylydon/msc-project
src/app/models/timestampInterval.js
JavaScript
mit
385
// const n = 5; // const s = "5"; // console.log(n === s); // console.log(n !== s); // console.log(n === Number(s)); // console.log(n !== Number(s)); // console.log(n == s); // console.log(n != s); // const a = {name: "an object"}; // const b = {name: "an object"}; // console.log(a === b); // console.log(a !== b); // console.log(a == b); // console.log(a != b); // let n = 0; // while (true) { // n += 0.1; // if (Math.abs(n - 0.3) < Number.EPSILON) { // break; // } // } // console.log(`Stopped at ${n}`); // console.log(1 + 2); // console.log("1" + "2"); // console.log(1 + "2"); // console.log("1" + 2); // const skipIt = false; // let x = 0; // const result = skipIt || x++; // console.log(x); // const skipIt = true; // let x = 0; // const result = skipIt && x++; // console.log(x); let x = 0, y = 10, z; z = (x++, y++); console.log(z);
ihomway/LearningJaveScript
GettingStarted/es6/ExpressionAndOperator.js
JavaScript
mit
874
var SudokuBoard = require('../src/js/SudokuBoard.js'); var stringFromBoardArray = require('./helper.js'); describe("SudokuBoard.insideBox", function(){ it("returns false if the cell is outside the given box", function(){ var upperLeft = [6, 0]; expect(SudokuBoard.insideBox(upperLeft, 4, 4)).toEqual(false); expect(SudokuBoard.insideBox(upperLeft, 4, 8)).toEqual(false); expect(SudokuBoard.insideBox(upperLeft, 0, 0)).toEqual(false); }); it("returns true if the cell is inside the given box", function(){ var upperLeft = [6, 0]; expect(SudokuBoard.insideBox(upperLeft, 6, 0)).toEqual(true); expect(SudokuBoard.insideBox(upperLeft, 6, 1)).toEqual(true); expect(SudokuBoard.insideBox(upperLeft, 7, 1)).toEqual(true); }); });
msergeant/sudoku-hint-machine
spec/SudokuBoard_insideBox.js
JavaScript
mit
766
"use strict"; let Input = FunctionObject.new({ controlScheme : "keyboard", priority : "keyboard" }, { update : function () { forevery(Keys.held, function (duration, key) { if (!foreach(Keys.handlers, function (handler) { if (handler.keys.contains(key) && handler.handler(key, duration === 1, false)) return true; if (Keys.heldKeys().length > 1 && handler.keys.contains(Keys.combination(Keys.heldKeys())) && handler.handler(Keys.combination(Keys.heldKeys()), duration === 1)) return true; })) { if (duration === 1 && !/unknown (.*)/.test(key)) { if (Input.controlScheme !== "keyboard" && (typeof Textbox === "undefined" || Textbox.dialogue.empty() || Textbox.dialogue.first().responses.empty())) Input.controlScheme = "keyboard"; if (Input.controlScheme === "keyboard") { if (Game.focused && typeof Textbox !== "undefined" && Textbox.active) { switch (key) { case Settings._("keys => primary"): Textbox.progress(); return true; case Settings._("keys => up"): Textbox.selectAdjacent(Directions.up); return true; case Settings._("keys => right"): Textbox.selectAdjacent(Directions.right); return true; case Settings._("keys => down"): Textbox.selectAdjacent(Directions.down); return true; case Settings._("keys => left"): Textbox.selectAdjacent(Directions.left); return true; default: if (!/unknown (.*)/.test(key)) { Textbox.key(Keys.combination(Keys.heldKeys())); } break; } } } else { if (![Settings._("keys => tertiary")].contains(key)) Input.controlScheme = "keyboard"; Textbox.requestRedraw = true; } } } }); forevery(Keys.held, function (duration, key) { Keys.held[key] = duration + 1; }); ++ Cursor.lastMoved; } }); let Keys = { name : function (key) { if (typeof key === "string") return key; if (key >= 48 && key <= 57) { // Numbers return String.fromCharCode(key); } if (key >= 65 && key <= 90) { // Letters return String.fromCharCode(key); } if (key >= 96 && key <= 105) { // Numpad numbers return "numpad " + (key - 96); } switch (key) { case 8: return "backspace"; case 9: return "tab"; case 13: return "return"; case 16: return "shift"; case 17: return "control"; case 18: return "option"; case 20: return "caps lock"; case 27: return "escape"; case 32: return "space"; case 33: return "page up"; case 34: return "page down"; case 35: return "end"; case 36: return "home"; case 37: return "left"; case 38: return "up"; case 39: return "right"; case 40: return "down"; case 46: return "delete"; case 91: return "command"; case 106: return "numpad *"; case 107: return "numpad +"; case 109: return "numpad -"; case 110: return "numpad ."; case 111: return "numpad /"; case 186: return ";"; case 187: return "="; case 188: return ","; case 189: return "-"; case 190: return "."; case 191: return "/"; case 192: return "`"; case 219: return "["; case 220: return "\\"; case 221: return "]"; case 222: return "\""; default: return "unknown (" + key + ")"; } }, held : {}, handlers : [], heldKeys : function () { var held = []; forevery(Keys.held, function (duration, key) { held.push(key); }); return held; }, pressedKeys : function () { var pressed = []; forevery(Keys.held, function (duration, key) { if (duration === 1) pressed.push(key); }); return pressed; }, isHeld : function (key) { return Keys.held.hasOwnProperty(key); }, isPressed : function (key) { return Keys.isHeld(key) && Keys.held[key].duration === 1; }, addHandler : function (handler, forWhichKeys, notifyOfReleases) { var data = { handler : handler, keys : wrapArray(forWhichKeys), notifyOfReleases : (arguments.length >= 3 && notifyOfReleases) }; Keys.handlers.push(data); return data; }, removeHandler : function (handler) { Keys.handlers.remove(Keys.handlers.indexOf(handler)); }, press : function (key) { if (!Keys.held.hasOwnProperty(key)) Keys.held[key] = 1; if (![Settings._("keys => tertiary")].contains(key)) Input.priority = "keyboard"; return false; }, release : function (key) { foreach(Keys.handlers, function (handler) { if (handler.keys.contains(key) && handler.notifyOfReleases && handler.handler(key, false, true)) return true; }); delete Keys.held[key]; return false; }, combination : function (keys) { var combo = []; if (arguments.length > 0 && Array.isArray(keys)) combo = keys; else { for (var i = 0; i < arguments.length; ++ i) combo.push(arguments[i]); } return combo.sort().join(", "); }, simulate : function (key) { foreach(Keys.handlers, function (handler) { if (handler.keys.contains(key)) handler.handler(key, true); }); } }; window.addEventListener("keydown", function (event) { if (Keys.press(Keys.name(event.keyCode))) { event.stopPropagation(); } if (!(event.metaKey || event.ctrlKey) && typeof Battle === "object" && Battle !== null && Battle.hasOwnProperty("canvas") && document.activeElement === Battle.canvas) event.preventDefault(); }); window.addEventListener("keyup", function (event) { if (Keys.release(Keys.name(event.keyCode))) { event.stopPropagation(); } if (!(event.metaKey || event.ctrlKey) && typeof Battle === "object" && Battle !== null && Battle.hasOwnProperty("canvas") && document.activeElement === Battle.canvas) event.preventDefault(); }); let Cursor = { x : null, y : null, lastMoved : 0, inArea : function (element, x, y, width, height) { var boundingRect = element.getBoundingClientRect(), cursorX = Cursor.x - boundingRect.left, cursorY = Cursor.y - boundingRect.top; return (cursorX >= x && cursorX < x + width && cursorY >= y && cursorY < y + height); }, click : function () { Input.controlScheme = "mouse"; var bubble = true; if (bubble && typeof Battle === "object" && Battle !== null && Battle.canvas) { if (Cursor.inArea(Battle.canvas, 0, 0, Battle.canvas.width, Battle.canvas.height)) { if (Battle.drawing.respondToClick()) { bubble = false; } } } if (bubble && typeof Textbox === "object" && Textbox.canvas) { if (Cursor.inArea(Textbox.canvas, 0, 0, Textbox.canvas.width, Textbox.canvas.height)) { Textbox.draw(); // Redraws the textbox so that the hovered response is updated on touchscreen devices Textbox.progress(); } } } }; window.addEventListener("mousemove", function (event) { Cursor.x = event.pageX - window.scrollX; Cursor.y = event.pageY - window.scrollY; Cursor.lastMoved = 0; Input.priority = "mouse"; }); window.addEventListener("mousedown", function (event) { if (event.button === 0) Cursor.click(event.button); });
varkor/pokengine
battle/scripts/objects/unique/Input.js
JavaScript
mit
7,070
$('div').each( function() { $(this).effect("explode", {}, 3000); });
ccraig/mustached-octo-dubstep
js/explode.js
JavaScript
mit
74
//<%= name %>
qtheninja/vulcanscaffold
generators/forge/templates/_client/_views/_object/_create/_createObject.js
JavaScript
mit
13