repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
bBlocks/dom
dom.js
function(selector, all) { if (!this.querySelector) {bb.warn('Find should be used with DOM elements'); return;} return all && this.querySelectorAll(selector) || this.querySelector(selector); }
javascript
function(selector, all) { if (!this.querySelector) {bb.warn('Find should be used with DOM elements'); return;} return all && this.querySelectorAll(selector) || this.querySelector(selector); }
[ "function", "(", "selector", ",", "all", ")", "{", "if", "(", "!", "this", ".", "querySelector", ")", "{", "bb", ".", "warn", "(", "'Find should be used with DOM elements'", ")", ";", "return", ";", "}", "return", "all", "&&", "this", ".", "querySelectorAll", "(", "selector", ")", "||", "this", ".", "querySelector", "(", "selector", ")", ";", "}" ]
Finds child element matching provided selector @param {string} selector - Selector has limitations based on the browser support. @param {boolean} all - Flag to find all matching elements. Otherwise fist found element is returned. @return {element|array|undefined} - Found element or array of elements
[ "Finds", "child", "element", "matching", "provided", "selector" ]
3381b3bf3a0415a852f60d8f53c7cac2765ee9b6
https://github.com/bBlocks/dom/blob/3381b3bf3a0415a852f60d8f53c7cac2765ee9b6/dom.js#L40-L43
train
bBlocks/dom
dom.js
function(html, tag) { var el = document.createElement(tag || 'div'); el.innerHTML = html; return el; }
javascript
function(html, tag) { var el = document.createElement(tag || 'div'); el.innerHTML = html; return el; }
[ "function", "(", "html", ",", "tag", ")", "{", "var", "el", "=", "document", ".", "createElement", "(", "tag", "||", "'div'", ")", ";", "el", ".", "innerHTML", "=", "html", ";", "return", "el", ";", "}" ]
Creates a new HTMLElement with provided contents @param {string} html - HTML contents @param {string=} tag - Optional tag of the element to create
[ "Creates", "a", "new", "HTMLElement", "with", "provided", "contents" ]
3381b3bf3a0415a852f60d8f53c7cac2765ee9b6
https://github.com/bBlocks/dom/blob/3381b3bf3a0415a852f60d8f53c7cac2765ee9b6/dom.js#L103-L107
train
enquirer/terminal-paginator
index.js
Paginator
function Paginator(options) { debug('initializing from <%s>', __filename); this.options = options || {}; this.footer = this.options.footer; if (typeof this.footer !== 'string') { this.footer = '(Move up and down to reveal more choices)'; } this.firstRender = true; this.lastIndex = 0; this.position = 0; }
javascript
function Paginator(options) { debug('initializing from <%s>', __filename); this.options = options || {}; this.footer = this.options.footer; if (typeof this.footer !== 'string') { this.footer = '(Move up and down to reveal more choices)'; } this.firstRender = true; this.lastIndex = 0; this.position = 0; }
[ "function", "Paginator", "(", "options", ")", "{", "debug", "(", "'initializing from <%s>'", ",", "__filename", ")", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "footer", "=", "this", ".", "options", ".", "footer", ";", "if", "(", "typeof", "this", ".", "footer", "!==", "'string'", ")", "{", "this", ".", "footer", "=", "'(Move up and down to reveal more choices)'", ";", "}", "this", ".", "firstRender", "=", "true", ";", "this", ".", "lastIndex", "=", "0", ";", "this", ".", "position", "=", "0", ";", "}" ]
The paginator keeps track of a position index in a list and returns a subset of the choices if the list is too long.
[ "The", "paginator", "keeps", "track", "of", "a", "position", "index", "in", "a", "list", "and", "returns", "a", "subset", "of", "the", "choices", "if", "the", "list", "is", "too", "long", "." ]
56413bd88a0870ee6c1d6ba897c0fc4111fc9bea
https://github.com/enquirer/terminal-paginator/blob/56413bd88a0870ee6c1d6ba897c0fc4111fc9bea/index.js#L13-L23
train
mongodb-js/electron-installer-run
lib/index.js
getBinPath
function getBinPath(cmd, fn) { which(cmd, function(err, bin) { if (err) { return fn(err); } fs.exists(bin, function(exists) { if (!exists) { return fn(new Error(format( 'Expected file for `%s` does not exist at `%s`', cmd, bin))); } fn(null, bin); }); }); }
javascript
function getBinPath(cmd, fn) { which(cmd, function(err, bin) { if (err) { return fn(err); } fs.exists(bin, function(exists) { if (!exists) { return fn(new Error(format( 'Expected file for `%s` does not exist at `%s`', cmd, bin))); } fn(null, bin); }); }); }
[ "function", "getBinPath", "(", "cmd", ",", "fn", ")", "{", "which", "(", "cmd", ",", "function", "(", "err", ",", "bin", ")", "{", "if", "(", "err", ")", "{", "return", "fn", "(", "err", ")", ";", "}", "fs", ".", "exists", "(", "bin", ",", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "{", "return", "fn", "(", "new", "Error", "(", "format", "(", "'Expected file for `%s` does not exist at `%s`'", ",", "cmd", ",", "bin", ")", ")", ")", ";", "}", "fn", "(", "null", ",", "bin", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Gets the absolute path for a `cmd`. @param {String} cmd - e.g. `codesign`. @param {Function} fn - Callback which receives `(err, binPath)`. @return {void}
[ "Gets", "the", "absolute", "path", "for", "a", "cmd", "." ]
dc47ecac35d5dd945cadb306a6a12975bf2c4ded
https://github.com/mongodb-js/electron-installer-run/blob/dc47ecac35d5dd945cadb306a6a12975bf2c4ded/lib/index.js#L13-L28
train
mongodb-js/electron-installer-run
lib/index.js
run
function run(cmd, args, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } if (typeof args === 'function') { fn = args; args = []; opts = {}; } getBinPath(cmd, function(err, bin) { if (err) { return fn(err); } debug('running', { cmd: cmd, args: args }); var output = []; var proc = spawn(bin, args, opts); proc.stdout.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.stderr.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.on('exit', function(code) { if (code !== 0) { debug('command failed!', { cmd: cmd, bin: bin, args: args, opts: opts, code: code, output: Buffer.concat(output).toString('utf-8') }); fn(new Error('Command failed! ' + 'Please try again with debugging enabled.'), Buffer.concat(output).toString('utf-8')); return; } debug('completed! %j', { cmd: cmd, bin: bin, args: args, opts: opts, code: code }); fn(null, Buffer.concat(output).toString('utf-8')); }); }); }
javascript
function run(cmd, args, opts, fn) { if (typeof opts === 'function') { fn = opts; opts = {}; } if (typeof args === 'function') { fn = args; args = []; opts = {}; } getBinPath(cmd, function(err, bin) { if (err) { return fn(err); } debug('running', { cmd: cmd, args: args }); var output = []; var proc = spawn(bin, args, opts); proc.stdout.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.stderr.on('data', function(buf) { buf.toString('utf-8').split('\n').map(function(line) { debug(' %s> %s', cmd, line); }); output.push(buf); }); proc.on('exit', function(code) { if (code !== 0) { debug('command failed!', { cmd: cmd, bin: bin, args: args, opts: opts, code: code, output: Buffer.concat(output).toString('utf-8') }); fn(new Error('Command failed! ' + 'Please try again with debugging enabled.'), Buffer.concat(output).toString('utf-8')); return; } debug('completed! %j', { cmd: cmd, bin: bin, args: args, opts: opts, code: code }); fn(null, Buffer.concat(output).toString('utf-8')); }); }); }
[ "function", "run", "(", "cmd", ",", "args", ",", "opts", ",", "fn", ")", "{", "if", "(", "typeof", "opts", "===", "'function'", ")", "{", "fn", "=", "opts", ";", "opts", "=", "{", "}", ";", "}", "if", "(", "typeof", "args", "===", "'function'", ")", "{", "fn", "=", "args", ";", "args", "=", "[", "]", ";", "opts", "=", "{", "}", ";", "}", "getBinPath", "(", "cmd", ",", "function", "(", "err", ",", "bin", ")", "{", "if", "(", "err", ")", "{", "return", "fn", "(", "err", ")", ";", "}", "debug", "(", "'running'", ",", "{", "cmd", ":", "cmd", ",", "args", ":", "args", "}", ")", ";", "var", "output", "=", "[", "]", ";", "var", "proc", "=", "spawn", "(", "bin", ",", "args", ",", "opts", ")", ";", "proc", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "buf", ")", "{", "buf", ".", "toString", "(", "'utf-8'", ")", ".", "split", "(", "'\\n'", ")", ".", "\\n", "map", ";", "(", "function", "(", "line", ")", "{", "debug", "(", "' %s> %s'", ",", "cmd", ",", "line", ")", ";", "}", ")", "}", ")", ";", "output", ".", "push", "(", "buf", ")", ";", "proc", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "buf", ")", "{", "buf", ".", "toString", "(", "'utf-8'", ")", ".", "split", "(", "'\\n'", ")", ".", "\\n", "map", ";", "(", "function", "(", "line", ")", "{", "debug", "(", "' %s> %s'", ",", "cmd", ",", "line", ")", ";", "}", ")", "}", ")", ";", "}", ")", ";", "}" ]
Use me when you want to run an external command instead of using `child_process` directly because I'll handle lots of platform edge cases for you and provide nice debugging output when things go wrong! @example var run = require('electron-installer-run'); var args = ['--verify', process.env.APP_PATH]; run('codesign', args, function(err){ if(err){ console.error('codesign verification failed!'); process.exit(1); } console.log('codesign verification succeeded!'); }); @param {String} cmd - The bin name of your command, e.g. `grep`. @param {Array} [args] - Arguments to pass to the command [Default `[]`]. @param {Object} [opts] - Options to pass to `child_process.spawn` [Default `{}`]. @param {Function} fn - Callback which recieves `(err, output)`.
[ "Use", "me", "when", "you", "want", "to", "run", "an", "external", "command", "instead", "of", "using", "child_process", "directly", "because", "I", "ll", "handle", "lots", "of", "platform", "edge", "cases", "for", "you", "and", "provide", "nice", "debugging", "output", "when", "things", "go", "wrong!" ]
dc47ecac35d5dd945cadb306a6a12975bf2c4ded
https://github.com/mongodb-js/electron-installer-run/blob/dc47ecac35d5dd945cadb306a6a12975bf2c4ded/lib/index.js#L52-L114
train
balderdashy/mast
newExample/bootstrap.js
bootstrap
function bootstrap(options, cb) { var adapters = options.adapters || {}; var connections = options.connections || {}; var collections = options.collections || {}; Object.keys(adapters).forEach(function(identity) { var def = adapters[identity]; // Make sure our adapter defs have `identity` properties def.identity = def.identity || identity; }); var extendedCollections = []; Object.keys(collections).forEach(function(identity) { var def = collections[identity]; // Make sure our collection defs have `identity` properties def.identity = def.identity || identity; // Fold object of collection definitions into an array // of extended Waterline collections. extendedCollections.push(Waterline.Collection.extend(def)); }); // Instantiate Waterline and load the already-extended // Waterline collections. var waterline = new Waterline(); extendedCollections.forEach(function(collection) { waterline.loadCollection(collection); }); // Initialize Waterline // (and tell it about our adapters) waterline.initialize({ adapters: adapters, connections: connections }, cb); return waterline; }
javascript
function bootstrap(options, cb) { var adapters = options.adapters || {}; var connections = options.connections || {}; var collections = options.collections || {}; Object.keys(adapters).forEach(function(identity) { var def = adapters[identity]; // Make sure our adapter defs have `identity` properties def.identity = def.identity || identity; }); var extendedCollections = []; Object.keys(collections).forEach(function(identity) { var def = collections[identity]; // Make sure our collection defs have `identity` properties def.identity = def.identity || identity; // Fold object of collection definitions into an array // of extended Waterline collections. extendedCollections.push(Waterline.Collection.extend(def)); }); // Instantiate Waterline and load the already-extended // Waterline collections. var waterline = new Waterline(); extendedCollections.forEach(function(collection) { waterline.loadCollection(collection); }); // Initialize Waterline // (and tell it about our adapters) waterline.initialize({ adapters: adapters, connections: connections }, cb); return waterline; }
[ "function", "bootstrap", "(", "options", ",", "cb", ")", "{", "var", "adapters", "=", "options", ".", "adapters", "||", "{", "}", ";", "var", "connections", "=", "options", ".", "connections", "||", "{", "}", ";", "var", "collections", "=", "options", ".", "collections", "||", "{", "}", ";", "Object", ".", "keys", "(", "adapters", ")", ".", "forEach", "(", "function", "(", "identity", ")", "{", "var", "def", "=", "adapters", "[", "identity", "]", ";", "def", ".", "identity", "=", "def", ".", "identity", "||", "identity", ";", "}", ")", ";", "var", "extendedCollections", "=", "[", "]", ";", "Object", ".", "keys", "(", "collections", ")", ".", "forEach", "(", "function", "(", "identity", ")", "{", "var", "def", "=", "collections", "[", "identity", "]", ";", "def", ".", "identity", "=", "def", ".", "identity", "||", "identity", ";", "extendedCollections", ".", "push", "(", "Waterline", ".", "Collection", ".", "extend", "(", "def", ")", ")", ";", "}", ")", ";", "var", "waterline", "=", "new", "Waterline", "(", ")", ";", "extendedCollections", ".", "forEach", "(", "function", "(", "collection", ")", "{", "waterline", ".", "loadCollection", "(", "collection", ")", ";", "}", ")", ";", "waterline", ".", "initialize", "(", "{", "adapters", ":", "adapters", ",", "connections", ":", "connections", "}", ",", "cb", ")", ";", "return", "waterline", ";", "}" ]
Simple bootstrap to set up Waterline given some collection, connection, and adapter definitions. @param options :: {Object} adapters [i.e. a dictionary] :: {Object} connections [i.e. a dictionary] :: {Object} collections [i.e. a dictionary] @param {Function} cb () {Error} err () ontology :: {Object} collections :: {Object} connections @return {Waterline}
[ "Simple", "bootstrap", "to", "set", "up", "Waterline", "given", "some", "collection", "connection", "and", "adapter", "definitions", "." ]
6fc2b07849ec6a6fe15f66e456e556e5270ed37f
https://github.com/balderdashy/mast/blob/6fc2b07849ec6a6fe15f66e456e556e5270ed37f/newExample/bootstrap.js#L19-L64
train
spyfu/spyfu-vue-factory
dist/spyfu-vue-factory.esm.js
function (name) { return { name: name, component: { render: function render(h) { return h('div'); }, functional: true }, path: '/' + name.replace(/[^\w]/g, "-") }; }
javascript
function (name) { return { name: name, component: { render: function render(h) { return h('div'); }, functional: true }, path: '/' + name.replace(/[^\w]/g, "-") }; }
[ "function", "(", "name", ")", "{", "return", "{", "name", ":", "name", ",", "component", ":", "{", "render", ":", "function", "render", "(", "h", ")", "{", "return", "h", "(", "'div'", ")", ";", "}", ",", "functional", ":", "true", "}", ",", "path", ":", "'/'", "+", "name", ".", "replace", "(", "/", "[^\\w]", "/", "g", ",", "\"-\"", ")", "}", ";", "}" ]
Stub a named route. @param {string} name the name of the route being stubbed @return {Array}
[ "Stub", "a", "named", "route", "." ]
9d0513ecbd7f56ab082ded01bb17a28ac4f72430
https://github.com/spyfu/spyfu-vue-factory/blob/9d0513ecbd7f56ab082ded01bb17a28ac4f72430/dist/spyfu-vue-factory.esm.js#L156-L167
train
spyfu/spyfu-vue-factory
dist/spyfu-vue-factory.esm.js
normalizeModules
function normalizeModules(modules) { var normalized = {}; Object.keys(modules).forEach(function (key) { var module = modules[key]; // make sure each vuex module has all keys defined normalized[key] = { actions: module.actions || {}, getters: module.getters || {}, modules: module.modules ? normalizeModules(module.modules) : {}, mutations: module.mutations || {}, namespaced: module.namespaced || false, state: {} }; // make sure our state is a fresh object if (typeof module.state === 'function') { normalized[key].state = module.state(); } else if (_typeof(module.state) === 'object') { normalized[key].state = JSON.parse(JSON.stringify(module.state)); } }); return normalized; }
javascript
function normalizeModules(modules) { var normalized = {}; Object.keys(modules).forEach(function (key) { var module = modules[key]; // make sure each vuex module has all keys defined normalized[key] = { actions: module.actions || {}, getters: module.getters || {}, modules: module.modules ? normalizeModules(module.modules) : {}, mutations: module.mutations || {}, namespaced: module.namespaced || false, state: {} }; // make sure our state is a fresh object if (typeof module.state === 'function') { normalized[key].state = module.state(); } else if (_typeof(module.state) === 'object') { normalized[key].state = JSON.parse(JSON.stringify(module.state)); } }); return normalized; }
[ "function", "normalizeModules", "(", "modules", ")", "{", "var", "normalized", "=", "{", "}", ";", "Object", ".", "keys", "(", "modules", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "module", "=", "modules", "[", "key", "]", ";", "normalized", "[", "key", "]", "=", "{", "actions", ":", "module", ".", "actions", "||", "{", "}", ",", "getters", ":", "module", ".", "getters", "||", "{", "}", ",", "modules", ":", "module", ".", "modules", "?", "normalizeModules", "(", "module", ".", "modules", ")", ":", "{", "}", ",", "mutations", ":", "module", ".", "mutations", "||", "{", "}", ",", "namespaced", ":", "module", ".", "namespaced", "||", "false", ",", "state", ":", "{", "}", "}", ";", "if", "(", "typeof", "module", ".", "state", "===", "'function'", ")", "{", "normalized", "[", "key", "]", ".", "state", "=", "module", ".", "state", "(", ")", ";", "}", "else", "if", "(", "_typeof", "(", "module", ".", "state", ")", "===", "'object'", ")", "{", "normalized", "[", "key", "]", ".", "state", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "module", ".", "state", ")", ")", ";", "}", "}", ")", ";", "return", "normalized", ";", "}" ]
helper function to evaluate the state functions of vuex modules
[ "helper", "function", "to", "evaluate", "the", "state", "functions", "of", "vuex", "modules" ]
9d0513ecbd7f56ab082ded01bb17a28ac4f72430
https://github.com/spyfu/spyfu-vue-factory/blob/9d0513ecbd7f56ab082ded01bb17a28ac4f72430/dist/spyfu-vue-factory.esm.js#L289-L314
train
spyfu/spyfu-vue-factory
dist/spyfu-vue-factory.esm.js
findModule
function findModule(store, namespace) { return namespace.split('/').reduce(function (obj, key) { // root modules will exist directly on the store if (obj && obj[key]) { return obj[key]; } // child stores will exist in a modules object if (obj && obj.modules && obj.modules[key]) { return obj.modules[key]; } // if we couldn't find the module, throw an error // istanbul ignore next throw new Error('Could not find module "' + namespace + '" in store.'); }, store); }
javascript
function findModule(store, namespace) { return namespace.split('/').reduce(function (obj, key) { // root modules will exist directly on the store if (obj && obj[key]) { return obj[key]; } // child stores will exist in a modules object if (obj && obj.modules && obj.modules[key]) { return obj.modules[key]; } // if we couldn't find the module, throw an error // istanbul ignore next throw new Error('Could not find module "' + namespace + '" in store.'); }, store); }
[ "function", "findModule", "(", "store", ",", "namespace", ")", "{", "return", "namespace", ".", "split", "(", "'/'", ")", ".", "reduce", "(", "function", "(", "obj", ",", "key", ")", "{", "if", "(", "obj", "&&", "obj", "[", "key", "]", ")", "{", "return", "obj", "[", "key", "]", ";", "}", "if", "(", "obj", "&&", "obj", ".", "modules", "&&", "obj", ".", "modules", "[", "key", "]", ")", "{", "return", "obj", ".", "modules", "[", "key", "]", ";", "}", "throw", "new", "Error", "(", "'Could not find module \"'", "+", "namespace", "+", "'\" in store.'", ")", ";", "}", ",", "store", ")", ";", "}" ]
helper to find vuex modules via their namespace
[ "helper", "to", "find", "vuex", "modules", "via", "their", "namespace" ]
9d0513ecbd7f56ab082ded01bb17a28ac4f72430
https://github.com/spyfu/spyfu-vue-factory/blob/9d0513ecbd7f56ab082ded01bb17a28ac4f72430/dist/spyfu-vue-factory.esm.js#L317-L333
train
express-bem/express-bem
lib/view-lookup.js
patchView
function patchView (ExpressView, opts) { var proto = ExpressView.prototype; function View (name, options) { options = options || {}; this.name = name; this.root = options.root; var engines = options.engines; this.defaultEngine = options.defaultEngine; var extensions = (typeof opts.extensions === 'function') ? opts.extensions() : opts.extensions; this.extensions = extensions; var ext = this.ext = extname(name, extensions); if (!ext && !this.defaultEngine) { throw Error('No default engine was specified and no extension was provided.'); } if (!ext) { name += (ext = this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine); } this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); this.path = this.lookup(name); } View.prototype = proto; function extname (name, extensions) { if (Array.isArray(extensions) && extensions.length > 0) { var ext; for (var i = 0, l = extensions.length; i < l; i += 1) { ext = extensions[i]; if (typeof name === 'string' && name.indexOf(ext) !== -1) { return ext; } } } return PATH.extname(name); } // replace original with new our own proto.lookup = createLookup(proto.lookup, opts); return View; }
javascript
function patchView (ExpressView, opts) { var proto = ExpressView.prototype; function View (name, options) { options = options || {}; this.name = name; this.root = options.root; var engines = options.engines; this.defaultEngine = options.defaultEngine; var extensions = (typeof opts.extensions === 'function') ? opts.extensions() : opts.extensions; this.extensions = extensions; var ext = this.ext = extname(name, extensions); if (!ext && !this.defaultEngine) { throw Error('No default engine was specified and no extension was provided.'); } if (!ext) { name += (ext = this.ext = (this.defaultEngine[0] !== '.' ? '.' : '') + this.defaultEngine); } this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); this.path = this.lookup(name); } View.prototype = proto; function extname (name, extensions) { if (Array.isArray(extensions) && extensions.length > 0) { var ext; for (var i = 0, l = extensions.length; i < l; i += 1) { ext = extensions[i]; if (typeof name === 'string' && name.indexOf(ext) !== -1) { return ext; } } } return PATH.extname(name); } // replace original with new our own proto.lookup = createLookup(proto.lookup, opts); return View; }
[ "function", "patchView", "(", "ExpressView", ",", "opts", ")", "{", "var", "proto", "=", "ExpressView", ".", "prototype", ";", "function", "View", "(", "name", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "name", "=", "name", ";", "this", ".", "root", "=", "options", ".", "root", ";", "var", "engines", "=", "options", ".", "engines", ";", "this", ".", "defaultEngine", "=", "options", ".", "defaultEngine", ";", "var", "extensions", "=", "(", "typeof", "opts", ".", "extensions", "===", "'function'", ")", "?", "opts", ".", "extensions", "(", ")", ":", "opts", ".", "extensions", ";", "this", ".", "extensions", "=", "extensions", ";", "var", "ext", "=", "this", ".", "ext", "=", "extname", "(", "name", ",", "extensions", ")", ";", "if", "(", "!", "ext", "&&", "!", "this", ".", "defaultEngine", ")", "{", "throw", "Error", "(", "'No default engine was specified and no extension was provided.'", ")", ";", "}", "if", "(", "!", "ext", ")", "{", "name", "+=", "(", "ext", "=", "this", ".", "ext", "=", "(", "this", ".", "defaultEngine", "[", "0", "]", "!==", "'.'", "?", "'.'", ":", "''", ")", "+", "this", ".", "defaultEngine", ")", ";", "}", "this", ".", "engine", "=", "engines", "[", "ext", "]", "||", "(", "engines", "[", "ext", "]", "=", "require", "(", "ext", ".", "slice", "(", "1", ")", ")", ".", "__express", ")", ";", "this", ".", "path", "=", "this", ".", "lookup", "(", "name", ")", ";", "}", "View", ".", "prototype", "=", "proto", ";", "function", "extname", "(", "name", ",", "extensions", ")", "{", "if", "(", "Array", ".", "isArray", "(", "extensions", ")", "&&", "extensions", ".", "length", ">", "0", ")", "{", "var", "ext", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "extensions", ".", "length", ";", "i", "<", "l", ";", "i", "+=", "1", ")", "{", "ext", "=", "extensions", "[", "i", "]", ";", "if", "(", "typeof", "name", "===", "'string'", "&&", "name", ".", "indexOf", "(", "ext", ")", "!==", "-", "1", ")", "{", "return", "ext", ";", "}", "}", "}", "return", "PATH", ".", "extname", "(", "name", ")", ";", "}", "proto", ".", "lookup", "=", "createLookup", "(", "proto", ".", "lookup", ",", "opts", ")", ";", "return", "View", ";", "}" ]
Patches express view to lookup in another directories @api @param {Function} ExpressView @param {{path: String, extensions: String[]|Function}} opts
[ "Patches", "express", "view", "to", "lookup", "in", "another", "directories" ]
6ea49e5ecdd8e949dd5051ecc5762e40cbcead9c
https://github.com/express-bem/express-bem/blob/6ea49e5ecdd8e949dd5051ecc5762e40cbcead9c/lib/view-lookup.js#L20-L59
train
ofzza/enTT
dist/ext/validation.js
ValidationExtension
function ValidationExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$reject = _ref.reject, reject = _ref$reject === undefined ? false : _ref$reject; _classCallCheck(this, ValidationExtension); // Store configuration var _this = _possibleConstructorReturn(this, (ValidationExtension.__proto__ || Object.getPrototypeOf(ValidationExtension)).call(this, { onEntityInstantiate: true, onChangeDetected: true })); _this.rejectInvalidValues = reject; return _this; }
javascript
function ValidationExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$reject = _ref.reject, reject = _ref$reject === undefined ? false : _ref$reject; _classCallCheck(this, ValidationExtension); // Store configuration var _this = _possibleConstructorReturn(this, (ValidationExtension.__proto__ || Object.getPrototypeOf(ValidationExtension)).call(this, { onEntityInstantiate: true, onChangeDetected: true })); _this.rejectInvalidValues = reject; return _this; }
[ "function", "ValidationExtension", "(", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ",", "_ref$reject", "=", "_ref", ".", "reject", ",", "reject", "=", "_ref$reject", "===", "undefined", "?", "false", ":", "_ref$reject", ";", "_classCallCheck", "(", "this", ",", "ValidationExtension", ")", ";", "var", "_this", "=", "_possibleConstructorReturn", "(", "this", ",", "(", "ValidationExtension", ".", "__proto__", "||", "Object", ".", "getPrototypeOf", "(", "ValidationExtension", ")", ")", ".", "call", "(", "this", ",", "{", "onEntityInstantiate", ":", "true", ",", "onChangeDetected", ":", "true", "}", ")", ")", ";", "_this", ".", "rejectInvalidValues", "=", "reject", ";", "return", "_this", ";", "}" ]
Creates an instance of ValidationExtension. @param {bool} reject If true, invalid values won't be assigned to the property @memberof ValidationExtension
[ "Creates", "an", "instance", "of", "ValidationExtension", "." ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/ext/validation.js#L48-L63
train
ofzza/enTT
dist/ext/validation.js
validateProperties
function validateProperties(entity, properties, changedPropertyName, changedPropertyValue, currentPropertyValue) { var _this2 = this; // Validate default property values _lodash2.default.forEach(properties, function (propertyConfiguration, propertyName) { if (isValidationProperty(propertyConfiguration)) { // Run validation function var validatedValue = propertyName !== changedPropertyName ? entity[propertyName] : changedPropertyValue, resetValue = propertyName !== changedPropertyName ? null : currentPropertyValue, validation = propertyConfiguration.validate(validatedValue, entity); // Check if validation successful if (validation === undefined) { // Reset validation error delete entity.validation[propertyName]; } else { // Store validation error entity.validation[propertyName] = new ValidationOutput({ property: propertyName, value: validatedValue, message: validation }); // If rejecting invalid values, reset value to current value if (_this2.rejectInvalidValues) { // Unset default value (wrap into EnTTBypassEverythingValue to bypass validation and watchers) entity[propertyName] = new _properties.EnTTBypassEverythingValue(resetValue); } } } }); }
javascript
function validateProperties(entity, properties, changedPropertyName, changedPropertyValue, currentPropertyValue) { var _this2 = this; // Validate default property values _lodash2.default.forEach(properties, function (propertyConfiguration, propertyName) { if (isValidationProperty(propertyConfiguration)) { // Run validation function var validatedValue = propertyName !== changedPropertyName ? entity[propertyName] : changedPropertyValue, resetValue = propertyName !== changedPropertyName ? null : currentPropertyValue, validation = propertyConfiguration.validate(validatedValue, entity); // Check if validation successful if (validation === undefined) { // Reset validation error delete entity.validation[propertyName]; } else { // Store validation error entity.validation[propertyName] = new ValidationOutput({ property: propertyName, value: validatedValue, message: validation }); // If rejecting invalid values, reset value to current value if (_this2.rejectInvalidValues) { // Unset default value (wrap into EnTTBypassEverythingValue to bypass validation and watchers) entity[propertyName] = new _properties.EnTTBypassEverythingValue(resetValue); } } } }); }
[ "function", "validateProperties", "(", "entity", ",", "properties", ",", "changedPropertyName", ",", "changedPropertyValue", ",", "currentPropertyValue", ")", "{", "var", "_this2", "=", "this", ";", "_lodash2", ".", "default", ".", "forEach", "(", "properties", ",", "function", "(", "propertyConfiguration", ",", "propertyName", ")", "{", "if", "(", "isValidationProperty", "(", "propertyConfiguration", ")", ")", "{", "var", "validatedValue", "=", "propertyName", "!==", "changedPropertyName", "?", "entity", "[", "propertyName", "]", ":", "changedPropertyValue", ",", "resetValue", "=", "propertyName", "!==", "changedPropertyName", "?", "null", ":", "currentPropertyValue", ",", "validation", "=", "propertyConfiguration", ".", "validate", "(", "validatedValue", ",", "entity", ")", ";", "if", "(", "validation", "===", "undefined", ")", "{", "delete", "entity", ".", "validation", "[", "propertyName", "]", ";", "}", "else", "{", "entity", ".", "validation", "[", "propertyName", "]", "=", "new", "ValidationOutput", "(", "{", "property", ":", "propertyName", ",", "value", ":", "validatedValue", ",", "message", ":", "validation", "}", ")", ";", "if", "(", "_this2", ".", "rejectInvalidValues", ")", "{", "entity", "[", "propertyName", "]", "=", "new", "_properties", ".", "EnTTBypassEverythingValue", "(", "resetValue", ")", ";", "}", "}", "}", "}", ")", ";", "}" ]
Performs property validation and outputs results to errors object @param {any} entity Entity instance @param {any} properties Entity's properties' configuration @param {any} changedPropertyName Name of the property being validated @param {any} changedPropertyValue Value being validated @param {any} currentPropertyValue Current property value
[ "Performs", "property", "validation", "and", "outputs", "results", "to", "errors", "object" ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/ext/validation.js#L136-L165
train
mongodb-js/precommit
index.js
resolve
function resolve(opts, done) { debug('resolving paths for globs:\n', JSON.stringify(opts.globs)); var tasks = opts.globs.map(function(pattern) { return function(cb) { debug('resolving `%s`...', pattern); glob(pattern, {}, function(err, files) { if (err) { return cb(err); } debug('resolved %d file(s) for `%s`', files.length, pattern); if (files.length > 0) { opts.files.push.apply(opts.files, files); } cb(); }); }; }); async.parallel(tasks, function(err) { if (err) { return done(err); } debug('checking and removing duplicate paths...'); opts.files = unique(opts.files); debug('final result has `%d` files', opts.files.length); done(null, opts.files); }); }
javascript
function resolve(opts, done) { debug('resolving paths for globs:\n', JSON.stringify(opts.globs)); var tasks = opts.globs.map(function(pattern) { return function(cb) { debug('resolving `%s`...', pattern); glob(pattern, {}, function(err, files) { if (err) { return cb(err); } debug('resolved %d file(s) for `%s`', files.length, pattern); if (files.length > 0) { opts.files.push.apply(opts.files, files); } cb(); }); }; }); async.parallel(tasks, function(err) { if (err) { return done(err); } debug('checking and removing duplicate paths...'); opts.files = unique(opts.files); debug('final result has `%d` files', opts.files.length); done(null, opts.files); }); }
[ "function", "resolve", "(", "opts", ",", "done", ")", "{", "debug", "(", "'resolving paths for globs:\\n'", ",", "\\n", ")", ";", "JSON", ".", "stringify", "(", "opts", ".", "globs", ")", "var", "tasks", "=", "opts", ".", "globs", ".", "map", "(", "function", "(", "pattern", ")", "{", "return", "function", "(", "cb", ")", "{", "debug", "(", "'resolving `%s`...'", ",", "pattern", ")", ";", "glob", "(", "pattern", ",", "{", "}", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "debug", "(", "'resolved %d file(s) for `%s`'", ",", "files", ".", "length", ",", "pattern", ")", ";", "if", "(", "files", ".", "length", ">", "0", ")", "{", "opts", ".", "files", ".", "push", ".", "apply", "(", "opts", ".", "files", ",", "files", ")", ";", "}", "cb", "(", ")", ";", "}", ")", ";", "}", ";", "}", ")", ";", "}" ]
Expand globs into paths. @param {Object} opts @param {Function} done
[ "Expand", "globs", "into", "paths", "." ]
28d7d6a972b57ce364aed6f21ba5d328199befff
https://github.com/mongodb-js/precommit/blob/28d7d6a972b57ce364aed6f21ba5d328199befff/index.js#L21-L47
train
onechiporenko/eslint-plugin-ember-cleanup
lib/utils/node.js
getPropertyNamesInParentObjectExpression
function getPropertyNamesInParentObjectExpression(node) { var objectExpression = obj.get(node, "parent.parent"); var ret = []; if (!objectExpression) { return ret; } objectExpression.properties.forEach(function (p) { if (p.value !== node) { ret.push(p.key.name); } }); return ret; }
javascript
function getPropertyNamesInParentObjectExpression(node) { var objectExpression = obj.get(node, "parent.parent"); var ret = []; if (!objectExpression) { return ret; } objectExpression.properties.forEach(function (p) { if (p.value !== node) { ret.push(p.key.name); } }); return ret; }
[ "function", "getPropertyNamesInParentObjectExpression", "(", "node", ")", "{", "var", "objectExpression", "=", "obj", ".", "get", "(", "node", ",", "\"parent.parent\"", ")", ";", "var", "ret", "=", "[", "]", ";", "if", "(", "!", "objectExpression", ")", "{", "return", "ret", ";", "}", "objectExpression", ".", "properties", ".", "forEach", "(", "function", "(", "p", ")", "{", "if", "(", "p", ".", "value", "!==", "node", ")", "{", "ret", ".", "push", "(", "p", ".", "key", ".", "name", ")", ";", "}", "}", ")", ";", "return", "ret", ";", "}" ]
Get list of all properties in the Object Expression node Object - is a "grand parent" for the provided node Result doesn't contain name of the `node` property @param {ASTNode} node @returns {string[]}
[ "Get", "list", "of", "all", "properties", "in", "the", "Object", "Expression", "node", "Object", "-", "is", "a", "grand", "parent", "for", "the", "provided", "node", "Result", "doesn", "t", "contain", "name", "of", "the", "node", "property" ]
83618c6ba242d6349f4d724d793bb6e05f057b88
https://github.com/onechiporenko/eslint-plugin-ember-cleanup/blob/83618c6ba242d6349f4d724d793bb6e05f057b88/lib/utils/node.js#L49-L61
train
yoshuawuyts/wayfarer-to-server
index.js
toServer
function toServer (router) { assert.equal(typeof router, 'function') const syms = getOwnSymbols(router) const sym = syms.length ? syms[0] : router._sym assert.ok(sym, 'router should be an instance of wayfarer') emit._subrouters = router._subrouters emit._routes = router._routes emit[sym] = true emit.emit = emit emit.on = on return emit // match a route and execute the corresponding callback // (obj, obj) -> null // original: {path, params parentDefault} function emit (route, req, res) { assert.equal(typeof route, 'string') assert.ok(req, 'no req specified') if (!req._ssa) { assert.ok(res, 'no res specified') } // handle server init if (isReq(req) && isRes(res)) { const ssa = createSsa({}, req, res) const dft = { node: { cb: [ router._default ] } } return router(route, ssa, dft) } // handle subrouter const params = req const parentDefault = res router(route, params, parentDefault) } // register a new route on a method // (str, obj) -> obj function on (route, methods) { assert.equal(typeof route, 'string') methods = methods || {} // mount subrouter if (methods[sym]) return router.on(route, methods) assert.equal(typeof methods, 'object') // mount http methods router.on(route, function (args) { demuxSsa(args, function (req, res, params) { const meth = methodist(req, defaultFn, methods) meth(req, res, params) // default function to call if methods don't match // null -> null function defaultFn () { router._default(args) } }) }) return emit } }
javascript
function toServer (router) { assert.equal(typeof router, 'function') const syms = getOwnSymbols(router) const sym = syms.length ? syms[0] : router._sym assert.ok(sym, 'router should be an instance of wayfarer') emit._subrouters = router._subrouters emit._routes = router._routes emit[sym] = true emit.emit = emit emit.on = on return emit // match a route and execute the corresponding callback // (obj, obj) -> null // original: {path, params parentDefault} function emit (route, req, res) { assert.equal(typeof route, 'string') assert.ok(req, 'no req specified') if (!req._ssa) { assert.ok(res, 'no res specified') } // handle server init if (isReq(req) && isRes(res)) { const ssa = createSsa({}, req, res) const dft = { node: { cb: [ router._default ] } } return router(route, ssa, dft) } // handle subrouter const params = req const parentDefault = res router(route, params, parentDefault) } // register a new route on a method // (str, obj) -> obj function on (route, methods) { assert.equal(typeof route, 'string') methods = methods || {} // mount subrouter if (methods[sym]) return router.on(route, methods) assert.equal(typeof methods, 'object') // mount http methods router.on(route, function (args) { demuxSsa(args, function (req, res, params) { const meth = methodist(req, defaultFn, methods) meth(req, res, params) // default function to call if methods don't match // null -> null function defaultFn () { router._default(args) } }) }) return emit } }
[ "function", "toServer", "(", "router", ")", "{", "assert", ".", "equal", "(", "typeof", "router", ",", "'function'", ")", "const", "syms", "=", "getOwnSymbols", "(", "router", ")", "const", "sym", "=", "syms", ".", "length", "?", "syms", "[", "0", "]", ":", "router", ".", "_sym", "assert", ".", "ok", "(", "sym", ",", "'router should be an instance of wayfarer'", ")", "emit", ".", "_subrouters", "=", "router", ".", "_subrouters", "emit", ".", "_routes", "=", "router", ".", "_routes", "emit", "[", "sym", "]", "=", "true", "emit", ".", "emit", "=", "emit", "emit", ".", "on", "=", "on", "return", "emit", "function", "emit", "(", "route", ",", "req", ",", "res", ")", "{", "assert", ".", "equal", "(", "typeof", "route", ",", "'string'", ")", "assert", ".", "ok", "(", "req", ",", "'no req specified'", ")", "if", "(", "!", "req", ".", "_ssa", ")", "{", "assert", ".", "ok", "(", "res", ",", "'no res specified'", ")", "}", "if", "(", "isReq", "(", "req", ")", "&&", "isRes", "(", "res", ")", ")", "{", "const", "ssa", "=", "createSsa", "(", "{", "}", ",", "req", ",", "res", ")", "const", "dft", "=", "{", "node", ":", "{", "cb", ":", "[", "router", ".", "_default", "]", "}", "}", "return", "router", "(", "route", ",", "ssa", ",", "dft", ")", "}", "const", "params", "=", "req", "const", "parentDefault", "=", "res", "router", "(", "route", ",", "params", ",", "parentDefault", ")", "}", "function", "on", "(", "route", ",", "methods", ")", "{", "assert", ".", "equal", "(", "typeof", "route", ",", "'string'", ")", "methods", "=", "methods", "||", "{", "}", "if", "(", "methods", "[", "sym", "]", ")", "return", "router", ".", "on", "(", "route", ",", "methods", ")", "assert", ".", "equal", "(", "typeof", "methods", ",", "'object'", ")", "router", ".", "on", "(", "route", ",", "function", "(", "args", ")", "{", "demuxSsa", "(", "args", ",", "function", "(", "req", ",", "res", ",", "params", ")", "{", "const", "meth", "=", "methodist", "(", "req", ",", "defaultFn", ",", "methods", ")", "meth", "(", "req", ",", "res", ",", "params", ")", "function", "defaultFn", "(", ")", "{", "router", ".", "_default", "(", "args", ")", "}", "}", ")", "}", ")", "return", "emit", "}", "}" ]
wrap req, res, wayfarer to create new server obj -> obj
[ "wrap", "req", "res", "wayfarer", "to", "create", "new", "server", "obj", "-", ">", "obj" ]
55df6e33111753e952b9655ac9ec8d38ad41c698
https://github.com/yoshuawuyts/wayfarer-to-server/blob/55df6e33111753e952b9655ac9ec8d38ad41c698/index.js#L12-L77
train
ply-ct/ply
lib/retrieval.js
function(location, name) { this.location = location; this.name = name; if (this.isUrl(location)) { if (this.name) this.name = require('sanitize-filename')(this.name, {replacement: '_'}); if (typeof window === 'undefined') this.request = require('request').defaults({headers: {'User-Agent': 'limberest'}}); else this.request = require('browser-request'); } else { this.storage = new Storage(this.location, this.name); } this.path = this.location; if (this.name) this.path += '/' + this.name; }
javascript
function(location, name) { this.location = location; this.name = name; if (this.isUrl(location)) { if (this.name) this.name = require('sanitize-filename')(this.name, {replacement: '_'}); if (typeof window === 'undefined') this.request = require('request').defaults({headers: {'User-Agent': 'limberest'}}); else this.request = require('browser-request'); } else { this.storage = new Storage(this.location, this.name); } this.path = this.location; if (this.name) this.path += '/' + this.name; }
[ "function", "(", "location", ",", "name", ")", "{", "this", ".", "location", "=", "location", ";", "this", ".", "name", "=", "name", ";", "if", "(", "this", ".", "isUrl", "(", "location", ")", ")", "{", "if", "(", "this", ".", "name", ")", "this", ".", "name", "=", "require", "(", "'sanitize-filename'", ")", "(", "this", ".", "name", ",", "{", "replacement", ":", "'_'", "}", ")", ";", "if", "(", "typeof", "window", "===", "'undefined'", ")", "this", ".", "request", "=", "require", "(", "'request'", ")", ".", "defaults", "(", "{", "headers", ":", "{", "'User-Agent'", ":", "'limberest'", "}", "}", ")", ";", "else", "this", ".", "request", "=", "require", "(", "'browser-request'", ")", ";", "}", "else", "{", "this", ".", "storage", "=", "new", "Storage", "(", "this", ".", "location", ",", "this", ".", "name", ")", ";", "}", "this", ".", "path", "=", "this", ".", "location", ";", "if", "(", "this", ".", "name", ")", "this", ".", "path", "+=", "'/'", "+", "this", ".", "name", ";", "}" ]
Abstraction that uses either URL retrieval or storage. name is optional
[ "Abstraction", "that", "uses", "either", "URL", "retrieval", "or", "storage", ".", "name", "is", "optional" ]
1d4146829845fedd917f5f0626cd74cc3845d0c8
https://github.com/ply-ct/ply/blob/1d4146829845fedd917f5f0626cd74cc3845d0c8/lib/retrieval.js#L8-L28
train
janus-toendering/options-parser
src/parser.js
function(opts, argv, error) { var parser = new Parser(opts, argv, error); return parser.parse(); }
javascript
function(opts, argv, error) { var parser = new Parser(opts, argv, error); return parser.parse(); }
[ "function", "(", "opts", ",", "argv", ",", "error", ")", "{", "var", "parser", "=", "new", "Parser", "(", "opts", ",", "argv", ",", "error", ")", ";", "return", "parser", ".", "parse", "(", ")", ";", "}" ]
Parses command-line arguments @param {object} opts @param {Array} argv argument array @param {Function} error callback handler for missing options etc (default: throw exception) @returns {{opt: {}, args: Array}}
[ "Parses", "command", "-", "line", "arguments" ]
f1e39aac203f26e7e4e67fadba63c8dce1c7d70e
https://github.com/janus-toendering/options-parser/blob/f1e39aac203f26e7e4e67fadba63c8dce1c7d70e/src/parser.js#L195-L199
train
cflynn07/power-radix
lib/index.js
PowerRadix
function PowerRadix (digits, sourceRadix) { sourceRadix = Array.isArray(sourceRadix) ? sourceRadix : B62.slice(0, sourceRadix); this._digits = Array.isArray(digits) ? digits : (digits+'').split(''); this._sourceRadixLength = new BigInt(sourceRadix.length+''); this._sourceRadixMap = sourceRadix.reduce(function (map, char, i) { map[char+''] = new BigInt(i+''); return map; }, {}); }
javascript
function PowerRadix (digits, sourceRadix) { sourceRadix = Array.isArray(sourceRadix) ? sourceRadix : B62.slice(0, sourceRadix); this._digits = Array.isArray(digits) ? digits : (digits+'').split(''); this._sourceRadixLength = new BigInt(sourceRadix.length+''); this._sourceRadixMap = sourceRadix.reduce(function (map, char, i) { map[char+''] = new BigInt(i+''); return map; }, {}); }
[ "function", "PowerRadix", "(", "digits", ",", "sourceRadix", ")", "{", "sourceRadix", "=", "Array", ".", "isArray", "(", "sourceRadix", ")", "?", "sourceRadix", ":", "B62", ".", "slice", "(", "0", ",", "sourceRadix", ")", ";", "this", ".", "_digits", "=", "Array", ".", "isArray", "(", "digits", ")", "?", "digits", ":", "(", "digits", "+", "''", ")", ".", "split", "(", "''", ")", ";", "this", ".", "_sourceRadixLength", "=", "new", "BigInt", "(", "sourceRadix", ".", "length", "+", "''", ")", ";", "this", ".", "_sourceRadixMap", "=", "sourceRadix", ".", "reduce", "(", "function", "(", "map", ",", "char", ",", "i", ")", "{", "map", "[", "char", "+", "''", "]", "=", "new", "BigInt", "(", "i", "+", "''", ")", ";", "return", "map", ";", "}", ",", "{", "}", ")", ";", "}" ]
Creates a new instance of PowerRadix @class @throws {InvalidArgumentException} @param {Array|String} digits @param {Array|Number} sourceRadix
[ "Creates", "a", "new", "instance", "of", "PowerRadix" ]
90a800fce273a8281ba3c784bde026826aab29ce
https://github.com/cflynn07/power-radix/blob/90a800fce273a8281ba3c784bde026826aab29ce/lib/index.js#L31-L39
train
quase/quasejs
.pnp.js
makeError
function makeError(code, message, data = {}) { const error = new Error(message); return Object.assign(error, {code, data}); }
javascript
function makeError(code, message, data = {}) { const error = new Error(message); return Object.assign(error, {code, data}); }
[ "function", "makeError", "(", "code", ",", "message", ",", "data", "=", "{", "}", ")", "{", "const", "error", "=", "new", "Error", "(", "message", ")", ";", "return", "Object", ".", "assign", "(", "error", ",", "{", "code", ",", "data", "}", ")", ";", "}" ]
Simple helper function that assign an error code to an error, so that it can more easily be caught and used by third-parties.
[ "Simple", "helper", "function", "that", "assign", "an", "error", "code", "to", "an", "error", "so", "that", "it", "can", "more", "easily", "be", "caught", "and", "used", "by", "third", "-", "parties", "." ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L54-L57
train
quase/quasejs
.pnp.js
getIssuerModule
function getIssuerModule(parent) { let issuer = parent; while (issuer && (issuer.id === '[eval]' || issuer.id === '<repl>' || !issuer.filename)) { issuer = issuer.parent; } return issuer; }
javascript
function getIssuerModule(parent) { let issuer = parent; while (issuer && (issuer.id === '[eval]' || issuer.id === '<repl>' || !issuer.filename)) { issuer = issuer.parent; } return issuer; }
[ "function", "getIssuerModule", "(", "parent", ")", "{", "let", "issuer", "=", "parent", ";", "while", "(", "issuer", "&&", "(", "issuer", ".", "id", "===", "'[eval]'", "||", "issuer", ".", "id", "===", "'<repl>'", "||", "!", "issuer", ".", "filename", ")", ")", "{", "issuer", "=", "issuer", ".", "parent", ";", "}", "return", "issuer", ";", "}" ]
Returns the module that should be used to resolve require calls. It's usually the direct parent, except if we're inside an eval expression.
[ "Returns", "the", "module", "that", "should", "be", "used", "to", "resolve", "require", "calls", ".", "It", "s", "usually", "the", "direct", "parent", "except", "if", "we", "re", "inside", "an", "eval", "expression", "." ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L12567-L12575
train
quase/quasejs
.pnp.js
applyNodeExtensionResolution
function applyNodeExtensionResolution(unqualifiedPath, {extensions}) { // We use this "infinite while" so that we can restart the process as long as we hit package folders while (true) { let stat; try { stat = statSync(unqualifiedPath); } catch (error) {} // If the file exists and is a file, we can stop right there if (stat && !stat.isDirectory()) { // If the very last component of the resolved path is a symlink to a file, we then resolve it to a file. We only // do this first the last component, and not the rest of the path! This allows us to support the case of bin // symlinks, where a symlink in "/xyz/pkg-name/.bin/bin-name" will point somewhere else (like "/xyz/pkg-name/index.js"). // In such a case, we want relative requires to be resolved relative to "/xyz/pkg-name/" rather than "/xyz/pkg-name/.bin/". // // Also note that the reason we must use readlink on the last component (instead of realpath on the whole path) // is that we must preserve the other symlinks, in particular those used by pnp to deambiguate packages using // peer dependencies. For example, "/xyz/.pnp/local/pnp-01234569/.bin/bin-name" should see its relative requires // be resolved relative to "/xyz/.pnp/local/pnp-0123456789/" rather than "/xyz/pkg-with-peers/", because otherwise // we would lose the information that would tell us what are the dependencies of pkg-with-peers relative to its // ancestors. if (lstatSync(unqualifiedPath).isSymbolicLink()) { unqualifiedPath = path.normalize(path.resolve(path.dirname(unqualifiedPath), readlinkSync(unqualifiedPath))); } return unqualifiedPath; } // If the file is a directory, we must check if it contains a package.json with a "main" entry if (stat && stat.isDirectory()) { let pkgJson; try { pkgJson = JSON.parse(readFileSync(`${unqualifiedPath}/package.json`, 'utf-8')); } catch (error) {} let nextUnqualifiedPath; if (pkgJson && pkgJson.main) { nextUnqualifiedPath = path.resolve(unqualifiedPath, pkgJson.main); } // If the "main" field changed the path, we start again from this new location if (nextUnqualifiedPath && nextUnqualifiedPath !== unqualifiedPath) { const resolution = applyNodeExtensionResolution(nextUnqualifiedPath, {extensions}); if (resolution !== null) { return resolution; } } } // Otherwise we check if we find a file that match one of the supported extensions const qualifiedPath = extensions .map(extension => { return `${unqualifiedPath}${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (qualifiedPath) { return qualifiedPath; } // Otherwise, we check if the path is a folder - in such a case, we try to use its index if (stat && stat.isDirectory()) { const indexPath = extensions .map(extension => { return `${unqualifiedPath}/index${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (indexPath) { return indexPath; } } // Otherwise there's nothing else we can do :( return null; } }
javascript
function applyNodeExtensionResolution(unqualifiedPath, {extensions}) { // We use this "infinite while" so that we can restart the process as long as we hit package folders while (true) { let stat; try { stat = statSync(unqualifiedPath); } catch (error) {} // If the file exists and is a file, we can stop right there if (stat && !stat.isDirectory()) { // If the very last component of the resolved path is a symlink to a file, we then resolve it to a file. We only // do this first the last component, and not the rest of the path! This allows us to support the case of bin // symlinks, where a symlink in "/xyz/pkg-name/.bin/bin-name" will point somewhere else (like "/xyz/pkg-name/index.js"). // In such a case, we want relative requires to be resolved relative to "/xyz/pkg-name/" rather than "/xyz/pkg-name/.bin/". // // Also note that the reason we must use readlink on the last component (instead of realpath on the whole path) // is that we must preserve the other symlinks, in particular those used by pnp to deambiguate packages using // peer dependencies. For example, "/xyz/.pnp/local/pnp-01234569/.bin/bin-name" should see its relative requires // be resolved relative to "/xyz/.pnp/local/pnp-0123456789/" rather than "/xyz/pkg-with-peers/", because otherwise // we would lose the information that would tell us what are the dependencies of pkg-with-peers relative to its // ancestors. if (lstatSync(unqualifiedPath).isSymbolicLink()) { unqualifiedPath = path.normalize(path.resolve(path.dirname(unqualifiedPath), readlinkSync(unqualifiedPath))); } return unqualifiedPath; } // If the file is a directory, we must check if it contains a package.json with a "main" entry if (stat && stat.isDirectory()) { let pkgJson; try { pkgJson = JSON.parse(readFileSync(`${unqualifiedPath}/package.json`, 'utf-8')); } catch (error) {} let nextUnqualifiedPath; if (pkgJson && pkgJson.main) { nextUnqualifiedPath = path.resolve(unqualifiedPath, pkgJson.main); } // If the "main" field changed the path, we start again from this new location if (nextUnqualifiedPath && nextUnqualifiedPath !== unqualifiedPath) { const resolution = applyNodeExtensionResolution(nextUnqualifiedPath, {extensions}); if (resolution !== null) { return resolution; } } } // Otherwise we check if we find a file that match one of the supported extensions const qualifiedPath = extensions .map(extension => { return `${unqualifiedPath}${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (qualifiedPath) { return qualifiedPath; } // Otherwise, we check if the path is a folder - in such a case, we try to use its index if (stat && stat.isDirectory()) { const indexPath = extensions .map(extension => { return `${unqualifiedPath}/index${extension}`; }) .find(candidateFile => { return existsSync(candidateFile); }); if (indexPath) { return indexPath; } } // Otherwise there's nothing else we can do :( return null; } }
[ "function", "applyNodeExtensionResolution", "(", "unqualifiedPath", ",", "{", "extensions", "}", ")", "{", "while", "(", "true", ")", "{", "let", "stat", ";", "try", "{", "stat", "=", "statSync", "(", "unqualifiedPath", ")", ";", "}", "catch", "(", "error", ")", "{", "}", "if", "(", "stat", "&&", "!", "stat", ".", "isDirectory", "(", ")", ")", "{", "if", "(", "lstatSync", "(", "unqualifiedPath", ")", ".", "isSymbolicLink", "(", ")", ")", "{", "unqualifiedPath", "=", "path", ".", "normalize", "(", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "unqualifiedPath", ")", ",", "readlinkSync", "(", "unqualifiedPath", ")", ")", ")", ";", "}", "return", "unqualifiedPath", ";", "}", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "let", "pkgJson", ";", "try", "{", "pkgJson", "=", "JSON", ".", "parse", "(", "readFileSync", "(", "`", "${", "unqualifiedPath", "}", "`", ",", "'utf-8'", ")", ")", ";", "}", "catch", "(", "error", ")", "{", "}", "let", "nextUnqualifiedPath", ";", "if", "(", "pkgJson", "&&", "pkgJson", ".", "main", ")", "{", "nextUnqualifiedPath", "=", "path", ".", "resolve", "(", "unqualifiedPath", ",", "pkgJson", ".", "main", ")", ";", "}", "if", "(", "nextUnqualifiedPath", "&&", "nextUnqualifiedPath", "!==", "unqualifiedPath", ")", "{", "const", "resolution", "=", "applyNodeExtensionResolution", "(", "nextUnqualifiedPath", ",", "{", "extensions", "}", ")", ";", "if", "(", "resolution", "!==", "null", ")", "{", "return", "resolution", ";", "}", "}", "}", "const", "qualifiedPath", "=", "extensions", ".", "map", "(", "extension", "=>", "{", "return", "`", "${", "unqualifiedPath", "}", "${", "extension", "}", "`", ";", "}", ")", ".", "find", "(", "candidateFile", "=>", "{", "return", "existsSync", "(", "candidateFile", ")", ";", "}", ")", ";", "if", "(", "qualifiedPath", ")", "{", "return", "qualifiedPath", ";", "}", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "const", "indexPath", "=", "extensions", ".", "map", "(", "extension", "=>", "{", "return", "`", "${", "unqualifiedPath", "}", "${", "extension", "}", "`", ";", "}", ")", ".", "find", "(", "candidateFile", "=>", "{", "return", "existsSync", "(", "candidateFile", ")", ";", "}", ")", ";", "if", "(", "indexPath", ")", "{", "return", "indexPath", ";", "}", "}", "return", "null", ";", "}", "}" ]
Implements the node resolution for folder access and extension selection
[ "Implements", "the", "node", "resolution", "for", "folder", "access", "and", "extension", "selection" ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L12598-L12689
train
quase/quasejs
.pnp.js
normalizePath
function normalizePath(fsPath) { fsPath = path.normalize(fsPath); if (process.platform === 'win32') { fsPath = fsPath.replace(backwardSlashRegExp, '/'); } return fsPath; }
javascript
function normalizePath(fsPath) { fsPath = path.normalize(fsPath); if (process.platform === 'win32') { fsPath = fsPath.replace(backwardSlashRegExp, '/'); } return fsPath; }
[ "function", "normalizePath", "(", "fsPath", ")", "{", "fsPath", "=", "path", ".", "normalize", "(", "fsPath", ")", ";", "if", "(", "process", ".", "platform", "===", "'win32'", ")", "{", "fsPath", "=", "fsPath", ".", "replace", "(", "backwardSlashRegExp", ",", "'/'", ")", ";", "}", "return", "fsPath", ";", "}" ]
Normalize path to posix format.
[ "Normalize", "path", "to", "posix", "format", "." ]
a8f46d6648db13abf30bbb4800fe63b25e49e1b3
https://github.com/quase/quasejs/blob/a8f46d6648db13abf30bbb4800fe63b25e49e1b3/.pnp.js#L12711-L12719
train
intesso/connect-locale
server.js
cleanupArray
function cleanupArray(obj, name) { var arr = obj[name]; if (!arr) throw new Error(name + ' option is missing'); if (Array.isArray(arr)) { arr = arr.join(','); } if (typeof arr !== 'string') throw new Error(name + ' option must be an Array or a comma separated String'); arr = arr.replace(/_/g, '-').replace(/\s/g, '').toLowerCase().split(','); return arr; }
javascript
function cleanupArray(obj, name) { var arr = obj[name]; if (!arr) throw new Error(name + ' option is missing'); if (Array.isArray(arr)) { arr = arr.join(','); } if (typeof arr !== 'string') throw new Error(name + ' option must be an Array or a comma separated String'); arr = arr.replace(/_/g, '-').replace(/\s/g, '').toLowerCase().split(','); return arr; }
[ "function", "cleanupArray", "(", "obj", ",", "name", ")", "{", "var", "arr", "=", "obj", "[", "name", "]", ";", "if", "(", "!", "arr", ")", "throw", "new", "Error", "(", "name", "+", "' option is missing'", ")", ";", "if", "(", "Array", ".", "isArray", "(", "arr", ")", ")", "{", "arr", "=", "arr", ".", "join", "(", "','", ")", ";", "}", "if", "(", "typeof", "arr", "!==", "'string'", ")", "throw", "new", "Error", "(", "name", "+", "' option must be an Array or a comma separated String'", ")", ";", "arr", "=", "arr", ".", "replace", "(", "/", "_", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "\\s", "/", "g", ",", "''", ")", ".", "toLowerCase", "(", ")", ".", "split", "(", "','", ")", ";", "return", "arr", ";", "}" ]
helper function to trim, lowerCase the comma separated string or array
[ "helper", "function", "to", "trim", "lowerCase", "the", "comma", "separated", "string", "or", "array" ]
87e08bfe30f98b7cac8333f86cddecfb7161d67e
https://github.com/intesso/connect-locale/blob/87e08bfe30f98b7cac8333f86cddecfb7161d67e/server.js#L51-L60
train
intesso/connect-locale
server.js
matchLocale
function matchLocale(locale) { var found = false; if (!locale) return false; locale = locale.replace(/_/g, '-').toLowerCase(); if (localesLookup[locale]) return localesLookup[locale]; if (options.matchSubTags) { while (~locale.indexOf('-')) { var index = locale.lastIndexOf('-'); locale = locale.substring(0, index); if (localesLookup[locale]) { found = localesLookup[locale]; break; } } } return found; }
javascript
function matchLocale(locale) { var found = false; if (!locale) return false; locale = locale.replace(/_/g, '-').toLowerCase(); if (localesLookup[locale]) return localesLookup[locale]; if (options.matchSubTags) { while (~locale.indexOf('-')) { var index = locale.lastIndexOf('-'); locale = locale.substring(0, index); if (localesLookup[locale]) { found = localesLookup[locale]; break; } } } return found; }
[ "function", "matchLocale", "(", "locale", ")", "{", "var", "found", "=", "false", ";", "if", "(", "!", "locale", ")", "return", "false", ";", "locale", "=", "locale", ".", "replace", "(", "/", "_", "/", "g", ",", "'-'", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "localesLookup", "[", "locale", "]", ")", "return", "localesLookup", "[", "locale", "]", ";", "if", "(", "options", ".", "matchSubTags", ")", "{", "while", "(", "~", "locale", ".", "indexOf", "(", "'-'", ")", ")", "{", "var", "index", "=", "locale", ".", "lastIndexOf", "(", "'-'", ")", ";", "locale", "=", "locale", ".", "substring", "(", "0", ",", "index", ")", ";", "if", "(", "localesLookup", "[", "locale", "]", ")", "{", "found", "=", "localesLookup", "[", "locale", "]", ";", "break", ";", "}", "}", "}", "return", "found", ";", "}" ]
helper function to detect locale or sublocale
[ "helper", "function", "to", "detect", "locale", "or", "sublocale" ]
87e08bfe30f98b7cac8333f86cddecfb7161d67e
https://github.com/intesso/connect-locale/blob/87e08bfe30f98b7cac8333f86cddecfb7161d67e/server.js#L64-L80
train
crcn/bindable.js
lib/collection/index.js
BindableCollection
function BindableCollection (source) { BindableObject.call(this, this); this.source = source || []; this._updateInfo(); this.bind("source", _.bind(this._onSourceChange, this)); }
javascript
function BindableCollection (source) { BindableObject.call(this, this); this.source = source || []; this._updateInfo(); this.bind("source", _.bind(this._onSourceChange, this)); }
[ "function", "BindableCollection", "(", "source", ")", "{", "BindableObject", ".", "call", "(", "this", ",", "this", ")", ";", "this", ".", "source", "=", "source", "||", "[", "]", ";", "this", ".", "_updateInfo", "(", ")", ";", "this", ".", "bind", "(", "\"source\"", ",", "_", ".", "bind", "(", "this", ".", "_onSourceChange", ",", "this", ")", ")", ";", "}" ]
Emitted when an item is removed @event remove @param {Object} item removed Emitted when items are replaced @event replace @param {Array} newItems @param {Array} oldItems
[ "Emitted", "when", "an", "item", "is", "removed" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L39-L44
train
crcn/bindable.js
lib/collection/index.js
function () { var items = Array.prototype.slice.call(arguments); this.source.push.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], this.length - 1); this.emit("update", { insert: items, index: this.length - 1}); }
javascript
function () { var items = Array.prototype.slice.call(arguments); this.source.push.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], this.length - 1); this.emit("update", { insert: items, index: this.length - 1}); }
[ "function", "(", ")", "{", "var", "items", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "this", ".", "source", ".", "push", ".", "apply", "(", "this", ".", "source", ",", "items", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "this", ".", "emit", "(", "\"insert\"", ",", "items", "[", "0", "]", ",", "this", ".", "length", "-", "1", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "insert", ":", "items", ",", "index", ":", "this", ".", "length", "-", "1", "}", ")", ";", "}" ]
Pushes an item onto the collection @method push @param {Object} item
[ "Pushes", "an", "item", "onto", "the", "collection" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L142-L150
train
crcn/bindable.js
lib/collection/index.js
function () { var items = Array.prototype.slice.call(arguments); this.source.unshift.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], 0); this.emit("update", { insert: items }); }
javascript
function () { var items = Array.prototype.slice.call(arguments); this.source.unshift.apply(this.source, items); this._updateInfo(); // DEPRECATED this.emit("insert", items[0], 0); this.emit("update", { insert: items }); }
[ "function", "(", ")", "{", "var", "items", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "this", ".", "source", ".", "unshift", ".", "apply", "(", "this", ".", "source", ",", "items", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "this", ".", "emit", "(", "\"insert\"", ",", "items", "[", "0", "]", ",", "0", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "insert", ":", "items", "}", ")", ";", "}" ]
Unshifts an item onto the collection @method unshift @param {Object} item
[ "Unshifts", "an", "item", "onto", "the", "collection" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L158-L167
train
crcn/bindable.js
lib/collection/index.js
function (index, count) { var newItems = Array.prototype.slice.call(arguments, 2), oldItems = this.source.splice.apply(this.source, arguments); this._updateInfo(); // DEPRECATED this.emit("replace", newItems, oldItems, index); this.emit("update", { insert: newItems, remove: oldItems }); }
javascript
function (index, count) { var newItems = Array.prototype.slice.call(arguments, 2), oldItems = this.source.splice.apply(this.source, arguments); this._updateInfo(); // DEPRECATED this.emit("replace", newItems, oldItems, index); this.emit("update", { insert: newItems, remove: oldItems }); }
[ "function", "(", "index", ",", "count", ")", "{", "var", "newItems", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ",", "oldItems", "=", "this", ".", "source", ".", "splice", ".", "apply", "(", "this", ".", "source", ",", "arguments", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "this", ".", "emit", "(", "\"replace\"", ",", "newItems", ",", "oldItems", ",", "index", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "insert", ":", "newItems", ",", "remove", ":", "oldItems", "}", ")", ";", "}" ]
Removes N Number of items @method splice @param {Number} index start index @param {Number} count number of items to remove
[ "Removes", "N", "Number", "of", "items" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L176-L185
train
crcn/bindable.js
lib/collection/index.js
function (item) { var i = this.indexOf(item); if (!~i) return false; this.source.splice(i, 1); this._updateInfo(); this.emit("remove", item, i); this.emit("update", { remove: [item] }); return item; }
javascript
function (item) { var i = this.indexOf(item); if (!~i) return false; this.source.splice(i, 1); this._updateInfo(); this.emit("remove", item, i); this.emit("update", { remove: [item] }); return item; }
[ "function", "(", "item", ")", "{", "var", "i", "=", "this", ".", "indexOf", "(", "item", ")", ";", "if", "(", "!", "~", "i", ")", "return", "false", ";", "this", ".", "source", ".", "splice", "(", "i", ",", "1", ")", ";", "this", ".", "_updateInfo", "(", ")", ";", "this", ".", "emit", "(", "\"remove\"", ",", "item", ",", "i", ")", ";", "this", ".", "emit", "(", "\"update\"", ",", "{", "remove", ":", "[", "item", "]", "}", ")", ";", "return", "item", ";", "}" ]
Removes an item from the collection @method remove @param {Object} item item to remove
[ "Removes", "an", "item", "from", "the", "collection" ]
562dcd4a0e208e2a11ac7613654b32b01c7d92ac
https://github.com/crcn/bindable.js/blob/562dcd4a0e208e2a11ac7613654b32b01c7d92ac/lib/collection/index.js#L193-L202
train
techninja/robopaint-mode-example
example.js
paperLoadedInit
function paperLoadedInit() { console.log('Paper ready!'); // Set center adjusters based on size of canvas $('#hcenter').attr({ value: 0, min: -(robopaint.canvas.width / 2), max: robopaint.canvas.width / 2 }); $('#vcenter').attr({ value: 0, min: -(robopaint.canvas.height / 2), max: robopaint.canvas.height / 2 }); $(window).resize(); // Use mode settings management on all "managed" class items. This // saves/loads settings from/into the elements on change/init. mode.settings.$manage('.managed'); // With Paper ready, send a single up to fill values for buffer & pen. mode.run('up'); }
javascript
function paperLoadedInit() { console.log('Paper ready!'); // Set center adjusters based on size of canvas $('#hcenter').attr({ value: 0, min: -(robopaint.canvas.width / 2), max: robopaint.canvas.width / 2 }); $('#vcenter').attr({ value: 0, min: -(robopaint.canvas.height / 2), max: robopaint.canvas.height / 2 }); $(window).resize(); // Use mode settings management on all "managed" class items. This // saves/loads settings from/into the elements on change/init. mode.settings.$manage('.managed'); // With Paper ready, send a single up to fill values for buffer & pen. mode.run('up'); }
[ "function", "paperLoadedInit", "(", ")", "{", "console", ".", "log", "(", "'Paper ready!'", ")", ";", "$", "(", "'#hcenter'", ")", ".", "attr", "(", "{", "value", ":", "0", ",", "min", ":", "-", "(", "robopaint", ".", "canvas", ".", "width", "/", "2", ")", ",", "max", ":", "robopaint", ".", "canvas", ".", "width", "/", "2", "}", ")", ";", "$", "(", "'#vcenter'", ")", ".", "attr", "(", "{", "value", ":", "0", ",", "min", ":", "-", "(", "robopaint", ".", "canvas", ".", "height", "/", "2", ")", ",", "max", ":", "robopaint", ".", "canvas", ".", "height", "/", "2", "}", ")", ";", "$", "(", "window", ")", ".", "resize", "(", ")", ";", "mode", ".", "settings", ".", "$manage", "(", "'.managed'", ")", ";", "mode", ".", "run", "(", "'up'", ")", ";", "}" ]
Callback that tells us that our Paper.js canvas is ready!
[ "Callback", "that", "tells", "us", "that", "our", "Paper", ".", "js", "canvas", "is", "ready!" ]
9af42cbe3e27f404185b812c0a91d8a354ba970b
https://github.com/techninja/robopaint-mode-example/blob/9af42cbe3e27f404185b812c0a91d8a354ba970b/example.js#L36-L60
train
smbape/node-umd-builder
lib/appenders/file.js
fileAppender
function fileAppender(config, layout) { const appender = new FileAppender(config, layout); // push file to the stack of open handlers appenderList.push(appender); return appender.write; }
javascript
function fileAppender(config, layout) { const appender = new FileAppender(config, layout); // push file to the stack of open handlers appenderList.push(appender); return appender.write; }
[ "function", "fileAppender", "(", "config", ",", "layout", ")", "{", "const", "appender", "=", "new", "FileAppender", "(", "config", ",", "layout", ")", ";", "appenderList", ".", "push", "(", "appender", ")", ";", "return", "appender", ".", "write", ";", "}" ]
File Appender writing the logs to a text file. Supports rolling of logs by size. @param file file log messages will be written to @param layout a function that takes a logevent and returns a string * (defaults to basicLayout). @param logSize - the maximum size (in bytes) for a log file, * if not provided then logs won't be rotated. @param numBackups - the number of log files to keep after logSize * has been reached (default 5) @param compress - flag that controls log file compression @param timezoneOffset - optional timezone offset in minutes (default system local) @param stripAnsi - flag that controls if ansi should be strip (default true)
[ "File", "Appender", "writing", "the", "logs", "to", "a", "text", "file", ".", "Supports", "rolling", "of", "logs", "by", "size", "." ]
73b03e8c985f2660948f5df71140e4a8fb162549
https://github.com/smbape/node-umd-builder/blob/73b03e8c985f2660948f5df71140e4a8fb162549/lib/appenders/file.js#L29-L36
train
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function (widgets) { if (!this.storage) { return true; } var serialized = _.map(widgets, function (widget) { var widgetObject = { title: widget.title, name: widget.name, style: widget.style, dataModelOptions: widget.dataModelOptions, storageHash: widget.storageHash, attrs: widget.attrs }; return widgetObject; }); var item = { widgets: serialized, hash: this.hash }; if (this.stringify) { item = JSON.stringify(item); } this.storage.setItem(this.id, item); return true; }
javascript
function (widgets) { if (!this.storage) { return true; } var serialized = _.map(widgets, function (widget) { var widgetObject = { title: widget.title, name: widget.name, style: widget.style, dataModelOptions: widget.dataModelOptions, storageHash: widget.storageHash, attrs: widget.attrs }; return widgetObject; }); var item = { widgets: serialized, hash: this.hash }; if (this.stringify) { item = JSON.stringify(item); } this.storage.setItem(this.id, item); return true; }
[ "function", "(", "widgets", ")", "{", "if", "(", "!", "this", ".", "storage", ")", "{", "return", "true", ";", "}", "var", "serialized", "=", "_", ".", "map", "(", "widgets", ",", "function", "(", "widget", ")", "{", "var", "widgetObject", "=", "{", "title", ":", "widget", ".", "title", ",", "name", ":", "widget", ".", "name", ",", "style", ":", "widget", ".", "style", ",", "dataModelOptions", ":", "widget", ".", "dataModelOptions", ",", "storageHash", ":", "widget", ".", "storageHash", ",", "attrs", ":", "widget", ".", "attrs", "}", ";", "return", "widgetObject", ";", "}", ")", ";", "var", "item", "=", "{", "widgets", ":", "serialized", ",", "hash", ":", "this", ".", "hash", "}", ";", "if", "(", "this", ".", "stringify", ")", "{", "item", "=", "JSON", ".", "stringify", "(", "item", ")", ";", "}", "this", ".", "storage", ".", "setItem", "(", "this", ".", "id", ",", "item", ")", ";", "return", "true", ";", "}" ]
Takes array of widget instance objects, serializes, and saves state. @param {Array} widgets scope.widgets from dashboard directive @return {Boolean} true on success, false on failure
[ "Takes", "array", "of", "widget", "instance", "objects", "serializes", "and", "saves", "state", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L786-L813
train
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function () { if (!this.storage) { return null; } var serialized; // try loading storage item serialized = this.storage.getItem(this.id); if (serialized) { // check for promise if (typeof serialized === 'object' && typeof serialized.then === 'function') { return this._handleAsyncLoad(serialized); } // otherwise handle synchronous load return this._handleSyncLoad(serialized); } else { return null; } }
javascript
function () { if (!this.storage) { return null; } var serialized; // try loading storage item serialized = this.storage.getItem(this.id); if (serialized) { // check for promise if (typeof serialized === 'object' && typeof serialized.then === 'function') { return this._handleAsyncLoad(serialized); } // otherwise handle synchronous load return this._handleSyncLoad(serialized); } else { return null; } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "storage", ")", "{", "return", "null", ";", "}", "var", "serialized", ";", "serialized", "=", "this", ".", "storage", ".", "getItem", "(", "this", ".", "id", ")", ";", "if", "(", "serialized", ")", "{", "if", "(", "typeof", "serialized", "===", "'object'", "&&", "typeof", "serialized", ".", "then", "===", "'function'", ")", "{", "return", "this", ".", "_handleAsyncLoad", "(", "serialized", ")", ";", "}", "return", "this", ".", "_handleSyncLoad", "(", "serialized", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Loads dashboard state from the storage object. Can handle a synchronous response or a promise. @return {Array|Promise} Array of widget definitions or a promise
[ "Loads", "dashboard", "state", "from", "the", "storage", "object", ".", "Can", "handle", "a", "synchronous", "response", "or", "a", "promise", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L821-L842
train
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
WidgetModel
function WidgetModel(Class, overrides) { var defaults = { title: 'Widget', name: Class.name, attrs: Class.attrs, dataAttrName: Class.dataAttrName, dataModelType: Class.dataModelType, dataModelArgs: Class.dataModelArgs, // used in data model constructor, not serialized //AW Need deep copy of options to support widget options editing dataModelOptions: Class.dataModelOptions, settingsModalOptions: Class.settingsModalOptions, onSettingsClose: Class.onSettingsClose, onSettingsDismiss: Class.onSettingsDismiss, style: Class.style }; overrides = overrides || {}; angular.extend(this, angular.copy(defaults), overrides); this.style = this.style || { width: '33%' }; this.setWidth(this.style.width); if (Class.templateUrl) { this.templateUrl = Class.templateUrl; } else if (Class.template) { this.template = Class.template; } else { var directive = Class.directive || Class.name; this.directive = directive; } }
javascript
function WidgetModel(Class, overrides) { var defaults = { title: 'Widget', name: Class.name, attrs: Class.attrs, dataAttrName: Class.dataAttrName, dataModelType: Class.dataModelType, dataModelArgs: Class.dataModelArgs, // used in data model constructor, not serialized //AW Need deep copy of options to support widget options editing dataModelOptions: Class.dataModelOptions, settingsModalOptions: Class.settingsModalOptions, onSettingsClose: Class.onSettingsClose, onSettingsDismiss: Class.onSettingsDismiss, style: Class.style }; overrides = overrides || {}; angular.extend(this, angular.copy(defaults), overrides); this.style = this.style || { width: '33%' }; this.setWidth(this.style.width); if (Class.templateUrl) { this.templateUrl = Class.templateUrl; } else if (Class.template) { this.template = Class.template; } else { var directive = Class.directive || Class.name; this.directive = directive; } }
[ "function", "WidgetModel", "(", "Class", ",", "overrides", ")", "{", "var", "defaults", "=", "{", "title", ":", "'Widget'", ",", "name", ":", "Class", ".", "name", ",", "attrs", ":", "Class", ".", "attrs", ",", "dataAttrName", ":", "Class", ".", "dataAttrName", ",", "dataModelType", ":", "Class", ".", "dataModelType", ",", "dataModelArgs", ":", "Class", ".", "dataModelArgs", ",", "dataModelOptions", ":", "Class", ".", "dataModelOptions", ",", "settingsModalOptions", ":", "Class", ".", "settingsModalOptions", ",", "onSettingsClose", ":", "Class", ".", "onSettingsClose", ",", "onSettingsDismiss", ":", "Class", ".", "onSettingsDismiss", ",", "style", ":", "Class", ".", "style", "}", ";", "overrides", "=", "overrides", "||", "{", "}", ";", "angular", ".", "extend", "(", "this", ",", "angular", ".", "copy", "(", "defaults", ")", ",", "overrides", ")", ";", "this", ".", "style", "=", "this", ".", "style", "||", "{", "width", ":", "'33%'", "}", ";", "this", ".", "setWidth", "(", "this", ".", "style", ".", "width", ")", ";", "if", "(", "Class", ".", "templateUrl", ")", "{", "this", ".", "templateUrl", "=", "Class", ".", "templateUrl", ";", "}", "else", "if", "(", "Class", ".", "template", ")", "{", "this", ".", "template", "=", "Class", ".", "template", ";", "}", "else", "{", "var", "directive", "=", "Class", ".", "directive", "||", "Class", ".", "name", ";", "this", ".", "directive", "=", "directive", ";", "}", "}" ]
constructor for widget model instances
[ "constructor", "for", "widget", "model", "instances" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L1044-L1072
train
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function (e) { var curX = e.clientX; var pixelChange = curX - initX; var newWidth = pixelWidth + pixelChange; $marquee.css('width', newWidth + 'px'); }
javascript
function (e) { var curX = e.clientX; var pixelChange = curX - initX; var newWidth = pixelWidth + pixelChange; $marquee.css('width', newWidth + 'px'); }
[ "function", "(", "e", ")", "{", "var", "curX", "=", "e", ".", "clientX", ";", "var", "pixelChange", "=", "curX", "-", "initX", ";", "var", "newWidth", "=", "pixelWidth", "+", "pixelChange", ";", "$marquee", ".", "css", "(", "'width'", ",", "newWidth", "+", "'px'", ")", ";", "}" ]
updates marquee with preview of new width
[ "updates", "marquee", "with", "preview", "of", "new", "width" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L1234-L1239
train
S3bb1/ah-dashboard-plugin
public/dashboard/app/angular-ui-dashboard.js
function (e) { // remove listener and marquee jQuery($window).off('mousemove', mousemove); $marquee.remove(); // calculate change in units var curX = e.clientX; var pixelChange = curX - initX; var unitChange = Math.round(pixelChange * transformMultiplier * 100) / 100; // add to initial unit width var newWidth = unitWidth * 1 + unitChange; widget.setWidth(newWidth + widthUnits); $scope.$emit('widgetChanged', widget); $scope.$apply(); }
javascript
function (e) { // remove listener and marquee jQuery($window).off('mousemove', mousemove); $marquee.remove(); // calculate change in units var curX = e.clientX; var pixelChange = curX - initX; var unitChange = Math.round(pixelChange * transformMultiplier * 100) / 100; // add to initial unit width var newWidth = unitWidth * 1 + unitChange; widget.setWidth(newWidth + widthUnits); $scope.$emit('widgetChanged', widget); $scope.$apply(); }
[ "function", "(", "e", ")", "{", "jQuery", "(", "$window", ")", ".", "off", "(", "'mousemove'", ",", "mousemove", ")", ";", "$marquee", ".", "remove", "(", ")", ";", "var", "curX", "=", "e", ".", "clientX", ";", "var", "pixelChange", "=", "curX", "-", "initX", ";", "var", "unitChange", "=", "Math", ".", "round", "(", "pixelChange", "*", "transformMultiplier", "*", "100", ")", "/", "100", ";", "var", "newWidth", "=", "unitWidth", "*", "1", "+", "unitChange", ";", "widget", ".", "setWidth", "(", "newWidth", "+", "widthUnits", ")", ";", "$scope", ".", "$emit", "(", "'widgetChanged'", ",", "widget", ")", ";", "$scope", ".", "$apply", "(", ")", ";", "}" ]
sets new widget width on mouseup
[ "sets", "new", "widget", "width", "on", "mouseup" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/app/angular-ui-dashboard.js#L1242-L1257
train
techninja/robopaint-mode-example
example.ps.js
onMouseMove
function onMouseMove(event) { project.deselectAll(); if (event.item) { event.item.selected = true; } }
javascript
function onMouseMove(event) { project.deselectAll(); if (event.item) { event.item.selected = true; } }
[ "function", "onMouseMove", "(", "event", ")", "{", "project", ".", "deselectAll", "(", ")", ";", "if", "(", "event", ".", "item", ")", "{", "event", ".", "item", ".", "selected", "=", "true", ";", "}", "}" ]
Show preview paths
[ "Show", "preview", "paths" ]
9af42cbe3e27f404185b812c0a91d8a354ba970b
https://github.com/techninja/robopaint-mode-example/blob/9af42cbe3e27f404185b812c0a91d8a354ba970b/example.ps.js#L24-L30
train
bigpipe/backtrace
index.js
Stack
function Stack(trace, options) { if (!(this instanceof Stack)) return new Stack(trace, options); if ('object' === typeof trace && !trace.length) { options = trace; trace = null; } options = options || {}; options.guess = 'guess' in options ? options.guess : true; if (!trace) { var imp = new stacktrace.implementation() , err = options.error || options.err || options.e , traced; traced = imp.run(err); trace = options.guess ? imp.guessAnonymousFunctions(traced) : traced; } this.traces = this.parse(trace); }
javascript
function Stack(trace, options) { if (!(this instanceof Stack)) return new Stack(trace, options); if ('object' === typeof trace && !trace.length) { options = trace; trace = null; } options = options || {}; options.guess = 'guess' in options ? options.guess : true; if (!trace) { var imp = new stacktrace.implementation() , err = options.error || options.err || options.e , traced; traced = imp.run(err); trace = options.guess ? imp.guessAnonymousFunctions(traced) : traced; } this.traces = this.parse(trace); }
[ "function", "Stack", "(", "trace", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Stack", ")", ")", "return", "new", "Stack", "(", "trace", ",", "options", ")", ";", "if", "(", "'object'", "===", "typeof", "trace", "&&", "!", "trace", ".", "length", ")", "{", "options", "=", "trace", ";", "trace", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "options", ".", "guess", "=", "'guess'", "in", "options", "?", "options", ".", "guess", ":", "true", ";", "if", "(", "!", "trace", ")", "{", "var", "imp", "=", "new", "stacktrace", ".", "implementation", "(", ")", ",", "err", "=", "options", ".", "error", "||", "options", ".", "err", "||", "options", ".", "e", ",", "traced", ";", "traced", "=", "imp", ".", "run", "(", "err", ")", ";", "trace", "=", "options", ".", "guess", "?", "imp", ".", "guessAnonymousFunctions", "(", "traced", ")", ":", "traced", ";", "}", "this", ".", "traces", "=", "this", ".", "parse", "(", "trace", ")", ";", "}" ]
Representation of a stack trace. Options: - **guess**: Guess the names of anonymous functions. @constructor @param {Array} trace Array of traces. @param {Object} err @api private
[ "Representation", "of", "a", "stack", "trace", "." ]
f9a5dfda5574d4660769d8dfa0ed2c491313837a
https://github.com/bigpipe/backtrace/blob/f9a5dfda5574d4660769d8dfa0ed2c491313837a/index.js#L17-L38
train
markfinger/cyclic-dependency-graph
src/graph.js
traceFromNode
function traceFromNode(name) { const job = { node: name, isValid: true }; invalidatePendingJobsForNode(pendingJobs, name); // Ensure the job can be tracked pendingJobs.push(job); // Force an asynchronous start to the tracing so that other parts of a // codebase can synchronously trigger the job to be invalidated. This // helps to avoid any unnecessary work that may no longer be relevant process.nextTick(startTracingNode); if (!hasSignalledStart) { hasSignalledStart = true; events.emit('started', {state: state}); } function startTracingNode() { // Handle situations where a job may have been invalidated further // down the stack from where the original call originated from if (!job.isValid) { return; } getDependencies(name) .then(handleDependencies) .catch(handleError) .then(signalIfCompleted); function handleDependencies(dependencies) { // If this job has been invalidated, we can ignore anything that may // have resulted from it if (!job.isValid) { return; } // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // Sanity check if (!isArray(dependencies)) { return Promise.reject( new Error(`Dependencies should be specified in an array. Received ${dependencies}`) ); } const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } // If there are any dependencies encountered that we don't already // know about, we start tracing them dependencies.forEach(depName => { if ( !isNodeDefined(state, depName) && !isNodePending(pendingJobs, depName) ) { traceFromNode(depName); } if (!isNodeDefined(state, depName)) { state = addNode(state, depName); } state = addEdge(state, name, depName); }); // Enable progress updates events.emit('traced', { node: name, diff: Diff({ from: previousState, to: state }) }); } function handleError(err) { // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // If the job has been invalidated, we ignore the error if (!job.isValid) { return; } const signal = { error: err, node: name, state: state }; errors.push(signal); events.emit('error', signal); } } }
javascript
function traceFromNode(name) { const job = { node: name, isValid: true }; invalidatePendingJobsForNode(pendingJobs, name); // Ensure the job can be tracked pendingJobs.push(job); // Force an asynchronous start to the tracing so that other parts of a // codebase can synchronously trigger the job to be invalidated. This // helps to avoid any unnecessary work that may no longer be relevant process.nextTick(startTracingNode); if (!hasSignalledStart) { hasSignalledStart = true; events.emit('started', {state: state}); } function startTracingNode() { // Handle situations where a job may have been invalidated further // down the stack from where the original call originated from if (!job.isValid) { return; } getDependencies(name) .then(handleDependencies) .catch(handleError) .then(signalIfCompleted); function handleDependencies(dependencies) { // If this job has been invalidated, we can ignore anything that may // have resulted from it if (!job.isValid) { return; } // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // Sanity check if (!isArray(dependencies)) { return Promise.reject( new Error(`Dependencies should be specified in an array. Received ${dependencies}`) ); } const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } // If there are any dependencies encountered that we don't already // know about, we start tracing them dependencies.forEach(depName => { if ( !isNodeDefined(state, depName) && !isNodePending(pendingJobs, depName) ) { traceFromNode(depName); } if (!isNodeDefined(state, depName)) { state = addNode(state, depName); } state = addEdge(state, name, depName); }); // Enable progress updates events.emit('traced', { node: name, diff: Diff({ from: previousState, to: state }) }); } function handleError(err) { // Indicate that this job is no longer blocking the `completed` stage pull(pendingJobs, job); // If the job has been invalidated, we ignore the error if (!job.isValid) { return; } const signal = { error: err, node: name, state: state }; errors.push(signal); events.emit('error', signal); } } }
[ "function", "traceFromNode", "(", "name", ")", "{", "const", "job", "=", "{", "node", ":", "name", ",", "isValid", ":", "true", "}", ";", "invalidatePendingJobsForNode", "(", "pendingJobs", ",", "name", ")", ";", "pendingJobs", ".", "push", "(", "job", ")", ";", "process", ".", "nextTick", "(", "startTracingNode", ")", ";", "if", "(", "!", "hasSignalledStart", ")", "{", "hasSignalledStart", "=", "true", ";", "events", ".", "emit", "(", "'started'", ",", "{", "state", ":", "state", "}", ")", ";", "}", "function", "startTracingNode", "(", ")", "{", "if", "(", "!", "job", ".", "isValid", ")", "{", "return", ";", "}", "getDependencies", "(", "name", ")", ".", "then", "(", "handleDependencies", ")", ".", "catch", "(", "handleError", ")", ".", "then", "(", "signalIfCompleted", ")", ";", "function", "handleDependencies", "(", "dependencies", ")", "{", "if", "(", "!", "job", ".", "isValid", ")", "{", "return", ";", "}", "pull", "(", "pendingJobs", ",", "job", ")", ";", "if", "(", "!", "isArray", "(", "dependencies", ")", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "`", "${", "dependencies", "}", "`", ")", ")", ";", "}", "const", "previousState", "=", "state", ";", "if", "(", "!", "isNodeDefined", "(", "state", ",", "name", ")", ")", "{", "state", "=", "addNode", "(", "state", ",", "name", ")", ";", "}", "dependencies", ".", "forEach", "(", "depName", "=>", "{", "if", "(", "!", "isNodeDefined", "(", "state", ",", "depName", ")", "&&", "!", "isNodePending", "(", "pendingJobs", ",", "depName", ")", ")", "{", "traceFromNode", "(", "depName", ")", ";", "}", "if", "(", "!", "isNodeDefined", "(", "state", ",", "depName", ")", ")", "{", "state", "=", "addNode", "(", "state", ",", "depName", ")", ";", "}", "state", "=", "addEdge", "(", "state", ",", "name", ",", "depName", ")", ";", "}", ")", ";", "events", ".", "emit", "(", "'traced'", ",", "{", "node", ":", "name", ",", "diff", ":", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", "}", ")", ";", "}", "function", "handleError", "(", "err", ")", "{", "pull", "(", "pendingJobs", ",", "job", ")", ";", "if", "(", "!", "job", ".", "isValid", ")", "{", "return", ";", "}", "const", "signal", "=", "{", "error", ":", "err", ",", "node", ":", "name", ",", "state", ":", "state", "}", ";", "errors", ".", "push", "(", "signal", ")", ";", "events", ".", "emit", "(", "'error'", ",", "signal", ")", ";", "}", "}", "}" ]
Invoke the specified `getDependencies` function and build the graph by recursively traversing unknown nodes @param {String} name
[ "Invoke", "the", "specified", "getDependencies", "function", "and", "build", "the", "graph", "by", "recursively", "traversing", "unknown", "nodes" ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L56-L158
train
markfinger/cyclic-dependency-graph
src/graph.js
pruneNode
function pruneNode(name) { const previousState = state; // If the node is still pending, invalidate the associated job so // that it becomes a no-op if (isNodePending(pendingJobs, name)) { invalidatePendingJobsForNode(pendingJobs, name); } if (isNodeDefined(state, name)) { let updatedState = previousState; const node = updatedState.get(name); node.dependents.forEach(dependent => { updatedState = removeEdge(updatedState, dependent, name); }); node.dependencies.forEach(dependency => { updatedState = removeEdge(updatedState, name, dependency); }); updatedState = removeNode(updatedState, name); state = updatedState; } signalIfCompleted(); return Diff({ from: previousState, to: state }); }
javascript
function pruneNode(name) { const previousState = state; // If the node is still pending, invalidate the associated job so // that it becomes a no-op if (isNodePending(pendingJobs, name)) { invalidatePendingJobsForNode(pendingJobs, name); } if (isNodeDefined(state, name)) { let updatedState = previousState; const node = updatedState.get(name); node.dependents.forEach(dependent => { updatedState = removeEdge(updatedState, dependent, name); }); node.dependencies.forEach(dependency => { updatedState = removeEdge(updatedState, name, dependency); }); updatedState = removeNode(updatedState, name); state = updatedState; } signalIfCompleted(); return Diff({ from: previousState, to: state }); }
[ "function", "pruneNode", "(", "name", ")", "{", "const", "previousState", "=", "state", ";", "if", "(", "isNodePending", "(", "pendingJobs", ",", "name", ")", ")", "{", "invalidatePendingJobsForNode", "(", "pendingJobs", ",", "name", ")", ";", "}", "if", "(", "isNodeDefined", "(", "state", ",", "name", ")", ")", "{", "let", "updatedState", "=", "previousState", ";", "const", "node", "=", "updatedState", ".", "get", "(", "name", ")", ";", "node", ".", "dependents", ".", "forEach", "(", "dependent", "=>", "{", "updatedState", "=", "removeEdge", "(", "updatedState", ",", "dependent", ",", "name", ")", ";", "}", ")", ";", "node", ".", "dependencies", ".", "forEach", "(", "dependency", "=>", "{", "updatedState", "=", "removeEdge", "(", "updatedState", ",", "name", ",", "dependency", ")", ";", "}", ")", ";", "updatedState", "=", "removeNode", "(", "updatedState", ",", "name", ")", ";", "state", "=", "updatedState", ";", "}", "signalIfCompleted", "(", ")", ";", "return", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", ";", "}" ]
Removes a node and its edges from the graph. Any pending jobs for the node will be invalidated. Be aware that pruning a single node may leave other nodes disconnected from an entry node. You may want to call `pruneDisconnectedNodes` to clean the graph of unwanted dependencies. @param {String} name @returns {Diff}
[ "Removes", "a", "node", "and", "its", "edges", "from", "the", "graph", ".", "Any", "pending", "jobs", "for", "the", "node", "will", "be", "invalidated", "." ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L171-L204
train
markfinger/cyclic-dependency-graph
src/graph.js
pruneDisconnectedNodes
function pruneDisconnectedNodes() { const previousState = state; const disconnected = findNodesDisconnectedFromEntryNodes(state); let updatedState = previousState; disconnected.forEach(name => { if (updatedState.has(name)) { const data = pruneNodeAndUniqueDependencies(updatedState, name); updatedState = data.nodes; } }); state = updatedState; return Diff({ from: previousState, to: state }); }
javascript
function pruneDisconnectedNodes() { const previousState = state; const disconnected = findNodesDisconnectedFromEntryNodes(state); let updatedState = previousState; disconnected.forEach(name => { if (updatedState.has(name)) { const data = pruneNodeAndUniqueDependencies(updatedState, name); updatedState = data.nodes; } }); state = updatedState; return Diff({ from: previousState, to: state }); }
[ "function", "pruneDisconnectedNodes", "(", ")", "{", "const", "previousState", "=", "state", ";", "const", "disconnected", "=", "findNodesDisconnectedFromEntryNodes", "(", "state", ")", ";", "let", "updatedState", "=", "previousState", ";", "disconnected", ".", "forEach", "(", "name", "=>", "{", "if", "(", "updatedState", ".", "has", "(", "name", ")", ")", "{", "const", "data", "=", "pruneNodeAndUniqueDependencies", "(", "updatedState", ",", "name", ")", ";", "updatedState", "=", "data", ".", "nodes", ";", "}", "}", ")", ";", "state", "=", "updatedState", ";", "return", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", ";", "}" ]
There are edge-cases where particular circular graphs may not have been pruned completely, so we may still be persisting references to nodes which are disconnected to the entry nodes. An easy example of a situation that can cause this is a tournament. https://en.wikipedia.org/wiki/Tournament_(graph_theory) To get around this problem, we need to walk the graph from the entry nodes, note any that are unreachable, and then prune them directly @returns {Diff}
[ "There", "are", "edge", "-", "cases", "where", "particular", "circular", "graphs", "may", "not", "have", "been", "pruned", "completely", "so", "we", "may", "still", "be", "persisting", "references", "to", "nodes", "which", "are", "disconnected", "to", "the", "entry", "nodes", "." ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L219-L237
train
markfinger/cyclic-dependency-graph
src/graph.js
setNodeAsEntry
function setNodeAsEntry(name) { const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } state = defineEntryNode(state, name); return Diff({ from: previousState, to: state }); }
javascript
function setNodeAsEntry(name) { const previousState = state; if (!isNodeDefined(state, name)) { state = addNode(state, name); } state = defineEntryNode(state, name); return Diff({ from: previousState, to: state }); }
[ "function", "setNodeAsEntry", "(", "name", ")", "{", "const", "previousState", "=", "state", ";", "if", "(", "!", "isNodeDefined", "(", "state", ",", "name", ")", ")", "{", "state", "=", "addNode", "(", "state", ",", "name", ")", ";", "}", "state", "=", "defineEntryNode", "(", "state", ",", "name", ")", ";", "return", "Diff", "(", "{", "from", ":", "previousState", ",", "to", ":", "state", "}", ")", ";", "}" ]
Dependency graphs emerge from one or more entry nodes. The ability to distinguish an entry node from a normal dependency node allows us to aggressively prune a node and all of its dependencies. As a basic example of why the concept is important, if `a -> b -> c` and we want to prune `b`, we know that we can safely prune `c` as well. But if `a -> b -> c -> a` and we want to prune `b`, then we need to know that `a` is an entry node, so that we don't traverse the cyclic graph and prune every node. This concept becomes increasingly important once we start dealing with more complicated cyclic graphs, as pruning can result in disconnected sub-graphs. For example, if we have `a -> b -> c -> d -> b` and we want to prune `a`, we can't safely prune `b -> c -> d -> b` as well, as `b` has a dependent `d`. However, if we don't prune them, then they are left disconnected from the other nodes. Hence we need to know a graph's entry points so that we can traverse it from the entries and find the nodes which are disconnected @param {String} name @returns {Diff}
[ "Dependency", "graphs", "emerge", "from", "one", "or", "more", "entry", "nodes", ".", "The", "ability", "to", "distinguish", "an", "entry", "node", "from", "a", "normal", "dependency", "node", "allows", "us", "to", "aggressively", "prune", "a", "node", "and", "all", "of", "its", "dependencies", "." ]
fac9249ec3a9d29199bed9fedcf99267b2c61c44
https://github.com/markfinger/cyclic-dependency-graph/blob/fac9249ec3a9d29199bed9fedcf99267b2c61c44/src/graph.js#L264-L277
train
Neil-G/redux-mastermind
lib/createUpdaterParts.js
processActionGroup
function processActionGroup(_ref2) { var _ref2$updateSchemaNam = _ref2.updateSchemaName, updateSchemaName = _ref2$updateSchemaNam === undefined ? undefined : _ref2$updateSchemaNam, _ref2$store = _ref2.store, store = _ref2$store === undefined ? _store : _ref2$store, _ref2$error = _ref2.error, error = _ref2$error === undefined ? {} : _ref2$error, _ref2$res = _ref2.res, res = _ref2$res === undefined ? {} : _ref2$res, _ref2$actionGroup = _ref2.actionGroup, actionGroup = _ref2$actionGroup === undefined ? {} : _ref2$actionGroup; if (actionGroup == undefined) return; var actionNames = Object.keys(actionGroup); actionNames.forEach(function (actionName) { var action = actionGroup[actionName]; // TODO: check for required fields: branch, location, operation, value || valueFunction, location || locationFunction // updateIn, update + updateIn, update // destructure action values used in processing var valueFunction = action.valueFunction, value = action.value, shouldDispatch = action.shouldDispatch, uiEventFunction = action.uiEventFunction, updateFunction = action.updateFunction, location = action.location, locationFunction = action.locationFunction, operation = action.operation; // create action to be processed var $action = {}; // update value $action.value = valueFunction ? valueFunction({ error: error, res: res, store: store, value: value }) : value; // update location $action.location = locationFunction ? locationFunction({ error: error, res: res, store: store, value: value }) : location; // add type $action.type = $action.location[0]; // trim first value from location $action.location = $action.location.slice(1); // add name $action.name = actionName; // add update function params $action.updateFunction = updateFunction ? updateFunction.bind(null, { res: res, error: error, store: store, fromJS: _immutable.fromJS, value: value }) : undefined; // add operation if ($action.updateFunction) { $action.operation = 'updateIn'; } else if (!$action.value) { $action.operation = 'deleteIn'; } else { $action.operation = 'setIn'; } // TODO: add meta information about the updateSchemaCreator // dispatch action depending on fire if (shouldDispatch == undefined || shouldDispatch({ error: error, res: res, store: store, value: value })) { // dispatch the action here store.dispatch($action); // fire ui event if (uiEventFunction) uiEventFunction({ action: action, value: value, res: res, error: error, store: store }); } }); }
javascript
function processActionGroup(_ref2) { var _ref2$updateSchemaNam = _ref2.updateSchemaName, updateSchemaName = _ref2$updateSchemaNam === undefined ? undefined : _ref2$updateSchemaNam, _ref2$store = _ref2.store, store = _ref2$store === undefined ? _store : _ref2$store, _ref2$error = _ref2.error, error = _ref2$error === undefined ? {} : _ref2$error, _ref2$res = _ref2.res, res = _ref2$res === undefined ? {} : _ref2$res, _ref2$actionGroup = _ref2.actionGroup, actionGroup = _ref2$actionGroup === undefined ? {} : _ref2$actionGroup; if (actionGroup == undefined) return; var actionNames = Object.keys(actionGroup); actionNames.forEach(function (actionName) { var action = actionGroup[actionName]; // TODO: check for required fields: branch, location, operation, value || valueFunction, location || locationFunction // updateIn, update + updateIn, update // destructure action values used in processing var valueFunction = action.valueFunction, value = action.value, shouldDispatch = action.shouldDispatch, uiEventFunction = action.uiEventFunction, updateFunction = action.updateFunction, location = action.location, locationFunction = action.locationFunction, operation = action.operation; // create action to be processed var $action = {}; // update value $action.value = valueFunction ? valueFunction({ error: error, res: res, store: store, value: value }) : value; // update location $action.location = locationFunction ? locationFunction({ error: error, res: res, store: store, value: value }) : location; // add type $action.type = $action.location[0]; // trim first value from location $action.location = $action.location.slice(1); // add name $action.name = actionName; // add update function params $action.updateFunction = updateFunction ? updateFunction.bind(null, { res: res, error: error, store: store, fromJS: _immutable.fromJS, value: value }) : undefined; // add operation if ($action.updateFunction) { $action.operation = 'updateIn'; } else if (!$action.value) { $action.operation = 'deleteIn'; } else { $action.operation = 'setIn'; } // TODO: add meta information about the updateSchemaCreator // dispatch action depending on fire if (shouldDispatch == undefined || shouldDispatch({ error: error, res: res, store: store, value: value })) { // dispatch the action here store.dispatch($action); // fire ui event if (uiEventFunction) uiEventFunction({ action: action, value: value, res: res, error: error, store: store }); } }); }
[ "function", "processActionGroup", "(", "_ref2", ")", "{", "var", "_ref2$updateSchemaNam", "=", "_ref2", ".", "updateSchemaName", ",", "updateSchemaName", "=", "_ref2$updateSchemaNam", "===", "undefined", "?", "undefined", ":", "_ref2$updateSchemaNam", ",", "_ref2$store", "=", "_ref2", ".", "store", ",", "store", "=", "_ref2$store", "===", "undefined", "?", "_store", ":", "_ref2$store", ",", "_ref2$error", "=", "_ref2", ".", "error", ",", "error", "=", "_ref2$error", "===", "undefined", "?", "{", "}", ":", "_ref2$error", ",", "_ref2$res", "=", "_ref2", ".", "res", ",", "res", "=", "_ref2$res", "===", "undefined", "?", "{", "}", ":", "_ref2$res", ",", "_ref2$actionGroup", "=", "_ref2", ".", "actionGroup", ",", "actionGroup", "=", "_ref2$actionGroup", "===", "undefined", "?", "{", "}", ":", "_ref2$actionGroup", ";", "if", "(", "actionGroup", "==", "undefined", ")", "return", ";", "var", "actionNames", "=", "Object", ".", "keys", "(", "actionGroup", ")", ";", "actionNames", ".", "forEach", "(", "function", "(", "actionName", ")", "{", "var", "action", "=", "actionGroup", "[", "actionName", "]", ";", "var", "valueFunction", "=", "action", ".", "valueFunction", ",", "value", "=", "action", ".", "value", ",", "shouldDispatch", "=", "action", ".", "shouldDispatch", ",", "uiEventFunction", "=", "action", ".", "uiEventFunction", ",", "updateFunction", "=", "action", ".", "updateFunction", ",", "location", "=", "action", ".", "location", ",", "locationFunction", "=", "action", ".", "locationFunction", ",", "operation", "=", "action", ".", "operation", ";", "var", "$action", "=", "{", "}", ";", "$action", ".", "value", "=", "valueFunction", "?", "valueFunction", "(", "{", "error", ":", "error", ",", "res", ":", "res", ",", "store", ":", "store", ",", "value", ":", "value", "}", ")", ":", "value", ";", "$action", ".", "location", "=", "locationFunction", "?", "locationFunction", "(", "{", "error", ":", "error", ",", "res", ":", "res", ",", "store", ":", "store", ",", "value", ":", "value", "}", ")", ":", "location", ";", "$action", ".", "type", "=", "$action", ".", "location", "[", "0", "]", ";", "$action", ".", "location", "=", "$action", ".", "location", ".", "slice", "(", "1", ")", ";", "$action", ".", "name", "=", "actionName", ";", "$action", ".", "updateFunction", "=", "updateFunction", "?", "updateFunction", ".", "bind", "(", "null", ",", "{", "res", ":", "res", ",", "error", ":", "error", ",", "store", ":", "store", ",", "fromJS", ":", "_immutable", ".", "fromJS", ",", "value", ":", "value", "}", ")", ":", "undefined", ";", "if", "(", "$action", ".", "updateFunction", ")", "{", "$action", ".", "operation", "=", "'updateIn'", ";", "}", "else", "if", "(", "!", "$action", ".", "value", ")", "{", "$action", ".", "operation", "=", "'deleteIn'", ";", "}", "else", "{", "$action", ".", "operation", "=", "'setIn'", ";", "}", "if", "(", "shouldDispatch", "==", "undefined", "||", "shouldDispatch", "(", "{", "error", ":", "error", ",", "res", ":", "res", ",", "store", ":", "store", ",", "value", ":", "value", "}", ")", ")", "{", "store", ".", "dispatch", "(", "$action", ")", ";", "if", "(", "uiEventFunction", ")", "uiEventFunction", "(", "{", "action", ":", "action", ",", "value", ":", "value", ",", "res", ":", "res", ",", "error", ":", "error", ",", "store", ":", "store", "}", ")", ";", "}", "}", ")", ";", "}" ]
this will process an object full of actions
[ "this", "will", "process", "an", "object", "full", "of", "actions" ]
669e2978b4a7cdd48fbd33d4fd6dbe47e92d3cef
https://github.com/Neil-G/redux-mastermind/blob/669e2978b4a7cdd48fbd33d4fd6dbe47e92d3cef/lib/createUpdaterParts.js#L18-L94
train
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(year) { var date = this._validate(year, this.minMonth, this.minDay, $.calendars.local.invalidYear); year = date.year(); var baktun = Math.floor(year / 400); year = year % 400; year += (year < 0 ? 400 : 0); var katun = Math.floor(year / 20); return baktun + '.' + katun + '.' + (year % 20); }
javascript
function(year) { var date = this._validate(year, this.minMonth, this.minDay, $.calendars.local.invalidYear); year = date.year(); var baktun = Math.floor(year / 400); year = year % 400; year += (year < 0 ? 400 : 0); var katun = Math.floor(year / 20); return baktun + '.' + katun + '.' + (year % 20); }
[ "function", "(", "year", ")", "{", "var", "date", "=", "this", ".", "_validate", "(", "year", ",", "this", ".", "minMonth", ",", "this", ".", "minDay", ",", "$", ".", "calendars", ".", "local", ".", "invalidYear", ")", ";", "year", "=", "date", ".", "year", "(", ")", ";", "var", "baktun", "=", "Math", ".", "floor", "(", "year", "/", "400", ")", ";", "year", "=", "year", "%", "400", ";", "year", "+=", "(", "year", "<", "0", "?", "400", ":", "0", ")", ";", "var", "katun", "=", "Math", ".", "floor", "(", "year", "/", "20", ")", ";", "return", "baktun", "+", "'.'", "+", "katun", "+", "'.'", "+", "(", "year", "%", "20", ")", ";", "}" ]
Format the year, if not a simple sequential number. @memberof MayanCalendar @param year {CDate|number} The date to format or the year to format. @return {string} The formatted year. @throws Error if an invalid year or a different calendar used.
[ "Format", "the", "year", "if", "not", "a", "simple", "sequential", "number", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L96-L104
train
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(years) { years = years.split('.'); if (years.length < 3) { throw 'Invalid Mayan year'; } var year = 0; for (var i = 0; i < years.length; i++) { var y = parseInt(years[i], 10); if (Math.abs(y) > 19 || (i > 0 && y < 0)) { throw 'Invalid Mayan year'; } year = year * 20 + y; } return year; }
javascript
function(years) { years = years.split('.'); if (years.length < 3) { throw 'Invalid Mayan year'; } var year = 0; for (var i = 0; i < years.length; i++) { var y = parseInt(years[i], 10); if (Math.abs(y) > 19 || (i > 0 && y < 0)) { throw 'Invalid Mayan year'; } year = year * 20 + y; } return year; }
[ "function", "(", "years", ")", "{", "years", "=", "years", ".", "split", "(", "'.'", ")", ";", "if", "(", "years", ".", "length", "<", "3", ")", "{", "throw", "'Invalid Mayan year'", ";", "}", "var", "year", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "years", ".", "length", ";", "i", "++", ")", "{", "var", "y", "=", "parseInt", "(", "years", "[", "i", "]", ",", "10", ")", ";", "if", "(", "Math", ".", "abs", "(", "y", ")", ">", "19", "||", "(", "i", ">", "0", "&&", "y", "<", "0", ")", ")", "{", "throw", "'Invalid Mayan year'", ";", "}", "year", "=", "year", "*", "20", "+", "y", ";", "}", "return", "year", ";", "}" ]
Convert from the formatted year back to a single number. @memberof MayanCalendar @param years {string} The year as n.n.n. @return {number} The sequential year. @throws Error if an invalid value is supplied.
[ "Convert", "from", "the", "formatted", "year", "back", "to", "a", "single", "number", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L111-L125
train
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(year, month, day) { var date = this._validate(year, month, day, $.calendars.local.invalidDate); var jd = date.toJD(); var haab = this._toHaab(jd); var tzolkin = this._toTzolkin(jd); return {haabMonthName: this.local.haabMonths[haab[0] - 1], haabMonth: haab[0], haabDay: haab[1], tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1], tzolkinDay: tzolkin[0], tzolkinTrecena: tzolkin[1]}; }
javascript
function(year, month, day) { var date = this._validate(year, month, day, $.calendars.local.invalidDate); var jd = date.toJD(); var haab = this._toHaab(jd); var tzolkin = this._toTzolkin(jd); return {haabMonthName: this.local.haabMonths[haab[0] - 1], haabMonth: haab[0], haabDay: haab[1], tzolkinDayName: this.local.tzolkinMonths[tzolkin[0] - 1], tzolkinDay: tzolkin[0], tzolkinTrecena: tzolkin[1]}; }
[ "function", "(", "year", ",", "month", ",", "day", ")", "{", "var", "date", "=", "this", ".", "_validate", "(", "year", ",", "month", ",", "day", ",", "$", ".", "calendars", ".", "local", ".", "invalidDate", ")", ";", "var", "jd", "=", "date", ".", "toJD", "(", ")", ";", "var", "haab", "=", "this", ".", "_toHaab", "(", "jd", ")", ";", "var", "tzolkin", "=", "this", ".", "_toTzolkin", "(", "jd", ")", ";", "return", "{", "haabMonthName", ":", "this", ".", "local", ".", "haabMonths", "[", "haab", "[", "0", "]", "-", "1", "]", ",", "haabMonth", ":", "haab", "[", "0", "]", ",", "haabDay", ":", "haab", "[", "1", "]", ",", "tzolkinDayName", ":", "this", ".", "local", ".", "tzolkinMonths", "[", "tzolkin", "[", "0", "]", "-", "1", "]", ",", "tzolkinDay", ":", "tzolkin", "[", "0", "]", ",", "tzolkinTrecena", ":", "tzolkin", "[", "1", "]", "}", ";", "}" ]
Retrieve additional information about a date - Haab and Tzolkin equivalents. @memberof MayanCalendar @param year {CDate|number} The date to examine or the year to examine. @param [month] {number} The month to examine. @param [day] {number} The day to examine. @return {object} Additional information - contents depends on calendar. @throws Error if an invalid date or a different calendar used.
[ "Retrieve", "additional", "information", "about", "a", "date", "-", "Haab", "and", "Tzolkin", "equivalents", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L208-L217
train
alexcjohnson/world-calendars
jquery-src/jquery.calendars.mayan.js
function(jd) { jd -= this.jdEpoch; var day = mod(jd + 8 + ((18 - 1) * 20), 365); return [Math.floor(day / 20) + 1, mod(day, 20)]; }
javascript
function(jd) { jd -= this.jdEpoch; var day = mod(jd + 8 + ((18 - 1) * 20), 365); return [Math.floor(day / 20) + 1, mod(day, 20)]; }
[ "function", "(", "jd", ")", "{", "jd", "-=", "this", ".", "jdEpoch", ";", "var", "day", "=", "mod", "(", "jd", "+", "8", "+", "(", "(", "18", "-", "1", ")", "*", "20", ")", ",", "365", ")", ";", "return", "[", "Math", ".", "floor", "(", "day", "/", "20", ")", "+", "1", ",", "mod", "(", "day", ",", "20", ")", "]", ";", "}" ]
Retrieve Haab date from a Julian date. @memberof MayanCalendar @private @param jd {number} The Julian date. @return {number[]} Corresponding Haab month and day.
[ "Retrieve", "Haab", "date", "from", "a", "Julian", "date", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.mayan.js#L224-L228
train
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js
function ( source, dest ) { var that = this; if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" ) { dest.className = source.className; } $(source).children().each( function (i) { that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] ); } ); }
javascript
function ( source, dest ) { var that = this; if ( source.nodeName.toUpperCase() === "TR" || source.nodeName.toUpperCase() === "TH" || source.nodeName.toUpperCase() === "TD" || source.nodeName.toUpperCase() === "SPAN" ) { dest.className = source.className; } $(source).children().each( function (i) { that._fnClassUpdate( $(source).children()[i], $(dest).children()[i] ); } ); }
[ "function", "(", "source", ",", "dest", ")", "{", "var", "that", "=", "this", ";", "if", "(", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"TR\"", "||", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"TH\"", "||", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"TD\"", "||", "source", ".", "nodeName", ".", "toUpperCase", "(", ")", "===", "\"SPAN\"", ")", "{", "dest", ".", "className", "=", "source", ".", "className", ";", "}", "$", "(", "source", ")", ".", "children", "(", ")", ".", "each", "(", "function", "(", "i", ")", "{", "that", ".", "_fnClassUpdate", "(", "$", "(", "source", ")", ".", "children", "(", ")", "[", "i", "]", ",", "$", "(", "dest", ")", ".", "children", "(", ")", "[", "i", "]", ")", ";", "}", ")", ";", "}" ]
Copy the classes of all child nodes from one element to another. This implies that the two have identical structure - no error checking is performed to that fact. @param {element} source Node to copy classes from @param {element} dest Node to copy classes too
[ "Copy", "the", "classes", "of", "all", "child", "nodes", "from", "one", "element", "to", "another", ".", "This", "implies", "that", "the", "two", "have", "identical", "structure", "-", "no", "error", "checking", "is", "performed", "to", "that", "fact", "." ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js#L669-L682
train
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js
function ( parent, original, clone ) { var that = this; var originals = $(parent +' tr', original); var height; $(parent+' tr', clone).each( function (k) { height = originals.eq( k ).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if ( navigator.appName == 'Microsoft Internet Explorer' ) { height = parseInt( height, 10 ) + 1; } $(this).css( 'height', height ); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq( k ).css( 'height', height ); } ); }
javascript
function ( parent, original, clone ) { var that = this; var originals = $(parent +' tr', original); var height; $(parent+' tr', clone).each( function (k) { height = originals.eq( k ).css('height'); // This is nasty :-(. IE has a sub-pixel error even when setting // the height below (the Firefox fix) which causes the fixed column // to go out of alignment. Need to add a pixel before the assignment // Can this be feature detected? Not sure how... if ( navigator.appName == 'Microsoft Internet Explorer' ) { height = parseInt( height, 10 ) + 1; } $(this).css( 'height', height ); // For Firefox to work, we need to also set the height of the // original row, to the value that we read from it! Otherwise there // is a sub-pixel rounding error originals.eq( k ).css( 'height', height ); } ); }
[ "function", "(", "parent", ",", "original", ",", "clone", ")", "{", "var", "that", "=", "this", ";", "var", "originals", "=", "$", "(", "parent", "+", "' tr'", ",", "original", ")", ";", "var", "height", ";", "$", "(", "parent", "+", "' tr'", ",", "clone", ")", ".", "each", "(", "function", "(", "k", ")", "{", "height", "=", "originals", ".", "eq", "(", "k", ")", ".", "css", "(", "'height'", ")", ";", "if", "(", "navigator", ".", "appName", "==", "'Microsoft Internet Explorer'", ")", "{", "height", "=", "parseInt", "(", "height", ",", "10", ")", "+", "1", ";", "}", "$", "(", "this", ")", ".", "css", "(", "'height'", ",", "height", ")", ";", "originals", ".", "eq", "(", "k", ")", ".", "css", "(", "'height'", ",", "height", ")", ";", "}", ")", ";", "}" ]
Equalise the heights of the rows in a given table node in a cross browser way. Note that this is more or less lifted as is from FixedColumns @method fnEqualiseHeights @returns void @param {string} parent Node type - thead, tbody or tfoot @param {element} original Original node to take the heights from @param {element} clone Copy the heights to @private
[ "Equalise", "the", "heights", "of", "the", "rows", "in", "a", "given", "table", "node", "in", "a", "cross", "browser", "way", ".", "Note", "that", "this", "is", "more", "or", "less", "lifted", "as", "is", "from", "FixedColumns" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/admin-lte/plugins/datatables/extensions/FixedHeader/js/dataTables.fixedHeader.js#L894-L918
train
apigee-internal/rbac-abacus
npm/bizancio.js
getCollector
function getCollector() { var collector = new Collector(); if (global['__coverage__']) { collector.add(global['__coverage__']); } else { console.error('No global coverage found for the node process'); } return collector; }
javascript
function getCollector() { var collector = new Collector(); if (global['__coverage__']) { collector.add(global['__coverage__']); } else { console.error('No global coverage found for the node process'); } return collector; }
[ "function", "getCollector", "(", ")", "{", "var", "collector", "=", "new", "Collector", "(", ")", ";", "if", "(", "global", "[", "'__coverage__'", "]", ")", "{", "collector", ".", "add", "(", "global", "[", "'__coverage__'", "]", ")", ";", "}", "else", "{", "console", ".", "error", "(", "'No global coverage found for the node process'", ")", ";", "}", "return", "collector", ";", "}" ]
returns the coverage collector, creating one and automatically adding the contents of the global coverage object. You can use this method in an exit handler to get the accumulated coverage.
[ "returns", "the", "coverage", "collector", "creating", "one", "and", "automatically", "adding", "the", "contents", "of", "the", "global", "coverage", "object", ".", "You", "can", "use", "this", "method", "in", "an", "exit", "handler", "to", "get", "the", "accumulated", "coverage", "." ]
6b3929194c0adf5adf3b9571fe0f25390c981f88
https://github.com/apigee-internal/rbac-abacus/blob/6b3929194c0adf5adf3b9571fe0f25390c981f88/npm/bizancio.js#L33-L42
train
smbape/node-umd-builder
lib/compilers/jst/template.js
template
function template(string, options, otherOptions) { // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). const settings = templateSettings; if (otherOptions && isIterateeCall(string, options, otherOptions)) { options = otherOptions = undefined; } string = baseToString(string); options = extendWith({ ignore: reIgnore }, otherOptions || options, settings, extendDefaults); const imports = extendWith({}, options.imports, settings.imports, extendDefaults); const importsKeys = keys(imports); const importsValues = baseValues(imports, importsKeys); let isEscaping, isEvaluating; let index = 0; const interpolate = options.interpolate || reNoMatch; let source = ["__p[__p.length] = '"]; // Compile the regexp to match each delimiter. const reDelimiters = RegExp( (options.ignore || reNoMatch).source + "|" + (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (options.esInterpolate !== false && interpolate.source === reInterpolate.source ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); // Use a sourceURL for easier debugging. const sourceURL = "//# sourceURL=" + ("sourceURL" in options ? options.sourceURL : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; string.replace(reDelimiters, function(match, ignoreValue, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { if (!interpolateValue) { interpolateValue = esTemplateValue; } // Escape characters that can't be included in string literals. source.push(string.slice(index, offset).replace(reUnescapedString, escapeStringChar)); if (!ignoreValue) { // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source.push("' +\n__e(" + escapeValue + ") +\n'"); } if (evaluateValue) { isEvaluating = true; source.push("';\n" + evaluateValue + ";\n__p[__p.length] = '"); } if (interpolateValue) { source.push("' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"); } } index = offset + match.length; // The JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value. return match; }); source.push("';\n"); source = source.join(""); // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. let variable = options.variable; if (variable == null) { source = "with (obj) {\n" + source + "\n}\n"; variable = "obj"; } // Cleanup code by stripping empty strings. source = isEvaluating ? source.replace(reEmptyStringLeading, "") : source; source = source.replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); // Frame code as the function body. const declaration = options.async ? "async function" : "function"; source = declaration + "(" + variable + ") {\n" + "if (" + variable + " == null) { " + variable + " = {}; }\n" + "var __t, __p = []" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\n" + "function print() { __p[__p.length] = __j.call(arguments, '') }\n" : ";\n" ) + source + "return __p.join(\"\")\n};"; const result = attempt(function() { // eslint-disable-next-line no-new-func return Function(importsKeys, sourceURL + "return " + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
javascript
function template(string, options, otherOptions) { // Based on John Resig's `tmpl` implementation (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). const settings = templateSettings; if (otherOptions && isIterateeCall(string, options, otherOptions)) { options = otherOptions = undefined; } string = baseToString(string); options = extendWith({ ignore: reIgnore }, otherOptions || options, settings, extendDefaults); const imports = extendWith({}, options.imports, settings.imports, extendDefaults); const importsKeys = keys(imports); const importsValues = baseValues(imports, importsKeys); let isEscaping, isEvaluating; let index = 0; const interpolate = options.interpolate || reNoMatch; let source = ["__p[__p.length] = '"]; // Compile the regexp to match each delimiter. const reDelimiters = RegExp( (options.ignore || reNoMatch).source + "|" + (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (options.esInterpolate !== false && interpolate.source === reInterpolate.source ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); // Use a sourceURL for easier debugging. const sourceURL = "//# sourceURL=" + ("sourceURL" in options ? options.sourceURL : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; string.replace(reDelimiters, function(match, ignoreValue, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { if (!interpolateValue) { interpolateValue = esTemplateValue; } // Escape characters that can't be included in string literals. source.push(string.slice(index, offset).replace(reUnescapedString, escapeStringChar)); if (!ignoreValue) { // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source.push("' +\n__e(" + escapeValue + ") +\n'"); } if (evaluateValue) { isEvaluating = true; source.push("';\n" + evaluateValue + ";\n__p[__p.length] = '"); } if (interpolateValue) { source.push("' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"); } } index = offset + match.length; // The JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value. return match; }); source.push("';\n"); source = source.join(""); // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. let variable = options.variable; if (variable == null) { source = "with (obj) {\n" + source + "\n}\n"; variable = "obj"; } // Cleanup code by stripping empty strings. source = isEvaluating ? source.replace(reEmptyStringLeading, "") : source; source = source.replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); // Frame code as the function body. const declaration = options.async ? "async function" : "function"; source = declaration + "(" + variable + ") {\n" + "if (" + variable + " == null) { " + variable + " = {}; }\n" + "var __t, __p = []" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\n" + "function print() { __p[__p.length] = __j.call(arguments, '') }\n" : ";\n" ) + source + "return __p.join(\"\")\n};"; const result = attempt(function() { // eslint-disable-next-line no-new-func return Function(importsKeys, sourceURL + "return " + source).apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; }
[ "function", "template", "(", "string", ",", "options", ",", "otherOptions", ")", "{", "const", "settings", "=", "templateSettings", ";", "if", "(", "otherOptions", "&&", "isIterateeCall", "(", "string", ",", "options", ",", "otherOptions", ")", ")", "{", "options", "=", "otherOptions", "=", "undefined", ";", "}", "string", "=", "baseToString", "(", "string", ")", ";", "options", "=", "extendWith", "(", "{", "ignore", ":", "reIgnore", "}", ",", "otherOptions", "||", "options", ",", "settings", ",", "extendDefaults", ")", ";", "const", "imports", "=", "extendWith", "(", "{", "}", ",", "options", ".", "imports", ",", "settings", ".", "imports", ",", "extendDefaults", ")", ";", "const", "importsKeys", "=", "keys", "(", "imports", ")", ";", "const", "importsValues", "=", "baseValues", "(", "imports", ",", "importsKeys", ")", ";", "let", "isEscaping", ",", "isEvaluating", ";", "let", "index", "=", "0", ";", "const", "interpolate", "=", "options", ".", "interpolate", "||", "reNoMatch", ";", "let", "source", "=", "[", "\"__p[__p.length] = '\"", "]", ";", "const", "reDelimiters", "=", "RegExp", "(", "(", "options", ".", "ignore", "||", "reNoMatch", ")", ".", "source", "+", "\"|\"", "+", "(", "options", ".", "escape", "||", "reNoMatch", ")", ".", "source", "+", "\"|\"", "+", "interpolate", ".", "source", "+", "\"|\"", "+", "(", "options", ".", "esInterpolate", "!==", "false", "&&", "interpolate", ".", "source", "===", "reInterpolate", ".", "source", "?", "reEsTemplate", ":", "reNoMatch", ")", ".", "source", "+", "\"|\"", "+", "(", "options", ".", "evaluate", "||", "reNoMatch", ")", ".", "source", "+", "\"|$\"", ",", "\"g\"", ")", ";", "const", "sourceURL", "=", "\"//# sourceURL=\"", "+", "(", "\"sourceURL\"", "in", "options", "?", "options", ".", "sourceURL", ":", "\"lodash.templateSources[\"", "+", "++", "templateCounter", "+", "\"]\"", ")", "+", "\"\\n\"", ";", "\\n", "string", ".", "replace", "(", "reDelimiters", ",", "function", "(", "match", ",", "ignoreValue", ",", "escapeValue", ",", "interpolateValue", ",", "esTemplateValue", ",", "evaluateValue", ",", "offset", ")", "{", "if", "(", "!", "interpolateValue", ")", "{", "interpolateValue", "=", "esTemplateValue", ";", "}", "source", ".", "push", "(", "string", ".", "slice", "(", "index", ",", "offset", ")", ".", "replace", "(", "reUnescapedString", ",", "escapeStringChar", ")", ")", ";", "if", "(", "!", "ignoreValue", ")", "{", "if", "(", "escapeValue", ")", "{", "isEscaping", "=", "true", ";", "source", ".", "push", "(", "\"' +\\n__e(\"", "+", "\\n", "+", "escapeValue", ")", ";", "}", "\") +\\n'\"", "\\n", "}", "if", "(", "evaluateValue", ")", "{", "isEvaluating", "=", "true", ";", "source", ".", "push", "(", "\"';\\n\"", "+", "\\n", "+", "evaluateValue", ")", ";", "}", "\";\\n__p[__p.length] = '\"", "}", ")", ";", "\\n", "if", "(", "interpolateValue", ")", "{", "source", ".", "push", "(", "\"' +\\n((__t = (\"", "+", "\\n", "+", "interpolateValue", ")", ";", "}", "\")) == null ? '' : __t) +\\n'\"", "\\n", "index", "=", "offset", "+", "match", ".", "length", ";", "return", "match", ";", "source", ".", "push", "(", "\"';\\n\"", ")", ";", "\\n", "source", "=", "source", ".", "join", "(", "\"\"", ")", ";", "let", "variable", "=", "options", ".", "variable", ";", "if", "(", "variable", "==", "null", ")", "{", "source", "=", "\"with (obj) {\\n\"", "+", "\\n", "+", "source", ";", "\"\\n}\\n\"", "}", "}" ]
Creates a compiled template function that can interpolate data properties in "interpolate" delimiters, HTML-escape interpolated data properties in "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data properties may be accessed as free variables in the template. If a setting object is provided it takes precedence over `_.templateSettings` values. **Note:** In the development build `_.template` utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging. For more information on precompiling templates see [lodash's custom builds documentation](https://lodash.com/custom-builds). For more information on Chrome extension sandboxes see [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). @static @memberOf _ @category String @param {string} [string=''] The template string. @param {Object} [options] The options object. @param {RegExp} [options.escape] The HTML "escape" delimiter. @param {RegExp} [options.evaluate] The "evaluate" delimiter. @param {Object} [options.imports] An object to import into the template as free variables. @param {RegExp} [options.interpolate] The "interpolate" delimiter. @param {string} [options.sourceURL] The sourceURL of the template's compiled source. @param {string} [options.variable] The data object variable name. @param- {Object} [otherOptions] Enables the legacy `options` param signature. @returns {Function} Returns the compiled template function. @example // using the "interpolate" delimiter to create a compiled template let compiled = _.template('hello <%= user %>!'); compiled({ 'user': 'fred' }); // => 'hello fred!' // using the HTML "escape" delimiter to escape data property values let compiled = _.template('<b><%- value %></b>'); compiled({ 'value': '<script>' }); // => '<b>&lt;script&gt;</b>' // using the "evaluate" delimiter to execute JavaScript and generate HTML let compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); compiled({ 'users': ['fred', 'barney'] }); // => '<li>fred</li><li>barney</li>' // using the internal `print` function in "evaluate" delimiters let compiled = _.template('<% print("hello " + user); %>!'); compiled({ 'user': 'barney' }); // => 'hello barney!' // using the ES delimiter as an alternative to the default "interpolate" delimiter let compiled = _.template('hello ${ user }!'); compiled({ 'user': 'pebbles' }); // => 'hello pebbles!' // using custom template delimiters _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; let compiled = _.template('hello {{ user }}!'); compiled({ 'user': 'mustache' }); // => 'hello mustache!' // using backslashes to treat delimiters as plain text let compiled = _.template('<%= "\\<%- value %\\>" %>'); compiled({ 'value': 'ignored' }); // => '<%- value %>' // using the `imports` option to import `jQuery` as `jq` let text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; let compiled = _.template(text, { 'imports': { 'jq': jQuery } }); compiled({ 'users': ['fred', 'barney'] }); // => '<li>fred</li><li>barney</li>' // using the `sourceURL` option to specify a custom sourceURL for the template let compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); compiled(data); // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector // using the `variable` option to ensure a with-statement isn't used in the compiled template let compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); compiled.source; // => function(data) { // var __t, __p = []; // __p[__p.length] = 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; // return __p; // } // using the `source` property to inline compiled templates for meaningful // line numbers in error messages and a stack trace fs.writeFileSync(path.join(cwd, 'jst.js'), '\ let JST = {\ "main": ' + _.template(mainText).source + '\ };\ ');
[ "Creates", "a", "compiled", "template", "function", "that", "can", "interpolate", "data", "properties", "in", "interpolate", "delimiters", "HTML", "-", "escape", "interpolated", "data", "properties", "in", "escape", "delimiters", "and", "execute", "JavaScript", "in", "evaluate", "delimiters", ".", "Data", "properties", "may", "be", "accessed", "as", "free", "variables", "in", "the", "template", ".", "If", "a", "setting", "object", "is", "provided", "it", "takes", "precedence", "over", "_", ".", "templateSettings", "values", "." ]
73b03e8c985f2660948f5df71140e4a8fb162549
https://github.com/smbape/node-umd-builder/blob/73b03e8c985f2660948f5df71140e4a8fb162549/lib/compilers/jst/template.js#L258-L360
train
S3bb1/ah-dashboard-plugin
public/dashboard/bower_components/fancytree/dist/src/jquery.fancytree.debug.js
function(ctx, force, deep, collapsed){ // ctx.tree.debug("**** PROFILER nodeRender"); var s = this.options.prefix + "render '" + ctx.node + "'"; /*jshint expr:true */ window.console && window.console.time && window.console.time(s); this._super(ctx, force, deep, collapsed); window.console && window.console.timeEnd && window.console.timeEnd(s); }
javascript
function(ctx, force, deep, collapsed){ // ctx.tree.debug("**** PROFILER nodeRender"); var s = this.options.prefix + "render '" + ctx.node + "'"; /*jshint expr:true */ window.console && window.console.time && window.console.time(s); this._super(ctx, force, deep, collapsed); window.console && window.console.timeEnd && window.console.timeEnd(s); }
[ "function", "(", "ctx", ",", "force", ",", "deep", ",", "collapsed", ")", "{", "var", "s", "=", "this", ".", "options", ".", "prefix", "+", "\"render '\"", "+", "ctx", ".", "node", "+", "\"'\"", ";", "window", ".", "console", "&&", "window", ".", "console", ".", "time", "&&", "window", ".", "console", ".", "time", "(", "s", ")", ";", "this", ".", "_super", "(", "ctx", ",", "force", ",", "deep", ",", "collapsed", ")", ";", "window", ".", "console", "&&", "window", ".", "console", ".", "timeEnd", "&&", "window", ".", "console", ".", "timeEnd", "(", "s", ")", ";", "}" ]
Overide virtual methods for this extension
[ "Overide", "virtual", "methods", "for", "this", "extension" ]
c283370ec0f99a25db5bb7029a98b4febf8c5251
https://github.com/S3bb1/ah-dashboard-plugin/blob/c283370ec0f99a25db5bb7029a98b4febf8c5251/public/dashboard/bower_components/fancytree/dist/src/jquery.fancytree.debug.js#L133-L140
train
tentwentyfour/helpbox
source/create-error-type.js
createErrorType
function createErrorType(initialize = undefined, ErrorClass = undefined, prototype = undefined) { ErrorClass = ErrorClass || Error; let Constructor = function (message) { let error = Object.create(Constructor.prototype); error.message = message; error.stack = (new Error).stack; if (initialize) { initialize(error, message); } return error; }; Constructor.prototype = Object.assign(Object.create(ErrorClass.prototype), prototype); return Constructor; }
javascript
function createErrorType(initialize = undefined, ErrorClass = undefined, prototype = undefined) { ErrorClass = ErrorClass || Error; let Constructor = function (message) { let error = Object.create(Constructor.prototype); error.message = message; error.stack = (new Error).stack; if (initialize) { initialize(error, message); } return error; }; Constructor.prototype = Object.assign(Object.create(ErrorClass.prototype), prototype); return Constructor; }
[ "function", "createErrorType", "(", "initialize", "=", "undefined", ",", "ErrorClass", "=", "undefined", ",", "prototype", "=", "undefined", ")", "{", "ErrorClass", "=", "ErrorClass", "||", "Error", ";", "let", "Constructor", "=", "function", "(", "message", ")", "{", "let", "error", "=", "Object", ".", "create", "(", "Constructor", ".", "prototype", ")", ";", "error", ".", "message", "=", "message", ";", "error", ".", "stack", "=", "(", "new", "Error", ")", ".", "stack", ";", "if", "(", "initialize", ")", "{", "initialize", "(", "error", ",", "message", ")", ";", "}", "return", "error", ";", "}", ";", "Constructor", ".", "prototype", "=", "Object", ".", "assign", "(", "Object", ".", "create", "(", "ErrorClass", ".", "prototype", ")", ",", "prototype", ")", ";", "return", "Constructor", ";", "}" ]
Return a constructor for a new error type. @function createErrorType @param initialize {Function} A function that gets passed the constructed error and the passed message and runs during the construction of new instances. @param ErrorClass {Function} An error class you wish to subclass. Defaults to Error. @param prototype {Object} Additional properties and methods for the new error type. @return {Function} The constructor for the new error type.
[ "Return", "a", "constructor", "for", "a", "new", "error", "type", "." ]
94b802016d81391b486f02bd61f7ec89ff5fe8e7
https://github.com/tentwentyfour/helpbox/blob/94b802016d81391b486f02bd61f7ec89ff5fe8e7/source/create-error-type.js#L15-L34
train
joelvh/Sysmo.js
lib/sysmo.js
function(target, namespace, graph) { //if the first param is a string, //we are including the namespace on Sysmo if (typeof target == 'string') { graph = namespace; namespace = target; target = Sysmo; } //create namespace on target Sysmo.namespace(namespace, target); //get inner most object in namespace target = Sysmo.getDeepValue(target, namespace); //merge graph on inner most object in namespace return Sysmo.extend(target, graph); }
javascript
function(target, namespace, graph) { //if the first param is a string, //we are including the namespace on Sysmo if (typeof target == 'string') { graph = namespace; namespace = target; target = Sysmo; } //create namespace on target Sysmo.namespace(namespace, target); //get inner most object in namespace target = Sysmo.getDeepValue(target, namespace); //merge graph on inner most object in namespace return Sysmo.extend(target, graph); }
[ "function", "(", "target", ",", "namespace", ",", "graph", ")", "{", "if", "(", "typeof", "target", "==", "'string'", ")", "{", "graph", "=", "namespace", ";", "namespace", "=", "target", ";", "target", "=", "Sysmo", ";", "}", "Sysmo", ".", "namespace", "(", "namespace", ",", "target", ")", ";", "target", "=", "Sysmo", ".", "getDeepValue", "(", "target", ",", "namespace", ")", ";", "return", "Sysmo", ".", "extend", "(", "target", ",", "graph", ")", ";", "}" ]
include an object graph in another
[ "include", "an", "object", "graph", "in", "another" ]
0487e562437c3933f66f4c29505d0c50ccb3e8e9
https://github.com/joelvh/Sysmo.js/blob/0487e562437c3933f66f4c29505d0c50ccb3e8e9/lib/sysmo.js#L69-L86
train
joelvh/Sysmo.js
lib/sysmo.js
function(namespace, target) { target = target || {}; var names = namespace.split('.'), context = target; for (var i = 0; i < names.length; i++) { var name = names[i]; context = (name in context) ? context[name] : (context[name] = {}); } return target; }
javascript
function(namespace, target) { target = target || {}; var names = namespace.split('.'), context = target; for (var i = 0; i < names.length; i++) { var name = names[i]; context = (name in context) ? context[name] : (context[name] = {}); } return target; }
[ "function", "(", "namespace", ",", "target", ")", "{", "target", "=", "target", "||", "{", "}", ";", "var", "names", "=", "namespace", ".", "split", "(", "'.'", ")", ",", "context", "=", "target", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "{", "var", "name", "=", "names", "[", "i", "]", ";", "context", "=", "(", "name", "in", "context", ")", "?", "context", "[", "name", "]", ":", "(", "context", "[", "name", "]", "=", "{", "}", ")", ";", "}", "return", "target", ";", "}" ]
build an object graph from a namespace. adds properties to the target object or returns a new object graph.
[ "build", "an", "object", "graph", "from", "a", "namespace", ".", "adds", "properties", "to", "the", "target", "object", "or", "returns", "a", "new", "object", "graph", "." ]
0487e562437c3933f66f4c29505d0c50ccb3e8e9
https://github.com/joelvh/Sysmo.js/blob/0487e562437c3933f66f4c29505d0c50ccb3e8e9/lib/sysmo.js#L90-L103
train
joelvh/Sysmo.js
lib/sysmo.js
function (target, path, traverseArrays) { // if traversing arrays is enabled and this is an array, loop // may be a "array-like" node list (or similar), in which case it needs to be converted if (traverseArrays && Sysmo.isArrayLike(target)) { target = Sysmo.makeArray(target); var children = []; for (var i = 0; i < target.length; i++) { // recursively loop through children var child = Sysmo.getDeepValue(target[i], path, traverseArrays); // ignore if undefined if (typeof child != "undefined") { //flatten array because the original path points to one flat result set if (Sysmo.isArray(child)) { for (var j = 0; j < child.length; j++) { children.push(child[j]); } } else { children.push(child); } } } return (children.length) ? children : void(0); } var invoke_regex = /\(\)$/, properties = path.split('.'), property; if (target != null && properties.length) { var propertyName = properties.shift(), invoke = invoke_regex.test(propertyName) if (invoke) { propertyName = propertyName.replace(invoke_regex, ""); } if (invoke && propertyName in target) { target = target[propertyName](); } else { target = target[propertyName]; } path = properties.join('.'); if (path) { target = Sysmo.getDeepValue(target, path, traverseArrays); } } return target; }
javascript
function (target, path, traverseArrays) { // if traversing arrays is enabled and this is an array, loop // may be a "array-like" node list (or similar), in which case it needs to be converted if (traverseArrays && Sysmo.isArrayLike(target)) { target = Sysmo.makeArray(target); var children = []; for (var i = 0; i < target.length; i++) { // recursively loop through children var child = Sysmo.getDeepValue(target[i], path, traverseArrays); // ignore if undefined if (typeof child != "undefined") { //flatten array because the original path points to one flat result set if (Sysmo.isArray(child)) { for (var j = 0; j < child.length; j++) { children.push(child[j]); } } else { children.push(child); } } } return (children.length) ? children : void(0); } var invoke_regex = /\(\)$/, properties = path.split('.'), property; if (target != null && properties.length) { var propertyName = properties.shift(), invoke = invoke_regex.test(propertyName) if (invoke) { propertyName = propertyName.replace(invoke_regex, ""); } if (invoke && propertyName in target) { target = target[propertyName](); } else { target = target[propertyName]; } path = properties.join('.'); if (path) { target = Sysmo.getDeepValue(target, path, traverseArrays); } } return target; }
[ "function", "(", "target", ",", "path", ",", "traverseArrays", ")", "{", "if", "(", "traverseArrays", "&&", "Sysmo", ".", "isArrayLike", "(", "target", ")", ")", "{", "target", "=", "Sysmo", ".", "makeArray", "(", "target", ")", ";", "var", "children", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "target", ".", "length", ";", "i", "++", ")", "{", "var", "child", "=", "Sysmo", ".", "getDeepValue", "(", "target", "[", "i", "]", ",", "path", ",", "traverseArrays", ")", ";", "if", "(", "typeof", "child", "!=", "\"undefined\"", ")", "{", "if", "(", "Sysmo", ".", "isArray", "(", "child", ")", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "child", ".", "length", ";", "j", "++", ")", "{", "children", ".", "push", "(", "child", "[", "j", "]", ")", ";", "}", "}", "else", "{", "children", ".", "push", "(", "child", ")", ";", "}", "}", "}", "return", "(", "children", ".", "length", ")", "?", "children", ":", "void", "(", "0", ")", ";", "}", "var", "invoke_regex", "=", "/", "\\(\\)$", "/", ",", "properties", "=", "path", ".", "split", "(", "'.'", ")", ",", "property", ";", "if", "(", "target", "!=", "null", "&&", "properties", ".", "length", ")", "{", "var", "propertyName", "=", "properties", ".", "shift", "(", ")", ",", "invoke", "=", "invoke_regex", ".", "test", "(", "propertyName", ")", "if", "(", "invoke", ")", "{", "propertyName", "=", "propertyName", ".", "replace", "(", "invoke_regex", ",", "\"\"", ")", ";", "}", "if", "(", "invoke", "&&", "propertyName", "in", "target", ")", "{", "target", "=", "target", "[", "propertyName", "]", "(", ")", ";", "}", "else", "{", "target", "=", "target", "[", "propertyName", "]", ";", "}", "path", "=", "properties", ".", "join", "(", "'.'", ")", ";", "if", "(", "path", ")", "{", "target", "=", "Sysmo", ".", "getDeepValue", "(", "target", ",", "path", ",", "traverseArrays", ")", ";", "}", "}", "return", "target", ";", "}" ]
get the value of a property deeply nested in an object hierarchy
[ "get", "the", "value", "of", "a", "property", "deeply", "nested", "in", "an", "object", "hierarchy" ]
0487e562437c3933f66f4c29505d0c50ccb3e8e9
https://github.com/joelvh/Sysmo.js/blob/0487e562437c3933f66f4c29505d0c50ccb3e8e9/lib/sysmo.js#L105-L166
train
alv-ch/styleguide
src/assets/fabricator/scripts/fabricator.js
function () { var href = window.location.href, items = parsedItems(), id, index; // get window 'id' if (href.indexOf('#') > -1) { id = window.location.hash.replace('#', ''); } else { id = window.location.pathname.split('/').pop().replace(/\.[^/.]+$/, ''); } // In case the first menu item isn't the index page. if (id === '') { id = 'index'; } // find the window id in the items array index = (items.indexOf(id) > -1) ? items.indexOf(id) : 0; // set the matched item as active fabricator.dom.menuItems[index].classList.add('f-active'); }
javascript
function () { var href = window.location.href, items = parsedItems(), id, index; // get window 'id' if (href.indexOf('#') > -1) { id = window.location.hash.replace('#', ''); } else { id = window.location.pathname.split('/').pop().replace(/\.[^/.]+$/, ''); } // In case the first menu item isn't the index page. if (id === '') { id = 'index'; } // find the window id in the items array index = (items.indexOf(id) > -1) ? items.indexOf(id) : 0; // set the matched item as active fabricator.dom.menuItems[index].classList.add('f-active'); }
[ "function", "(", ")", "{", "var", "href", "=", "window", ".", "location", ".", "href", ",", "items", "=", "parsedItems", "(", ")", ",", "id", ",", "index", ";", "if", "(", "href", ".", "indexOf", "(", "'#'", ")", ">", "-", "1", ")", "{", "id", "=", "window", ".", "location", ".", "hash", ".", "replace", "(", "'#'", ",", "''", ")", ";", "}", "else", "{", "id", "=", "window", ".", "location", ".", "pathname", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", ".", "replace", "(", "/", "\\.[^/.]+$", "/", ",", "''", ")", ";", "}", "if", "(", "id", "===", "''", ")", "{", "id", "=", "'index'", ";", "}", "index", "=", "(", "items", ".", "indexOf", "(", "id", ")", ">", "-", "1", ")", "?", "items", ".", "indexOf", "(", "id", ")", ":", "0", ";", "fabricator", ".", "dom", ".", "menuItems", "[", "index", "]", ".", "classList", ".", "add", "(", "'f-active'", ")", ";", "}" ]
Match the 'id' in the window location with the menu item, set menu item as active
[ "Match", "the", "id", "in", "the", "window", "location", "with", "the", "menu", "item", "set", "menu", "item", "as", "active" ]
197269a8d80fdc760c1bf2b39f82cbc539c861d8
https://github.com/alv-ch/styleguide/blob/197269a8d80fdc760c1bf2b39f82cbc539c861d8/src/assets/fabricator/scripts/fabricator.js#L133-L157
train
ofzza/enTT
tasks/task-3-script-babel.js
sourceRootFn
function sourceRootFn (file) { let sourcePath = file.history[0], targetPath = path.join(__dirname, '../src/'), relativePath = path.join(path.relative(sourcePath, targetPath), './src'); return relativePath; }
javascript
function sourceRootFn (file) { let sourcePath = file.history[0], targetPath = path.join(__dirname, '../src/'), relativePath = path.join(path.relative(sourcePath, targetPath), './src'); return relativePath; }
[ "function", "sourceRootFn", "(", "file", ")", "{", "let", "sourcePath", "=", "file", ".", "history", "[", "0", "]", ",", "targetPath", "=", "path", ".", "join", "(", "__dirname", ",", "'../src/'", ")", ",", "relativePath", "=", "path", ".", "join", "(", "path", ".", "relative", "(", "sourcePath", ",", "targetPath", ")", ",", "'./src'", ")", ";", "return", "relativePath", ";", "}" ]
Composes source-maps' sourceRoot property for a file @param {any} file File being processed @returns {any} sourceRoot value
[ "Composes", "source", "-", "maps", "sourceRoot", "property", "for", "a", "file" ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/tasks/task-3-script-babel.js#L45-L50
train
ofzza/enTT
dist/ext/dynamic-properties.js
DynamicPropertiesExtension
function DynamicPropertiesExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$deferred = _ref.deferred, deferred = _ref$deferred === undefined ? false : _ref$deferred; _classCallCheck(this, DynamicPropertiesExtension); return _possibleConstructorReturn(this, (DynamicPropertiesExtension.__proto__ || Object.getPrototypeOf(DynamicPropertiesExtension)).call(this, { processShorthandPropertyConfiguration: true, updatePropertyConfiguration: true, // If not deferred, regenerate dynamic property value on initialization and change detected onEntityInstantiate: !deferred, onChangeDetected: !deferred, // If deferred, regenerate dynamic property value on get interceptPropertyGet: deferred })); }
javascript
function DynamicPropertiesExtension() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$deferred = _ref.deferred, deferred = _ref$deferred === undefined ? false : _ref$deferred; _classCallCheck(this, DynamicPropertiesExtension); return _possibleConstructorReturn(this, (DynamicPropertiesExtension.__proto__ || Object.getPrototypeOf(DynamicPropertiesExtension)).call(this, { processShorthandPropertyConfiguration: true, updatePropertyConfiguration: true, // If not deferred, regenerate dynamic property value on initialization and change detected onEntityInstantiate: !deferred, onChangeDetected: !deferred, // If deferred, regenerate dynamic property value on get interceptPropertyGet: deferred })); }
[ "function", "DynamicPropertiesExtension", "(", ")", "{", "var", "_ref", "=", "arguments", ".", "length", ">", "0", "&&", "arguments", "[", "0", "]", "!==", "undefined", "?", "arguments", "[", "0", "]", ":", "{", "}", ",", "_ref$deferred", "=", "_ref", ".", "deferred", ",", "deferred", "=", "_ref$deferred", "===", "undefined", "?", "false", ":", "_ref$deferred", ";", "_classCallCheck", "(", "this", ",", "DynamicPropertiesExtension", ")", ";", "return", "_possibleConstructorReturn", "(", "this", ",", "(", "DynamicPropertiesExtension", ".", "__proto__", "||", "Object", ".", "getPrototypeOf", "(", "DynamicPropertiesExtension", ")", ")", ".", "call", "(", "this", ",", "{", "processShorthandPropertyConfiguration", ":", "true", ",", "updatePropertyConfiguration", ":", "true", ",", "onEntityInstantiate", ":", "!", "deferred", ",", "onChangeDetected", ":", "!", "deferred", ",", "interceptPropertyGet", ":", "deferred", "}", ")", ")", ";", "}" ]
Creates an instance of DynamicPropertiesExtension. @param {any} deferred If true, the dynamic property value will be generated each time the property getter is called instead of on change detection @memberof DynamicPropertiesExtension
[ "Creates", "an", "instance", "of", "DynamicPropertiesExtension", "." ]
fdf27de4142b3c65a3e51dee70e0d7625dff897c
https://github.com/ofzza/enTT/blob/fdf27de4142b3c65a3e51dee70e0d7625dff897c/dist/ext/dynamic-properties.js#L54-L70
train
expo/project-repl
index.js
readFileAsync
async function readFileAsync(...args) { return new Promise((resolve, reject) => { fs.readFile(...args, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }
javascript
async function readFileAsync(...args) { return new Promise((resolve, reject) => { fs.readFile(...args, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); }
[ "async", "function", "readFileAsync", "(", "...", "args", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "readFile", "(", "...", "args", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "result", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Promise interface for `fs.readFile` @param {<string> | <Buffer> | <URL> | <integer>} p filename or file descriptor @param {<Object> | <string>} options
[ "Promise", "interface", "for", "fs", ".", "readFile" ]
9c4c91d6cbe9ce2c42a82329505b1148d06d6d44
https://github.com/expo/project-repl/blob/9c4c91d6cbe9ce2c42a82329505b1148d06d6d44/index.js#L12-L22
train
ggarek/debug-dude
lib/index.js
createLoggers
function createLoggers(ns) { var debug = (0, _debug2['default'])(ns + ':debug'); debug.log = function () { return console.log.apply(console, arguments); }; var log = (0, _debug2['default'])(ns + ':log'); log.log = function () { return console.log.apply(console, arguments); }; var info = (0, _debug2['default'])(ns + ':info'); info.log = function () { return console.info.apply(console, arguments); }; var warn = (0, _debug2['default'])(ns + ':warn'); warn.log = function () { return console.warn.apply(console, arguments); }; var error = (0, _debug2['default'])(ns + ':error'); error.log = function () { return console.error.apply(console, arguments); }; return { debug: debug, log: log, info: info, warn: warn, error: error }; }
javascript
function createLoggers(ns) { var debug = (0, _debug2['default'])(ns + ':debug'); debug.log = function () { return console.log.apply(console, arguments); }; var log = (0, _debug2['default'])(ns + ':log'); log.log = function () { return console.log.apply(console, arguments); }; var info = (0, _debug2['default'])(ns + ':info'); info.log = function () { return console.info.apply(console, arguments); }; var warn = (0, _debug2['default'])(ns + ':warn'); warn.log = function () { return console.warn.apply(console, arguments); }; var error = (0, _debug2['default'])(ns + ':error'); error.log = function () { return console.error.apply(console, arguments); }; return { debug: debug, log: log, info: info, warn: warn, error: error }; }
[ "function", "createLoggers", "(", "ns", ")", "{", "var", "debug", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':debug'", ")", ";", "debug", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "log", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "log", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':log'", ")", ";", "log", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "log", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "info", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':info'", ")", ";", "info", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "info", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "warn", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':warn'", ")", ";", "warn", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "warn", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "var", "error", "=", "(", "0", ",", "_debug2", "[", "'default'", "]", ")", "(", "ns", "+", "':error'", ")", ";", "error", ".", "log", "=", "function", "(", ")", "{", "return", "console", ".", "error", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "return", "{", "debug", ":", "debug", ",", "log", ":", "log", ",", "info", ":", "info", ",", "warn", ":", "warn", ",", "error", ":", "error", "}", ";", "}" ]
Create debug instances and bind log method to specific console method
[ "Create", "debug", "instances", "and", "bind", "log", "method", "to", "specific", "console", "method" ]
c6ddca34863630a7d257f22b9ea332110cdb60c5
https://github.com/ggarek/debug-dude/blob/c6ddca34863630a7d257f22b9ea332110cdb60c5/lib/index.js#L18-L51
train
mikolalysenko/red-blue-line-segment-intersect
rblsi.js
BruteForceList
function BruteForceList(capacity) { this.intervals = pool.mallocDouble(2 * capacity) this.index = pool.mallocInt32(capacity) this.count = 0 }
javascript
function BruteForceList(capacity) { this.intervals = pool.mallocDouble(2 * capacity) this.index = pool.mallocInt32(capacity) this.count = 0 }
[ "function", "BruteForceList", "(", "capacity", ")", "{", "this", ".", "intervals", "=", "pool", ".", "mallocDouble", "(", "2", "*", "capacity", ")", "this", ".", "index", "=", "pool", ".", "mallocInt32", "(", "capacity", ")", "this", ".", "count", "=", "0", "}" ]
It is silly, but this is faster than doing the right thing for up to a few thousand segments, which hardly occurs in practice.
[ "It", "is", "silly", "but", "this", "is", "faster", "than", "doing", "the", "right", "thing", "for", "up", "to", "a", "few", "thousand", "segments", "which", "hardly", "occurs", "in", "practice", "." ]
d8ecd805e1846d8f3644ef84b410cb6110c1c00f
https://github.com/mikolalysenko/red-blue-line-segment-intersect/blob/d8ecd805e1846d8f3644ef84b410cb6110c1c00f/rblsi.js#L55-L59
train
yaniswang/PromiseClass
lib/promiseclass.js
chaiSupportChainPromise
function chaiSupportChainPromise(chai, utils){ function copyChainPromise(promise, assertion){ let protoPromise = Object.getPrototypeOf(promise); let protoNames = Object.getOwnPropertyNames(protoPromise); let protoAssertion = Object.getPrototypeOf(assertion); protoNames.forEach(function(protoName){ if(protoName !== 'constructor' && !protoAssertion[protoName]){ assertion[protoName] = promise[protoName].bind(promise); } }); } function doAsserterAsync(asserter, assertion, args){ let self = utils.flag(assertion, "object"); if(self && self.then && typeof self.then === "function"){ let promise = self.then(function(value){ assertion._obj = value; asserter.apply(assertion, args); return value; }, function(error){ assertion._obj = new Error(error); asserter.apply(assertion, args); }); copyChainPromise(promise, assertion); } else{ return asserter.apply(assertion, args); } } let Assertion = chai.Assertion; let propertyNames = Object.getOwnPropertyNames(Assertion.prototype); let propertyDescs = {}; propertyNames.forEach(function (name) { propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name); }); let methodNames = propertyNames.filter(function (name) { return name !== "assert" && typeof propertyDescs[name].value === "function"; }); methodNames.forEach(function (methodName) { Assertion.overwriteMethod(methodName, function (originalMethod) { return function () { doAsserterAsync(originalMethod, this, arguments); }; }); }); let getterNames = propertyNames.filter(function (name) { return name !== "_obj" && typeof propertyDescs[name].get === "function"; }); getterNames.forEach(function (getterName) { let isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName); if (isChainableMethod) { Assertion.overwriteChainableMethod( getterName, function (originalMethod) { return function() { doAsserterAsync(originalMethod, this, arguments); }; }, function (originalGetter) { return function() { doAsserterAsync(originalGetter, this); }; } ); } else { Assertion.overwriteProperty(getterName, function (originalGetter) { return function () { doAsserterAsync(originalGetter, this); }; }); } }); }
javascript
function chaiSupportChainPromise(chai, utils){ function copyChainPromise(promise, assertion){ let protoPromise = Object.getPrototypeOf(promise); let protoNames = Object.getOwnPropertyNames(protoPromise); let protoAssertion = Object.getPrototypeOf(assertion); protoNames.forEach(function(protoName){ if(protoName !== 'constructor' && !protoAssertion[protoName]){ assertion[protoName] = promise[protoName].bind(promise); } }); } function doAsserterAsync(asserter, assertion, args){ let self = utils.flag(assertion, "object"); if(self && self.then && typeof self.then === "function"){ let promise = self.then(function(value){ assertion._obj = value; asserter.apply(assertion, args); return value; }, function(error){ assertion._obj = new Error(error); asserter.apply(assertion, args); }); copyChainPromise(promise, assertion); } else{ return asserter.apply(assertion, args); } } let Assertion = chai.Assertion; let propertyNames = Object.getOwnPropertyNames(Assertion.prototype); let propertyDescs = {}; propertyNames.forEach(function (name) { propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name); }); let methodNames = propertyNames.filter(function (name) { return name !== "assert" && typeof propertyDescs[name].value === "function"; }); methodNames.forEach(function (methodName) { Assertion.overwriteMethod(methodName, function (originalMethod) { return function () { doAsserterAsync(originalMethod, this, arguments); }; }); }); let getterNames = propertyNames.filter(function (name) { return name !== "_obj" && typeof propertyDescs[name].get === "function"; }); getterNames.forEach(function (getterName) { let isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName); if (isChainableMethod) { Assertion.overwriteChainableMethod( getterName, function (originalMethod) { return function() { doAsserterAsync(originalMethod, this, arguments); }; }, function (originalGetter) { return function() { doAsserterAsync(originalGetter, this); }; } ); } else { Assertion.overwriteProperty(getterName, function (originalGetter) { return function () { doAsserterAsync(originalGetter, this); }; }); } }); }
[ "function", "chaiSupportChainPromise", "(", "chai", ",", "utils", ")", "{", "function", "copyChainPromise", "(", "promise", ",", "assertion", ")", "{", "let", "protoPromise", "=", "Object", ".", "getPrototypeOf", "(", "promise", ")", ";", "let", "protoNames", "=", "Object", ".", "getOwnPropertyNames", "(", "protoPromise", ")", ";", "let", "protoAssertion", "=", "Object", ".", "getPrototypeOf", "(", "assertion", ")", ";", "protoNames", ".", "forEach", "(", "function", "(", "protoName", ")", "{", "if", "(", "protoName", "!==", "'constructor'", "&&", "!", "protoAssertion", "[", "protoName", "]", ")", "{", "assertion", "[", "protoName", "]", "=", "promise", "[", "protoName", "]", ".", "bind", "(", "promise", ")", ";", "}", "}", ")", ";", "}", "function", "doAsserterAsync", "(", "asserter", ",", "assertion", ",", "args", ")", "{", "let", "self", "=", "utils", ".", "flag", "(", "assertion", ",", "\"object\"", ")", ";", "if", "(", "self", "&&", "self", ".", "then", "&&", "typeof", "self", ".", "then", "===", "\"function\"", ")", "{", "let", "promise", "=", "self", ".", "then", "(", "function", "(", "value", ")", "{", "assertion", ".", "_obj", "=", "value", ";", "asserter", ".", "apply", "(", "assertion", ",", "args", ")", ";", "return", "value", ";", "}", ",", "function", "(", "error", ")", "{", "assertion", ".", "_obj", "=", "new", "Error", "(", "error", ")", ";", "asserter", ".", "apply", "(", "assertion", ",", "args", ")", ";", "}", ")", ";", "copyChainPromise", "(", "promise", ",", "assertion", ")", ";", "}", "else", "{", "return", "asserter", ".", "apply", "(", "assertion", ",", "args", ")", ";", "}", "}", "let", "Assertion", "=", "chai", ".", "Assertion", ";", "let", "propertyNames", "=", "Object", ".", "getOwnPropertyNames", "(", "Assertion", ".", "prototype", ")", ";", "let", "propertyDescs", "=", "{", "}", ";", "propertyNames", ".", "forEach", "(", "function", "(", "name", ")", "{", "propertyDescs", "[", "name", "]", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "Assertion", ".", "prototype", ",", "name", ")", ";", "}", ")", ";", "let", "methodNames", "=", "propertyNames", ".", "filter", "(", "function", "(", "name", ")", "{", "return", "name", "!==", "\"assert\"", "&&", "typeof", "propertyDescs", "[", "name", "]", ".", "value", "===", "\"function\"", ";", "}", ")", ";", "methodNames", ".", "forEach", "(", "function", "(", "methodName", ")", "{", "Assertion", ".", "overwriteMethod", "(", "methodName", ",", "function", "(", "originalMethod", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalMethod", ",", "this", ",", "arguments", ")", ";", "}", ";", "}", ")", ";", "}", ")", ";", "let", "getterNames", "=", "propertyNames", ".", "filter", "(", "function", "(", "name", ")", "{", "return", "name", "!==", "\"_obj\"", "&&", "typeof", "propertyDescs", "[", "name", "]", ".", "get", "===", "\"function\"", ";", "}", ")", ";", "getterNames", ".", "forEach", "(", "function", "(", "getterName", ")", "{", "let", "isChainableMethod", "=", "Assertion", ".", "prototype", ".", "__methods", ".", "hasOwnProperty", "(", "getterName", ")", ";", "if", "(", "isChainableMethod", ")", "{", "Assertion", ".", "overwriteChainableMethod", "(", "getterName", ",", "function", "(", "originalMethod", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalMethod", ",", "this", ",", "arguments", ")", ";", "}", ";", "}", ",", "function", "(", "originalGetter", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalGetter", ",", "this", ")", ";", "}", ";", "}", ")", ";", "}", "else", "{", "Assertion", ".", "overwriteProperty", "(", "getterName", ",", "function", "(", "originalGetter", ")", "{", "return", "function", "(", ")", "{", "doAsserterAsync", "(", "originalGetter", ",", "this", ")", ";", "}", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
support ChainPromise for chai
[ "support", "ChainPromise", "for", "chai" ]
3ead8295500618eb7730eecb71ebcbb3294b9729
https://github.com/yaniswang/PromiseClass/blob/3ead8295500618eb7730eecb71ebcbb3294b9729/lib/promiseclass.js#L161-L237
train
tcardoso2/vermon
PluginManager.js
RemovePlugin
function RemovePlugin (ext_module_id) { let copy = plugins[ext_module_id] let runPreWorkflowFunctions = function () { if (!plugins[ext_module_id].PreRemovePlugin) throw new Error('Error: PreRemovePlugin function must be implemented.') plugins[ext_module_id].PreRemovePlugin() } let runPostWorkflowFunctions = function () { if (!copy.PostRemovePlugin) throw new Error('Error: PostRemovePlugin function must be implemented.') copy.PostRemovePlugin(module.exports) } runPreWorkflowFunctions() delete plugins[ext_module_id] log.info('Removed Plugin', ext_module_id) runPostWorkflowFunctions() return true }
javascript
function RemovePlugin (ext_module_id) { let copy = plugins[ext_module_id] let runPreWorkflowFunctions = function () { if (!plugins[ext_module_id].PreRemovePlugin) throw new Error('Error: PreRemovePlugin function must be implemented.') plugins[ext_module_id].PreRemovePlugin() } let runPostWorkflowFunctions = function () { if (!copy.PostRemovePlugin) throw new Error('Error: PostRemovePlugin function must be implemented.') copy.PostRemovePlugin(module.exports) } runPreWorkflowFunctions() delete plugins[ext_module_id] log.info('Removed Plugin', ext_module_id) runPostWorkflowFunctions() return true }
[ "function", "RemovePlugin", "(", "ext_module_id", ")", "{", "let", "copy", "=", "plugins", "[", "ext_module_id", "]", "let", "runPreWorkflowFunctions", "=", "function", "(", ")", "{", "if", "(", "!", "plugins", "[", "ext_module_id", "]", ".", "PreRemovePlugin", ")", "throw", "new", "Error", "(", "'Error: PreRemovePlugin function must be implemented.'", ")", "plugins", "[", "ext_module_id", "]", ".", "PreRemovePlugin", "(", ")", "}", "let", "runPostWorkflowFunctions", "=", "function", "(", ")", "{", "if", "(", "!", "copy", ".", "PostRemovePlugin", ")", "throw", "new", "Error", "(", "'Error: PostRemovePlugin function must be implemented.'", ")", "copy", ".", "PostRemovePlugin", "(", "module", ".", "exports", ")", "}", "runPreWorkflowFunctions", "(", ")", "delete", "plugins", "[", "ext_module_id", "]", "log", ".", "info", "(", "'Removed Plugin'", ",", "ext_module_id", ")", "runPostWorkflowFunctions", "(", ")", "return", "true", "}" ]
Removes an existing Extention plugin from the library @param {string} ext_module_id is the id of the module to remove. @return {boolean} True the plugin was successfully removed.
[ "Removes", "an", "existing", "Extention", "plugin", "from", "the", "library" ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/PluginManager.js#L54-L73
train
tcardoso2/vermon
main.js
_InternalAddEnvironment
function _InternalAddEnvironment (env = new ent.Environment()) { if (env instanceof ent.Environment) { em.SetEnvironment(env) return true } else { log.warning("'environment' object is not of type Environment") } return false }
javascript
function _InternalAddEnvironment (env = new ent.Environment()) { if (env instanceof ent.Environment) { em.SetEnvironment(env) return true } else { log.warning("'environment' object is not of type Environment") } return false }
[ "function", "_InternalAddEnvironment", "(", "env", "=", "new", "ent", ".", "Environment", "(", ")", ")", "{", "if", "(", "env", "instanceof", "ent", ".", "Environment", ")", "{", "em", ".", "SetEnvironment", "(", "env", ")", "return", "true", "}", "else", "{", "log", ".", "warning", "(", "\"'environment' object is not of type Environment\"", ")", "}", "return", "false", "}" ]
Adds an Environment into the current context. The environment needs to be if instance Environment, if not if fails silently, logs the error in the logger and returns false. @param {object} env is the Environment object to add. This function is internal @internal @returns {Boolean} true if the environment is successfully created.
[ "Adds", "an", "Environment", "into", "the", "current", "context", ".", "The", "environment", "needs", "to", "be", "if", "instance", "Environment", "if", "not", "if", "fails", "silently", "logs", "the", "error", "in", "the", "logger", "and", "returns", "false", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L69-L77
train
tcardoso2/vermon
main.js
AddDetectorToSubEnvironmentOnly
function AddDetectorToSubEnvironmentOnly (detector, force = false, subEnvironment) { return em.AddDetectorToSubEnvironmentOnly(detector, force, subEnvironment) }
javascript
function AddDetectorToSubEnvironmentOnly (detector, force = false, subEnvironment) { return em.AddDetectorToSubEnvironmentOnly(detector, force, subEnvironment) }
[ "function", "AddDetectorToSubEnvironmentOnly", "(", "detector", ",", "force", "=", "false", ",", "subEnvironment", ")", "{", "return", "em", ".", "AddDetectorToSubEnvironmentOnly", "(", "detector", ",", "force", ",", "subEnvironment", ")", "}" ]
Adds a detector to a SubEnvironment. Assumes that the main Environment is a MultiEnvironment. @param {object} detector is the MotionDetector object to add. @param {boolean} force can be set to true to push the detector even if not of {MotionDetector} instance @param {string} subEnvironment is the Environment to add to, within the MultiEnvironment @returns {Boolean} true if the detector is successfully created. @public
[ "Adds", "a", "detector", "to", "a", "SubEnvironment", ".", "Assumes", "that", "the", "main", "Environment", "is", "a", "MultiEnvironment", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L167-L169
train
tcardoso2/vermon
main.js
RemoveNotifier
function RemoveNotifier (notifier, silent = false) { let index = em.GetNotifiers().indexOf(notifier) log.info('Removing Notifier...') if (index > -1) { if (!silent) { em.GetNotifiers()[index].notify('Removing Notifier...') } em.GetNotifiers().splice(index, 1) return true } else { log.info(chalk.yellow(`Notifier ${notifier} not found, ignoring and returning false...`)) } return false }
javascript
function RemoveNotifier (notifier, silent = false) { let index = em.GetNotifiers().indexOf(notifier) log.info('Removing Notifier...') if (index > -1) { if (!silent) { em.GetNotifiers()[index].notify('Removing Notifier...') } em.GetNotifiers().splice(index, 1) return true } else { log.info(chalk.yellow(`Notifier ${notifier} not found, ignoring and returning false...`)) } return false }
[ "function", "RemoveNotifier", "(", "notifier", ",", "silent", "=", "false", ")", "{", "let", "index", "=", "em", ".", "GetNotifiers", "(", ")", ".", "indexOf", "(", "notifier", ")", "log", ".", "info", "(", "'Removing Notifier...'", ")", "if", "(", "index", ">", "-", "1", ")", "{", "if", "(", "!", "silent", ")", "{", "em", ".", "GetNotifiers", "(", ")", "[", "index", "]", ".", "notify", "(", "'Removing Notifier...'", ")", "}", "em", ".", "GetNotifiers", "(", ")", ".", "splice", "(", "index", ",", "1", ")", "return", "true", "}", "else", "{", "log", ".", "info", "(", "chalk", ".", "yellow", "(", "`", "${", "notifier", "}", "`", ")", ")", "}", "return", "false", "}" ]
Removes an existing notifier from the context. Does not fail if the notifier is not found. @param {object} notifier is the notifier instance to remove. @param {booleal} sileng states if = true the removal should not send a notification @returns true if the notifier was found (and subsequently removed). @public
[ "Removes", "an", "existing", "notifier", "from", "the", "context", ".", "Does", "not", "fail", "if", "the", "notifier", "is", "not", "found", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L203-L216
train
tcardoso2/vermon
main.js
RemoveDetector
function RemoveDetector (detector) { let index = motionDetectors.indexOf(detector) log.info('Removing Detector...') if (index > -1) { em.GetEnvironment().unbindDetector(detector) motionDetectors.splice(index, 1) // Redundant: Motion detectors are also copied to environment! em.GetEnvironment().motionDetectors.splice(index, 1) return true } else { log.info(chalk.yellow(`Detector ${detector} not found, ignoring and returning false...`)) } return false }
javascript
function RemoveDetector (detector) { let index = motionDetectors.indexOf(detector) log.info('Removing Detector...') if (index > -1) { em.GetEnvironment().unbindDetector(detector) motionDetectors.splice(index, 1) // Redundant: Motion detectors are also copied to environment! em.GetEnvironment().motionDetectors.splice(index, 1) return true } else { log.info(chalk.yellow(`Detector ${detector} not found, ignoring and returning false...`)) } return false }
[ "function", "RemoveDetector", "(", "detector", ")", "{", "let", "index", "=", "motionDetectors", ".", "indexOf", "(", "detector", ")", "log", ".", "info", "(", "'Removing Detector...'", ")", "if", "(", "index", ">", "-", "1", ")", "{", "em", ".", "GetEnvironment", "(", ")", ".", "unbindDetector", "(", "detector", ")", "motionDetectors", ".", "splice", "(", "index", ",", "1", ")", "em", ".", "GetEnvironment", "(", ")", ".", "motionDetectors", ".", "splice", "(", "index", ",", "1", ")", "return", "true", "}", "else", "{", "log", ".", "info", "(", "chalk", ".", "yellow", "(", "`", "${", "detector", "}", "`", ")", ")", "}", "return", "false", "}" ]
Removes an existing MotionDetector from the context, including its event listeners. Does not fail if the detector is not found. @param {object} detector is the MotionDetector instance to remove. @returns true if the detector was found (and subsequently removed). @public
[ "Removes", "an", "existing", "MotionDetector", "from", "the", "context", "including", "its", "event", "listeners", ".", "Does", "not", "fail", "if", "the", "detector", "is", "not", "found", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L225-L238
train
tcardoso2/vermon
main.js
GetSubEnvironment
function GetSubEnvironment (subEnvironmentName) { let e = GetSubEnvironments()[subEnvironmentName] if (!e) { throw new Error('SubEnvironment does not exist.') } if (!(e instanceof ent.Environment)) { throw new Error('SubEnvironment is invalid.') } return e }
javascript
function GetSubEnvironment (subEnvironmentName) { let e = GetSubEnvironments()[subEnvironmentName] if (!e) { throw new Error('SubEnvironment does not exist.') } if (!(e instanceof ent.Environment)) { throw new Error('SubEnvironment is invalid.') } return e }
[ "function", "GetSubEnvironment", "(", "subEnvironmentName", ")", "{", "let", "e", "=", "GetSubEnvironments", "(", ")", "[", "subEnvironmentName", "]", "if", "(", "!", "e", ")", "{", "throw", "new", "Error", "(", "'SubEnvironment does not exist.'", ")", "}", "if", "(", "!", "(", "e", "instanceof", "ent", ".", "Environment", ")", ")", "{", "throw", "new", "Error", "(", "'SubEnvironment is invalid.'", ")", "}", "return", "e", "}" ]
Gets a particular sub-Environments of the context, raises error if it's not of type Environment. @returns Environment object. @public
[ "Gets", "a", "particular", "sub", "-", "Environments", "of", "the", "context", "raises", "error", "if", "it", "s", "not", "of", "type", "Environment", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L273-L282
train
tcardoso2/vermon
main.js
GetMotionDetector
function GetMotionDetector (name) { // It's assumed the number of motion detectors will be sufficiently small to be ok to iterate without major loss of efficiency console.log("Attention! this function GetMotionDetectors returns a singleton of motion detectors! If you are running several instances only one instance prevails!"); return _.filter(motionDetectors, x => x.name === name)[0] // Another alternative way: lodash.filter(motionDetectors, { 'name': 'Something' } ); }
javascript
function GetMotionDetector (name) { // It's assumed the number of motion detectors will be sufficiently small to be ok to iterate without major loss of efficiency console.log("Attention! this function GetMotionDetectors returns a singleton of motion detectors! If you are running several instances only one instance prevails!"); return _.filter(motionDetectors, x => x.name === name)[0] // Another alternative way: lodash.filter(motionDetectors, { 'name': 'Something' } ); }
[ "function", "GetMotionDetector", "(", "name", ")", "{", "console", ".", "log", "(", "\"Attention! this function GetMotionDetectors returns a singleton of motion detectors! If you are running several instances only one instance prevails!\"", ")", ";", "return", "_", ".", "filter", "(", "motionDetectors", ",", "x", "=>", "x", ".", "name", "===", "name", ")", "[", "0", "]", "}" ]
Gets the Motion Detectors with the given name. Will throw an exception if there is no Motion detector with such name. @param {string} name is the name of the MotionDetector instance to get. @returns a MotionDetector objects. Attention! motion detectors is a singleton! @public
[ "Gets", "the", "Motion", "Detectors", "with", "the", "given", "name", ".", "Will", "throw", "an", "exception", "if", "there", "is", "no", "Motion", "detector", "with", "such", "name", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L313-L318
train
tcardoso2/vermon
main.js
GetFilters
function GetFilters () { let result = [] log.debug(`Fetching filters in the existing ${motionDetectors.length} detector(s)...`) for (let i in motionDetectors) { result = result.concat(motionDetectors[i].filters) } log.debug(`Getting ${result.length} filters...`) return result }
javascript
function GetFilters () { let result = [] log.debug(`Fetching filters in the existing ${motionDetectors.length} detector(s)...`) for (let i in motionDetectors) { result = result.concat(motionDetectors[i].filters) } log.debug(`Getting ${result.length} filters...`) return result }
[ "function", "GetFilters", "(", ")", "{", "let", "result", "=", "[", "]", "log", ".", "debug", "(", "`", "${", "motionDetectors", ".", "length", "}", "`", ")", "for", "(", "let", "i", "in", "motionDetectors", ")", "{", "result", "=", "result", ".", "concat", "(", "motionDetectors", "[", "i", "]", ".", "filters", ")", "}", "log", ".", "debug", "(", "`", "${", "result", ".", "length", "}", "`", ")", "return", "result", "}" ]
Gets all the existing Filters present in the current context. @returns {object} an Array of Filter objects. @public
[ "Gets", "all", "the", "existing", "Filters", "present", "in", "the", "current", "context", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L325-L333
train
tcardoso2/vermon
main.js
Reset
function Reset () { log.info('Reseting environment...') for (let m in motionDetectors) { RemoveDetector(motionDetectors[m]) } for (let n in em.GetNotifiers()) { RemoveNotifier(em.GetNotifiers()[n], true) } em.SetNotifiers([]) if (em.GetEnvironment()) { em.GetEnvironment().removeAllListeners('changedState') em.GetEnvironment().exit() em.SetEnvironment(undefined) } motionDetectors = [] Object.keys(pm.GetPlugins()).forEach(function (key) { let p = pm.GetPlugins()[key] console.log(` Attempting to reset plugin ${p.id} with key ${key}...`) if (p.Reset) { p.Reset() log.info('ok.') } }) pm.ResetPlugins() config = {} log.info('Done Reseting environment.') }
javascript
function Reset () { log.info('Reseting environment...') for (let m in motionDetectors) { RemoveDetector(motionDetectors[m]) } for (let n in em.GetNotifiers()) { RemoveNotifier(em.GetNotifiers()[n], true) } em.SetNotifiers([]) if (em.GetEnvironment()) { em.GetEnvironment().removeAllListeners('changedState') em.GetEnvironment().exit() em.SetEnvironment(undefined) } motionDetectors = [] Object.keys(pm.GetPlugins()).forEach(function (key) { let p = pm.GetPlugins()[key] console.log(` Attempting to reset plugin ${p.id} with key ${key}...`) if (p.Reset) { p.Reset() log.info('ok.') } }) pm.ResetPlugins() config = {} log.info('Done Reseting environment.') }
[ "function", "Reset", "(", ")", "{", "log", ".", "info", "(", "'Reseting environment...'", ")", "for", "(", "let", "m", "in", "motionDetectors", ")", "{", "RemoveDetector", "(", "motionDetectors", "[", "m", "]", ")", "}", "for", "(", "let", "n", "in", "em", ".", "GetNotifiers", "(", ")", ")", "{", "RemoveNotifier", "(", "em", ".", "GetNotifiers", "(", ")", "[", "n", "]", ",", "true", ")", "}", "em", ".", "SetNotifiers", "(", "[", "]", ")", "if", "(", "em", ".", "GetEnvironment", "(", ")", ")", "{", "em", ".", "GetEnvironment", "(", ")", ".", "removeAllListeners", "(", "'changedState'", ")", "em", ".", "GetEnvironment", "(", ")", ".", "exit", "(", ")", "em", ".", "SetEnvironment", "(", "undefined", ")", "}", "motionDetectors", "=", "[", "]", "Object", ".", "keys", "(", "pm", ".", "GetPlugins", "(", ")", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "let", "p", "=", "pm", ".", "GetPlugins", "(", ")", "[", "key", "]", "console", ".", "log", "(", "`", "${", "p", ".", "id", "}", "${", "key", "}", "`", ")", "if", "(", "p", ".", "Reset", ")", "{", "p", ".", "Reset", "(", ")", "log", ".", "info", "(", "'ok.'", ")", "}", "}", ")", "pm", ".", "ResetPlugins", "(", ")", "config", "=", "{", "}", "log", ".", "info", "(", "'Done Reseting environment.'", ")", "}" ]
Resets the current context environment, notifiers and motion detectors. @public
[ "Resets", "the", "current", "context", "environment", "notifiers", "and", "motion", "detectors", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L339-L365
train
tcardoso2/vermon
main.js
_StartPlugins
function _StartPlugins (e, m, n, f) { log.info(`Checking if any plugin exists which should be started...`) let plugins = pm.GetPlugins() Object.keys(plugins).forEach(function (key) { let p = plugins[key] log.info(` Plugin found. Checking plugin signature methods ShouldStart and Start for plugin ${key}...`) if (!p.ShouldStart) throw new Error("A plugin must have a 'ShouldStart' method implemented.") if (!p.Start) throw new Error("A plugin must have a 'Start' method implemented.") // TODO, add a way to call StartWithConfig log.info(' Checking if plugin should start...') if (p.ShouldStart(e, m, n, f, config)) { log.info('Plugin should start = true. Starting plugin...') p.Start(e, m, n, f, config) } else { log.info('Plugin will not start because returned false when asked if it should start.') } console.log('ok.') }) }
javascript
function _StartPlugins (e, m, n, f) { log.info(`Checking if any plugin exists which should be started...`) let plugins = pm.GetPlugins() Object.keys(plugins).forEach(function (key) { let p = plugins[key] log.info(` Plugin found. Checking plugin signature methods ShouldStart and Start for plugin ${key}...`) if (!p.ShouldStart) throw new Error("A plugin must have a 'ShouldStart' method implemented.") if (!p.Start) throw new Error("A plugin must have a 'Start' method implemented.") // TODO, add a way to call StartWithConfig log.info(' Checking if plugin should start...') if (p.ShouldStart(e, m, n, f, config)) { log.info('Plugin should start = true. Starting plugin...') p.Start(e, m, n, f, config) } else { log.info('Plugin will not start because returned false when asked if it should start.') } console.log('ok.') }) }
[ "function", "_StartPlugins", "(", "e", ",", "m", ",", "n", ",", "f", ")", "{", "log", ".", "info", "(", "`", "`", ")", "let", "plugins", "=", "pm", ".", "GetPlugins", "(", ")", "Object", ".", "keys", "(", "plugins", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "let", "p", "=", "plugins", "[", "key", "]", "log", ".", "info", "(", "`", "${", "key", "}", "`", ")", "if", "(", "!", "p", ".", "ShouldStart", ")", "throw", "new", "Error", "(", "\"A plugin must have a 'ShouldStart' method implemented.\"", ")", "if", "(", "!", "p", ".", "Start", ")", "throw", "new", "Error", "(", "\"A plugin must have a 'Start' method implemented.\"", ")", "log", ".", "info", "(", "' Checking if plugin should start...'", ")", "if", "(", "p", ".", "ShouldStart", "(", "e", ",", "m", ",", "n", ",", "f", ",", "config", ")", ")", "{", "log", ".", "info", "(", "'Plugin should start = true. Starting plugin...'", ")", "p", ".", "Start", "(", "e", ",", "m", ",", "n", ",", "f", ",", "config", ")", "}", "else", "{", "log", ".", "info", "(", "'Plugin will not start because returned false when asked if it should start.'", ")", "}", "console", ".", "log", "(", "'ok.'", ")", "}", ")", "}" ]
Internal function which Starts all the Plugins, ran when StartWithConfir is called. Throws an Error if any of the plugins does not implement the "Start" method. @param {e} The current Environment. @param {m} The current MotionDetectors. @param {n} The current Notifiers. @param {f} The current Filters.
[ "Internal", "function", "which", "Starts", "all", "the", "Plugins", "ran", "when", "StartWithConfir", "is", "called", ".", "Throws", "an", "Error", "if", "any", "of", "the", "plugins", "does", "not", "implement", "the", "Start", "method", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L417-L435
train
tcardoso2/vermon
main.js
SaveAllToConfig
function SaveAllToConfig (src, callback, force = false) { let status = 1 let message let resultError = function (message) { message = `Error: ${message}` log.error(message) callback(1, message) } let resultWarning = function (message) { message = `Warn: ${message}` log.warning(message) callback(0, message) } let addConfigDefinitions = function (jsonContent) { return jsonContent = 'profiles = ' + jsonContent + '\nexports.profiles = profiles;' + '\nexports.default = profiles.default;' } if (fs.existsSync(src) && !force) { return resultError('File exists, if you want to overwrite it, use the force attribute') } else { let contents = addConfigDefinitions(_InternalSerializeCurrentContext()) fs.writeFile(src, contents, function (err) { if (err) { return resultError(err) } else { status = 0 message = 'Success' } callback(status, message) }) } }
javascript
function SaveAllToConfig (src, callback, force = false) { let status = 1 let message let resultError = function (message) { message = `Error: ${message}` log.error(message) callback(1, message) } let resultWarning = function (message) { message = `Warn: ${message}` log.warning(message) callback(0, message) } let addConfigDefinitions = function (jsonContent) { return jsonContent = 'profiles = ' + jsonContent + '\nexports.profiles = profiles;' + '\nexports.default = profiles.default;' } if (fs.existsSync(src) && !force) { return resultError('File exists, if you want to overwrite it, use the force attribute') } else { let contents = addConfigDefinitions(_InternalSerializeCurrentContext()) fs.writeFile(src, contents, function (err) { if (err) { return resultError(err) } else { status = 0 message = 'Success' } callback(status, message) }) } }
[ "function", "SaveAllToConfig", "(", "src", ",", "callback", ",", "force", "=", "false", ")", "{", "let", "status", "=", "1", "let", "message", "let", "resultError", "=", "function", "(", "message", ")", "{", "message", "=", "`", "${", "message", "}", "`", "log", ".", "error", "(", "message", ")", "callback", "(", "1", ",", "message", ")", "}", "let", "resultWarning", "=", "function", "(", "message", ")", "{", "message", "=", "`", "${", "message", "}", "`", "log", ".", "warning", "(", "message", ")", "callback", "(", "0", ",", "message", ")", "}", "let", "addConfigDefinitions", "=", "function", "(", "jsonContent", ")", "{", "return", "jsonContent", "=", "'profiles = '", "+", "jsonContent", "+", "'\\nexports.profiles = profiles;'", "+", "\\n", "}", "'\\nexports.default = profiles.default;'", "}" ]
Saves all the Environment, Detector, Notifiers and Filters information into a config file @param {String} src is the path of the config file to use @param {Function} callback is the callback function to call once the Save is all done, it passes status and message as arguments to the function: \m status = 0: Successfully has performed the action. status = 1: Error: File exists already. @param {Boolean} force true if the user wants to overwrite an already existing file.
[ "Saves", "all", "the", "Environment", "Detector", "Notifiers", "and", "Filters", "information", "into", "a", "config", "file" ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L710-L747
train
tcardoso2/vermon
main.js
_InternalSerializeCurrentContext
function _InternalSerializeCurrentContext () { let profile = { default: {} } // Separate this function into another utils library. let serializeEntity = function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } } let serializeArray = function (ent) { let entityName for (let ei in ent) { // First, it creates as many entries of the same object as existing and initializes as empty arrays if (ent[ei].constructor.name !== entityName) { entityName = ent[ei].constructor.name profile.default[entityName] = [] } } for (let ei in ent) { // Then it reiterates again, this time pushing the contents to the correct array record profile.default[ent[ei].constructor.name].push(ent[ei]) } } serializeEntity(GetEnvironment()) serializeArray(GetMotionDetectors()) serializeArray(GetNotifiers()) serializeArray(GetFilters()) return utils.JSON.stringify(profile) }
javascript
function _InternalSerializeCurrentContext () { let profile = { default: {} } // Separate this function into another utils library. let serializeEntity = function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } } let serializeArray = function (ent) { let entityName for (let ei in ent) { // First, it creates as many entries of the same object as existing and initializes as empty arrays if (ent[ei].constructor.name !== entityName) { entityName = ent[ei].constructor.name profile.default[entityName] = [] } } for (let ei in ent) { // Then it reiterates again, this time pushing the contents to the correct array record profile.default[ent[ei].constructor.name].push(ent[ei]) } } serializeEntity(GetEnvironment()) serializeArray(GetMotionDetectors()) serializeArray(GetNotifiers()) serializeArray(GetFilters()) return utils.JSON.stringify(profile) }
[ "function", "_InternalSerializeCurrentContext", "(", ")", "{", "let", "profile", "=", "{", "default", ":", "{", "}", "}", "let", "serializeEntity", "=", "function", "(", "ent", ")", "{", "if", "(", "ent", ".", "constructor", ".", "name", "===", "'Array'", ")", "{", "serializeArray", "(", ")", "}", "else", "{", "profile", ".", "default", "[", "ent", ".", "constructor", ".", "name", "]", "=", "ent", "}", "}", "let", "serializeArray", "=", "function", "(", "ent", ")", "{", "let", "entityName", "for", "(", "let", "ei", "in", "ent", ")", "{", "if", "(", "ent", "[", "ei", "]", ".", "constructor", ".", "name", "!==", "entityName", ")", "{", "entityName", "=", "ent", "[", "ei", "]", ".", "constructor", ".", "name", "profile", ".", "default", "[", "entityName", "]", "=", "[", "]", "}", "}", "for", "(", "let", "ei", "in", "ent", ")", "{", "profile", ".", "default", "[", "ent", "[", "ei", "]", ".", "constructor", ".", "name", "]", ".", "push", "(", "ent", "[", "ei", "]", ")", "}", "}", "serializeEntity", "(", "GetEnvironment", "(", ")", ")", "serializeArray", "(", "GetMotionDetectors", "(", ")", ")", "serializeArray", "(", "GetNotifiers", "(", ")", ")", "serializeArray", "(", "GetFilters", "(", ")", ")", "return", "utils", ".", "JSON", ".", "stringify", "(", "profile", ")", "}" ]
Internal function which serializes the current Context into the format matching the "profile" object of the config file. @returns {object} Returns a "profile" object in JSON.stringify format @internal
[ "Internal", "function", "which", "serializes", "the", "current", "Context", "into", "the", "format", "matching", "the", "profile", "object", "of", "the", "config", "file", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L755-L788
train
tcardoso2/vermon
main.js
function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } }
javascript
function (ent) { if (ent.constructor.name === 'Array') { serializeArray() } else { profile.default[ent.constructor.name] = ent } }
[ "function", "(", "ent", ")", "{", "if", "(", "ent", ".", "constructor", ".", "name", "===", "'Array'", ")", "{", "serializeArray", "(", ")", "}", "else", "{", "profile", ".", "default", "[", "ent", ".", "constructor", ".", "name", "]", "=", "ent", "}", "}" ]
Separate this function into another utils library.
[ "Separate", "this", "function", "into", "another", "utils", "library", "." ]
8fccd8fe87de98bdc77cd2cbe91e85118dc71a16
https://github.com/tcardoso2/vermon/blob/8fccd8fe87de98bdc77cd2cbe91e85118dc71a16/main.js#L759-L765
train
alexcjohnson/world-calendars
jquery-src/jquery.calendars.picker.ext.js
function(onHover) { return function(picker, calendar, inst) { if ($.isFunction(onHover)) { var target = this; var renderer = inst.options.renderer; picker.find(renderer.daySelector + ' a, ' + renderer.daySelector + ' span'). hover(function() { onHover.apply(target, [$(target).calendarsPicker('retrieveDate', this), this.nodeName.toLowerCase() === 'a']); }, function() { onHover.apply(target, []); }); } }; }
javascript
function(onHover) { return function(picker, calendar, inst) { if ($.isFunction(onHover)) { var target = this; var renderer = inst.options.renderer; picker.find(renderer.daySelector + ' a, ' + renderer.daySelector + ' span'). hover(function() { onHover.apply(target, [$(target).calendarsPicker('retrieveDate', this), this.nodeName.toLowerCase() === 'a']); }, function() { onHover.apply(target, []); }); } }; }
[ "function", "(", "onHover", ")", "{", "return", "function", "(", "picker", ",", "calendar", ",", "inst", ")", "{", "if", "(", "$", ".", "isFunction", "(", "onHover", ")", ")", "{", "var", "target", "=", "this", ";", "var", "renderer", "=", "inst", ".", "options", ".", "renderer", ";", "picker", ".", "find", "(", "renderer", ".", "daySelector", "+", "' a, '", "+", "renderer", ".", "daySelector", "+", "' span'", ")", ".", "hover", "(", "function", "(", ")", "{", "onHover", ".", "apply", "(", "target", ",", "[", "$", "(", "target", ")", ".", "calendarsPicker", "(", "'retrieveDate'", ",", "this", ")", ",", "this", ".", "nodeName", ".", "toLowerCase", "(", ")", "===", "'a'", "]", ")", ";", "}", ",", "function", "(", ")", "{", "onHover", ".", "apply", "(", "target", ",", "[", "]", ")", ";", "}", ")", ";", "}", "}", ";", "}" ]
A function to call when a date is hovered. @callback CalendarsPickerOnHover @param date {CDate} The date being hovered or <code>null</code> on exit. @param selectable {boolean} <code>true</code> if this date is selectable, <code>false</code> if not. @example function showHovered(date, selectable) { $('#feedback').text('You are viewing ' + (date ? date.formatDate() : 'nothing')); } Add a callback when hovering over dates. Found in the <code>jquery.calendars.picker.ext.js</code> module. @memberof CalendarsPicker @param onHover {CalendarsPickerOnHover} The callback when hovering. @example onShow: $.calendarsPicker.hoverCallback(showHovered)
[ "A", "function", "to", "call", "when", "a", "date", "is", "hovered", "." ]
810693882512dec1b804456f8d435b962bd6cf31
https://github.com/alexcjohnson/world-calendars/blob/810693882512dec1b804456f8d435b962bd6cf31/jquery-src/jquery.calendars.picker.ext.js#L111-L124
train
ImAdamTM/actions-ai-app
bin/lib/store.js
Store
function Store(context, app, data) { const state = Object.assign({}, defaultState, data); return { dispatch(key, payload) { const reducers = context.reducers[key]; /* istanbul ignore next */ if (!reducers) return; for (let i = 0, len = reducers.length; i < len; i += 1) { const reducer = reducers[i]; const newState = reducer.method(state[reducer.namespace], payload); if (newState === undefined) { debug( chalk.bold('Reducer did not return a new state:'), chalk.bold.magenta(`${reducer.namespace}.${key}`)); } else { state[reducer.namespace] = newState; } } app.data = Object.assign({}, app.data, state); }, getState() { return state; }, }; }
javascript
function Store(context, app, data) { const state = Object.assign({}, defaultState, data); return { dispatch(key, payload) { const reducers = context.reducers[key]; /* istanbul ignore next */ if (!reducers) return; for (let i = 0, len = reducers.length; i < len; i += 1) { const reducer = reducers[i]; const newState = reducer.method(state[reducer.namespace], payload); if (newState === undefined) { debug( chalk.bold('Reducer did not return a new state:'), chalk.bold.magenta(`${reducer.namespace}.${key}`)); } else { state[reducer.namespace] = newState; } } app.data = Object.assign({}, app.data, state); }, getState() { return state; }, }; }
[ "function", "Store", "(", "context", ",", "app", ",", "data", ")", "{", "const", "state", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultState", ",", "data", ")", ";", "return", "{", "dispatch", "(", "key", ",", "payload", ")", "{", "const", "reducers", "=", "context", ".", "reducers", "[", "key", "]", ";", "if", "(", "!", "reducers", ")", "return", ";", "for", "(", "let", "i", "=", "0", ",", "len", "=", "reducers", ".", "length", ";", "i", "<", "len", ";", "i", "+=", "1", ")", "{", "const", "reducer", "=", "reducers", "[", "i", "]", ";", "const", "newState", "=", "reducer", ".", "method", "(", "state", "[", "reducer", ".", "namespace", "]", ",", "payload", ")", ";", "if", "(", "newState", "===", "undefined", ")", "{", "debug", "(", "chalk", ".", "bold", "(", "'Reducer did not return a new state:'", ")", ",", "chalk", ".", "bold", ".", "magenta", "(", "`", "${", "reducer", ".", "namespace", "}", "${", "key", "}", "`", ")", ")", ";", "}", "else", "{", "state", "[", "reducer", ".", "namespace", "]", "=", "newState", ";", "}", "}", "app", ".", "data", "=", "Object", ".", "assign", "(", "{", "}", ",", "app", ".", "data", ",", "state", ")", ";", "}", ",", "getState", "(", ")", "{", "return", "state", ";", "}", ",", "}", ";", "}" ]
The data `Store` is used to manage the session data for the application. We do not want to manipulate `app.data` directly as it becomes un-managable as things expand. Instead, we use a `redux` style approach where the data is managed via state. To learn more, read the [redux docs](http://redux.js.org/docs/basics/) @param {App} context the current instance context @param {Object} app the app response data @param {Object} data the data to assign to the state on creation @return {Object} the exposed methods for manipulating the store/state @private
[ "The", "data", "Store", "is", "used", "to", "manage", "the", "session", "data", "for", "the", "application", ".", "We", "do", "not", "want", "to", "manipulate", "app", ".", "data", "directly", "as", "it", "becomes", "un", "-", "managable", "as", "things", "expand", ".", "Instead", "we", "use", "a", "redux", "style", "approach", "where", "the", "data", "is", "managed", "via", "state", "." ]
2a236dde0508610ad38654c22669eab949260777
https://github.com/ImAdamTM/actions-ai-app/blob/2a236dde0508610ad38654c22669eab949260777/bin/lib/store.js#L22-L50
train
dinoboff/firebase-json
index.js
error
function error(original, fileName) { if ( original == null || original.location == null || original.location.start == null ) { return original; } const start = original.location.start; const lineNumber = start.line == null ? 1 : start.line; const columnNumber = start.column == null ? 1 : start.column; const err = new SyntaxError(`Line ${lineNumber}, column ${columnNumber}: ${original.message}`); Object.assign(err, {fileName, lineNumber, columnNumber, original}); if (fileName == null) { return err; } err.stack = `SyntaxError: ${err.message}\n at ${fileName}:${lineNumber}:${columnNumber} `; return err; }
javascript
function error(original, fileName) { if ( original == null || original.location == null || original.location.start == null ) { return original; } const start = original.location.start; const lineNumber = start.line == null ? 1 : start.line; const columnNumber = start.column == null ? 1 : start.column; const err = new SyntaxError(`Line ${lineNumber}, column ${columnNumber}: ${original.message}`); Object.assign(err, {fileName, lineNumber, columnNumber, original}); if (fileName == null) { return err; } err.stack = `SyntaxError: ${err.message}\n at ${fileName}:${lineNumber}:${columnNumber} `; return err; }
[ "function", "error", "(", "original", ",", "fileName", ")", "{", "if", "(", "original", "==", "null", "||", "original", ".", "location", "==", "null", "||", "original", ".", "location", ".", "start", "==", "null", ")", "{", "return", "original", ";", "}", "const", "start", "=", "original", ".", "location", ".", "start", ";", "const", "lineNumber", "=", "start", ".", "line", "==", "null", "?", "1", ":", "start", ".", "line", ";", "const", "columnNumber", "=", "start", ".", "column", "==", "null", "?", "1", ":", "start", ".", "column", ";", "const", "err", "=", "new", "SyntaxError", "(", "`", "${", "lineNumber", "}", "${", "columnNumber", "}", "${", "original", ".", "message", "}", "`", ")", ";", "Object", ".", "assign", "(", "err", ",", "{", "fileName", ",", "lineNumber", ",", "columnNumber", ",", "original", "}", ")", ";", "if", "(", "fileName", "==", "null", ")", "{", "return", "err", ";", "}", "err", ".", "stack", "=", "`", "${", "err", ".", "message", "}", "\\n", "${", "fileName", "}", "${", "lineNumber", "}", "${", "columnNumber", "}", "`", ";", "return", "err", ";", "}" ]
Create a SyntaxError with fileName, lineNumber, columnNumber and stack pointing to the syntax error in the the json file. @param {Error} original Pegjs syntax error @param {string} fileName JSON file name @return {Error}
[ "Create", "a", "SyntaxError", "with", "fileName", "lineNumber", "columnNumber", "and", "stack", "pointing", "to", "the", "syntax", "error", "in", "the", "the", "json", "file", "." ]
9f9c34e0167510916223bb4045127a81e02fd39f
https://github.com/dinoboff/firebase-json/blob/9f9c34e0167510916223bb4045127a81e02fd39f/index.js#L14-L39
train
dinoboff/firebase-json
index.js
astValue
function astValue(node) { switch (node.type) { case 'ExpressionStatement': return astValue(node.expression); case 'ObjectExpression': return node.properties.reduce( (obj, prop) => Object.assign(obj, {[prop.key.value]: astValue(prop.value)}), {} ); case 'ArrayExpression': return node.elements.map(element => astValue(element)); case 'Literal': return node.value; default: throw new Error(`Unexpected ast node type: ${node.type}`); } }
javascript
function astValue(node) { switch (node.type) { case 'ExpressionStatement': return astValue(node.expression); case 'ObjectExpression': return node.properties.reduce( (obj, prop) => Object.assign(obj, {[prop.key.value]: astValue(prop.value)}), {} ); case 'ArrayExpression': return node.elements.map(element => astValue(element)); case 'Literal': return node.value; default: throw new Error(`Unexpected ast node type: ${node.type}`); } }
[ "function", "astValue", "(", "node", ")", "{", "switch", "(", "node", ".", "type", ")", "{", "case", "'ExpressionStatement'", ":", "return", "astValue", "(", "node", ".", "expression", ")", ";", "case", "'ObjectExpression'", ":", "return", "node", ".", "properties", ".", "reduce", "(", "(", "obj", ",", "prop", ")", "=>", "Object", ".", "assign", "(", "obj", ",", "{", "[", "prop", ".", "key", ".", "value", "]", ":", "astValue", "(", "prop", ".", "value", ")", "}", ")", ",", "{", "}", ")", ";", "case", "'ArrayExpression'", ":", "return", "node", ".", "elements", ".", "map", "(", "element", "=>", "astValue", "(", "element", ")", ")", ";", "case", "'Literal'", ":", "return", "node", ".", "value", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "node", ".", "type", "}", "`", ")", ";", "}", "}" ]
Evaluate AST node to a value. @param {object} node Node to evaluate @return {any}
[ "Evaluate", "AST", "node", "to", "a", "value", "." ]
9f9c34e0167510916223bb4045127a81e02fd39f
https://github.com/dinoboff/firebase-json/blob/9f9c34e0167510916223bb4045127a81e02fd39f/index.js#L47-L70
train
smbape/node-umd-builder
build.js
remove
function remove(file, options, done) { if (arguments.length === 2 && 'function' === typeof options) { done = options; options = {}; } if ('function' !== typeof done) { done = function() {}; } function callfile(file, stats, done) { fs.unlink(file, done); } function calldir(dir, stats, files, state, done) { if (state === 'end') { if (options.empty && dir === file) { done(); } else { if (stats.isSymbolicLink()) { fs.unlink(dir, done); } else { fs.rmdir(dir, function(er) { if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { // try in few time, last deletion is not completely ended setTimeout(function() { fs.rmdir(dir, done); }, 10); } else { done(er); } }); } } } else { done(); } } options = Object.assign({ fs: fs, resolve: true, followSymlink: false }, options); _explore(file, callfile, calldir, options, done); }
javascript
function remove(file, options, done) { if (arguments.length === 2 && 'function' === typeof options) { done = options; options = {}; } if ('function' !== typeof done) { done = function() {}; } function callfile(file, stats, done) { fs.unlink(file, done); } function calldir(dir, stats, files, state, done) { if (state === 'end') { if (options.empty && dir === file) { done(); } else { if (stats.isSymbolicLink()) { fs.unlink(dir, done); } else { fs.rmdir(dir, function(er) { if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { // try in few time, last deletion is not completely ended setTimeout(function() { fs.rmdir(dir, done); }, 10); } else { done(er); } }); } } } else { done(); } } options = Object.assign({ fs: fs, resolve: true, followSymlink: false }, options); _explore(file, callfile, calldir, options, done); }
[ "function", "remove", "(", "file", ",", "options", ",", "done", ")", "{", "if", "(", "arguments", ".", "length", "===", "2", "&&", "'function'", "===", "typeof", "options", ")", "{", "done", "=", "options", ";", "options", "=", "{", "}", ";", "}", "if", "(", "'function'", "!==", "typeof", "done", ")", "{", "done", "=", "function", "(", ")", "{", "}", ";", "}", "function", "callfile", "(", "file", ",", "stats", ",", "done", ")", "{", "fs", ".", "unlink", "(", "file", ",", "done", ")", ";", "}", "function", "calldir", "(", "dir", ",", "stats", ",", "files", ",", "state", ",", "done", ")", "{", "if", "(", "state", "===", "'end'", ")", "{", "if", "(", "options", ".", "empty", "&&", "dir", "===", "file", ")", "{", "done", "(", ")", ";", "}", "else", "{", "if", "(", "stats", ".", "isSymbolicLink", "(", ")", ")", "{", "fs", ".", "unlink", "(", "dir", ",", "done", ")", ";", "}", "else", "{", "fs", ".", "rmdir", "(", "dir", ",", "function", "(", "er", ")", "{", "if", "(", "er", "&&", "(", "er", ".", "code", "===", "'ENOTEMPTY'", "||", "er", ".", "code", "===", "'EEXIST'", "||", "er", ".", "code", "===", "'EPERM'", ")", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "fs", ".", "rmdir", "(", "dir", ",", "done", ")", ";", "}", ",", "10", ")", ";", "}", "else", "{", "done", "(", "er", ")", ";", "}", "}", ")", ";", "}", "}", "}", "else", "{", "done", "(", ")", ";", "}", "}", "options", "=", "Object", ".", "assign", "(", "{", "fs", ":", "fs", ",", "resolve", ":", "true", ",", "followSymlink", ":", "false", "}", ",", "options", ")", ";", "_explore", "(", "file", ",", "callfile", ",", "calldir", ",", "options", ",", "done", ")", ";", "}" ]
rm -rf. Symlink are not resolved by default, avoiding unwanted deep deletion there should be a way to do it with rimraf, but too much options digging to find a way to do it @param {String} file or folder to remove @param {Function} done called on end
[ "rm", "-", "rf", ".", "Symlink", "are", "not", "resolved", "by", "default", "avoiding", "unwanted", "deep", "deletion", "there", "should", "be", "a", "way", "to", "do", "it", "with", "rimraf", "but", "too", "much", "options", "digging", "to", "find", "a", "way", "to", "do", "it" ]
73b03e8c985f2660948f5df71140e4a8fb162549
https://github.com/smbape/node-umd-builder/blob/73b03e8c985f2660948f5df71140e4a8fb162549/build.js#L111-L157
train
sat-utils/sat-api-lib
libs/ingest-csv.js
processFiles
function processFiles(bucket, key, transform, cb, currentFileNum=0, lastFileNum=0, arn=null, retries=0) { const maxRetries = 5 var nextFileNum = (currentFileNum < lastFileNum) ? currentFileNum + 1 : null //invokeLambda(bucket, key, currentFileNum, lastFileNum, arn) processFile( bucket, `${key}${currentFileNum}.csv`, transform ).then((n_scenes) => { invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) cb() }).catch((e) => { // if CSV failed, try it again if (retries < maxRetries) { invokeLambda(bucket, key, currentFileNum, lastFileNum, arn, retries + 1) } else { // log and move onto the next one console.log(`error: maxRetries hit in file ${currentFileNum}`) invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) } cb() }) }
javascript
function processFiles(bucket, key, transform, cb, currentFileNum=0, lastFileNum=0, arn=null, retries=0) { const maxRetries = 5 var nextFileNum = (currentFileNum < lastFileNum) ? currentFileNum + 1 : null //invokeLambda(bucket, key, currentFileNum, lastFileNum, arn) processFile( bucket, `${key}${currentFileNum}.csv`, transform ).then((n_scenes) => { invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) cb() }).catch((e) => { // if CSV failed, try it again if (retries < maxRetries) { invokeLambda(bucket, key, currentFileNum, lastFileNum, arn, retries + 1) } else { // log and move onto the next one console.log(`error: maxRetries hit in file ${currentFileNum}`) invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, 0) } cb() }) }
[ "function", "processFiles", "(", "bucket", ",", "key", ",", "transform", ",", "cb", ",", "currentFileNum", "=", "0", ",", "lastFileNum", "=", "0", ",", "arn", "=", "null", ",", "retries", "=", "0", ")", "{", "const", "maxRetries", "=", "5", "var", "nextFileNum", "=", "(", "currentFileNum", "<", "lastFileNum", ")", "?", "currentFileNum", "+", "1", ":", "null", "processFile", "(", "bucket", ",", "`", "${", "key", "}", "${", "currentFileNum", "}", "`", ",", "transform", ")", ".", "then", "(", "(", "n_scenes", ")", "=>", "{", "invokeLambda", "(", "bucket", ",", "key", ",", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "0", ")", "cb", "(", ")", "}", ")", ".", "catch", "(", "(", "e", ")", "=>", "{", "if", "(", "retries", "<", "maxRetries", ")", "{", "invokeLambda", "(", "bucket", ",", "key", ",", "currentFileNum", ",", "lastFileNum", ",", "arn", ",", "retries", "+", "1", ")", "}", "else", "{", "console", ".", "log", "(", "`", "${", "currentFileNum", "}", "`", ")", "invokeLambda", "(", "bucket", ",", "key", ",", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "0", ")", "}", "cb", "(", ")", "}", ")", "}" ]
Process 1 or more CSV files by processing one at a time, then invoking the next
[ "Process", "1", "or", "more", "CSV", "files", "by", "processing", "one", "at", "a", "time", "then", "invoking", "the", "next" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/ingest-csv.js#L123-L145
train
sat-utils/sat-api-lib
libs/ingest-csv.js
processFile
function processFile(bucket, key, transform) { // get the csv file s3://${bucket}/${key} console.log(`Processing s3://${bucket}/${key}`) const s3 = new AWS.S3() const csvStream = csv.parse({ headers: true, objectMode: true }) s3.getObject({Bucket: bucket, Key: key}).createReadStream().pipe(csvStream) return es.streamToEs(csvStream, transform, esClient, index) }
javascript
function processFile(bucket, key, transform) { // get the csv file s3://${bucket}/${key} console.log(`Processing s3://${bucket}/${key}`) const s3 = new AWS.S3() const csvStream = csv.parse({ headers: true, objectMode: true }) s3.getObject({Bucket: bucket, Key: key}).createReadStream().pipe(csvStream) return es.streamToEs(csvStream, transform, esClient, index) }
[ "function", "processFile", "(", "bucket", ",", "key", ",", "transform", ")", "{", "console", ".", "log", "(", "`", "${", "bucket", "}", "${", "key", "}", "`", ")", "const", "s3", "=", "new", "AWS", ".", "S3", "(", ")", "const", "csvStream", "=", "csv", ".", "parse", "(", "{", "headers", ":", "true", ",", "objectMode", ":", "true", "}", ")", "s3", ".", "getObject", "(", "{", "Bucket", ":", "bucket", ",", "Key", ":", "key", "}", ")", ".", "createReadStream", "(", ")", ".", "pipe", "(", "csvStream", ")", "return", "es", ".", "streamToEs", "(", "csvStream", ",", "transform", ",", "esClient", ",", "index", ")", "}" ]
Process single CSV file
[ "Process", "single", "CSV", "file" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/ingest-csv.js#L149-L156
train
sat-utils/sat-api-lib
libs/ingest-csv.js
invokeLambda
function invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, retries) { // figure out if there's a next file to process if (nextFileNum && arn) { const stepfunctions = new AWS.StepFunctions() const params = { stateMachineArn: arn, input: JSON.stringify({ bucket, key, currentFileNum: nextFileNum, lastFileNum, arn, retries}), name: `ingest_${nextFileNum}_${Date.now()}` } stepfunctions.startExecution(params, function(err, data) { if (err) { console.log(err, err.stack) } else { console.log(`launched ${JSON.stringify(params)}`) } }) } }
javascript
function invokeLambda(bucket, key, nextFileNum, lastFileNum, arn, retries) { // figure out if there's a next file to process if (nextFileNum && arn) { const stepfunctions = new AWS.StepFunctions() const params = { stateMachineArn: arn, input: JSON.stringify({ bucket, key, currentFileNum: nextFileNum, lastFileNum, arn, retries}), name: `ingest_${nextFileNum}_${Date.now()}` } stepfunctions.startExecution(params, function(err, data) { if (err) { console.log(err, err.stack) } else { console.log(`launched ${JSON.stringify(params)}`) } }) } }
[ "function", "invokeLambda", "(", "bucket", ",", "key", ",", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "retries", ")", "{", "if", "(", "nextFileNum", "&&", "arn", ")", "{", "const", "stepfunctions", "=", "new", "AWS", ".", "StepFunctions", "(", ")", "const", "params", "=", "{", "stateMachineArn", ":", "arn", ",", "input", ":", "JSON", ".", "stringify", "(", "{", "bucket", ",", "key", ",", "currentFileNum", ":", "nextFileNum", ",", "lastFileNum", ",", "arn", ",", "retries", "}", ")", ",", "name", ":", "`", "${", "nextFileNum", "}", "${", "Date", ".", "now", "(", ")", "}", "`", "}", "stepfunctions", ".", "startExecution", "(", "params", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "err", ",", "err", ".", "stack", ")", "}", "else", "{", "console", ".", "log", "(", "`", "${", "JSON", ".", "stringify", "(", "params", ")", "}", "`", ")", "}", "}", ")", "}", "}" ]
kick off processing next CSV file
[ "kick", "off", "processing", "next", "CSV", "file" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/ingest-csv.js#L160-L177
train
sat-utils/sat-api-lib
libs/es.js
connect
async function connect() { let esConfig let client // use local client if (!process.env.ES_HOST) { client = new elasticsearch.Client({host: 'localhost:9200'}) } else { await new Promise((resolve, reject) => AWS.config.getCredentials((err) => { if (err) return reject(err) resolve() })) esConfig = { host: process.env.ES_HOST, connectionClass: httpAwsEs, amazonES: { region: process.env.AWS_DEFAULT_REGION || 'us-east-1', credentials: AWS.config.credentials }, // Note that this doesn't abort the query. requestTimeout: 120000 // milliseconds } client = new elasticsearch.Client(esConfig) } await new Promise((resolve, reject) => client.ping({requestTimeout: 1000}, (err) => { if (err) { console.log('unable to connect to elasticsearch') reject('unable to connect to elasticsearch') } else { resolve() } })) return client }
javascript
async function connect() { let esConfig let client // use local client if (!process.env.ES_HOST) { client = new elasticsearch.Client({host: 'localhost:9200'}) } else { await new Promise((resolve, reject) => AWS.config.getCredentials((err) => { if (err) return reject(err) resolve() })) esConfig = { host: process.env.ES_HOST, connectionClass: httpAwsEs, amazonES: { region: process.env.AWS_DEFAULT_REGION || 'us-east-1', credentials: AWS.config.credentials }, // Note that this doesn't abort the query. requestTimeout: 120000 // milliseconds } client = new elasticsearch.Client(esConfig) } await new Promise((resolve, reject) => client.ping({requestTimeout: 1000}, (err) => { if (err) { console.log('unable to connect to elasticsearch') reject('unable to connect to elasticsearch') } else { resolve() } })) return client }
[ "async", "function", "connect", "(", ")", "{", "let", "esConfig", "let", "client", "if", "(", "!", "process", ".", "env", ".", "ES_HOST", ")", "{", "client", "=", "new", "elasticsearch", ".", "Client", "(", "{", "host", ":", "'localhost:9200'", "}", ")", "}", "else", "{", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "AWS", ".", "config", ".", "getCredentials", "(", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", "resolve", "(", ")", "}", ")", ")", "esConfig", "=", "{", "host", ":", "process", ".", "env", ".", "ES_HOST", ",", "connectionClass", ":", "httpAwsEs", ",", "amazonES", ":", "{", "region", ":", "process", ".", "env", ".", "AWS_DEFAULT_REGION", "||", "'us-east-1'", ",", "credentials", ":", "AWS", ".", "config", ".", "credentials", "}", ",", "requestTimeout", ":", "120000", "}", "client", "=", "new", "elasticsearch", ".", "Client", "(", "esConfig", ")", "}", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "client", ".", "ping", "(", "{", "requestTimeout", ":", "1000", "}", ",", "(", "err", ")", "=>", "{", "if", "(", "err", ")", "{", "console", ".", "log", "(", "'unable to connect to elasticsearch'", ")", "reject", "(", "'unable to connect to elasticsearch'", ")", "}", "else", "{", "resolve", "(", ")", "}", "}", ")", ")", "return", "client", "}" ]
Connect to an Elasticsearch cluster
[ "Connect", "to", "an", "Elasticsearch", "cluster" ]
74ef1cb09789ecc9c18512781a95eada6fdc3813
https://github.com/sat-utils/sat-api-lib/blob/74ef1cb09789ecc9c18512781a95eada6fdc3813/libs/es.js#L30-L66
train
alianza-dev/az-search-sorter
src/index.js
_stringsByCharOrder
function _stringsByCharOrder(stringToMatch, givenString) { const matchingIndexes = getMatchingStringIndexes(stringToMatch, givenString); if (!matchingIndexes || !matchingIndexes.length) { return _matchRankMap.noMatch; } else { return _matchRankMap.matches; } }
javascript
function _stringsByCharOrder(stringToMatch, givenString) { const matchingIndexes = getMatchingStringIndexes(stringToMatch, givenString); if (!matchingIndexes || !matchingIndexes.length) { return _matchRankMap.noMatch; } else { return _matchRankMap.matches; } }
[ "function", "_stringsByCharOrder", "(", "stringToMatch", ",", "givenString", ")", "{", "const", "matchingIndexes", "=", "getMatchingStringIndexes", "(", "stringToMatch", ",", "givenString", ")", ";", "if", "(", "!", "matchingIndexes", "||", "!", "matchingIndexes", ".", "length", ")", "{", "return", "_matchRankMap", ".", "noMatch", ";", "}", "else", "{", "return", "_matchRankMap", ".", "matches", ";", "}", "}" ]
Returns a _matchRankMap.matches or noMatch score based on whether the characters in the givenString are found in order in the stringToMatch @param {string} stringToMatch - the string to match @param {string} givenString - the string that is given @returns {number} - matches rank or noMatch rank @private
[ "Returns", "a", "_matchRankMap", ".", "matches", "or", "noMatch", "score", "based", "on", "whether", "the", "characters", "in", "the", "givenString", "are", "found", "in", "order", "in", "the", "stringToMatch" ]
c981b206272e80712f4681cfd1f2d4eceaa6f433
https://github.com/alianza-dev/az-search-sorter/blob/c981b206272e80712f4681cfd1f2d4eceaa6f433/src/index.js#L142-L149
train
hex7c0/startline
index.js
readlin
function readlin(options, start, end) { return readline.createInterface({ input: interfac(options, start, end), output: null, terminal: false, }); }
javascript
function readlin(options, start, end) { return readline.createInterface({ input: interfac(options, start, end), output: null, terminal: false, }); }
[ "function", "readlin", "(", "options", ",", "start", ",", "end", ")", "{", "return", "readline", ".", "createInterface", "(", "{", "input", ":", "interfac", "(", "options", ",", "start", ",", "end", ")", ",", "output", ":", "null", ",", "terminal", ":", "false", ",", "}", ")", ";", "}" ]
build readline interface @function readlin @param {Object} options - various options. Check README.md @param {Integer} start - starting bytes @param {Integer} [end] - ending bytes @return {Objetc}
[ "build", "readline", "interface" ]
805505ea36247b93a36fb82b97a2f3f3026b7a27
https://github.com/hex7c0/startline/blob/805505ea36247b93a36fb82b97a2f3f3026b7a27/index.js#L67-L74
train
chevex-archived/shotgun-client
client/shotgun.client.js
function (options) { var clientShell = this, context = {}, // Default settings. defaultSettings = { namespace: 'shotgun', debug: false }; // Override default settings with supplied options. var settings = clientShell.settings = extend(true, {}, defaultSettings, options); // Instruct socket.io to connect to the server. var socket = clientShell.socket = io.connect('/' + settings.namespace); // Proxy any listeners onto the socket itself. clientShell.on = function () { socket.on.apply(socket, arguments); return clientShell; }; // Proxy any emit calls onto the socket itself. clientShell.emit = function () { socket.emit.apply(socket, arguments); return clientShell; }; function getCookies() { var cookies = {}; if (document.cookie.length > 0) document.cookie.split(';').forEach(function (cookie) { var components = cookie.split('='), name = components[0].trim(), value = components[1]; if (name.indexOf(settings.namespace + '-') === 0) { name = name.replace(settings.namespace + '-', ''); cookies[name] = decodeURIComponent(value); } }); return cookies; } clientShell // Save context when it changes. .on('contextChanged', function (contextData) { context = contextData; }) // Create a function for setting cookies in the browser. .on('setCookie', function (name, value, days) { var expiration = new Date(); expiration.setDate(expiration.getDate() + days); value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString()); document.cookie = settings.namespace + '-' + name + "=" + value; }) .on('getCookie', function (name, callback) { // Create a cookies property on the context and fill it with all the cookies for this shell. var cookies = getCookies(); callback(cookies[name]); }) .on('getAllCookies', function (callback) { var cookies = getCookies(); callback(cookies); }); // Create an execute function that looks similar to the shotgun shell execute function for ease of use. clientShell.execute = function (cmdStr, contextOverride, options) { // If a context was passed in then override the stored context with it. if (contextOverride) context = contextOverride; socket.emit('execute', cmdStr, context, options); return clientShell; }; return clientShell; }
javascript
function (options) { var clientShell = this, context = {}, // Default settings. defaultSettings = { namespace: 'shotgun', debug: false }; // Override default settings with supplied options. var settings = clientShell.settings = extend(true, {}, defaultSettings, options); // Instruct socket.io to connect to the server. var socket = clientShell.socket = io.connect('/' + settings.namespace); // Proxy any listeners onto the socket itself. clientShell.on = function () { socket.on.apply(socket, arguments); return clientShell; }; // Proxy any emit calls onto the socket itself. clientShell.emit = function () { socket.emit.apply(socket, arguments); return clientShell; }; function getCookies() { var cookies = {}; if (document.cookie.length > 0) document.cookie.split(';').forEach(function (cookie) { var components = cookie.split('='), name = components[0].trim(), value = components[1]; if (name.indexOf(settings.namespace + '-') === 0) { name = name.replace(settings.namespace + '-', ''); cookies[name] = decodeURIComponent(value); } }); return cookies; } clientShell // Save context when it changes. .on('contextChanged', function (contextData) { context = contextData; }) // Create a function for setting cookies in the browser. .on('setCookie', function (name, value, days) { var expiration = new Date(); expiration.setDate(expiration.getDate() + days); value = encodeURIComponent(value) + ((days === null) ? "" : ";expires=" + expiration.toUTCString()); document.cookie = settings.namespace + '-' + name + "=" + value; }) .on('getCookie', function (name, callback) { // Create a cookies property on the context and fill it with all the cookies for this shell. var cookies = getCookies(); callback(cookies[name]); }) .on('getAllCookies', function (callback) { var cookies = getCookies(); callback(cookies); }); // Create an execute function that looks similar to the shotgun shell execute function for ease of use. clientShell.execute = function (cmdStr, contextOverride, options) { // If a context was passed in then override the stored context with it. if (contextOverride) context = contextOverride; socket.emit('execute', cmdStr, context, options); return clientShell; }; return clientShell; }
[ "function", "(", "options", ")", "{", "var", "clientShell", "=", "this", ",", "context", "=", "{", "}", ",", "defaultSettings", "=", "{", "namespace", ":", "'shotgun'", ",", "debug", ":", "false", "}", ";", "var", "settings", "=", "clientShell", ".", "settings", "=", "extend", "(", "true", ",", "{", "}", ",", "defaultSettings", ",", "options", ")", ";", "var", "socket", "=", "clientShell", ".", "socket", "=", "io", ".", "connect", "(", "'/'", "+", "settings", ".", "namespace", ")", ";", "clientShell", ".", "on", "=", "function", "(", ")", "{", "socket", ".", "on", ".", "apply", "(", "socket", ",", "arguments", ")", ";", "return", "clientShell", ";", "}", ";", "clientShell", ".", "emit", "=", "function", "(", ")", "{", "socket", ".", "emit", ".", "apply", "(", "socket", ",", "arguments", ")", ";", "return", "clientShell", ";", "}", ";", "function", "getCookies", "(", ")", "{", "var", "cookies", "=", "{", "}", ";", "if", "(", "document", ".", "cookie", ".", "length", ">", "0", ")", "document", ".", "cookie", ".", "split", "(", "';'", ")", ".", "forEach", "(", "function", "(", "cookie", ")", "{", "var", "components", "=", "cookie", ".", "split", "(", "'='", ")", ",", "name", "=", "components", "[", "0", "]", ".", "trim", "(", ")", ",", "value", "=", "components", "[", "1", "]", ";", "if", "(", "name", ".", "indexOf", "(", "settings", ".", "namespace", "+", "'-'", ")", "===", "0", ")", "{", "name", "=", "name", ".", "replace", "(", "settings", ".", "namespace", "+", "'-'", ",", "''", ")", ";", "cookies", "[", "name", "]", "=", "decodeURIComponent", "(", "value", ")", ";", "}", "}", ")", ";", "return", "cookies", ";", "}", "clientShell", ".", "on", "(", "'contextChanged'", ",", "function", "(", "contextData", ")", "{", "context", "=", "contextData", ";", "}", ")", ".", "on", "(", "'setCookie'", ",", "function", "(", "name", ",", "value", ",", "days", ")", "{", "var", "expiration", "=", "new", "Date", "(", ")", ";", "expiration", ".", "setDate", "(", "expiration", ".", "getDate", "(", ")", "+", "days", ")", ";", "value", "=", "encodeURIComponent", "(", "value", ")", "+", "(", "(", "days", "===", "null", ")", "?", "\"\"", ":", "\";expires=\"", "+", "expiration", ".", "toUTCString", "(", ")", ")", ";", "document", ".", "cookie", "=", "settings", ".", "namespace", "+", "'-'", "+", "name", "+", "\"=\"", "+", "value", ";", "}", ")", ".", "on", "(", "'getCookie'", ",", "function", "(", "name", ",", "callback", ")", "{", "var", "cookies", "=", "getCookies", "(", ")", ";", "callback", "(", "cookies", "[", "name", "]", ")", ";", "}", ")", ".", "on", "(", "'getAllCookies'", ",", "function", "(", "callback", ")", "{", "var", "cookies", "=", "getCookies", "(", ")", ";", "callback", "(", "cookies", ")", ";", "}", ")", ";", "clientShell", ".", "execute", "=", "function", "(", "cmdStr", ",", "contextOverride", ",", "options", ")", "{", "if", "(", "contextOverride", ")", "context", "=", "contextOverride", ";", "socket", ".", "emit", "(", "'execute'", ",", "cmdStr", ",", "context", ",", "options", ")", ";", "return", "clientShell", ";", "}", ";", "return", "clientShell", ";", "}" ]
Shotgun client shell.
[ "Shotgun", "client", "shell", "." ]
1b046d665fc241aaf42a60bdd64d5c19e4d07399
https://github.com/chevex-archived/shotgun-client/blob/1b046d665fc241aaf42a60bdd64d5c19e4d07399/client/shotgun.client.js#L85-L159
train
stackgl/gl-mat2
transpose.js
transpose
function transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a1 = a[1] out[1] = a[2] out[2] = a1 } else { out[0] = a[0] out[1] = a[2] out[2] = a[1] out[3] = a[3] } return out }
javascript
function transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a1 = a[1] out[1] = a[2] out[2] = a1 } else { out[0] = a[0] out[1] = a[2] out[2] = a[1] out[3] = a[3] } return out }
[ "function", "transpose", "(", "out", ",", "a", ")", "{", "if", "(", "out", "===", "a", ")", "{", "var", "a1", "=", "a", "[", "1", "]", "out", "[", "1", "]", "=", "a", "[", "2", "]", "out", "[", "2", "]", "=", "a1", "}", "else", "{", "out", "[", "0", "]", "=", "a", "[", "0", "]", "out", "[", "1", "]", "=", "a", "[", "2", "]", "out", "[", "2", "]", "=", "a", "[", "1", "]", "out", "[", "3", "]", "=", "a", "[", "3", "]", "}", "return", "out", "}" ]
Transpose the values of a mat2 @alias mat2.transpose @param {mat2} out the receiving matrix @param {mat2} a the source matrix @returns {mat2} out
[ "Transpose", "the", "values", "of", "a", "mat2" ]
d6a04d55d605150240dc8e57ca7d2821aaa23c56
https://github.com/stackgl/gl-mat2/blob/d6a04d55d605150240dc8e57ca7d2821aaa23c56/transpose.js#L11-L25
train
Tabcorp/require-lint
lib/index.js
_compile
function _compile(str, filename) { var parent = this; try { var requires = detective(str); } catch (ex) { ex.toString = function() { return filename + ':' + this.loc.line + '\n ' + ex.message; } throw ex; } requires.forEach(function(req) { if (modules.isRelative(req)) { Module._load(req, parent); } else { if (!modules.isCore(req)) { dependencies.push(modules.name(req)); } } }); }
javascript
function _compile(str, filename) { var parent = this; try { var requires = detective(str); } catch (ex) { ex.toString = function() { return filename + ':' + this.loc.line + '\n ' + ex.message; } throw ex; } requires.forEach(function(req) { if (modules.isRelative(req)) { Module._load(req, parent); } else { if (!modules.isCore(req)) { dependencies.push(modules.name(req)); } } }); }
[ "function", "_compile", "(", "str", ",", "filename", ")", "{", "var", "parent", "=", "this", ";", "try", "{", "var", "requires", "=", "detective", "(", "str", ")", ";", "}", "catch", "(", "ex", ")", "{", "ex", ".", "toString", "=", "function", "(", ")", "{", "return", "filename", "+", "':'", "+", "this", ".", "loc", ".", "line", "+", "'\\n '", "+", "\\n", ";", "}", "ex", ".", "message", "}", "throw", "ex", ";", "}" ]
override of Module._compile to find all call to "require"
[ "override", "of", "Module", ".", "_compile", "to", "find", "all", "call", "to", "require" ]
5c7ef7b3f39af24cb32dd1dd066d6671f9415ef0
https://github.com/Tabcorp/require-lint/blob/5c7ef7b3f39af24cb32dd1dd066d6671f9415ef0/lib/index.js#L30-L49
train
Dafrok/BMapLib.Heatmap
index.js
store
function store(hmap){ var _ = { // data is a two dimensional array // a datapoint gets saved as data[point-x-value][point-y-value] // the value at [point-x-value][point-y-value] is the occurrence of the datapoint data: [], // tight coupling of the heatmap object heatmap: hmap }; // the max occurrence - the heatmaps radial gradient alpha transition is based on it this.max = 1; this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; }
javascript
function store(hmap){ var _ = { // data is a two dimensional array // a datapoint gets saved as data[point-x-value][point-y-value] // the value at [point-x-value][point-y-value] is the occurrence of the datapoint data: [], // tight coupling of the heatmap object heatmap: hmap }; // the max occurrence - the heatmaps radial gradient alpha transition is based on it this.max = 1; this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; }
[ "function", "store", "(", "hmap", ")", "{", "var", "_", "=", "{", "data", ":", "[", "]", ",", "heatmap", ":", "hmap", "}", ";", "this", ".", "max", "=", "1", ";", "this", ".", "get", "=", "function", "(", "key", ")", "{", "return", "_", "[", "key", "]", ";", "}", ";", "this", ".", "set", "=", "function", "(", "key", ",", "value", ")", "{", "_", "[", "key", "]", "=", "value", ";", "}", ";", "}" ]
store object constructor a heatmap contains a store the store has to know about the heatmap in order to trigger heatmap updates when datapoints get added
[ "store", "object", "constructor", "a", "heatmap", "contains", "a", "store", "the", "store", "has", "to", "know", "about", "the", "heatmap", "in", "order", "to", "trigger", "heatmap", "updates", "when", "datapoints", "get", "added" ]
710f22b68834b26bd1202944ba6137e42968b75d
https://github.com/Dafrok/BMapLib.Heatmap/blob/710f22b68834b26bd1202944ba6137e42968b75d/index.js#L33-L52
train
Dafrok/BMapLib.Heatmap
index.js
function(x, y){ if(x < 0 || y < 0) return; var me = this, heatmap = me.get("heatmap"), data = me.get("data"); if(!data[x]) data[x] = []; if(!data[x][y]) data[x][y] = 0; // if count parameter is set increment by count otherwise by 1 data[x][y]+=(arguments.length<3)?1:arguments[2]; me.set("data", data); // do we have a new maximum? if(me.max < data[x][y]){ // max changed, we need to redraw all existing(lower) datapoints heatmap.get("actx").clearRect(0,0,heatmap.get("width"),heatmap.get("height")); me.setDataSet({ max: data[x][y], data: data }, true); return; } heatmap.drawAlpha(x, y, data[x][y], true); }
javascript
function(x, y){ if(x < 0 || y < 0) return; var me = this, heatmap = me.get("heatmap"), data = me.get("data"); if(!data[x]) data[x] = []; if(!data[x][y]) data[x][y] = 0; // if count parameter is set increment by count otherwise by 1 data[x][y]+=(arguments.length<3)?1:arguments[2]; me.set("data", data); // do we have a new maximum? if(me.max < data[x][y]){ // max changed, we need to redraw all existing(lower) datapoints heatmap.get("actx").clearRect(0,0,heatmap.get("width"),heatmap.get("height")); me.setDataSet({ max: data[x][y], data: data }, true); return; } heatmap.drawAlpha(x, y, data[x][y], true); }
[ "function", "(", "x", ",", "y", ")", "{", "if", "(", "x", "<", "0", "||", "y", "<", "0", ")", "return", ";", "var", "me", "=", "this", ",", "heatmap", "=", "me", ".", "get", "(", "\"heatmap\"", ")", ",", "data", "=", "me", ".", "get", "(", "\"data\"", ")", ";", "if", "(", "!", "data", "[", "x", "]", ")", "data", "[", "x", "]", "=", "[", "]", ";", "if", "(", "!", "data", "[", "x", "]", "[", "y", "]", ")", "data", "[", "x", "]", "[", "y", "]", "=", "0", ";", "data", "[", "x", "]", "[", "y", "]", "+=", "(", "arguments", ".", "length", "<", "3", ")", "?", "1", ":", "arguments", "[", "2", "]", ";", "me", ".", "set", "(", "\"data\"", ",", "data", ")", ";", "if", "(", "me", ".", "max", "<", "data", "[", "x", "]", "[", "y", "]", ")", "{", "heatmap", ".", "get", "(", "\"actx\"", ")", ".", "clearRect", "(", "0", ",", "0", ",", "heatmap", ".", "get", "(", "\"width\"", ")", ",", "heatmap", ".", "get", "(", "\"height\"", ")", ")", ";", "me", ".", "setDataSet", "(", "{", "max", ":", "data", "[", "x", "]", "[", "y", "]", ",", "data", ":", "data", "}", ",", "true", ")", ";", "return", ";", "}", "heatmap", ".", "drawAlpha", "(", "x", ",", "y", ",", "data", "[", "x", "]", "[", "y", "]", ",", "true", ")", ";", "}" ]
function for adding datapoints to the store datapoints are usually defined by x and y but could also contain a third parameter which represents the occurrence
[ "function", "for", "adding", "datapoints", "to", "the", "store", "datapoints", "are", "usually", "defined", "by", "x", "and", "y", "but", "could", "also", "contain", "a", "third", "parameter", "which", "represents", "the", "occurrence" ]
710f22b68834b26bd1202944ba6137e42968b75d
https://github.com/Dafrok/BMapLib.Heatmap/blob/710f22b68834b26bd1202944ba6137e42968b75d/index.js#L57-L83
train
Dafrok/BMapLib.Heatmap
index.js
heatmap
function heatmap(config){ // private variables var _ = { radius : 40, element : {}, canvas : {}, acanvas: {}, ctx : {}, actx : {}, legend: null, visible : true, width : 0, height : 0, max : false, gradient : false, opacity: 180, premultiplyAlpha: false, bounds: { l: 1000, r: 0, t: 1000, b: 0 }, debug: false }; // heatmap store containing the datapoints and information about the maximum // accessible via instance.store this.store = new store(this); this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; // configure the heatmap when an instance gets created this.configure(config); // and initialize it this.init(); }
javascript
function heatmap(config){ // private variables var _ = { radius : 40, element : {}, canvas : {}, acanvas: {}, ctx : {}, actx : {}, legend: null, visible : true, width : 0, height : 0, max : false, gradient : false, opacity: 180, premultiplyAlpha: false, bounds: { l: 1000, r: 0, t: 1000, b: 0 }, debug: false }; // heatmap store containing the datapoints and information about the maximum // accessible via instance.store this.store = new store(this); this.get = function(key){ return _[key]; }; this.set = function(key, value){ _[key] = value; }; // configure the heatmap when an instance gets created this.configure(config); // and initialize it this.init(); }
[ "function", "heatmap", "(", "config", ")", "{", "var", "_", "=", "{", "radius", ":", "40", ",", "element", ":", "{", "}", ",", "canvas", ":", "{", "}", ",", "acanvas", ":", "{", "}", ",", "ctx", ":", "{", "}", ",", "actx", ":", "{", "}", ",", "legend", ":", "null", ",", "visible", ":", "true", ",", "width", ":", "0", ",", "height", ":", "0", ",", "max", ":", "false", ",", "gradient", ":", "false", ",", "opacity", ":", "180", ",", "premultiplyAlpha", ":", "false", ",", "bounds", ":", "{", "l", ":", "1000", ",", "r", ":", "0", ",", "t", ":", "1000", ",", "b", ":", "0", "}", ",", "debug", ":", "false", "}", ";", "this", ".", "store", "=", "new", "store", "(", "this", ")", ";", "this", ".", "get", "=", "function", "(", "key", ")", "{", "return", "_", "[", "key", "]", ";", "}", ";", "this", ".", "set", "=", "function", "(", "key", ",", "value", ")", "{", "_", "[", "key", "]", "=", "value", ";", "}", ";", "this", ".", "configure", "(", "config", ")", ";", "this", ".", "init", "(", ")", ";", "}" ]
heatmap object constructor
[ "heatmap", "object", "constructor" ]
710f22b68834b26bd1202944ba6137e42968b75d
https://github.com/Dafrok/BMapLib.Heatmap/blob/710f22b68834b26bd1202944ba6137e42968b75d/index.js#L309-L348
train
Infomaker/cropjs
example/handlers/upload.js
function(directoryName, cbUpload, cbError) { this.directory = directoryName; this.name = ''; this.localPath = ''; this.virtualPath = ''; this.onUpload = cbUpload; this.onError = cbError; }
javascript
function(directoryName, cbUpload, cbError) { this.directory = directoryName; this.name = ''; this.localPath = ''; this.virtualPath = ''; this.onUpload = cbUpload; this.onError = cbError; }
[ "function", "(", "directoryName", ",", "cbUpload", ",", "cbError", ")", "{", "this", ".", "directory", "=", "directoryName", ";", "this", ".", "name", "=", "''", ";", "this", ".", "localPath", "=", "''", ";", "this", ".", "virtualPath", "=", "''", ";", "this", ".", "onUpload", "=", "cbUpload", ";", "this", ".", "onError", "=", "cbError", ";", "}" ]
File upload handler @param cbUpload @param cbError @param directoryName
[ "File", "upload", "handler" ]
10a84e6d83d07b327cbed3714e42b5ba3bd506b5
https://github.com/Infomaker/cropjs/blob/10a84e6d83d07b327cbed3714e42b5ba3bd506b5/example/handlers/upload.js#L10-L17
train
unicornjs/unicornjs
lib/uAlive.js
uServicesManager
function uServicesManager(){ client.publish('uServicesChannel', 'UPDATE'); listenClient.on('message', function(channel, message) { client.get('uServices', function(err, reply) { if (reply !== null) { uServices = JSON.parse(reply); } }); }); listenClient.on("error", function (err) { console.log("Redis listen "+ err); listenClient.quit(); }); listenClient.subscribe('uServicesChannel'); }
javascript
function uServicesManager(){ client.publish('uServicesChannel', 'UPDATE'); listenClient.on('message', function(channel, message) { client.get('uServices', function(err, reply) { if (reply !== null) { uServices = JSON.parse(reply); } }); }); listenClient.on("error", function (err) { console.log("Redis listen "+ err); listenClient.quit(); }); listenClient.subscribe('uServicesChannel'); }
[ "function", "uServicesManager", "(", ")", "{", "client", ".", "publish", "(", "'uServicesChannel'", ",", "'UPDATE'", ")", ";", "listenClient", ".", "on", "(", "'message'", ",", "function", "(", "channel", ",", "message", ")", "{", "client", ".", "get", "(", "'uServices'", ",", "function", "(", "err", ",", "reply", ")", "{", "if", "(", "reply", "!==", "null", ")", "{", "uServices", "=", "JSON", ".", "parse", "(", "reply", ")", ";", "}", "}", ")", ";", "}", ")", ";", "listenClient", ".", "on", "(", "\"error\"", ",", "function", "(", "err", ")", "{", "console", ".", "log", "(", "\"Redis listen \"", "+", "err", ")", ";", "listenClient", ".", "quit", "(", ")", ";", "}", ")", ";", "listenClient", ".", "subscribe", "(", "'uServicesChannel'", ")", ";", "}" ]
Worker Logic I want this to listen always Listen for UPDATE in the uServices object
[ "Worker", "Logic", "I", "want", "this", "to", "listen", "always", "Listen", "for", "UPDATE", "in", "the", "uServices", "object" ]
840812b83648262ea5e71b0e9b876a00bcf7125b
https://github.com/unicornjs/unicornjs/blob/840812b83648262ea5e71b0e9b876a00bcf7125b/lib/uAlive.js#L116-L135
train
stezu/node-stream
lib/consumers/v2/wait.js
throughWithCallback
function throughWithCallback(onData) { return through.obj(function (chunk, enc, next) { if (onData) { onData(null, chunk); } next(null, chunk); }); }
javascript
function throughWithCallback(onData) { return through.obj(function (chunk, enc, next) { if (onData) { onData(null, chunk); } next(null, chunk); }); }
[ "function", "throughWithCallback", "(", "onData", ")", "{", "return", "through", ".", "obj", "(", "function", "(", "chunk", ",", "enc", ",", "next", ")", "{", "if", "(", "onData", ")", "{", "onData", "(", "null", ",", "chunk", ")", ";", "}", "next", "(", "null", ",", "chunk", ")", ";", "}", ")", ";", "}" ]
Create a through stream that simply calls a callback with the contents. Make sure to also pass the data along so the stream continues. @private @static @since 1.3.0 @category Utilities @param {Function} onData - Callback with an error or parsed JSON. @returns {Stream} - Transform Stream
[ "Create", "a", "through", "stream", "that", "simply", "calls", "a", "callback", "with", "the", "contents", ".", "Make", "sure", "to", "also", "pass", "the", "data", "along", "so", "the", "stream", "continues", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v2/wait.js#L18-L28
train
stezu/node-stream
lib/consumers/v2/wait.js
waitObj
function waitObj(callback) { var data = []; return pipeline.obj( through.obj( function transform(chunk, enc, next) { data.push(chunk); next(); }, function Flush(next) { this.push(data); next(); } ), throughWithCallback(callback) ); }
javascript
function waitObj(callback) { var data = []; return pipeline.obj( through.obj( function transform(chunk, enc, next) { data.push(chunk); next(); }, function Flush(next) { this.push(data); next(); } ), throughWithCallback(callback) ); }
[ "function", "waitObj", "(", "callback", ")", "{", "var", "data", "=", "[", "]", ";", "return", "pipeline", ".", "obj", "(", "through", ".", "obj", "(", "function", "transform", "(", "chunk", ",", "enc", ",", "next", ")", "{", "data", ".", "push", "(", "chunk", ")", ";", "next", "(", ")", ";", "}", ",", "function", "Flush", "(", "next", ")", "{", "this", ".", "push", "(", "data", ")", ";", "next", "(", ")", ";", "}", ")", ",", "throughWithCallback", "(", "callback", ")", ")", ";", "}" ]
Creates a new stream with a single value that's an array of every item in the stream. @static @method wait.obj @since 1.0.0 @category Consumers @param {Function} callback - A function to be called with the contents of the stream. This is a convenience to avoid listening to the data/end events of the stream. @returns {Stream.Transform} - Transform stream. @example // get all of the items in an object stream objStream .pipe(nodeStream.wait.obj()); // => [{ 'name': 'paul' }, { 'name': 'lisa' }, { 'name': 'mary' }]
[ "Creates", "a", "new", "stream", "with", "a", "single", "value", "that", "s", "an", "array", "of", "every", "item", "in", "the", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v2/wait.js#L52-L70
train
stezu/node-stream
lib/consumers/v2/wait.js
wait
function wait(callback) { return pipeline.obj( waitObj(), through.obj(function (chunk, enc, next) { next(null, Buffer.concat(chunk.map(function (item) { return new Buffer(item, enc); }))); }), throughWithCallback(callback) ); }
javascript
function wait(callback) { return pipeline.obj( waitObj(), through.obj(function (chunk, enc, next) { next(null, Buffer.concat(chunk.map(function (item) { return new Buffer(item, enc); }))); }), throughWithCallback(callback) ); }
[ "function", "wait", "(", "callback", ")", "{", "return", "pipeline", ".", "obj", "(", "waitObj", "(", ")", ",", "through", ".", "obj", "(", "function", "(", "chunk", ",", "enc", ",", "next", ")", "{", "next", "(", "null", ",", "Buffer", ".", "concat", "(", "chunk", ".", "map", "(", "function", "(", "item", ")", "{", "return", "new", "Buffer", "(", "item", ",", "enc", ")", ";", "}", ")", ")", ")", ";", "}", ")", ",", "throughWithCallback", "(", "callback", ")", ")", ";", "}" ]
Creates a new stream with a single value that's a Buffer of the entire contents of the stream. @static @since 1.0.0 @category Consumers @param {Function} callback - A function to be called with the contents of the stream. This is a convenience to avoid listening to the data/end events of the stream. @returns {Stream.Transform} - Transform stream. @example // get the entire contents of a file fs.createReadStream('example.txt') .pipe(nodeStream.wait()); // => Buffer
[ "Creates", "a", "new", "stream", "with", "a", "single", "value", "that", "s", "a", "Buffer", "of", "the", "entire", "contents", "of", "the", "stream", "." ]
f70c03351746c958865a854f614932f1df441b9b
https://github.com/stezu/node-stream/blob/f70c03351746c958865a854f614932f1df441b9b/lib/consumers/v2/wait.js#L93-L104
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
shallowEqual
function shallowEqual(actual, expected) { var keys = Object.keys(expected); var _arr2 = keys; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var key = _arr2[_i2]; if (actual[key] !== expected[key]) { return false; } } return true; }
javascript
function shallowEqual(actual, expected) { var keys = Object.keys(expected); var _arr2 = keys; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var key = _arr2[_i2]; if (actual[key] !== expected[key]) { return false; } } return true; }
[ "function", "shallowEqual", "(", "actual", ",", "expected", ")", "{", "var", "keys", "=", "Object", ".", "keys", "(", "expected", ")", ";", "var", "_arr2", "=", "keys", ";", "for", "(", "var", "_i2", "=", "0", ";", "_i2", "<", "_arr2", ".", "length", ";", "_i2", "++", ")", "{", "var", "key", "=", "_arr2", "[", "_i2", "]", ";", "if", "(", "actual", "[", "key", "]", "!==", "expected", "[", "key", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Test if an object is shallowly equal.
[ "Test", "if", "an", "object", "is", "shallowly", "equal", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L231-L243
train
noderaider/repackage
jspm_packages/npm/[email protected]/lib/types/index.js
appendToMemberExpression
function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; }
javascript
function appendToMemberExpression(member, append, computed) { member.object = t.memberExpression(member.object, member.property, member.computed); member.property = append; member.computed = !!computed; return member; }
[ "function", "appendToMemberExpression", "(", "member", ",", "append", ",", "computed", ")", "{", "member", ".", "object", "=", "t", ".", "memberExpression", "(", "member", ".", "object", ",", "member", ".", "property", ",", "member", ".", "computed", ")", ";", "member", ".", "property", "=", "append", ";", "member", ".", "computed", "=", "!", "!", "computed", ";", "return", "member", ";", "}" ]
Append a node to a member expression.
[ "Append", "a", "node", "to", "a", "member", "expression", "." ]
9f14246db3327abb0c4a5d7a3d55bd7816ebbd40
https://github.com/noderaider/repackage/blob/9f14246db3327abb0c4a5d7a3d55bd7816ebbd40/jspm_packages/npm/[email protected]/lib/types/index.js#L249-L254
train