id
int32
0
58k
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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
54,900
gtriggiano/dnsmq-messagebus
src/PubConnection.js
publish
function publish (channel, ...args) { _publishStream.emit('message', channel, uniqueId(`${node.name}_`), ...args) }
javascript
function publish (channel, ...args) { _publishStream.emit('message', channel, uniqueId(`${node.name}_`), ...args) }
[ "function", "publish", "(", "channel", ",", "...", "args", ")", "{", "_publishStream", ".", "emit", "(", "'message'", ",", "channel", ",", "uniqueId", "(", "`", "${", "node", ".", "name", "}", "`", ")", ",", "...", "args", ")", "}" ]
takes a list of strings|buffers to publish as message's frames in the channel passed as first argument; decorates each message with a uid @param {string} channel @param {[string|buffer]} args
[ "takes", "a", "list", "of", "strings|buffers", "to", "publish", "as", "message", "s", "frames", "in", "the", "channel", "passed", "as", "first", "argument", ";", "decorates", "each", "message", "with", "a", "uid" ]
ab935cae537f8a7e61a6ed6fba247661281c9374
https://github.com/gtriggiano/dnsmq-messagebus/blob/ab935cae537f8a7e61a6ed6fba247661281c9374/src/PubConnection.js#L132-L134
54,901
mrdaniellewis/node-tributary
index.js
Tributary
function Tributary( options ) { options = options || {}; stream.Transform.call( this, { encoding: options.encoding } ); this.getStream = options.getStream || function( filename, cb ) { return cb(); }; this._matcher = new Matcher( options.placeholderStart || '<!-- include ', options.placeholderEnd !== undefined ? options.placeholderEnd : ' -->', options.maxPathLength, options.delimiter ); this._tributaryState = { chunk: null, cursor: 0, contentStart: 0, contentEnd: -1, remainder: 0 }; }
javascript
function Tributary( options ) { options = options || {}; stream.Transform.call( this, { encoding: options.encoding } ); this.getStream = options.getStream || function( filename, cb ) { return cb(); }; this._matcher = new Matcher( options.placeholderStart || '<!-- include ', options.placeholderEnd !== undefined ? options.placeholderEnd : ' -->', options.maxPathLength, options.delimiter ); this._tributaryState = { chunk: null, cursor: 0, contentStart: 0, contentEnd: -1, remainder: 0 }; }
[ "function", "Tributary", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "stream", ".", "Transform", ".", "call", "(", "this", ",", "{", "encoding", ":", "options", ".", "encoding", "}", ")", ";", "this", ".", "getStream", "=", "options", ".", "getStream", "||", "function", "(", "filename", ",", "cb", ")", "{", "return", "cb", "(", ")", ";", "}", ";", "this", ".", "_matcher", "=", "new", "Matcher", "(", "options", ".", "placeholderStart", "||", "'<!-- include '", ",", "options", ".", "placeholderEnd", "!==", "undefined", "?", "options", ".", "placeholderEnd", ":", "' -->'", ",", "options", ".", "maxPathLength", ",", "options", ".", "delimiter", ")", ";", "this", ".", "_tributaryState", "=", "{", "chunk", ":", "null", ",", "cursor", ":", "0", ",", "contentStart", ":", "0", ",", "contentEnd", ":", "-", "1", ",", "remainder", ":", "0", "}", ";", "}" ]
Include one stream in another @param {String} [options.placeholderStart="<!-- include "] The start placeholder @param {String} [options.placeholderStart=" -->"] The end placeholder @param {Integer} [options.maxPathLength=512] The maximum length of a path @param {String} [options.delmiter="] The delimiter to use for filenames, a single character @param {Function} getStream A function that when provided with a filename and callback will return a stream to be included.
[ "Include", "one", "stream", "in", "another" ]
8fb0deee6adf1d1a1b075dd51a0511c88215e49f
https://github.com/mrdaniellewis/node-tributary/blob/8fb0deee6adf1d1a1b075dd51a0511c88215e49f/index.js#L115-L140
54,902
AGCPartners/mysql-transit
index.js
MysqlTransit
function MysqlTransit(dbOriginal, dbTemp, connectionParameters) { this.dbOriginal = dbOriginal; this.dbTemp = dbTemp; this.connectionParameters = connectionParameters; this.queryQueue = []; this.tablesToDrop = []; this.tablesToCreate = []; this.interactive = true; return this._init(); }
javascript
function MysqlTransit(dbOriginal, dbTemp, connectionParameters) { this.dbOriginal = dbOriginal; this.dbTemp = dbTemp; this.connectionParameters = connectionParameters; this.queryQueue = []; this.tablesToDrop = []; this.tablesToCreate = []; this.interactive = true; return this._init(); }
[ "function", "MysqlTransit", "(", "dbOriginal", ",", "dbTemp", ",", "connectionParameters", ")", "{", "this", ".", "dbOriginal", "=", "dbOriginal", ";", "this", ".", "dbTemp", "=", "dbTemp", ";", "this", ".", "connectionParameters", "=", "connectionParameters", ";", "this", ".", "queryQueue", "=", "[", "]", ";", "this", ".", "tablesToDrop", "=", "[", "]", ";", "this", ".", "tablesToCreate", "=", "[", "]", ";", "this", ".", "interactive", "=", "true", ";", "return", "this", ".", "_init", "(", ")", ";", "}" ]
Initialize the MysqlTransit object @param dbOriginal name of the database to migrate @param dbTemp name of the database to be migrated @param connectionParameters object with { port: mysqlParams.options.port, host: mysqlParams.options.host, user: mysqlParams.user, password: mysqlParams.password }
[ "Initialize", "the", "MysqlTransit", "object" ]
d3cc3701166be3d41826c4b3bf1a596ed4c1f03a
https://github.com/AGCPartners/mysql-transit/blob/d3cc3701166be3d41826c4b3bf1a596ed4c1f03a/index.js#L22-L31
54,903
MiguelCastillo/stream-joint
index.js
joint
function joint(streams) { if (!(streams instanceof Array)) { streams = Array.prototype.slice.call(arguments); } return streams.reduce(function(thru, stream) { if (stream) { thru.pipe(stream); } return thru; }, through()); }
javascript
function joint(streams) { if (!(streams instanceof Array)) { streams = Array.prototype.slice.call(arguments); } return streams.reduce(function(thru, stream) { if (stream) { thru.pipe(stream); } return thru; }, through()); }
[ "function", "joint", "(", "streams", ")", "{", "if", "(", "!", "(", "streams", "instanceof", "Array", ")", ")", "{", "streams", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "}", "return", "streams", ".", "reduce", "(", "function", "(", "thru", ",", "stream", ")", "{", "if", "(", "stream", ")", "{", "thru", ".", "pipe", "(", "stream", ")", ";", "}", "return", "thru", ";", "}", ",", "through", "(", ")", ")", ";", "}" ]
Take all incoming streams combine them into a single through stream. Writing to the returned stream will write to all streams passed in. Handy for chaining writable streams. @param {...Streams} List of streams to merge @returns {Stream} Returns a single through stream
[ "Take", "all", "incoming", "streams", "combine", "them", "into", "a", "single", "through", "stream", ".", "Writing", "to", "the", "returned", "stream", "will", "write", "to", "all", "streams", "passed", "in", "." ]
86986b2611e46be6bd84e27016600fc2e5022834
https://github.com/MiguelCastillo/stream-joint/blob/86986b2611e46be6bd84e27016600fc2e5022834/index.js#L14-L25
54,904
pine/typescript-after-extends
lib/extends.js
createNamedClass
function createNamedClass (name, klass, baseKlass, superFunc) { if (!superFunc) { superFunc = function () { baseKlass.call(this); }; } return new Function( 'klass', 'superFunc', 'return function ' + name + ' () {' + 'superFunc.apply(this, arguments);' + 'klass.apply(this, arguments);' + '};' )(klass, superFunc); }
javascript
function createNamedClass (name, klass, baseKlass, superFunc) { if (!superFunc) { superFunc = function () { baseKlass.call(this); }; } return new Function( 'klass', 'superFunc', 'return function ' + name + ' () {' + 'superFunc.apply(this, arguments);' + 'klass.apply(this, arguments);' + '};' )(klass, superFunc); }
[ "function", "createNamedClass", "(", "name", ",", "klass", ",", "baseKlass", ",", "superFunc", ")", "{", "if", "(", "!", "superFunc", ")", "{", "superFunc", "=", "function", "(", ")", "{", "baseKlass", ".", "call", "(", "this", ")", ";", "}", ";", "}", "return", "new", "Function", "(", "'klass'", ",", "'superFunc'", ",", "'return function '", "+", "name", "+", "' () {'", "+", "'superFunc.apply(this, arguments);'", "+", "'klass.apply(this, arguments);'", "+", "'};'", ")", "(", "klass", ",", "superFunc", ")", ";", "}" ]
Create named class with extends
[ "Create", "named", "class", "with", "extends" ]
bbe2523beef3bcd1c836ca74a07ac0eafd1858d3
https://github.com/pine/typescript-after-extends/blob/bbe2523beef3bcd1c836ca74a07ac0eafd1858d3/lib/extends.js#L18-L32
54,905
pine/typescript-after-extends
lib/extends.js
afterExtends
function afterExtends (klass, baseKlass, superFunc) { var newKlass = createNamedClass(klass.name, klass, baseKlass, superFunc); newKlass.prototype = createPrototype(klass, baseKlass, newKlass); return newKlass; }
javascript
function afterExtends (klass, baseKlass, superFunc) { var newKlass = createNamedClass(klass.name, klass, baseKlass, superFunc); newKlass.prototype = createPrototype(klass, baseKlass, newKlass); return newKlass; }
[ "function", "afterExtends", "(", "klass", ",", "baseKlass", ",", "superFunc", ")", "{", "var", "newKlass", "=", "createNamedClass", "(", "klass", ".", "name", ",", "klass", ",", "baseKlass", ",", "superFunc", ")", ";", "newKlass", ".", "prototype", "=", "createPrototype", "(", "klass", ",", "baseKlass", ",", "newKlass", ")", ";", "return", "newKlass", ";", "}" ]
TypeScript extends later
[ "TypeScript", "extends", "later" ]
bbe2523beef3bcd1c836ca74a07ac0eafd1858d3
https://github.com/pine/typescript-after-extends/blob/bbe2523beef3bcd1c836ca74a07ac0eafd1858d3/lib/extends.js#L49-L54
54,906
allanmboyd/docit
lib/docit.js
processMethodOutTag
function processMethodOutTag(tag, typeMarkdown) { var md = ""; if (tag.type) { md += applyMarkdown(tag.type, settings.get(typeMarkdown)) + " "; } md += tag.comment; return md; }
javascript
function processMethodOutTag(tag, typeMarkdown) { var md = ""; if (tag.type) { md += applyMarkdown(tag.type, settings.get(typeMarkdown)) + " "; } md += tag.comment; return md; }
[ "function", "processMethodOutTag", "(", "tag", ",", "typeMarkdown", ")", "{", "var", "md", "=", "\"\"", ";", "if", "(", "tag", ".", "type", ")", "{", "md", "+=", "applyMarkdown", "(", "tag", ".", "type", ",", "settings", ".", "get", "(", "typeMarkdown", ")", ")", "+", "\" \"", ";", "}", "md", "+=", "tag", ".", "comment", ";", "return", "md", ";", "}" ]
Process either a return or throws tag. @param tag the tag @param {String} typeMarkdown the markdown identifier to associate with the type of the tag if present @return {String} the markdown for the tag @private
[ "Process", "either", "a", "return", "or", "throws", "tag", "." ]
e972b6e3a9792f649e9fed9115b45cb010c90c8f
https://github.com/allanmboyd/docit/blob/e972b6e3a9792f649e9fed9115b45cb010c90c8f/lib/docit.js#L303-L310
54,907
skazska/marking-codes
v0.js
encode
function encode(batch, id, ver) { //producerId min 2 digits let producerId = b36.int2Str36(batch.producerId).padStart(2, '0'); //producerId min 3 digits let batchId = b36.int2Str36(batch.id).padStart(3, '0'); //id min 2 digits id = b36.int2Str36(id).padStart(3, '0'); let msg = composeCode(producerId, batchId, id); let sign = sign2Str36(dsa.doSign(batch.dsa, batch.privateKey, msg, hash.vsHash)); let codeDescr = generateCodeDescr(producerId, batchId, id, sign, ver); return codeDescr ? (codeDescr + msg + sign) : ''; }
javascript
function encode(batch, id, ver) { //producerId min 2 digits let producerId = b36.int2Str36(batch.producerId).padStart(2, '0'); //producerId min 3 digits let batchId = b36.int2Str36(batch.id).padStart(3, '0'); //id min 2 digits id = b36.int2Str36(id).padStart(3, '0'); let msg = composeCode(producerId, batchId, id); let sign = sign2Str36(dsa.doSign(batch.dsa, batch.privateKey, msg, hash.vsHash)); let codeDescr = generateCodeDescr(producerId, batchId, id, sign, ver); return codeDescr ? (codeDescr + msg + sign) : ''; }
[ "function", "encode", "(", "batch", ",", "id", ",", "ver", ")", "{", "//producerId min 2 digits", "let", "producerId", "=", "b36", ".", "int2Str36", "(", "batch", ".", "producerId", ")", ".", "padStart", "(", "2", ",", "'0'", ")", ";", "//producerId min 3 digits", "let", "batchId", "=", "b36", ".", "int2Str36", "(", "batch", ".", "id", ")", ".", "padStart", "(", "3", ",", "'0'", ")", ";", "//id min 2 digits", "id", "=", "b36", ".", "int2Str36", "(", "id", ")", ".", "padStart", "(", "3", ",", "'0'", ")", ";", "let", "msg", "=", "composeCode", "(", "producerId", ",", "batchId", ",", "id", ")", ";", "let", "sign", "=", "sign2Str36", "(", "dsa", ".", "doSign", "(", "batch", ".", "dsa", ",", "batch", ".", "privateKey", ",", "msg", ",", "hash", ".", "vsHash", ")", ")", ";", "let", "codeDescr", "=", "generateCodeDescr", "(", "producerId", ",", "batchId", ",", "id", ",", "sign", ",", "ver", ")", ";", "return", "codeDescr", "?", "(", "codeDescr", "+", "msg", "+", "sign", ")", ":", "''", ";", "}" ]
creates alphanum representation of marking code @param {{id: number, dsa: {q: number, p: number, g: number}, version: number, producerId: number, publicKey: number, privateKey: number}} batch @param {*} id @param {number} [ver]
[ "creates", "alphanum", "representation", "of", "marking", "code" ]
64c81c39db3dd8a8b17b0bf5e66e4da04d13a846
https://github.com/skazska/marking-codes/blob/64c81c39db3dd8a8b17b0bf5e66e4da04d13a846/v0.js#L168-L183
54,908
elidoran/node-ansi2
lib/index.js
build
function build(writable, options) { return writable && writable._ansi2 || (writable._ansi2 = new Ansi(writable, options)) }
javascript
function build(writable, options) { return writable && writable._ansi2 || (writable._ansi2 = new Ansi(writable, options)) }
[ "function", "build", "(", "writable", ",", "options", ")", "{", "return", "writable", "&&", "writable", ".", "_ansi2", "||", "(", "writable", ".", "_ansi2", "=", "new", "Ansi", "(", "writable", ",", "options", ")", ")", "}" ]
return one we already made or make a new one
[ "return", "one", "we", "already", "made", "or", "make", "a", "new", "one" ]
7171989aeaaa917fba925bd676bb89df19b28525
https://github.com/elidoran/node-ansi2/blob/7171989aeaaa917fba925bd676bb89df19b28525/lib/index.js#L11-L13
54,909
Augmentedjs/augmented
scripts/legacy/legacy.js
loadAndParseFile
function loadAndParseFile(filename, settings) { Augmented.ajax({ url: filename, async: true, cache: settings.cache, contentType: 'text/plain;charset=' + settings.encoding, dataType: 'text', success: function (data, status) { logger.debug("message bundel ajax call - success"); parseData(data, settings.mode); }, error: function(data, status) { logger.debug("message bundel ajax call - fail " + data); } }); }
javascript
function loadAndParseFile(filename, settings) { Augmented.ajax({ url: filename, async: true, cache: settings.cache, contentType: 'text/plain;charset=' + settings.encoding, dataType: 'text', success: function (data, status) { logger.debug("message bundel ajax call - success"); parseData(data, settings.mode); }, error: function(data, status) { logger.debug("message bundel ajax call - fail " + data); } }); }
[ "function", "loadAndParseFile", "(", "filename", ",", "settings", ")", "{", "Augmented", ".", "ajax", "(", "{", "url", ":", "filename", ",", "async", ":", "true", ",", "cache", ":", "settings", ".", "cache", ",", "contentType", ":", "'text/plain;charset='", "+", "settings", ".", "encoding", ",", "dataType", ":", "'text'", ",", "success", ":", "function", "(", "data", ",", "status", ")", "{", "logger", ".", "debug", "(", "\"message bundel ajax call - success\"", ")", ";", "parseData", "(", "data", ",", "settings", ".", "mode", ")", ";", "}", ",", "error", ":", "function", "(", "data", ",", "status", ")", "{", "logger", ".", "debug", "(", "\"message bundel ajax call - fail \"", "+", "data", ")", ";", "}", "}", ")", ";", "}" ]
Load and parse .properties files @method loadAndParseFile @memberof i18nBase @param filename @param settings
[ "Load", "and", "parse", ".", "properties", "files" ]
430567d411ab9e77953232bb600c08080ed33146
https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/legacy/legacy.js#L299-L314
54,910
Augmentedjs/augmented
scripts/legacy/legacy.js
function(array) { var sarr = []; var i = 0; for (i=0; i<array.length;i++) { var a = array[i]; var o = {}; o.name = a.name; o.value = a.value; o.type = a.type; if (a.type === "checkbox") { o.value = (a.checked) ? "on" : "off"; } sarr.push(o); } return sarr; }
javascript
function(array) { var sarr = []; var i = 0; for (i=0; i<array.length;i++) { var a = array[i]; var o = {}; o.name = a.name; o.value = a.value; o.type = a.type; if (a.type === "checkbox") { o.value = (a.checked) ? "on" : "off"; } sarr.push(o); } return sarr; }
[ "function", "(", "array", ")", "{", "var", "sarr", "=", "[", "]", ";", "var", "i", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "var", "a", "=", "array", "[", "i", "]", ";", "var", "o", "=", "{", "}", ";", "o", ".", "name", "=", "a", ".", "name", ";", "o", ".", "value", "=", "a", ".", "value", ";", "o", ".", "type", "=", "a", ".", "type", ";", "if", "(", "a", ".", "type", "===", "\"checkbox\"", ")", "{", "o", ".", "value", "=", "(", "a", ".", "checked", ")", "?", "\"on\"", ":", "\"off\"", ";", "}", "sarr", ".", "push", "(", "o", ")", ";", "}", "return", "sarr", ";", "}" ]
Get form data.
[ "Get", "form", "data", "." ]
430567d411ab9e77953232bb600c08080ed33146
https://github.com/Augmentedjs/augmented/blob/430567d411ab9e77953232bb600c08080ed33146/scripts/legacy/legacy.js#L742-L758
54,911
exis-io/ngRiffle
release/ngRiffle.js
success
function success(domain){ if(auth0){ //if auth0 then we don't have user storage connection.user = new DomainWrapper(domain); connection.user.join(); sessionPromise.then(resolve); }else{ //if auth1 use user class to wrap domain and implement user storage and load user data connection.user = new User(self, domain); connection.user.join(); sessionPromise.then(load); } }
javascript
function success(domain){ if(auth0){ //if auth0 then we don't have user storage connection.user = new DomainWrapper(domain); connection.user.join(); sessionPromise.then(resolve); }else{ //if auth1 use user class to wrap domain and implement user storage and load user data connection.user = new User(self, domain); connection.user.join(); sessionPromise.then(load); } }
[ "function", "success", "(", "domain", ")", "{", "if", "(", "auth0", ")", "{", "//if auth0 then we don't have user storage", "connection", ".", "user", "=", "new", "DomainWrapper", "(", "domain", ")", ";", "connection", ".", "user", ".", "join", "(", ")", ";", "sessionPromise", ".", "then", "(", "resolve", ")", ";", "}", "else", "{", "//if auth1 use user class to wrap domain and implement user storage and load user data", "connection", ".", "user", "=", "new", "User", "(", "self", ",", "domain", ")", ";", "connection", ".", "user", ".", "join", "(", ")", ";", "sessionPromise", ".", "then", "(", "load", ")", ";", "}", "}" ]
if we get success from the registrar on login continue depending on auth level
[ "if", "we", "get", "success", "from", "the", "registrar", "on", "login", "continue", "depending", "on", "auth", "level" ]
e468353262bbe829e74975def19656fe4a37821f
https://github.com/exis-io/ngRiffle/blob/e468353262bbe829e74975def19656fe4a37821f/release/ngRiffle.js#L938-L950
54,912
Dashron/Roads-Models
libs/model.js
applyModelMethods
function applyModelMethods (model, definition) { for (var i in definition.methods) { if (i === 'definition') { throw new Error('Invalid model definition provided. "definition" is a reserved word'); } model.prototype[i] = definition.methods[i]; } }
javascript
function applyModelMethods (model, definition) { for (var i in definition.methods) { if (i === 'definition') { throw new Error('Invalid model definition provided. "definition" is a reserved word'); } model.prototype[i] = definition.methods[i]; } }
[ "function", "applyModelMethods", "(", "model", ",", "definition", ")", "{", "for", "(", "var", "i", "in", "definition", ".", "methods", ")", "{", "if", "(", "i", "===", "'definition'", ")", "{", "throw", "new", "Error", "(", "'Invalid model definition provided. \"definition\" is a reserved word'", ")", ";", "}", "model", ".", "prototype", "[", "i", "]", "=", "definition", ".", "methods", "[", "i", "]", ";", "}", "}" ]
Used in setModel @param {[type]} model [description] @param {[type]} definition [description] @return {[type]} [description]
[ "Used", "in", "setModel" ]
e7820410ae75a8f579bad59e3047f8b3e3bc01f1
https://github.com/Dashron/Roads-Models/blob/e7820410ae75a8f579bad59e3047f8b3e3bc01f1/libs/model.js#L470-L478
54,913
zenflow/obs-router
lib/index.js
function(patterns, options) { var self = this; if (!(typeof patterns=='object')){throw new Error('ObsRouter constructor expects patterns object as first argument')} options = options || {}; EventEmitter.call(self); if (process.browser){ //bind to window by default self._bindToWindow = 'bindToWindow' in options ? options.bindToWindow : true; if (self._bindToWindow){ // add to module-scoped list of routers routers.push(self); // override any url input with window location options.url = window.document.location.pathname + window.document.location.search; } } // initialise state self.patterns = patterns; self.name = null; self.params = {}; self.routes = {}; _.forEach(_.keys(self.patterns), function(route){ self.routes[route] = null; }); // normalise state self._update(options.url || '', false); // implement initialEmit option if (options.initialEmit){ var cancel = cancellableNextTick(function(){ self._emit(); }); self.once('url', cancel); } }
javascript
function(patterns, options) { var self = this; if (!(typeof patterns=='object')){throw new Error('ObsRouter constructor expects patterns object as first argument')} options = options || {}; EventEmitter.call(self); if (process.browser){ //bind to window by default self._bindToWindow = 'bindToWindow' in options ? options.bindToWindow : true; if (self._bindToWindow){ // add to module-scoped list of routers routers.push(self); // override any url input with window location options.url = window.document.location.pathname + window.document.location.search; } } // initialise state self.patterns = patterns; self.name = null; self.params = {}; self.routes = {}; _.forEach(_.keys(self.patterns), function(route){ self.routes[route] = null; }); // normalise state self._update(options.url || '', false); // implement initialEmit option if (options.initialEmit){ var cancel = cancellableNextTick(function(){ self._emit(); }); self.once('url', cancel); } }
[ "function", "(", "patterns", ",", "options", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "(", "typeof", "patterns", "==", "'object'", ")", ")", "{", "throw", "new", "Error", "(", "'ObsRouter constructor expects patterns object as first argument'", ")", "}", "options", "=", "options", "||", "{", "}", ";", "EventEmitter", ".", "call", "(", "self", ")", ";", "if", "(", "process", ".", "browser", ")", "{", "//bind to window by default\r", "self", ".", "_bindToWindow", "=", "'bindToWindow'", "in", "options", "?", "options", ".", "bindToWindow", ":", "true", ";", "if", "(", "self", ".", "_bindToWindow", ")", "{", "// add to module-scoped list of routers\r", "routers", ".", "push", "(", "self", ")", ";", "// override any url input with window location\r", "options", ".", "url", "=", "window", ".", "document", ".", "location", ".", "pathname", "+", "window", ".", "document", ".", "location", ".", "search", ";", "}", "}", "// initialise state\r", "self", ".", "patterns", "=", "patterns", ";", "self", ".", "name", "=", "null", ";", "self", ".", "params", "=", "{", "}", ";", "self", ".", "routes", "=", "{", "}", ";", "_", ".", "forEach", "(", "_", ".", "keys", "(", "self", ".", "patterns", ")", ",", "function", "(", "route", ")", "{", "self", ".", "routes", "[", "route", "]", "=", "null", ";", "}", ")", ";", "// normalise state\r", "self", ".", "_update", "(", "options", ".", "url", "||", "''", ",", "false", ")", ";", "// implement initialEmit option\r", "if", "(", "options", ".", "initialEmit", ")", "{", "var", "cancel", "=", "cancellableNextTick", "(", "function", "(", ")", "{", "self", ".", "_emit", "(", ")", ";", "}", ")", ";", "self", ".", "once", "(", "'url'", ",", "cancel", ")", ";", "}", "}" ]
Mutable observable abstraction of url as route with parameters @example var router = new ObsRouter({ home: '/', blog: '/blog(/tag/:tag)(/:slug)', contact: '/contact' }, { initialEmit: true, bindToWindow: false, url: '/?foo=bar' }); console.log(router.url, router.name, router.params, router.routes); -> '/?foo=bar' 'home' {foo: 'bar'} {home: {foo: 'bar'}, blog: null, contact: null} @class ObsRouter @param {Object} patterns Pathname patterns keyed by route names. @param {Object} [options] Options @param {Boolean} [options.initialEmit=false] If true, events will be emitted after nextTick, unless emitted earlier due to changes, ensuring that events are emitted at least once. @param {Boolean} [options.bindToWindow=true] Bind to document location if running in browser @param {string} [options.url=""] Initial url. If binding to document loctation then this is ignored.
[ "Mutable", "observable", "abstraction", "of", "url", "as", "route", "with", "parameters" ]
dd9934bfaa5099f477e7f06d8a3f2deed92ee142
https://github.com/zenflow/obs-router/blob/dd9934bfaa5099f477e7f06d8a3f2deed92ee142/lib/index.js#L50-L82
54,914
deepjs/deep-restful
lib/http.js
function(object, options) { var self = this; return deep.when(getSchema(this)) .done(function(schema) { return deep.Arguments([object, options]); }); }
javascript
function(object, options) { var self = this; return deep.when(getSchema(this)) .done(function(schema) { return deep.Arguments([object, options]); }); }
[ "function", "(", "object", ",", "options", ")", "{", "var", "self", "=", "this", ";", "return", "deep", ".", "when", "(", "getSchema", "(", "this", ")", ")", ".", "done", "(", "function", "(", "schema", ")", "{", "return", "deep", ".", "Arguments", "(", "[", "object", ",", "options", "]", ")", ";", "}", ")", ";", "}" ]
retrieve Schema if @param {[type]} object [description] @param {[type]} options [description] @return {[type]} [description]
[ "retrieve", "Schema", "if" ]
44c5e1e5526a821522ab5e3004f66ffc7840f551
https://github.com/deepjs/deep-restful/blob/44c5e1e5526a821522ab5e3004f66ffc7840f551/lib/http.js#L121-L127
54,915
tracker1/mssql-ng
src/connections/open.js
handleConnectionCallback
function handleConnectionCallback(err, resolve, reject, key, connection) { debug('handleConnectionCallback','start'); //error, remove cached entry, reject the promise if (err) { debug('handleConnectionCallback','error',err); delete promises[key]; return reject(err); } //patch close method for caching shadowClose(connection); //create a reference to the original connection for cleanup connection._mssqlngKey = key; //add connection to the pool connections[connection._mssqlngKey] = connection; //resolve the promise debug('handleConnectionCallback','success'); return resolve(connection); }
javascript
function handleConnectionCallback(err, resolve, reject, key, connection) { debug('handleConnectionCallback','start'); //error, remove cached entry, reject the promise if (err) { debug('handleConnectionCallback','error',err); delete promises[key]; return reject(err); } //patch close method for caching shadowClose(connection); //create a reference to the original connection for cleanup connection._mssqlngKey = key; //add connection to the pool connections[connection._mssqlngKey] = connection; //resolve the promise debug('handleConnectionCallback','success'); return resolve(connection); }
[ "function", "handleConnectionCallback", "(", "err", ",", "resolve", ",", "reject", ",", "key", ",", "connection", ")", "{", "debug", "(", "'handleConnectionCallback'", ",", "'start'", ")", ";", "//error, remove cached entry, reject the promise", "if", "(", "err", ")", "{", "debug", "(", "'handleConnectionCallback'", ",", "'error'", ",", "err", ")", ";", "delete", "promises", "[", "key", "]", ";", "return", "reject", "(", "err", ")", ";", "}", "//patch close method for caching", "shadowClose", "(", "connection", ")", ";", "//create a reference to the original connection for cleanup", "connection", ".", "_mssqlngKey", "=", "key", ";", "//add connection to the pool", "connections", "[", "connection", ".", "_mssqlngKey", "]", "=", "connection", ";", "//resolve the promise", "debug", "(", "'handleConnectionCallback'", ",", "'success'", ")", ";", "return", "resolve", "(", "connection", ")", ";", "}" ]
handle promise resolution for connection callback
[ "handle", "promise", "resolution", "for", "connection", "callback" ]
7f32135d33f9b8324fdd94656136cae4087464ce
https://github.com/tracker1/mssql-ng/blob/7f32135d33f9b8324fdd94656136cae4087464ce/src/connections/open.js#L80-L102
54,916
MiguelCastillo/spromise
src/samdy.js
load
function load(mod) { if (typeof(mod.factory) === "function") { return require(mod.deps, mod.factory); } return mod.factory; }
javascript
function load(mod) { if (typeof(mod.factory) === "function") { return require(mod.deps, mod.factory); } return mod.factory; }
[ "function", "load", "(", "mod", ")", "{", "if", "(", "typeof", "(", "mod", ".", "factory", ")", "===", "\"function\"", ")", "{", "return", "require", "(", "mod", ".", "deps", ",", "mod", ".", "factory", ")", ";", "}", "return", "mod", ".", "factory", ";", "}" ]
Load the module by calling its factory with the appropriate dependencies, if at all possible
[ "Load", "the", "module", "by", "calling", "its", "factory", "with", "the", "appropriate", "dependencies", "if", "at", "all", "possible" ]
faef0a81e88a871095393980fccdd7980e7c3f89
https://github.com/MiguelCastillo/spromise/blob/faef0a81e88a871095393980fccdd7980e7c3f89/src/samdy.js#L14-L19
54,917
vfile/vfile-find-up
index.js
handle
function handle(filePath) { var file = toVFile(filePath) var result = test(file) if (mask(result, INCLUDE)) { if (one) { callback(null, file) return true } results.push(file) } if (mask(result, BREAK)) { callback(null, one ? null : results) return true } }
javascript
function handle(filePath) { var file = toVFile(filePath) var result = test(file) if (mask(result, INCLUDE)) { if (one) { callback(null, file) return true } results.push(file) } if (mask(result, BREAK)) { callback(null, one ? null : results) return true } }
[ "function", "handle", "(", "filePath", ")", "{", "var", "file", "=", "toVFile", "(", "filePath", ")", "var", "result", "=", "test", "(", "file", ")", "if", "(", "mask", "(", "result", ",", "INCLUDE", ")", ")", "{", "if", "(", "one", ")", "{", "callback", "(", "null", ",", "file", ")", "return", "true", "}", "results", ".", "push", "(", "file", ")", "}", "if", "(", "mask", "(", "result", ",", "BREAK", ")", ")", "{", "callback", "(", "null", ",", "one", "?", "null", ":", "results", ")", "return", "true", "}", "}" ]
Test a file and check what should be done with the resulting file.
[ "Test", "a", "file", "and", "check", "what", "should", "be", "done", "with", "the", "resulting", "file", "." ]
93dc51a499a7888b11f8d5e01e4fd0ae3615c391
https://github.com/vfile/vfile-find-up/blob/93dc51a499a7888b11f8d5e01e4fd0ae3615c391/index.js#L47-L64
54,918
vfile/vfile-find-up
index.js
once
function once(child) { if (handle(current) === true) { return } readdir(current, onread) function onread(error, entries) { var length = entries ? entries.length : 0 var index = -1 var entry if (error) { entries = [] } while (++index < length) { entry = entries[index] if (entry !== child && handle(resolve(current, entry)) === true) { return } } child = current current = dirname(current) if (current === child) { callback(null, one ? null : results) return } once(basename(child)) } }
javascript
function once(child) { if (handle(current) === true) { return } readdir(current, onread) function onread(error, entries) { var length = entries ? entries.length : 0 var index = -1 var entry if (error) { entries = [] } while (++index < length) { entry = entries[index] if (entry !== child && handle(resolve(current, entry)) === true) { return } } child = current current = dirname(current) if (current === child) { callback(null, one ? null : results) return } once(basename(child)) } }
[ "function", "once", "(", "child", ")", "{", "if", "(", "handle", "(", "current", ")", "===", "true", ")", "{", "return", "}", "readdir", "(", "current", ",", "onread", ")", "function", "onread", "(", "error", ",", "entries", ")", "{", "var", "length", "=", "entries", "?", "entries", ".", "length", ":", "0", "var", "index", "=", "-", "1", "var", "entry", "if", "(", "error", ")", "{", "entries", "=", "[", "]", "}", "while", "(", "++", "index", "<", "length", ")", "{", "entry", "=", "entries", "[", "index", "]", "if", "(", "entry", "!==", "child", "&&", "handle", "(", "resolve", "(", "current", ",", "entry", ")", ")", "===", "true", ")", "{", "return", "}", "}", "child", "=", "current", "current", "=", "dirname", "(", "current", ")", "if", "(", "current", "===", "child", ")", "{", "callback", "(", "null", ",", "one", "?", "null", ":", "results", ")", "return", "}", "once", "(", "basename", "(", "child", ")", ")", "}", "}" ]
Check one directory.
[ "Check", "one", "directory", "." ]
93dc51a499a7888b11f8d5e01e4fd0ae3615c391
https://github.com/vfile/vfile-find-up/blob/93dc51a499a7888b11f8d5e01e4fd0ae3615c391/index.js#L67-L101
54,919
webwallet/sdk-node
sdk.js
generateTransactionRequest
function generateTransactionRequest(signer, transaction, options) { let iou = { amt: transaction.amount, cur: transaction.currency, sub: signer.address, aud: transaction.destination, nce: String(Math.floor(Math.random() * 1000000000)) }; return createTransactionRequestStatement(signer, iou, options); }
javascript
function generateTransactionRequest(signer, transaction, options) { let iou = { amt: transaction.amount, cur: transaction.currency, sub: signer.address, aud: transaction.destination, nce: String(Math.floor(Math.random() * 1000000000)) }; return createTransactionRequestStatement(signer, iou, options); }
[ "function", "generateTransactionRequest", "(", "signer", ",", "transaction", ",", "options", ")", "{", "let", "iou", "=", "{", "amt", ":", "transaction", ".", "amount", ",", "cur", ":", "transaction", ".", "currency", ",", "sub", ":", "signer", ".", "address", ",", "aud", ":", "transaction", ".", "destination", ",", "nce", ":", "String", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "1000000000", ")", ")", "}", ";", "return", "createTransactionRequestStatement", "(", "signer", ",", "iou", ",", "options", ")", ";", "}" ]
Generates a transaction request document in the form of an IOU @param {Object} signer - Wallet whose private key is to be used for signing the IOU @param {Object} transaction - Transaction parameters @param {Object} options @return {Object} - A cryptographically signed IOU
[ "Generates", "a", "transaction", "request", "document", "in", "the", "form", "of", "an", "IOU" ]
594081202f39dd648c33e6ddaa5da0590826a62f
https://github.com/webwallet/sdk-node/blob/594081202f39dd648c33e6ddaa5da0590826a62f/sdk.js#L68-L78
54,920
webwallet/sdk-node
sdk.js
registerWalletAddress
function registerWalletAddress(url, body, options) { options = options || {}; url = resolveURL(url, '/address'); return new P(function (resolve, reject) { request({ url: url, method: options.method || 'POST', body: body, json: true, headers: options.headers }, function (err, res, body) { if (err) return reject(err); return resolve(body); }); }); }
javascript
function registerWalletAddress(url, body, options) { options = options || {}; url = resolveURL(url, '/address'); return new P(function (resolve, reject) { request({ url: url, method: options.method || 'POST', body: body, json: true, headers: options.headers }, function (err, res, body) { if (err) return reject(err); return resolve(body); }); }); }
[ "function", "registerWalletAddress", "(", "url", ",", "body", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "url", "=", "resolveURL", "(", "url", ",", "'/address'", ")", ";", "return", "new", "P", "(", "function", "(", "resolve", ",", "reject", ")", "{", "request", "(", "{", "url", ":", "url", ",", "method", ":", "options", ".", "method", "||", "'POST'", ",", "body", ":", "body", ",", "json", ":", "true", ",", "headers", ":", "options", ".", "headers", "}", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "return", "resolve", "(", "body", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Sends a wallet address registration request to the supplied URL @param {string} url - The URL of a webwallet server @param {Object} body - A wallet address registration statement @param {Object} options - Request parameters such as method and headers @return {Promise} - Resolves to the response body
[ "Sends", "a", "wallet", "address", "registration", "request", "to", "the", "supplied", "URL" ]
594081202f39dd648c33e6ddaa5da0590826a62f
https://github.com/webwallet/sdk-node/blob/594081202f39dd648c33e6ddaa5da0590826a62f/sdk.js#L86-L102
54,921
webwallet/sdk-node
sdk.js
checkAddressBalance
function checkAddressBalance(url, address, options) { options = options || {}; let path = '/address/.../balance'.replace('...', address); url = resolveURL(url, path); return new P(function (resolve, reject) { request({ url: url, method: 'GET', headers: options.headers }, function (err, res, body) { if (err) return reject(err); return resolve(body); }); }); }
javascript
function checkAddressBalance(url, address, options) { options = options || {}; let path = '/address/.../balance'.replace('...', address); url = resolveURL(url, path); return new P(function (resolve, reject) { request({ url: url, method: 'GET', headers: options.headers }, function (err, res, body) { if (err) return reject(err); return resolve(body); }); }); }
[ "function", "checkAddressBalance", "(", "url", ",", "address", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "let", "path", "=", "'/address/.../balance'", ".", "replace", "(", "'...'", ",", "address", ")", ";", "url", "=", "resolveURL", "(", "url", ",", "path", ")", ";", "return", "new", "P", "(", "function", "(", "resolve", ",", "reject", ")", "{", "request", "(", "{", "url", ":", "url", ",", "method", ":", "'GET'", ",", "headers", ":", "options", ".", "headers", "}", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "return", "resolve", "(", "body", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Checks the balance of a wallet address @param {string} url - The URL of a webwallet server @param {string} address - A wallet address @param {Object} options - Request parameters such as headers @return {Promise} - Resolves to the response body
[ "Checks", "the", "balance", "of", "a", "wallet", "address" ]
594081202f39dd648c33e6ddaa5da0590826a62f
https://github.com/webwallet/sdk-node/blob/594081202f39dd648c33e6ddaa5da0590826a62f/sdk.js#L158-L173
54,922
webwallet/sdk-node
sdk.js
generateKeyPair
function generateKeyPair(scheme) { let keypair; let keys; switch (scheme) { case 'ed25519': case 'secp256k1': keypair = schemes[scheme].genKeyPair(); keys = { scheme: scheme, private: keypair.getPrivate('hex'), public: keypair.getPublic('hex') }; break; default: throw new Error('invalid-scheme'); break; } return keys; }
javascript
function generateKeyPair(scheme) { let keypair; let keys; switch (scheme) { case 'ed25519': case 'secp256k1': keypair = schemes[scheme].genKeyPair(); keys = { scheme: scheme, private: keypair.getPrivate('hex'), public: keypair.getPublic('hex') }; break; default: throw new Error('invalid-scheme'); break; } return keys; }
[ "function", "generateKeyPair", "(", "scheme", ")", "{", "let", "keypair", ";", "let", "keys", ";", "switch", "(", "scheme", ")", "{", "case", "'ed25519'", ":", "case", "'secp256k1'", ":", "keypair", "=", "schemes", "[", "scheme", "]", ".", "genKeyPair", "(", ")", ";", "keys", "=", "{", "scheme", ":", "scheme", ",", "private", ":", "keypair", ".", "getPrivate", "(", "'hex'", ")", ",", "public", ":", "keypair", ".", "getPublic", "(", "'hex'", ")", "}", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'invalid-scheme'", ")", ";", "break", ";", "}", "return", "keys", ";", "}" ]
Generates a pair of cryptographic keys @param {string} scheme - A cryptographic scheme @return {Object} keys - A cryptographic key pair
[ "Generates", "a", "pair", "of", "cryptographic", "keys" ]
594081202f39dd648c33e6ddaa5da0590826a62f
https://github.com/webwallet/sdk-node/blob/594081202f39dd648c33e6ddaa5da0590826a62f/sdk.js#L187-L207
54,923
webwallet/sdk-node
sdk.js
deriveWalletAddress
function deriveWalletAddress(publicKey, type) { let keyBuffer = new Buffer(publicKey, 'hex'); let firstHash = crypto.createHash('sha256').update(keyBuffer).digest(); let secondHash = ripemd160(firstHash); let extendedHash = (type === 'issuer' ? '57' : '87') + secondHash.toString('hex'); let base58Public = bs58check.encode(new Buffer(extendedHash, 'hex')); return base58Public; }
javascript
function deriveWalletAddress(publicKey, type) { let keyBuffer = new Buffer(publicKey, 'hex'); let firstHash = crypto.createHash('sha256').update(keyBuffer).digest(); let secondHash = ripemd160(firstHash); let extendedHash = (type === 'issuer' ? '57' : '87') + secondHash.toString('hex'); let base58Public = bs58check.encode(new Buffer(extendedHash, 'hex')); return base58Public; }
[ "function", "deriveWalletAddress", "(", "publicKey", ",", "type", ")", "{", "let", "keyBuffer", "=", "new", "Buffer", "(", "publicKey", ",", "'hex'", ")", ";", "let", "firstHash", "=", "crypto", ".", "createHash", "(", "'sha256'", ")", ".", "update", "(", "keyBuffer", ")", ".", "digest", "(", ")", ";", "let", "secondHash", "=", "ripemd160", "(", "firstHash", ")", ";", "let", "extendedHash", "=", "(", "type", "===", "'issuer'", "?", "'57'", ":", "'87'", ")", "+", "secondHash", ".", "toString", "(", "'hex'", ")", ";", "let", "base58Public", "=", "bs58check", ".", "encode", "(", "new", "Buffer", "(", "extendedHash", ",", "'hex'", ")", ")", ";", "return", "base58Public", ";", "}" ]
Derives a wallet address from a public key @param {<type>} publicKey - A public key to derive the address from @param {string} type - The type of wallet address to derive @return {string} base58public - A base58check encoded wallet address
[ "Derives", "a", "wallet", "address", "from", "a", "public", "key" ]
594081202f39dd648c33e6ddaa5da0590826a62f
https://github.com/webwallet/sdk-node/blob/594081202f39dd648c33e6ddaa5da0590826a62f/sdk.js#L214-L222
54,924
webwallet/sdk-node
sdk.js
createAddressRegistrationStatement
function createAddressRegistrationStatement(address, keys, options) { options = options || {}; /* Create an extended JSON Web Signatures object */ let jws = { hash: { type: (hashes.indexOf(options.hash) > -1) ? options.hash : 'sha256', value: '' }, payload: { address: address, keys: [ keys.public ], threshold: 1 }, signatures: [ { header: { alg: keys.scheme, kid: '0' }, signature: '' } ] }; /* Generate a cryptogrphic hash of the payload */ jws.hash.value = crypto.createHash(jws.hash.type) .update(JSON.stringify(jws.payload)).digest('hex'); /* Sign the hash of the payload */ jws.signatures[0].signature = schemes[keys.scheme] .sign(jws.hash.value, keys.private, 'hex').toDER('hex'); return jws; }
javascript
function createAddressRegistrationStatement(address, keys, options) { options = options || {}; /* Create an extended JSON Web Signatures object */ let jws = { hash: { type: (hashes.indexOf(options.hash) > -1) ? options.hash : 'sha256', value: '' }, payload: { address: address, keys: [ keys.public ], threshold: 1 }, signatures: [ { header: { alg: keys.scheme, kid: '0' }, signature: '' } ] }; /* Generate a cryptogrphic hash of the payload */ jws.hash.value = crypto.createHash(jws.hash.type) .update(JSON.stringify(jws.payload)).digest('hex'); /* Sign the hash of the payload */ jws.signatures[0].signature = schemes[keys.scheme] .sign(jws.hash.value, keys.private, 'hex').toDER('hex'); return jws; }
[ "function", "createAddressRegistrationStatement", "(", "address", ",", "keys", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "/* Create an extended JSON Web Signatures object */", "let", "jws", "=", "{", "hash", ":", "{", "type", ":", "(", "hashes", ".", "indexOf", "(", "options", ".", "hash", ")", ">", "-", "1", ")", "?", "options", ".", "hash", ":", "'sha256'", ",", "value", ":", "''", "}", ",", "payload", ":", "{", "address", ":", "address", ",", "keys", ":", "[", "keys", ".", "public", "]", ",", "threshold", ":", "1", "}", ",", "signatures", ":", "[", "{", "header", ":", "{", "alg", ":", "keys", ".", "scheme", ",", "kid", ":", "'0'", "}", ",", "signature", ":", "''", "}", "]", "}", ";", "/* Generate a cryptogrphic hash of the payload */", "jws", ".", "hash", ".", "value", "=", "crypto", ".", "createHash", "(", "jws", ".", "hash", ".", "type", ")", ".", "update", "(", "JSON", ".", "stringify", "(", "jws", ".", "payload", ")", ")", ".", "digest", "(", "'hex'", ")", ";", "/* Sign the hash of the payload */", "jws", ".", "signatures", "[", "0", "]", ".", "signature", "=", "schemes", "[", "keys", ".", "scheme", "]", ".", "sign", "(", "jws", ".", "hash", ".", "value", ",", "keys", ".", "private", ",", "'hex'", ")", ".", "toDER", "(", "'hex'", ")", ";", "return", "jws", ";", "}" ]
Creates and signs a statement to be sent for registering an address @param {string} address - A wallet address @param {Object} keys - An object containing a cryptograhic key pair @param {Object} options - Parameters such as hash type @return {Object} - A cryptographically signed statement
[ "Creates", "and", "signs", "a", "statement", "to", "be", "sent", "for", "registering", "an", "address" ]
594081202f39dd648c33e6ddaa5da0590826a62f
https://github.com/webwallet/sdk-node/blob/594081202f39dd648c33e6ddaa5da0590826a62f/sdk.js#L230-L266
54,925
webwallet/sdk-node
sdk.js
resolveURL
function resolveURL(url, path) { if (typeof url !== 'string' || typeof path !== 'string') { return new Error('url-and-path-required'); } /* Remove leading and duplicate slashes */ url = url.replace(/\/{2,}/g, '/').replace(/^\//, '').replace(':/','://'); let parsedUrl = urlModule.parse(url); if (protocols.indexOf(parsedUrl.protocol) < 0 || !parsedUrl.host) { return new Error('invalid-url'); } let resolvedUrl = urlModule.resolve(parsedUrl.href, path); return resolvedUrl; }
javascript
function resolveURL(url, path) { if (typeof url !== 'string' || typeof path !== 'string') { return new Error('url-and-path-required'); } /* Remove leading and duplicate slashes */ url = url.replace(/\/{2,}/g, '/').replace(/^\//, '').replace(':/','://'); let parsedUrl = urlModule.parse(url); if (protocols.indexOf(parsedUrl.protocol) < 0 || !parsedUrl.host) { return new Error('invalid-url'); } let resolvedUrl = urlModule.resolve(parsedUrl.href, path); return resolvedUrl; }
[ "function", "resolveURL", "(", "url", ",", "path", ")", "{", "if", "(", "typeof", "url", "!==", "'string'", "||", "typeof", "path", "!==", "'string'", ")", "{", "return", "new", "Error", "(", "'url-and-path-required'", ")", ";", "}", "/* Remove leading and duplicate slashes */", "url", "=", "url", ".", "replace", "(", "/", "\\/{2,}", "/", "g", ",", "'/'", ")", ".", "replace", "(", "/", "^\\/", "/", ",", "''", ")", ".", "replace", "(", "':/'", ",", "'://'", ")", ";", "let", "parsedUrl", "=", "urlModule", ".", "parse", "(", "url", ")", ";", "if", "(", "protocols", ".", "indexOf", "(", "parsedUrl", ".", "protocol", ")", "<", "0", "||", "!", "parsedUrl", ".", "host", ")", "{", "return", "new", "Error", "(", "'invalid-url'", ")", ";", "}", "let", "resolvedUrl", "=", "urlModule", ".", "resolve", "(", "parsedUrl", ".", "href", ",", "path", ")", ";", "return", "resolvedUrl", ";", "}" ]
Resolves a URL given a path @param {string} url - URL to resolve @param {string} path - Path to append to base URL @return {string} resolvedUrl - A valid URL
[ "Resolves", "a", "URL", "given", "a", "path" ]
594081202f39dd648c33e6ddaa5da0590826a62f
https://github.com/webwallet/sdk-node/blob/594081202f39dd648c33e6ddaa5da0590826a62f/sdk.js#L312-L327
54,926
fhellwig/pkgconfig
pkgconfig.js
merge
function merge(target, source) { if (source === null) { return target } var props = Object.getOwnPropertyNames(target) props.forEach(function (name) { var s = gettype(source[name]) if (s !== 'undefined') { var t = gettype(target[name]) if (t !== s) { throw new Error(`Type mismatch between '${t}' and '${s}' for '${name}'`) } if (t === 'object') { merge(target[name], source[name]) } else { target[name] = source[name] } } }) return target }
javascript
function merge(target, source) { if (source === null) { return target } var props = Object.getOwnPropertyNames(target) props.forEach(function (name) { var s = gettype(source[name]) if (s !== 'undefined') { var t = gettype(target[name]) if (t !== s) { throw new Error(`Type mismatch between '${t}' and '${s}' for '${name}'`) } if (t === 'object') { merge(target[name], source[name]) } else { target[name] = source[name] } } }) return target }
[ "function", "merge", "(", "target", ",", "source", ")", "{", "if", "(", "source", "===", "null", ")", "{", "return", "target", "}", "var", "props", "=", "Object", ".", "getOwnPropertyNames", "(", "target", ")", "props", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "s", "=", "gettype", "(", "source", "[", "name", "]", ")", "if", "(", "s", "!==", "'undefined'", ")", "{", "var", "t", "=", "gettype", "(", "target", "[", "name", "]", ")", "if", "(", "t", "!==", "s", ")", "{", "throw", "new", "Error", "(", "`", "${", "t", "}", "${", "s", "}", "${", "name", "}", "`", ")", "}", "if", "(", "t", "===", "'object'", ")", "{", "merge", "(", "target", "[", "name", "]", ",", "source", "[", "name", "]", ")", "}", "else", "{", "target", "[", "name", "]", "=", "source", "[", "name", "]", "}", "}", "}", ")", "return", "target", "}" ]
Merges the source with the target. The target is modified and returned.
[ "Merges", "the", "source", "with", "the", "target", ".", "The", "target", "is", "modified", "and", "returned", "." ]
f085bae69877d5a1607088ca71018ecf2839e02d
https://github.com/fhellwig/pkgconfig/blob/f085bae69877d5a1607088ca71018ecf2839e02d/pkgconfig.js#L96-L116
54,927
NexwayGroup/grunt-sass-bootstrapper
tasks/sass_bootstrapper.js
findIndexInArray
function findIndexInArray(array, callback) { var _length = array.length; for (var i = 0; i < _length; i++) { if (callback(array[i])) return i; } return -1; }
javascript
function findIndexInArray(array, callback) { var _length = array.length; for (var i = 0; i < _length; i++) { if (callback(array[i])) return i; } return -1; }
[ "function", "findIndexInArray", "(", "array", ",", "callback", ")", "{", "var", "_length", "=", "array", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "_length", ";", "i", "++", ")", "{", "if", "(", "callback", "(", "array", "[", "i", "]", ")", ")", "return", "i", ";", "}", "return", "-", "1", ";", "}" ]
Find position of an array element when callback function return true. @param array {array} Array to seek @param callback {function} Callback function to test element @returns {number} Index of eleement or -1 if not found
[ "Find", "position", "of", "an", "array", "element", "when", "callback", "function", "return", "true", "." ]
4f152dd7e796e0f289f7085fed28d9e61e8dec47
https://github.com/NexwayGroup/grunt-sass-bootstrapper/blob/4f152dd7e796e0f289f7085fed28d9e61e8dec47/tasks/sass_bootstrapper.js#L95-L101
54,928
NexwayGroup/grunt-sass-bootstrapper
tasks/sass_bootstrapper.js
replaceInArray
function replaceInArray(array, indexToReplace, indexToInsert) { var _removedArray = array.splice(indexToReplace, 1); array.splice(indexToInsert, 0, _removedArray[0]); return array; }
javascript
function replaceInArray(array, indexToReplace, indexToInsert) { var _removedArray = array.splice(indexToReplace, 1); array.splice(indexToInsert, 0, _removedArray[0]); return array; }
[ "function", "replaceInArray", "(", "array", ",", "indexToReplace", ",", "indexToInsert", ")", "{", "var", "_removedArray", "=", "array", ".", "splice", "(", "indexToReplace", ",", "1", ")", ";", "array", ".", "splice", "(", "indexToInsert", ",", "0", ",", "_removedArray", "[", "0", "]", ")", ";", "return", "array", ";", "}" ]
Remove item by its index and place it to another position @param indexToReplace {number} current item position @param indexToInsert {number} index where item should be placed
[ "Remove", "item", "by", "its", "index", "and", "place", "it", "to", "another", "position" ]
4f152dd7e796e0f289f7085fed28d9e61e8dec47
https://github.com/NexwayGroup/grunt-sass-bootstrapper/blob/4f152dd7e796e0f289f7085fed28d9e61e8dec47/tasks/sass_bootstrapper.js#L109-L113
54,929
NexwayGroup/grunt-sass-bootstrapper
tasks/sass_bootstrapper.js
getArrayOfPartials
function getArrayOfPartials() { var _partialsArr = []; for (var file in mainPartialList) { if (mainPartialList.hasOwnProperty(file)) { _partialsArr.push(file); } } return _partialsArr; }
javascript
function getArrayOfPartials() { var _partialsArr = []; for (var file in mainPartialList) { if (mainPartialList.hasOwnProperty(file)) { _partialsArr.push(file); } } return _partialsArr; }
[ "function", "getArrayOfPartials", "(", ")", "{", "var", "_partialsArr", "=", "[", "]", ";", "for", "(", "var", "file", "in", "mainPartialList", ")", "{", "if", "(", "mainPartialList", ".", "hasOwnProperty", "(", "file", ")", ")", "{", "_partialsArr", ".", "push", "(", "file", ")", ";", "}", "}", "return", "_partialsArr", ";", "}" ]
Get array of partial names from mainPartialList @returns {Array} Array of partials
[ "Get", "array", "of", "partial", "names", "from", "mainPartialList" ]
4f152dd7e796e0f289f7085fed28d9e61e8dec47
https://github.com/NexwayGroup/grunt-sass-bootstrapper/blob/4f152dd7e796e0f289f7085fed28d9e61e8dec47/tasks/sass_bootstrapper.js#L138-L146
54,930
NexwayGroup/grunt-sass-bootstrapper
tasks/sass_bootstrapper.js
parseFile
function parseFile(importKeyword, requiresKeyword, filePath) { var _lines = grunt.file.read(filePath).split(NEW_LINE), _values = { imports: {}, requires: {} }; // Search for keywords in file for (var i = _lines.length - 1; i >= 0; i--) { var line = _lines[i]; if (line.indexOf(importKeyword) !== -1) { // get import value var _importValue = line.match(/("|')(.*?)("|')/)[2]; // Create full path to help looking for file and minimalize // errors if there are duplicated filenames _importValue = Path.join(Path.dirname(filePath), _importValue.sassToPath()); // Windows support. Replace backslashes into slashes. _importValue = _importValue.replace(/\\/g, "/"); // Append new import value to list _values.imports['import' + i] = _importValue; } if (line.indexOf(requiresKeyword) !== -1) { // get require value var _requireValue = line.match(/("|')(.*?)("|')/)[2]; // Create new dependency object var _requireObject = { requires: _requireValue.sassToPath(), fileName: filePath }; // Append new require value to list _values.requires['require' + i] = _requireObject; } } return _values; }
javascript
function parseFile(importKeyword, requiresKeyword, filePath) { var _lines = grunt.file.read(filePath).split(NEW_LINE), _values = { imports: {}, requires: {} }; // Search for keywords in file for (var i = _lines.length - 1; i >= 0; i--) { var line = _lines[i]; if (line.indexOf(importKeyword) !== -1) { // get import value var _importValue = line.match(/("|')(.*?)("|')/)[2]; // Create full path to help looking for file and minimalize // errors if there are duplicated filenames _importValue = Path.join(Path.dirname(filePath), _importValue.sassToPath()); // Windows support. Replace backslashes into slashes. _importValue = _importValue.replace(/\\/g, "/"); // Append new import value to list _values.imports['import' + i] = _importValue; } if (line.indexOf(requiresKeyword) !== -1) { // get require value var _requireValue = line.match(/("|')(.*?)("|')/)[2]; // Create new dependency object var _requireObject = { requires: _requireValue.sassToPath(), fileName: filePath }; // Append new require value to list _values.requires['require' + i] = _requireObject; } } return _values; }
[ "function", "parseFile", "(", "importKeyword", ",", "requiresKeyword", ",", "filePath", ")", "{", "var", "_lines", "=", "grunt", ".", "file", ".", "read", "(", "filePath", ")", ".", "split", "(", "NEW_LINE", ")", ",", "_values", "=", "{", "imports", ":", "{", "}", ",", "requires", ":", "{", "}", "}", ";", "// Search for keywords in file", "for", "(", "var", "i", "=", "_lines", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "line", "=", "_lines", "[", "i", "]", ";", "if", "(", "line", ".", "indexOf", "(", "importKeyword", ")", "!==", "-", "1", ")", "{", "// get import value", "var", "_importValue", "=", "line", ".", "match", "(", "/", "(\"|')(.*?)(\"|')", "/", ")", "[", "2", "]", ";", "// Create full path to help looking for file and minimalize", "// errors if there are duplicated filenames", "_importValue", "=", "Path", ".", "join", "(", "Path", ".", "dirname", "(", "filePath", ")", ",", "_importValue", ".", "sassToPath", "(", ")", ")", ";", "// Windows support. Replace backslashes into slashes.", "_importValue", "=", "_importValue", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "\"/\"", ")", ";", "// Append new import value to list", "_values", ".", "imports", "[", "'import'", "+", "i", "]", "=", "_importValue", ";", "}", "if", "(", "line", ".", "indexOf", "(", "requiresKeyword", ")", "!==", "-", "1", ")", "{", "// get require value", "var", "_requireValue", "=", "line", ".", "match", "(", "/", "(\"|')(.*?)(\"|')", "/", ")", "[", "2", "]", ";", "// Create new dependency object", "var", "_requireObject", "=", "{", "requires", ":", "_requireValue", ".", "sassToPath", "(", ")", ",", "fileName", ":", "filePath", "}", ";", "// Append new require value to list", "_values", ".", "requires", "[", "'require'", "+", "i", "]", "=", "_requireObject", ";", "}", "}", "return", "_values", ";", "}" ]
Parses the given file for import keywords and DI keywords @param importKeyword {string} sass import keyword @param requiresKeyword {string} dependency injection keyword @param filePath {string} file to be parsed @returns {Object} list of all founded import values
[ "Parses", "the", "given", "file", "for", "import", "keywords", "and", "DI", "keywords" ]
4f152dd7e796e0f289f7085fed28d9e61e8dec47
https://github.com/NexwayGroup/grunt-sass-bootstrapper/blob/4f152dd7e796e0f289f7085fed28d9e61e8dec47/tasks/sass_bootstrapper.js#L156-L194
54,931
NexwayGroup/grunt-sass-bootstrapper
tasks/sass_bootstrapper.js
orderByDependency
function orderByDependency(partialsArray) { var _doPass = true, _reqCache = {}; // repeat sorting operation until // there is no replacing procedure during // one pass (bubble sorting). while (_doPass) { _doPass = false; // Iterate through every partial in the list and check its // dependency (requirements) partialsArray.forEach(function (partialName, partialIndex) { // Get require list for current partial var _requireList = mainPartialList[partialName].requires; // for each requirement in require object do... for (var rKey in _requireList) { // Check if current key is _requireList property if (!_requireList.hasOwnProperty(rKey)) { // if not go to next iteration continue; } // Current partial filename without root folder var _fileName = mainPartialList[partialName].removedRoot, // Index of current partial in partialsArray, -1 if not found. _requireIndex = findIndexInArray(partialsArray, function (partialName) { return (partialName.match(_requireList[rKey].requires) !== null); }), _requireObject = _requireList[rKey]; // Check require cache for dependency loop if (_reqCache[_requireObject.requires + _fileName]) { // dependency loop detected, throw an error and break program grunt.fail.fatal( 'Dependency loop detected!!! \nFiles that have dependency loop: \n' + mainPartialList[partialsArray[_requireIndex]].fileName + '\n' + _requireObject.fileName ); } // If requirement is found and its position is incorrect if (_requireIndex > -1 && _requireIndex > partialIndex) { // Remove partial from current index and insert // it before partial that requires it. partialsArray = replaceInArray(partialsArray, _requireIndex, partialIndex); // Replacing procedure occured so do one more pass. _doPass = true; // add requirement to require cache for dependency loop handling _reqCache[_fileName + _requireObject.requires] = true; } else if (_requireIndex === -1) { // invalid requirement, throw a warning grunt.log.warn( 'File: ' + mainPartialList[partialName].fileName + ' is depending on non existing partial "' + _requireObject.requires + '"' ); } } // end for }); // end for each } // end while // Return reordered file list return partialsArray; }
javascript
function orderByDependency(partialsArray) { var _doPass = true, _reqCache = {}; // repeat sorting operation until // there is no replacing procedure during // one pass (bubble sorting). while (_doPass) { _doPass = false; // Iterate through every partial in the list and check its // dependency (requirements) partialsArray.forEach(function (partialName, partialIndex) { // Get require list for current partial var _requireList = mainPartialList[partialName].requires; // for each requirement in require object do... for (var rKey in _requireList) { // Check if current key is _requireList property if (!_requireList.hasOwnProperty(rKey)) { // if not go to next iteration continue; } // Current partial filename without root folder var _fileName = mainPartialList[partialName].removedRoot, // Index of current partial in partialsArray, -1 if not found. _requireIndex = findIndexInArray(partialsArray, function (partialName) { return (partialName.match(_requireList[rKey].requires) !== null); }), _requireObject = _requireList[rKey]; // Check require cache for dependency loop if (_reqCache[_requireObject.requires + _fileName]) { // dependency loop detected, throw an error and break program grunt.fail.fatal( 'Dependency loop detected!!! \nFiles that have dependency loop: \n' + mainPartialList[partialsArray[_requireIndex]].fileName + '\n' + _requireObject.fileName ); } // If requirement is found and its position is incorrect if (_requireIndex > -1 && _requireIndex > partialIndex) { // Remove partial from current index and insert // it before partial that requires it. partialsArray = replaceInArray(partialsArray, _requireIndex, partialIndex); // Replacing procedure occured so do one more pass. _doPass = true; // add requirement to require cache for dependency loop handling _reqCache[_fileName + _requireObject.requires] = true; } else if (_requireIndex === -1) { // invalid requirement, throw a warning grunt.log.warn( 'File: ' + mainPartialList[partialName].fileName + ' is depending on non existing partial "' + _requireObject.requires + '"' ); } } // end for }); // end for each } // end while // Return reordered file list return partialsArray; }
[ "function", "orderByDependency", "(", "partialsArray", ")", "{", "var", "_doPass", "=", "true", ",", "_reqCache", "=", "{", "}", ";", "// repeat sorting operation until", "// there is no replacing procedure during", "// one pass (bubble sorting).", "while", "(", "_doPass", ")", "{", "_doPass", "=", "false", ";", "// Iterate through every partial in the list and check its", "// dependency (requirements)", "partialsArray", ".", "forEach", "(", "function", "(", "partialName", ",", "partialIndex", ")", "{", "// Get require list for current partial", "var", "_requireList", "=", "mainPartialList", "[", "partialName", "]", ".", "requires", ";", "// for each requirement in require object do...", "for", "(", "var", "rKey", "in", "_requireList", ")", "{", "// Check if current key is _requireList property", "if", "(", "!", "_requireList", ".", "hasOwnProperty", "(", "rKey", ")", ")", "{", "// if not go to next iteration", "continue", ";", "}", "// Current partial filename without root folder", "var", "_fileName", "=", "mainPartialList", "[", "partialName", "]", ".", "removedRoot", ",", "// Index of current partial in partialsArray, -1 if not found.", "_requireIndex", "=", "findIndexInArray", "(", "partialsArray", ",", "function", "(", "partialName", ")", "{", "return", "(", "partialName", ".", "match", "(", "_requireList", "[", "rKey", "]", ".", "requires", ")", "!==", "null", ")", ";", "}", ")", ",", "_requireObject", "=", "_requireList", "[", "rKey", "]", ";", "// Check require cache for dependency loop", "if", "(", "_reqCache", "[", "_requireObject", ".", "requires", "+", "_fileName", "]", ")", "{", "// dependency loop detected, throw an error and break program", "grunt", ".", "fail", ".", "fatal", "(", "'Dependency loop detected!!! \\nFiles that have dependency loop: \\n'", "+", "mainPartialList", "[", "partialsArray", "[", "_requireIndex", "]", "]", ".", "fileName", "+", "'\\n'", "+", "_requireObject", ".", "fileName", ")", ";", "}", "// If requirement is found and its position is incorrect", "if", "(", "_requireIndex", ">", "-", "1", "&&", "_requireIndex", ">", "partialIndex", ")", "{", "// Remove partial from current index and insert", "// it before partial that requires it.", "partialsArray", "=", "replaceInArray", "(", "partialsArray", ",", "_requireIndex", ",", "partialIndex", ")", ";", "// Replacing procedure occured so do one more pass.", "_doPass", "=", "true", ";", "// add requirement to require cache for dependency loop handling", "_reqCache", "[", "_fileName", "+", "_requireObject", ".", "requires", "]", "=", "true", ";", "}", "else", "if", "(", "_requireIndex", "===", "-", "1", ")", "{", "// invalid requirement, throw a warning", "grunt", ".", "log", ".", "warn", "(", "'File: '", "+", "mainPartialList", "[", "partialName", "]", ".", "fileName", "+", "' is depending on non existing partial \"'", "+", "_requireObject", ".", "requires", "+", "'\"'", ")", ";", "}", "}", "// end for", "}", ")", ";", "// end for each", "}", "// end while", "// Return reordered file list", "return", "partialsArray", ";", "}" ]
Reorders partials in a given list by their dependencies. Dependencies are taken from mainPartialList which has to be generated first. @param partialsArray {array} array of sass/scss partials @returns {array} reordered array of partials
[ "Reorders", "partials", "in", "a", "given", "list", "by", "their", "dependencies", ".", "Dependencies", "are", "taken", "from", "mainPartialList", "which", "has", "to", "be", "generated", "first", "." ]
4f152dd7e796e0f289f7085fed28d9e61e8dec47
https://github.com/NexwayGroup/grunt-sass-bootstrapper/blob/4f152dd7e796e0f289f7085fed28d9e61e8dec47/tasks/sass_bootstrapper.js#L204-L271
54,932
NexwayGroup/grunt-sass-bootstrapper
tasks/sass_bootstrapper.js
generateBootstrapContent
function generateBootstrapContent(partialsArray, lineDelimiter) { var _bootstrapContent = '', _folderGroup = ''; partialsArray.forEach(function (partialName) { var _sassPath = mainPartialList[partialName].removedRoot, _currentRoot = _sassPath.parseRootFolder(); if (options.useRelativePaths) { // if useRelativePaths option is set to true the result file will use paths relative to bootstrap file // in this case filterRootPaths option is not used _sassPath = Path.relative(Path.dirname(options.bootstrapFile), mainPartialList[partialName].fileName.toSassFormat()); // remove file extension _sassPath = _sassPath.replace(Path.extname(_sassPath), ''); // Windows support. Replace backslashes into slashes. _sassPath = _sassPath.replace(/\\/g, "/"); } else { _sassPath = _sassPath.toSassFormat(); } // if current root folder has changed, write new root folder // as a comment and set new current folder if (_folderGroup != _currentRoot) { _bootstrapContent += NEW_LINE + '// ' + _currentRoot + NEW_LINE; _folderGroup = _currentRoot; } // append import line _bootstrapContent += options.importKeyword + ' "' + _sassPath + '"' + lineDelimiter + NEW_LINE; }); return _bootstrapContent; }
javascript
function generateBootstrapContent(partialsArray, lineDelimiter) { var _bootstrapContent = '', _folderGroup = ''; partialsArray.forEach(function (partialName) { var _sassPath = mainPartialList[partialName].removedRoot, _currentRoot = _sassPath.parseRootFolder(); if (options.useRelativePaths) { // if useRelativePaths option is set to true the result file will use paths relative to bootstrap file // in this case filterRootPaths option is not used _sassPath = Path.relative(Path.dirname(options.bootstrapFile), mainPartialList[partialName].fileName.toSassFormat()); // remove file extension _sassPath = _sassPath.replace(Path.extname(_sassPath), ''); // Windows support. Replace backslashes into slashes. _sassPath = _sassPath.replace(/\\/g, "/"); } else { _sassPath = _sassPath.toSassFormat(); } // if current root folder has changed, write new root folder // as a comment and set new current folder if (_folderGroup != _currentRoot) { _bootstrapContent += NEW_LINE + '// ' + _currentRoot + NEW_LINE; _folderGroup = _currentRoot; } // append import line _bootstrapContent += options.importKeyword + ' "' + _sassPath + '"' + lineDelimiter + NEW_LINE; }); return _bootstrapContent; }
[ "function", "generateBootstrapContent", "(", "partialsArray", ",", "lineDelimiter", ")", "{", "var", "_bootstrapContent", "=", "''", ",", "_folderGroup", "=", "''", ";", "partialsArray", ".", "forEach", "(", "function", "(", "partialName", ")", "{", "var", "_sassPath", "=", "mainPartialList", "[", "partialName", "]", ".", "removedRoot", ",", "_currentRoot", "=", "_sassPath", ".", "parseRootFolder", "(", ")", ";", "if", "(", "options", ".", "useRelativePaths", ")", "{", "// if useRelativePaths option is set to true the result file will use paths relative to bootstrap file", "// in this case filterRootPaths option is not used", "_sassPath", "=", "Path", ".", "relative", "(", "Path", ".", "dirname", "(", "options", ".", "bootstrapFile", ")", ",", "mainPartialList", "[", "partialName", "]", ".", "fileName", ".", "toSassFormat", "(", ")", ")", ";", "// remove file extension", "_sassPath", "=", "_sassPath", ".", "replace", "(", "Path", ".", "extname", "(", "_sassPath", ")", ",", "''", ")", ";", "// Windows support. Replace backslashes into slashes.", "_sassPath", "=", "_sassPath", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "\"/\"", ")", ";", "}", "else", "{", "_sassPath", "=", "_sassPath", ".", "toSassFormat", "(", ")", ";", "}", "// if current root folder has changed, write new root folder", "// as a comment and set new current folder", "if", "(", "_folderGroup", "!=", "_currentRoot", ")", "{", "_bootstrapContent", "+=", "NEW_LINE", "+", "'// '", "+", "_currentRoot", "+", "NEW_LINE", ";", "_folderGroup", "=", "_currentRoot", ";", "}", "// append import line", "_bootstrapContent", "+=", "options", ".", "importKeyword", "+", "' \"'", "+", "_sassPath", "+", "'\"'", "+", "lineDelimiter", "+", "NEW_LINE", ";", "}", ")", ";", "return", "_bootstrapContent", ";", "}" ]
Generate content for bootstrap file @param partialsArray {array} list of partials to import by bootstrap file @param lineDelimiter {string} symbol at the end of the line @returns {string} formatted file content
[ "Generate", "content", "for", "bootstrap", "file" ]
4f152dd7e796e0f289f7085fed28d9e61e8dec47
https://github.com/NexwayGroup/grunt-sass-bootstrapper/blob/4f152dd7e796e0f289f7085fed28d9e61e8dec47/tasks/sass_bootstrapper.js#L280-L312
54,933
mnichols/ankh
lib/startable-model.js
StartableModel
function StartableModel(model,instance) { if(!model) { throw new Error('model is required') } if(!instance) { throw new Error('instance is required') } if(!(this instanceof StartableModel)) { return new StartableModel(model,instance,index) } this.model = model this.key = model.key this.instance= instance this.fn = instance[model.startable] if(!this.fn) { throw new Error('The instance of ' + this.key + ' does not have a method ' + model.startable + ' which is required for starting this service.') } this.inject = (this.fn.inject || []) this.hasDeps = (this.inject.length > 0) }
javascript
function StartableModel(model,instance) { if(!model) { throw new Error('model is required') } if(!instance) { throw new Error('instance is required') } if(!(this instanceof StartableModel)) { return new StartableModel(model,instance,index) } this.model = model this.key = model.key this.instance= instance this.fn = instance[model.startable] if(!this.fn) { throw new Error('The instance of ' + this.key + ' does not have a method ' + model.startable + ' which is required for starting this service.') } this.inject = (this.fn.inject || []) this.hasDeps = (this.inject.length > 0) }
[ "function", "StartableModel", "(", "model", ",", "instance", ")", "{", "if", "(", "!", "model", ")", "{", "throw", "new", "Error", "(", "'model is required'", ")", "}", "if", "(", "!", "instance", ")", "{", "throw", "new", "Error", "(", "'instance is required'", ")", "}", "if", "(", "!", "(", "this", "instanceof", "StartableModel", ")", ")", "{", "return", "new", "StartableModel", "(", "model", ",", "instance", ",", "index", ")", "}", "this", ".", "model", "=", "model", "this", ".", "key", "=", "model", ".", "key", "this", ".", "instance", "=", "instance", "this", ".", "fn", "=", "instance", "[", "model", ".", "startable", "]", "if", "(", "!", "this", ".", "fn", ")", "{", "throw", "new", "Error", "(", "'The instance of '", "+", "this", ".", "key", "+", "' does not have a method '", "+", "model", ".", "startable", "+", "' which is required for starting this service.'", ")", "}", "this", ".", "inject", "=", "(", "this", ".", "fn", ".", "inject", "||", "[", "]", ")", "this", ".", "hasDeps", "=", "(", "this", ".", "inject", ".", "length", ">", "0", ")", "}" ]
Encapsulate a startable function description @class StartableModel
[ "Encapsulate", "a", "startable", "function", "description" ]
b5f6eae24b2dece4025b4f11cea7f1560d3b345f
https://github.com/mnichols/ankh/blob/b5f6eae24b2dece4025b4f11cea7f1560d3b345f/lib/startable-model.js#L9-L32
54,934
Zingle/fail
fail.js
fail
function fail(err, status=1) { console.log(process.env.DEBUG ? err.stack : err.message); process.exit(status); }
javascript
function fail(err, status=1) { console.log(process.env.DEBUG ? err.stack : err.message); process.exit(status); }
[ "function", "fail", "(", "err", ",", "status", "=", "1", ")", "{", "console", ".", "log", "(", "process", ".", "env", ".", "DEBUG", "?", "err", ".", "stack", ":", "err", ".", "message", ")", ";", "process", ".", "exit", "(", "status", ")", ";", "}" ]
Print error and exit. @param {Error} err @param {number} [status]
[ "Print", "error", "and", "exit", "." ]
41bc523da28d222dbcf6be996f5d42b1023a3822
https://github.com/Zingle/fail/blob/41bc523da28d222dbcf6be996f5d42b1023a3822/fail.js#L6-L9
54,935
relief-melone/limitpromises
src/limitpromises.js
autoSpliceLaunchArray
function autoSpliceLaunchArray(LaunchArray, TypeKey){ var indFirstElement = currentPromiseArrays[TypeKey].indexOf(LaunchArray[0]); var indLastElement = currentPromiseArrays[TypeKey].indexOf(LaunchArray[LaunchArray.length-1]); Promise.all(LaunchArray.map(e => {return e.result})).then(() => { currentPromiseArrays[TypeKey].splice(indFirstElement, indLastElement); }, err => { currentPromiseArrays[TypeKey].splice(indFirstElement, indLastElement); }); }
javascript
function autoSpliceLaunchArray(LaunchArray, TypeKey){ var indFirstElement = currentPromiseArrays[TypeKey].indexOf(LaunchArray[0]); var indLastElement = currentPromiseArrays[TypeKey].indexOf(LaunchArray[LaunchArray.length-1]); Promise.all(LaunchArray.map(e => {return e.result})).then(() => { currentPromiseArrays[TypeKey].splice(indFirstElement, indLastElement); }, err => { currentPromiseArrays[TypeKey].splice(indFirstElement, indLastElement); }); }
[ "function", "autoSpliceLaunchArray", "(", "LaunchArray", ",", "TypeKey", ")", "{", "var", "indFirstElement", "=", "currentPromiseArrays", "[", "TypeKey", "]", ".", "indexOf", "(", "LaunchArray", "[", "0", "]", ")", ";", "var", "indLastElement", "=", "currentPromiseArrays", "[", "TypeKey", "]", ".", "indexOf", "(", "LaunchArray", "[", "LaunchArray", ".", "length", "-", "1", "]", ")", ";", "Promise", ".", "all", "(", "LaunchArray", ".", "map", "(", "e", "=>", "{", "return", "e", ".", "result", "}", ")", ")", ".", "then", "(", "(", ")", "=>", "{", "currentPromiseArrays", "[", "TypeKey", "]", ".", "splice", "(", "indFirstElement", ",", "indLastElement", ")", ";", "}", ",", "err", "=>", "{", "currentPromiseArrays", "[", "TypeKey", "]", ".", "splice", "(", "indFirstElement", ",", "indLastElement", ")", ";", "}", ")", ";", "}" ]
As the stack in currentPromiseArrays might get very long and slow down the application we will splice all of the launchArrays already completely resolved out of the currentPromiseArrays As currentPromiseArrays can get extremely large and we want to keep the app performant, autoSplice will automatically remove a LaunchArray from the currentPromiseArrays after all of them have either been resolved or one is rejected @param {Object[]} LaunchArray LaunchArray you want to enable autosplice for @param {String} TypeKey The TypeKey or Group that the Launcharray is of @returns {void}
[ "As", "the", "stack", "in", "currentPromiseArrays", "might", "get", "very", "long", "and", "slow", "down", "the", "application", "we", "will", "splice", "all", "of", "the", "launchArrays", "already", "completely", "resolved", "out", "of", "the", "currentPromiseArrays", "As", "currentPromiseArrays", "can", "get", "extremely", "large", "and", "we", "want", "to", "keep", "the", "app", "performant", "autoSplice", "will", "automatically", "remove", "a", "LaunchArray", "from", "the", "currentPromiseArrays", "after", "all", "of", "them", "have", "either", "been", "resolved", "or", "one", "is", "rejected" ]
1735b92749740204b597c1c6026257d54ade8200
https://github.com/relief-melone/limitpromises/blob/1735b92749740204b597c1c6026257d54ade8200/src/limitpromises.js#L168-L176
54,936
phated/grunt-enyo
tasks/init/bootplate/root/enyo/source/ajax/Jsonp.js
function(inParams, inCallbackFunctionName) { if (enyo.isString(inParams)) { return inParams.replace("=?", "=" + inCallbackFunctionName); } else { var params = enyo.mixin({}, inParams); params[this.callbackName] = inCallbackFunctionName; return enyo.Ajax.objectToQuery(params); } }
javascript
function(inParams, inCallbackFunctionName) { if (enyo.isString(inParams)) { return inParams.replace("=?", "=" + inCallbackFunctionName); } else { var params = enyo.mixin({}, inParams); params[this.callbackName] = inCallbackFunctionName; return enyo.Ajax.objectToQuery(params); } }
[ "function", "(", "inParams", ",", "inCallbackFunctionName", ")", "{", "if", "(", "enyo", ".", "isString", "(", "inParams", ")", ")", "{", "return", "inParams", ".", "replace", "(", "\"=?\"", ",", "\"=\"", "+", "inCallbackFunctionName", ")", ";", "}", "else", "{", "var", "params", "=", "enyo", ".", "mixin", "(", "{", "}", ",", "inParams", ")", ";", "params", "[", "this", ".", "callbackName", "]", "=", "inCallbackFunctionName", ";", "return", "enyo", ".", "Ajax", ".", "objectToQuery", "(", "params", ")", ";", "}", "}" ]
for a string version of inParams, we follow the convention of replacing the string "=?" with the callback name. For the more common case of inParams being an object, we'll add a argument named using the callbackName published property.
[ "for", "a", "string", "version", "of", "inParams", "we", "follow", "the", "convention", "of", "replacing", "the", "string", "=", "?", "with", "the", "callback", "name", ".", "For", "the", "more", "common", "case", "of", "inParams", "being", "an", "object", "we", "ll", "add", "a", "argument", "named", "using", "the", "callbackName", "published", "property", "." ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/bootplate/root/enyo/source/ajax/Jsonp.js#L111-L119
54,937
intervolga/bem-utils
lib/dirs-exist.js
stupidDirsExist
function stupidDirsExist(dirs) { const check = []; dirs.forEach((dir) => { check.push(dirExist(dir)); }); return Promise.all(check).then((results) => { // Combine to single object return dirs.reduce(function(prev, item, i) { prev[item] = !!results[i]; return prev; }, {}); }); }
javascript
function stupidDirsExist(dirs) { const check = []; dirs.forEach((dir) => { check.push(dirExist(dir)); }); return Promise.all(check).then((results) => { // Combine to single object return dirs.reduce(function(prev, item, i) { prev[item] = !!results[i]; return prev; }, {}); }); }
[ "function", "stupidDirsExist", "(", "dirs", ")", "{", "const", "check", "=", "[", "]", ";", "dirs", ".", "forEach", "(", "(", "dir", ")", "=>", "{", "check", ".", "push", "(", "dirExist", "(", "dir", ")", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "check", ")", ".", "then", "(", "(", "results", ")", "=>", "{", "// Combine to single object", "return", "dirs", ".", "reduce", "(", "function", "(", "prev", ",", "item", ",", "i", ")", "{", "prev", "[", "item", "]", "=", "!", "!", "results", "[", "i", "]", ";", "return", "prev", ";", "}", ",", "{", "}", ")", ";", "}", ")", ";", "}" ]
Check if dirs exist, all at once @param {Array} dirs @return {Promise} {dir: exist}
[ "Check", "if", "dirs", "exist", "all", "at", "once" ]
3b81bb9bc408275486175326dc7f35c563a46563
https://github.com/intervolga/bem-utils/blob/3b81bb9bc408275486175326dc7f35c563a46563/lib/dirs-exist.js#L9-L23
54,938
intervolga/bem-utils
lib/dirs-exist.js
dirsExist
function dirsExist(dirs) { if (0 === dirs.length) { return new Promise((resolve) => { resolve({}); }); } // Group dirs by '/' count const dirsByDepth = dirs.reduce(function(prev, curItem) { const depth = curItem.split(path.sep).length; (prev[depth] = prev[depth] || []).push(curItem); return prev; }, {}); // Extract min depth dirs const allDepths = Object.keys(dirsByDepth).map(Number); const currDepth = Math.min(...allDepths); const currDirs = dirsByDepth[currDepth]; // Prepare result object const result = dirs.reduce(function(prev, item) { prev[item] = null; return prev; }, {}); // Check if min depth dirs exist return stupidDirsExist(currDirs).then((localResult) => { Object.keys(result).forEach((dir) => { if (null !== result[dir]) { return; } Object.keys(localResult).forEach((localDir) => { // Transfer local check result to global "as is" result[localDir] = localResult[localDir]; // Additionally check if we can mark more deeper directories // as non-existing if (false === localResult[localDir] && dir.slice(0, localDir.length + 1) === localDir + path.sep) { result[dir] = false; } }); }); // Extract not checked dirs const restDirs = dirs.filter((dir) => { return null === result[dir]; }); return dirsExist(restDirs); }).then((finalResult) => { // Transfer local check result to global "as is" Object.keys(finalResult).forEach((finalDir) => { result[finalDir] = finalResult[finalDir]; }); return result; }); }
javascript
function dirsExist(dirs) { if (0 === dirs.length) { return new Promise((resolve) => { resolve({}); }); } // Group dirs by '/' count const dirsByDepth = dirs.reduce(function(prev, curItem) { const depth = curItem.split(path.sep).length; (prev[depth] = prev[depth] || []).push(curItem); return prev; }, {}); // Extract min depth dirs const allDepths = Object.keys(dirsByDepth).map(Number); const currDepth = Math.min(...allDepths); const currDirs = dirsByDepth[currDepth]; // Prepare result object const result = dirs.reduce(function(prev, item) { prev[item] = null; return prev; }, {}); // Check if min depth dirs exist return stupidDirsExist(currDirs).then((localResult) => { Object.keys(result).forEach((dir) => { if (null !== result[dir]) { return; } Object.keys(localResult).forEach((localDir) => { // Transfer local check result to global "as is" result[localDir] = localResult[localDir]; // Additionally check if we can mark more deeper directories // as non-existing if (false === localResult[localDir] && dir.slice(0, localDir.length + 1) === localDir + path.sep) { result[dir] = false; } }); }); // Extract not checked dirs const restDirs = dirs.filter((dir) => { return null === result[dir]; }); return dirsExist(restDirs); }).then((finalResult) => { // Transfer local check result to global "as is" Object.keys(finalResult).forEach((finalDir) => { result[finalDir] = finalResult[finalDir]; }); return result; }); }
[ "function", "dirsExist", "(", "dirs", ")", "{", "if", "(", "0", "===", "dirs", ".", "length", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ")", "=>", "{", "resolve", "(", "{", "}", ")", ";", "}", ")", ";", "}", "// Group dirs by '/' count", "const", "dirsByDepth", "=", "dirs", ".", "reduce", "(", "function", "(", "prev", ",", "curItem", ")", "{", "const", "depth", "=", "curItem", ".", "split", "(", "path", ".", "sep", ")", ".", "length", ";", "(", "prev", "[", "depth", "]", "=", "prev", "[", "depth", "]", "||", "[", "]", ")", ".", "push", "(", "curItem", ")", ";", "return", "prev", ";", "}", ",", "{", "}", ")", ";", "// Extract min depth dirs", "const", "allDepths", "=", "Object", ".", "keys", "(", "dirsByDepth", ")", ".", "map", "(", "Number", ")", ";", "const", "currDepth", "=", "Math", ".", "min", "(", "...", "allDepths", ")", ";", "const", "currDirs", "=", "dirsByDepth", "[", "currDepth", "]", ";", "// Prepare result object", "const", "result", "=", "dirs", ".", "reduce", "(", "function", "(", "prev", ",", "item", ")", "{", "prev", "[", "item", "]", "=", "null", ";", "return", "prev", ";", "}", ",", "{", "}", ")", ";", "// Check if min depth dirs exist", "return", "stupidDirsExist", "(", "currDirs", ")", ".", "then", "(", "(", "localResult", ")", "=>", "{", "Object", ".", "keys", "(", "result", ")", ".", "forEach", "(", "(", "dir", ")", "=>", "{", "if", "(", "null", "!==", "result", "[", "dir", "]", ")", "{", "return", ";", "}", "Object", ".", "keys", "(", "localResult", ")", ".", "forEach", "(", "(", "localDir", ")", "=>", "{", "// Transfer local check result to global \"as is\"", "result", "[", "localDir", "]", "=", "localResult", "[", "localDir", "]", ";", "// Additionally check if we can mark more deeper directories", "// as non-existing", "if", "(", "false", "===", "localResult", "[", "localDir", "]", "&&", "dir", ".", "slice", "(", "0", ",", "localDir", ".", "length", "+", "1", ")", "===", "localDir", "+", "path", ".", "sep", ")", "{", "result", "[", "dir", "]", "=", "false", ";", "}", "}", ")", ";", "}", ")", ";", "// Extract not checked dirs", "const", "restDirs", "=", "dirs", ".", "filter", "(", "(", "dir", ")", "=>", "{", "return", "null", "===", "result", "[", "dir", "]", ";", "}", ")", ";", "return", "dirsExist", "(", "restDirs", ")", ";", "}", ")", ".", "then", "(", "(", "finalResult", ")", "=>", "{", "// Transfer local check result to global \"as is\"", "Object", ".", "keys", "(", "finalResult", ")", ".", "forEach", "(", "(", "finalDir", ")", "=>", "{", "result", "[", "finalDir", "]", "=", "finalResult", "[", "finalDir", "]", ";", "}", ")", ";", "return", "result", ";", "}", ")", ";", "}" ]
Check if directories exist. Step by step. From root to leaves. @param {Array} dirs @return {Promise} {dir: exist}
[ "Check", "if", "directories", "exist", ".", "Step", "by", "step", ".", "From", "root", "to", "leaves", "." ]
3b81bb9bc408275486175326dc7f35c563a46563
https://github.com/intervolga/bem-utils/blob/3b81bb9bc408275486175326dc7f35c563a46563/lib/dirs-exist.js#L31-L92
54,939
usco/usco-stl-parser
dist/parseStream.js
parseASCIIChunk
function parseASCIIChunk(workChunk) { var data = (0, _utils.ensureString)(workChunk); // console.log('parseASCII') var result = void 0, text = void 0; var patternNormal = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; var patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; var patternFace = /facet([\s\S]*?)endfacet/g; var posArray = []; var normArray = []; var faces = 0; var offset = 0; while ((result = patternFace.exec(data)) !== null) { var length = 0; text = result[0]; offset = result.index + text.length; while ((result = patternNormal.exec(text)) !== null) { normArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); normArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); normArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); } while ((result = patternVertex.exec(text)) !== null) { posArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); length += 1; } faces += 1; } var positions = new Float32Array(faces * 3 * 3); var normals = new Float32Array(faces * 3 * 3); positions.set(posArray); normals.set(normArray); // compute offsets, remainderData etc for next chunk etc var remainderTextData = data.slice(offset); // console.log('remainderData', remainderTextData) var remainderData = new Buffer(remainderTextData); return { faceOffset: faces, remainderData: remainderData, positions: positions, normals: normals }; }
javascript
function parseASCIIChunk(workChunk) { var data = (0, _utils.ensureString)(workChunk); // console.log('parseASCII') var result = void 0, text = void 0; var patternNormal = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; var patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g; var patternFace = /facet([\s\S]*?)endfacet/g; var posArray = []; var normArray = []; var faces = 0; var offset = 0; while ((result = patternFace.exec(data)) !== null) { var length = 0; text = result[0]; offset = result.index + text.length; while ((result = patternNormal.exec(text)) !== null) { normArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); normArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); normArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); } while ((result = patternVertex.exec(text)) !== null) { posArray.push(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])); length += 1; } faces += 1; } var positions = new Float32Array(faces * 3 * 3); var normals = new Float32Array(faces * 3 * 3); positions.set(posArray); normals.set(normArray); // compute offsets, remainderData etc for next chunk etc var remainderTextData = data.slice(offset); // console.log('remainderData', remainderTextData) var remainderData = new Buffer(remainderTextData); return { faceOffset: faces, remainderData: remainderData, positions: positions, normals: normals }; }
[ "function", "parseASCIIChunk", "(", "workChunk", ")", "{", "var", "data", "=", "(", "0", ",", "_utils", ".", "ensureString", ")", "(", "workChunk", ")", ";", "// console.log('parseASCII')", "var", "result", "=", "void", "0", ",", "text", "=", "void", "0", ";", "var", "patternNormal", "=", "/", "normal[\\s]+([\\-+]?[0-9]+\\.?[0-9]*([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+", "/", "g", ";", "var", "patternVertex", "=", "/", "vertex[\\s]+([\\-+]?[0-9]+\\.?[0-9]*([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+[\\s]+([\\-+]?[0-9]*\\.?[0-9]+([eE][\\-+]?[0-9]+)?)+", "/", "g", ";", "var", "patternFace", "=", "/", "facet([\\s\\S]*?)endfacet", "/", "g", ";", "var", "posArray", "=", "[", "]", ";", "var", "normArray", "=", "[", "]", ";", "var", "faces", "=", "0", ";", "var", "offset", "=", "0", ";", "while", "(", "(", "result", "=", "patternFace", ".", "exec", "(", "data", ")", ")", "!==", "null", ")", "{", "var", "length", "=", "0", ";", "text", "=", "result", "[", "0", "]", ";", "offset", "=", "result", ".", "index", "+", "text", ".", "length", ";", "while", "(", "(", "result", "=", "patternNormal", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "normArray", ".", "push", "(", "parseFloat", "(", "result", "[", "1", "]", ")", ",", "parseFloat", "(", "result", "[", "3", "]", ")", ",", "parseFloat", "(", "result", "[", "5", "]", ")", ")", ";", "normArray", ".", "push", "(", "parseFloat", "(", "result", "[", "1", "]", ")", ",", "parseFloat", "(", "result", "[", "3", "]", ")", ",", "parseFloat", "(", "result", "[", "5", "]", ")", ")", ";", "normArray", ".", "push", "(", "parseFloat", "(", "result", "[", "1", "]", ")", ",", "parseFloat", "(", "result", "[", "3", "]", ")", ",", "parseFloat", "(", "result", "[", "5", "]", ")", ")", ";", "}", "while", "(", "(", "result", "=", "patternVertex", ".", "exec", "(", "text", ")", ")", "!==", "null", ")", "{", "posArray", ".", "push", "(", "parseFloat", "(", "result", "[", "1", "]", ")", ",", "parseFloat", "(", "result", "[", "3", "]", ")", ",", "parseFloat", "(", "result", "[", "5", "]", ")", ")", ";", "length", "+=", "1", ";", "}", "faces", "+=", "1", ";", "}", "var", "positions", "=", "new", "Float32Array", "(", "faces", "*", "3", "*", "3", ")", ";", "var", "normals", "=", "new", "Float32Array", "(", "faces", "*", "3", "*", "3", ")", ";", "positions", ".", "set", "(", "posArray", ")", ";", "normals", ".", "set", "(", "normArray", ")", ";", "// compute offsets, remainderData etc for next chunk etc", "var", "remainderTextData", "=", "data", ".", "slice", "(", "offset", ")", ";", "// console.log('remainderData', remainderTextData)", "var", "remainderData", "=", "new", "Buffer", "(", "remainderTextData", ")", ";", "return", "{", "faceOffset", ":", "faces", ",", "remainderData", ":", "remainderData", ",", "positions", ":", "positions", ",", "normals", ":", "normals", "}", ";", "}" ]
ASCII stl parsing
[ "ASCII", "stl", "parsing" ]
49eb402f124723d8f74cc67f24a7017c2b99bca4
https://github.com/usco/usco-stl-parser/blob/49eb402f124723d8f74cc67f24a7017c2b99bca4/dist/parseStream.js#L114-L159
54,940
ikondrat/franky
src/ds/Set.js
function (value) { var res; if (this.has(value)) { res = this.items.splice( x.indexOf(this.items, value), 1 ); } return res; }
javascript
function (value) { var res; if (this.has(value)) { res = this.items.splice( x.indexOf(this.items, value), 1 ); } return res; }
[ "function", "(", "value", ")", "{", "var", "res", ";", "if", "(", "this", ".", "has", "(", "value", ")", ")", "{", "res", "=", "this", ".", "items", ".", "splice", "(", "x", ".", "indexOf", "(", "this", ".", "items", ",", "value", ")", ",", "1", ")", ";", "}", "return", "res", ";", "}" ]
Removes value from Set @param value @returns <Item>
[ "Removes", "value", "from", "Set" ]
6a7368891f39620a225e37c4a56d2bf99644c3e7
https://github.com/ikondrat/franky/blob/6a7368891f39620a225e37c4a56d2bf99644c3e7/src/ds/Set.js#L37-L46
54,941
ikondrat/franky
src/ds/Set.js
function (callback) { for (var i = 0, l = this.items.length; i < l; i++) { callback(this.items[i], i, this.items); } return this; }
javascript
function (callback) { for (var i = 0, l = this.items.length; i < l; i++) { callback(this.items[i], i, this.items); } return this; }
[ "function", "(", "callback", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "this", ".", "items", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "callback", "(", "this", ".", "items", "[", "i", "]", ",", "i", ",", "this", ".", "items", ")", ";", "}", "return", "this", ";", "}" ]
Iterates through values and void callback @param callback
[ "Iterates", "through", "values", "and", "void", "callback" ]
6a7368891f39620a225e37c4a56d2bf99644c3e7
https://github.com/ikondrat/franky/blob/6a7368891f39620a225e37c4a56d2bf99644c3e7/src/ds/Set.js#L62-L67
54,942
ugate/releasebot
lib/committer.js
argv
function argv(k) { if (!nargv) { nargv = process.argv.slice(0, 2); } var v = '', m = null; var x = new RegExp(k + regexKeyVal.source); nargv.every(function(e) { m = e.match(x); if (m && m.length) { v = m[0]; return false; } }); return v; }
javascript
function argv(k) { if (!nargv) { nargv = process.argv.slice(0, 2); } var v = '', m = null; var x = new RegExp(k + regexKeyVal.source); nargv.every(function(e) { m = e.match(x); if (m && m.length) { v = m[0]; return false; } }); return v; }
[ "function", "argv", "(", "k", ")", "{", "if", "(", "!", "nargv", ")", "{", "nargv", "=", "process", ".", "argv", ".", "slice", "(", "0", ",", "2", ")", ";", "}", "var", "v", "=", "''", ",", "m", "=", "null", ";", "var", "x", "=", "new", "RegExp", "(", "k", "+", "regexKeyVal", ".", "source", ")", ";", "nargv", ".", "every", "(", "function", "(", "e", ")", "{", "m", "=", "e", ".", "match", "(", "x", ")", ";", "if", "(", "m", "&&", "m", ".", "length", ")", "{", "v", "=", "m", "[", "0", "]", ";", "return", "false", ";", "}", "}", ")", ";", "return", "v", ";", "}" ]
find via node CLI argument in the format key="value"
[ "find", "via", "node", "CLI", "argument", "in", "the", "format", "key", "=", "value" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/committer.js#L56-L70
54,943
ugate/releasebot
lib/committer.js
clone
function clone(c, wl, bl) { var cl = {}, cp, t; for (var keys = Object.keys(c), l = 0; l < keys.length; l++) { cp = c[keys[l]]; if (bl && bl.indexOf(cp) >= 0) { continue; } if (Array.isArray(cp)) { cl[keys[l]] = cp.slice(0); } else if ((t = typeof cp) === 'function') { if (!wl || wl.indexOf(cp) >= 0) { cl[keys[l]] = cp; // cp.bind(cp); } } else if (cp == null || t === 'string' || t === 'number' || t === 'boolean' || util.isRegExp(cp) || util.isDate(cp) || util.isError(cp)) { cl[keys[l]] = cp; } else if (t !== 'undefined') { cl[keys[l]] = clone(cp, wl, bl); } } return cl; }
javascript
function clone(c, wl, bl) { var cl = {}, cp, t; for (var keys = Object.keys(c), l = 0; l < keys.length; l++) { cp = c[keys[l]]; if (bl && bl.indexOf(cp) >= 0) { continue; } if (Array.isArray(cp)) { cl[keys[l]] = cp.slice(0); } else if ((t = typeof cp) === 'function') { if (!wl || wl.indexOf(cp) >= 0) { cl[keys[l]] = cp; // cp.bind(cp); } } else if (cp == null || t === 'string' || t === 'number' || t === 'boolean' || util.isRegExp(cp) || util.isDate(cp) || util.isError(cp)) { cl[keys[l]] = cp; } else if (t !== 'undefined') { cl[keys[l]] = clone(cp, wl, bl); } } return cl; }
[ "function", "clone", "(", "c", ",", "wl", ",", "bl", ")", "{", "var", "cl", "=", "{", "}", ",", "cp", ",", "t", ";", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "c", ")", ",", "l", "=", "0", ";", "l", "<", "keys", ".", "length", ";", "l", "++", ")", "{", "cp", "=", "c", "[", "keys", "[", "l", "]", "]", ";", "if", "(", "bl", "&&", "bl", ".", "indexOf", "(", "cp", ")", ">=", "0", ")", "{", "continue", ";", "}", "if", "(", "Array", ".", "isArray", "(", "cp", ")", ")", "{", "cl", "[", "keys", "[", "l", "]", "]", "=", "cp", ".", "slice", "(", "0", ")", ";", "}", "else", "if", "(", "(", "t", "=", "typeof", "cp", ")", "===", "'function'", ")", "{", "if", "(", "!", "wl", "||", "wl", ".", "indexOf", "(", "cp", ")", ">=", "0", ")", "{", "cl", "[", "keys", "[", "l", "]", "]", "=", "cp", ";", "// cp.bind(cp);", "}", "}", "else", "if", "(", "cp", "==", "null", "||", "t", "===", "'string'", "||", "t", "===", "'number'", "||", "t", "===", "'boolean'", "||", "util", ".", "isRegExp", "(", "cp", ")", "||", "util", ".", "isDate", "(", "cp", ")", "||", "util", ".", "isError", "(", "cp", ")", ")", "{", "cl", "[", "keys", "[", "l", "]", "]", "=", "cp", ";", "}", "else", "if", "(", "t", "!==", "'undefined'", ")", "{", "cl", "[", "keys", "[", "l", "]", "]", "=", "clone", "(", "cp", ",", "wl", ",", "bl", ")", ";", "}", "}", "return", "cl", ";", "}" ]
Clones an object @param c the {Commit} to clone @param wl an array of white list functions that will be included in the clone (null to include all) @param bl an array of black list property values that will be excluded from the clone @returns {Object} clone
[ "Clones", "an", "object" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/committer.js#L352-L373
54,944
ugate/releasebot
lib/committer.js
pkgPropUpd
function pkgPropUpd(pd, u, n, r) { var v = null; if (u && pd.oldVer !== self.version && self.version) { v = self.version; } else if (n && pd.oldVer !== self.next.version && self.next.version) { v = self.next.version; } else if (r && self.prev.version) { v = self.prev.version; } pd.version = v; if (v && !pd.props) { pd.pkg.version = v; pd.propChangeCount++; } if (pd.props && pd.pkgParent) { pd.props.forEach(function pkgProp(p) { if (pd.pkgParent[p] && (!pd.pkg[p] || pd.pkgParent[p] !== pd.pkg[p])) { // sync parent package property with the current one pd.pkg[p] = pd.pkgParent[p]; pd.propChangeCount++; } }); } return v; }
javascript
function pkgPropUpd(pd, u, n, r) { var v = null; if (u && pd.oldVer !== self.version && self.version) { v = self.version; } else if (n && pd.oldVer !== self.next.version && self.next.version) { v = self.next.version; } else if (r && self.prev.version) { v = self.prev.version; } pd.version = v; if (v && !pd.props) { pd.pkg.version = v; pd.propChangeCount++; } if (pd.props && pd.pkgParent) { pd.props.forEach(function pkgProp(p) { if (pd.pkgParent[p] && (!pd.pkg[p] || pd.pkgParent[p] !== pd.pkg[p])) { // sync parent package property with the current one pd.pkg[p] = pd.pkgParent[p]; pd.propChangeCount++; } }); } return v; }
[ "function", "pkgPropUpd", "(", "pd", ",", "u", ",", "n", ",", "r", ")", "{", "var", "v", "=", "null", ";", "if", "(", "u", "&&", "pd", ".", "oldVer", "!==", "self", ".", "version", "&&", "self", ".", "version", ")", "{", "v", "=", "self", ".", "version", ";", "}", "else", "if", "(", "n", "&&", "pd", ".", "oldVer", "!==", "self", ".", "next", ".", "version", "&&", "self", ".", "next", ".", "version", ")", "{", "v", "=", "self", ".", "next", ".", "version", ";", "}", "else", "if", "(", "r", "&&", "self", ".", "prev", ".", "version", ")", "{", "v", "=", "self", ".", "prev", ".", "version", ";", "}", "pd", ".", "version", "=", "v", ";", "if", "(", "v", "&&", "!", "pd", ".", "props", ")", "{", "pd", ".", "pkg", ".", "version", "=", "v", ";", "pd", ".", "propChangeCount", "++", ";", "}", "if", "(", "pd", ".", "props", "&&", "pd", ".", "pkgParent", ")", "{", "pd", ".", "props", ".", "forEach", "(", "function", "pkgProp", "(", "p", ")", "{", "if", "(", "pd", ".", "pkgParent", "[", "p", "]", "&&", "(", "!", "pd", ".", "pkg", "[", "p", "]", "||", "pd", ".", "pkgParent", "[", "p", "]", "!==", "pd", ".", "pkg", "[", "p", "]", ")", ")", "{", "// sync parent package property with the current one", "pd", ".", "pkg", "[", "p", "]", "=", "pd", ".", "pkgParent", "[", "p", "]", ";", "pd", ".", "propChangeCount", "++", ";", "}", "}", ")", ";", "}", "return", "v", ";", "}" ]
updates the package version or a set of properties from a parent package for a given package data element and flag
[ "updates", "the", "package", "version", "or", "a", "set", "of", "properties", "from", "a", "parent", "package", "for", "a", "given", "package", "data", "element", "and", "flag" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/committer.js#L551-L575
54,945
ugate/releasebot
lib/committer.js
vmtchs
function vmtchs(start, end, skips) { var s = ''; for (var i = start; i <= end; i++) { if (skips && skips.indexOf(i) >= 0) { continue; } s += self.versionMatch[i] || ''; } return s; }
javascript
function vmtchs(start, end, skips) { var s = ''; for (var i = start; i <= end; i++) { if (skips && skips.indexOf(i) >= 0) { continue; } s += self.versionMatch[i] || ''; } return s; }
[ "function", "vmtchs", "(", "start", ",", "end", ",", "skips", ")", "{", "var", "s", "=", "''", ";", "for", "(", "var", "i", "=", "start", ";", "i", "<=", "end", ";", "i", "++", ")", "{", "if", "(", "skips", "&&", "skips", ".", "indexOf", "(", "i", ")", ">=", "0", ")", "{", "continue", ";", "}", "s", "+=", "self", ".", "versionMatch", "[", "i", "]", "||", "''", ";", "}", "return", "s", ";", "}" ]
reconstructs the version matches
[ "reconstructs", "the", "version", "matches" ]
1a2ff42796e77f47f9590992c014fee461aad80b
https://github.com/ugate/releasebot/blob/1a2ff42796e77f47f9590992c014fee461aad80b/lib/committer.js#L708-L717
54,946
skerit/alchemy-styleboost
public/ckeditor/4.4dev/plugins/a11yhelp/dialogs/a11yhelp.js
buildHelpContents
function buildHelpContents() { var pageTpl = '<div class="cke_accessibility_legend" role="document" aria-labelledby="' + id + '_arialbl" tabIndex="-1">%1</div>' + '<span id="' + id + '_arialbl" class="cke_voice_label">' + lang.contents + ' </span>', sectionTpl = '<h1>%1</h1><dl>%2</dl>', itemTpl = '<dt>%1</dt><dd>%2</dd>'; var pageHtml = [], sections = lang.legend, sectionLength = sections.length; for ( var i = 0; i < sectionLength; i++ ) { var section = sections[ i ], sectionHtml = [], items = section.items, itemsLength = items.length; for ( var j = 0; j < itemsLength; j++ ) { var item = items[ j ], itemLegend = item.legend.replace( variablesPattern, replaceVariables ); // (#9765) If some commands haven't been replaced in the legend, // most likely their keystrokes are unavailable and we shouldn't include // them in our help list. if ( itemLegend.match( variablesPattern ) ) continue; sectionHtml.push( itemTpl.replace( '%1', item.name ).replace( '%2', itemLegend ) ); } pageHtml.push( sectionTpl.replace( '%1', section.name ).replace( '%2', sectionHtml.join( '' ) ) ); } return pageTpl.replace( '%1', pageHtml.join( '' ) ); }
javascript
function buildHelpContents() { var pageTpl = '<div class="cke_accessibility_legend" role="document" aria-labelledby="' + id + '_arialbl" tabIndex="-1">%1</div>' + '<span id="' + id + '_arialbl" class="cke_voice_label">' + lang.contents + ' </span>', sectionTpl = '<h1>%1</h1><dl>%2</dl>', itemTpl = '<dt>%1</dt><dd>%2</dd>'; var pageHtml = [], sections = lang.legend, sectionLength = sections.length; for ( var i = 0; i < sectionLength; i++ ) { var section = sections[ i ], sectionHtml = [], items = section.items, itemsLength = items.length; for ( var j = 0; j < itemsLength; j++ ) { var item = items[ j ], itemLegend = item.legend.replace( variablesPattern, replaceVariables ); // (#9765) If some commands haven't been replaced in the legend, // most likely their keystrokes are unavailable and we shouldn't include // them in our help list. if ( itemLegend.match( variablesPattern ) ) continue; sectionHtml.push( itemTpl.replace( '%1', item.name ).replace( '%2', itemLegend ) ); } pageHtml.push( sectionTpl.replace( '%1', section.name ).replace( '%2', sectionHtml.join( '' ) ) ); } return pageTpl.replace( '%1', pageHtml.join( '' ) ); }
[ "function", "buildHelpContents", "(", ")", "{", "var", "pageTpl", "=", "'<div class=\"cke_accessibility_legend\" role=\"document\" aria-labelledby=\"'", "+", "id", "+", "'_arialbl\" tabIndex=\"-1\">%1</div>'", "+", "'<span id=\"'", "+", "id", "+", "'_arialbl\" class=\"cke_voice_label\">'", "+", "lang", ".", "contents", "+", "' </span>'", ",", "sectionTpl", "=", "'<h1>%1</h1><dl>%2</dl>'", ",", "itemTpl", "=", "'<dt>%1</dt><dd>%2</dd>'", ";", "var", "pageHtml", "=", "[", "]", ",", "sections", "=", "lang", ".", "legend", ",", "sectionLength", "=", "sections", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "sectionLength", ";", "i", "++", ")", "{", "var", "section", "=", "sections", "[", "i", "]", ",", "sectionHtml", "=", "[", "]", ",", "items", "=", "section", ".", "items", ",", "itemsLength", "=", "items", ".", "length", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "itemsLength", ";", "j", "++", ")", "{", "var", "item", "=", "items", "[", "j", "]", ",", "itemLegend", "=", "item", ".", "legend", ".", "replace", "(", "variablesPattern", ",", "replaceVariables", ")", ";", "// (#9765) If some commands haven't been replaced in the legend,\r", "// most likely their keystrokes are unavailable and we shouldn't include\r", "// them in our help list.\r", "if", "(", "itemLegend", ".", "match", "(", "variablesPattern", ")", ")", "continue", ";", "sectionHtml", ".", "push", "(", "itemTpl", ".", "replace", "(", "'%1'", ",", "item", ".", "name", ")", ".", "replace", "(", "'%2'", ",", "itemLegend", ")", ")", ";", "}", "pageHtml", ".", "push", "(", "sectionTpl", ".", "replace", "(", "'%1'", ",", "section", ".", "name", ")", ".", "replace", "(", "'%2'", ",", "sectionHtml", ".", "join", "(", "''", ")", ")", ")", ";", "}", "return", "pageTpl", ".", "replace", "(", "'%1'", ",", "pageHtml", ".", "join", "(", "''", ")", ")", ";", "}" ]
Create the help list directly from lang file entries.
[ "Create", "the", "help", "list", "directly", "from", "lang", "file", "entries", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/plugins/a11yhelp/dialogs/a11yhelp.js#L121-L154
54,947
bvalosek/sack
lib/getArguments.js
getArguments
function getArguments(f, amended) { var functionCode = f.toString(); if(amended){ //This is a fix for when we are passed anonymous functions (which are passed to us as unassigned) //ex: "function (a, b, c) { }" //These are actually parse errors so we'll try adding an assignment to fix the parse error functionCode = 'var a=' + functionCode; } try{ var ast = babylon.parse(functionCode); var functionDecl = findFunctionDecl(ast); if(!functionDecl) return []; return functionDecl.params.map(p => p.name); }catch(e){ //try one more time if(!amended){ return getArguments(f, true); } throw new Error('Could not parse:\n' + functionCode + '\n' + e); } }
javascript
function getArguments(f, amended) { var functionCode = f.toString(); if(amended){ //This is a fix for when we are passed anonymous functions (which are passed to us as unassigned) //ex: "function (a, b, c) { }" //These are actually parse errors so we'll try adding an assignment to fix the parse error functionCode = 'var a=' + functionCode; } try{ var ast = babylon.parse(functionCode); var functionDecl = findFunctionDecl(ast); if(!functionDecl) return []; return functionDecl.params.map(p => p.name); }catch(e){ //try one more time if(!amended){ return getArguments(f, true); } throw new Error('Could not parse:\n' + functionCode + '\n' + e); } }
[ "function", "getArguments", "(", "f", ",", "amended", ")", "{", "var", "functionCode", "=", "f", ".", "toString", "(", ")", ";", "if", "(", "amended", ")", "{", "//This is a fix for when we are passed anonymous functions (which are passed to us as unassigned)", "//ex: \"function (a, b, c) { }\"", "//These are actually parse errors so we'll try adding an assignment to fix the parse error", "functionCode", "=", "'var a='", "+", "functionCode", ";", "}", "try", "{", "var", "ast", "=", "babylon", ".", "parse", "(", "functionCode", ")", ";", "var", "functionDecl", "=", "findFunctionDecl", "(", "ast", ")", ";", "if", "(", "!", "functionDecl", ")", "return", "[", "]", ";", "return", "functionDecl", ".", "params", ".", "map", "(", "p", "=>", "p", ".", "name", ")", ";", "}", "catch", "(", "e", ")", "{", "//try one more time", "if", "(", "!", "amended", ")", "{", "return", "getArguments", "(", "f", ",", "true", ")", ";", "}", "throw", "new", "Error", "(", "'Could not parse:\\n'", "+", "functionCode", "+", "'\\n'", "+", "e", ")", ";", "}", "}" ]
Get the parameter names of a function. @param {Function} f A function. @return {Array.<String>} An array of the argument names of a function.
[ "Get", "the", "parameter", "names", "of", "a", "function", "." ]
65e2ab133b6c40400c200c2e071052dea6b23c24
https://github.com/bvalosek/sack/blob/65e2ab133b6c40400c200c2e071052dea6b23c24/lib/getArguments.js#L10-L34
54,948
ForbesLindesay-Unmaintained/sauce-test
lib/run-chromedriver.js
runChromedriver
function runChromedriver(location, remote, options) { assert(remote === 'chromedriver', 'expected remote to be chromedriver'); if (!options.chromedriverStarted) { chromedriver.start(); } var throttle = options.throttle || function (fn) { return fn(); }; return throttle(function () { return runSingleBrowser(location, 'http://localhost:9515/', options.platform || options.capabilities || {}, { name: options.name, debug: options.debug, httpDebug: options.httpDebug, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout }); }).then(function (result) { if (!options.keepChromedriverAlive) { chromedriver.stop(); } return result; }, function (err) { if (!options.keepChromedriverAlive) { chromedriver.stop(); } throw err; }); }
javascript
function runChromedriver(location, remote, options) { assert(remote === 'chromedriver', 'expected remote to be chromedriver'); if (!options.chromedriverStarted) { chromedriver.start(); } var throttle = options.throttle || function (fn) { return fn(); }; return throttle(function () { return runSingleBrowser(location, 'http://localhost:9515/', options.platform || options.capabilities || {}, { name: options.name, debug: options.debug, httpDebug: options.httpDebug, allowExceptions: options.allowExceptions, testComplete: options.testComplete, testPassed: options.testPassed, timeout: options.timeout }); }).then(function (result) { if (!options.keepChromedriverAlive) { chromedriver.stop(); } return result; }, function (err) { if (!options.keepChromedriverAlive) { chromedriver.stop(); } throw err; }); }
[ "function", "runChromedriver", "(", "location", ",", "remote", ",", "options", ")", "{", "assert", "(", "remote", "===", "'chromedriver'", ",", "'expected remote to be chromedriver'", ")", ";", "if", "(", "!", "options", ".", "chromedriverStarted", ")", "{", "chromedriver", ".", "start", "(", ")", ";", "}", "var", "throttle", "=", "options", ".", "throttle", "||", "function", "(", "fn", ")", "{", "return", "fn", "(", ")", ";", "}", ";", "return", "throttle", "(", "function", "(", ")", "{", "return", "runSingleBrowser", "(", "location", ",", "'http://localhost:9515/'", ",", "options", ".", "platform", "||", "options", ".", "capabilities", "||", "{", "}", ",", "{", "name", ":", "options", ".", "name", ",", "debug", ":", "options", ".", "debug", ",", "httpDebug", ":", "options", ".", "httpDebug", ",", "allowExceptions", ":", "options", ".", "allowExceptions", ",", "testComplete", ":", "options", ".", "testComplete", ",", "testPassed", ":", "options", ".", "testPassed", ",", "timeout", ":", "options", ".", "timeout", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "if", "(", "!", "options", ".", "keepChromedriverAlive", ")", "{", "chromedriver", ".", "stop", "(", ")", ";", "}", "return", "result", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "!", "options", ".", "keepChromedriverAlive", ")", "{", "chromedriver", ".", "stop", "(", ")", ";", "}", "throw", "err", ";", "}", ")", ";", "}" ]
Run a test using chromedriver, then stops chrome driver and returns the result @option {Function} throttle @option {Object} platform|capabilities @option {Boolean} debug @option {Boolean} allowExceptions @option {String|Function} testComplete @option {String|Function} testPassed @option {String} timeout @option {Boolean} chromedriverStarted @option {Boolean} keepChromedriverAlive Returns: ```js { "passed": true, "duration": "3000" } ``` @param {Location} location @param {Object} remote @param {Object} platform @param {Options} options @returns {Promise}
[ "Run", "a", "test", "using", "chromedriver", "then", "stops", "chrome", "driver", "and", "returns", "the", "result" ]
7c671b3321dc63aefc00c1c8d49e943ead2e7f5e
https://github.com/ForbesLindesay-Unmaintained/sauce-test/blob/7c671b3321dc63aefc00c1c8d49e943ead2e7f5e/lib/run-chromedriver.js#L33-L61
54,949
OctaveWealth/passy
lib/bitString.js
pad
function pad (n, width, z) { if (typeof n !== 'string') throw new Error('bitString#pad: Need String'); z = z || '0'; while(n.length < width) { n = z + n; } return n; }
javascript
function pad (n, width, z) { if (typeof n !== 'string') throw new Error('bitString#pad: Need String'); z = z || '0'; while(n.length < width) { n = z + n; } return n; }
[ "function", "pad", "(", "n", ",", "width", ",", "z", ")", "{", "if", "(", "typeof", "n", "!==", "'string'", ")", "throw", "new", "Error", "(", "'bitString#pad: Need String'", ")", ";", "z", "=", "z", "||", "'0'", ";", "while", "(", "n", ".", "length", "<", "width", ")", "{", "n", "=", "z", "+", "n", ";", "}", "return", "n", ";", "}" ]
Pad a string to atleast desired width @param {string} n String to pad @param {integer} width Width to pad to @param {char=} z Optional pad char, defaults to '0' @return {string} Padded string
[ "Pad", "a", "string", "to", "atleast", "desired", "width" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/bitString.js#L48-L55
54,950
OctaveWealth/passy
lib/bitString.js
checksum
function checksum (bits, size) { if (bits == null || !isValid(bits)) throw new Error('bitString#checksum: Need valid bits'); if (size == null || size % 2 !== 0) throw new Error('bitString#checksum: size needs to be even'); var sumA = 0, sumB = 0, i; for (i = 0; i < bits.length; i++) { sumA = (sumA + parseInt(bits[i], 2)) % size; sumB = (sumB + sumA) % size; } return pad(sumB.toString(2), size / 2) + pad(sumA.toString(2), size / 2); }
javascript
function checksum (bits, size) { if (bits == null || !isValid(bits)) throw new Error('bitString#checksum: Need valid bits'); if (size == null || size % 2 !== 0) throw new Error('bitString#checksum: size needs to be even'); var sumA = 0, sumB = 0, i; for (i = 0; i < bits.length; i++) { sumA = (sumA + parseInt(bits[i], 2)) % size; sumB = (sumB + sumA) % size; } return pad(sumB.toString(2), size / 2) + pad(sumA.toString(2), size / 2); }
[ "function", "checksum", "(", "bits", ",", "size", ")", "{", "if", "(", "bits", "==", "null", "||", "!", "isValid", "(", "bits", ")", ")", "throw", "new", "Error", "(", "'bitString#checksum: Need valid bits'", ")", ";", "if", "(", "size", "==", "null", "||", "size", "%", "2", "!==", "0", ")", "throw", "new", "Error", "(", "'bitString#checksum: size needs to be even'", ")", ";", "var", "sumA", "=", "0", ",", "sumB", "=", "0", ",", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "bits", ".", "length", ";", "i", "++", ")", "{", "sumA", "=", "(", "sumA", "+", "parseInt", "(", "bits", "[", "i", "]", ",", "2", ")", ")", "%", "size", ";", "sumB", "=", "(", "sumB", "+", "sumA", ")", "%", "size", ";", "}", "return", "pad", "(", "sumB", ".", "toString", "(", "2", ")", ",", "size", "/", "2", ")", "+", "pad", "(", "sumA", ".", "toString", "(", "2", ")", ",", "size", "/", "2", ")", ";", "}" ]
Fletcher's checksum on a bitstring @param {string} bits Bitstring to checksum @param {integer} size Size of checksum, must be divisible by 2 @return {string} Return checksum as bitstring. With BA, ie sumA last;
[ "Fletcher", "s", "checksum", "on", "a", "bitstring" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/bitString.js#L72-L86
54,951
OctaveWealth/passy
lib/bitString.js
randomBits
function randomBits (n) { if (typeof n !== 'number') throw new Error('bitString#randomBits: Need number'); var buf = _randomBytes(Math.ceil(n/8)), bits = ''; for (var i = 0; i < n; i++) { bits += (buf[Math.floor(i / 8)] & (0x01 << (i % 8))) ? '1' : '0'; } return bits; }
javascript
function randomBits (n) { if (typeof n !== 'number') throw new Error('bitString#randomBits: Need number'); var buf = _randomBytes(Math.ceil(n/8)), bits = ''; for (var i = 0; i < n; i++) { bits += (buf[Math.floor(i / 8)] & (0x01 << (i % 8))) ? '1' : '0'; } return bits; }
[ "function", "randomBits", "(", "n", ")", "{", "if", "(", "typeof", "n", "!==", "'number'", ")", "throw", "new", "Error", "(", "'bitString#randomBits: Need number'", ")", ";", "var", "buf", "=", "_randomBytes", "(", "Math", ".", "ceil", "(", "n", "/", "8", ")", ")", ",", "bits", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "bits", "+=", "(", "buf", "[", "Math", ".", "floor", "(", "i", "/", "8", ")", "]", "&", "(", "0x01", "<<", "(", "i", "%", "8", ")", ")", ")", "?", "'1'", ":", "'0'", ";", "}", "return", "bits", ";", "}" ]
Get n random bits Get N randomBits as bitstring @param {integer} n Number of random bits to get @return {string} The random bitstring
[ "Get", "n", "random", "bits", "Get", "N", "randomBits", "as", "bitstring" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/bitString.js#L94-L102
54,952
meisterplayer/js-dev
gulp/changelog.js
createFormatChangelog
function createFormatChangelog(inPath) { if (!inPath) { throw new Error('Input path argument is required'); } return function formatChangelog() { return gulp.src(inPath) // Replace all version compare links. .pipe(replace(/\(http.*\) /g, ' ')) // Replace all commit links. .pipe(replace(/ \(\[.*/g, '')) .pipe(gulp.dest(file => file.base)); }; }
javascript
function createFormatChangelog(inPath) { if (!inPath) { throw new Error('Input path argument is required'); } return function formatChangelog() { return gulp.src(inPath) // Replace all version compare links. .pipe(replace(/\(http.*\) /g, ' ')) // Replace all commit links. .pipe(replace(/ \(\[.*/g, '')) .pipe(gulp.dest(file => file.base)); }; }
[ "function", "createFormatChangelog", "(", "inPath", ")", "{", "if", "(", "!", "inPath", ")", "{", "throw", "new", "Error", "(", "'Input path argument is required'", ")", ";", "}", "return", "function", "formatChangelog", "(", ")", "{", "return", "gulp", ".", "src", "(", "inPath", ")", "// Replace all version compare links.", ".", "pipe", "(", "replace", "(", "/", "\\(http.*\\) ", "/", "g", ",", "' '", ")", ")", "// Replace all commit links.", ".", "pipe", "(", "replace", "(", "/", " \\(\\[.*", "/", "g", ",", "''", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "file", "=>", "file", ".", "base", ")", ")", ";", "}", ";", "}" ]
Higher order function to create gulp function that strips links to the git repository from changelogs generated by conventional changelog. @param {string} inPath The path for the project's changelog @return {function} Function that can be used as a gulp task
[ "Higher", "order", "function", "to", "create", "gulp", "function", "that", "strips", "links", "to", "the", "git", "repository", "from", "changelogs", "generated", "by", "conventional", "changelog", "." ]
c2646678c49dcdaa120ba3f24824da52b0c63e31
https://github.com/meisterplayer/js-dev/blob/c2646678c49dcdaa120ba3f24824da52b0c63e31/gulp/changelog.js#L29-L42
54,953
dak0rn/espressojs
lib/espresso/dispatchRequest.js
function(parts) { var urls = []; var start = ''; // If the first part is empty // the original path begins with a slash so we // do that, too if( _.isEmpty(parts[0]) ) { start = '/'; urls[0] = '/'; // would not be generated in reduce() } _.reduce(parts, function(acc, value){ if( ! _.isString(value) || _.isEmpty(value) ) return acc; acc += value; // Push w/out trailing slash urls.push(acc); return acc + '/'; }, start ); return urls; }
javascript
function(parts) { var urls = []; var start = ''; // If the first part is empty // the original path begins with a slash so we // do that, too if( _.isEmpty(parts[0]) ) { start = '/'; urls[0] = '/'; // would not be generated in reduce() } _.reduce(parts, function(acc, value){ if( ! _.isString(value) || _.isEmpty(value) ) return acc; acc += value; // Push w/out trailing slash urls.push(acc); return acc + '/'; }, start ); return urls; }
[ "function", "(", "parts", ")", "{", "var", "urls", "=", "[", "]", ";", "var", "start", "=", "''", ";", "// If the first part is empty", "// the original path begins with a slash so we", "// do that, too", "if", "(", "_", ".", "isEmpty", "(", "parts", "[", "0", "]", ")", ")", "{", "start", "=", "'/'", ";", "urls", "[", "0", "]", "=", "'/'", ";", "// would not be generated in reduce()", "}", "_", ".", "reduce", "(", "parts", ",", "function", "(", "acc", ",", "value", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "value", ")", "||", "_", ".", "isEmpty", "(", "value", ")", ")", "return", "acc", ";", "acc", "+=", "value", ";", "// Push w/out trailing slash", "urls", ".", "push", "(", "acc", ")", ";", "return", "acc", "+", "'/'", ";", "}", ",", "start", ")", ";", "return", "urls", ";", "}" ]
Function that creates a list of parent URLs for a given relative URL.
[ "Function", "that", "creates", "a", "list", "of", "parent", "URLs", "for", "a", "given", "relative", "URL", "." ]
7f8e015f31113215abbe9988ae7f2c7dd5d8572b
https://github.com/dak0rn/espressojs/blob/7f8e015f31113215abbe9988ae7f2c7dd5d8572b/lib/espresso/dispatchRequest.js#L63-L90
54,954
dak0rn/espressojs
lib/espresso/dispatchRequest.js
function(urls, skipMissing) { var i = -1; var j; var handlers = []; var url; var resource; var urlsLength = urls.length; var resourcesLength = this._resources.length; var foundHandler; // All URLs while( ++i < urlsLength ) { url = urls[i]; foundHandler = undefined; // No handler yet j = -1; // All resources while( ++j < resourcesLength ) { resource = this._resources[j]; if( ! resource.getPattern().matches(url) ) continue; // If this handler does not want to use cascading // we remove every handler that might have been executed // before it if( false === resource.getOption('cascading') ) handlers = []; handlers.push({ path: url, handler: resource }); foundHandler = resource; break; } // One handler missing? Chain is broken, return an error if required if( _.isUndefined(foundHandler) && ! skipMissing ) return null; } return handlers; }
javascript
function(urls, skipMissing) { var i = -1; var j; var handlers = []; var url; var resource; var urlsLength = urls.length; var resourcesLength = this._resources.length; var foundHandler; // All URLs while( ++i < urlsLength ) { url = urls[i]; foundHandler = undefined; // No handler yet j = -1; // All resources while( ++j < resourcesLength ) { resource = this._resources[j]; if( ! resource.getPattern().matches(url) ) continue; // If this handler does not want to use cascading // we remove every handler that might have been executed // before it if( false === resource.getOption('cascading') ) handlers = []; handlers.push({ path: url, handler: resource }); foundHandler = resource; break; } // One handler missing? Chain is broken, return an error if required if( _.isUndefined(foundHandler) && ! skipMissing ) return null; } return handlers; }
[ "function", "(", "urls", ",", "skipMissing", ")", "{", "var", "i", "=", "-", "1", ";", "var", "j", ";", "var", "handlers", "=", "[", "]", ";", "var", "url", ";", "var", "resource", ";", "var", "urlsLength", "=", "urls", ".", "length", ";", "var", "resourcesLength", "=", "this", ".", "_resources", ".", "length", ";", "var", "foundHandler", ";", "// All URLs", "while", "(", "++", "i", "<", "urlsLength", ")", "{", "url", "=", "urls", "[", "i", "]", ";", "foundHandler", "=", "undefined", ";", "// No handler yet", "j", "=", "-", "1", ";", "// All resources", "while", "(", "++", "j", "<", "resourcesLength", ")", "{", "resource", "=", "this", ".", "_resources", "[", "j", "]", ";", "if", "(", "!", "resource", ".", "getPattern", "(", ")", ".", "matches", "(", "url", ")", ")", "continue", ";", "// If this handler does not want to use cascading", "// we remove every handler that might have been executed", "// before it", "if", "(", "false", "===", "resource", ".", "getOption", "(", "'cascading'", ")", ")", "handlers", "=", "[", "]", ";", "handlers", ".", "push", "(", "{", "path", ":", "url", ",", "handler", ":", "resource", "}", ")", ";", "foundHandler", "=", "resource", ";", "break", ";", "}", "// One handler missing? Chain is broken, return an error if required", "if", "(", "_", ".", "isUndefined", "(", "foundHandler", ")", "&&", "!", "skipMissing", ")", "return", "null", ";", "}", "return", "handlers", ";", "}" ]
Finds all handlers for the given URLs. If `skipMissing` is `false`, `null` will be returned if a handler was not found. this = api$this @param {array} urls List of URLs to handle @param {boolean} skipMissing Skip missing "holes"?
[ "Finds", "all", "handlers", "for", "the", "given", "URLs", ".", "If", "skipMissing", "is", "false", "null", "will", "be", "returned", "if", "a", "handler", "was", "not", "found", "." ]
7f8e015f31113215abbe9988ae7f2c7dd5d8572b
https://github.com/dak0rn/espressojs/blob/7f8e015f31113215abbe9988ae7f2c7dd5d8572b/lib/espresso/dispatchRequest.js#L133-L175
54,955
dak0rn/espressojs
lib/espresso/dispatchRequest.js
function(resource) { var handler = resource.handler.getCallback(request.method); request.api.handler = handler; request.path = resource.path; var context = resource.handler.getContext(); context.__espressojs = { chainIsComplete: chainIsComplete, // Reference to the currently processed handler handler: resource.handler, // Currently processed path path: resource.path }; return context; }
javascript
function(resource) { var handler = resource.handler.getCallback(request.method); request.api.handler = handler; request.path = resource.path; var context = resource.handler.getContext(); context.__espressojs = { chainIsComplete: chainIsComplete, // Reference to the currently processed handler handler: resource.handler, // Currently processed path path: resource.path }; return context; }
[ "function", "(", "resource", ")", "{", "var", "handler", "=", "resource", ".", "handler", ".", "getCallback", "(", "request", ".", "method", ")", ";", "request", ".", "api", ".", "handler", "=", "handler", ";", "request", ".", "path", "=", "resource", ".", "path", ";", "var", "context", "=", "resource", ".", "handler", ".", "getContext", "(", ")", ";", "context", ".", "__espressojs", "=", "{", "chainIsComplete", ":", "chainIsComplete", ",", "// Reference to the currently processed handler", "handler", ":", "resource", ".", "handler", ",", "// Currently processed path", "path", ":", "resource", ".", "path", "}", ";", "return", "context", ";", "}" ]
Helper function used to prepare the handler invokation Uses and manipulates 'global' state like `chainIsComplete` and `request`. @param {object} resource A resource entry containing a path (`.path`) and the corresponding Handler. @return {object} The `this` context for the resource handler.
[ "Helper", "function", "used", "to", "prepare", "the", "handler", "invokation", "Uses", "and", "manipulates", "global", "state", "like", "chainIsComplete", "and", "request", "." ]
7f8e015f31113215abbe9988ae7f2c7dd5d8572b
https://github.com/dak0rn/espressojs/blob/7f8e015f31113215abbe9988ae7f2c7dd5d8572b/lib/espresso/dispatchRequest.js#L186-L203
54,956
tether/request-text
index.js
setup
function setup (request, options, ...args) { const len = request.headers['content-length'] const encoding = request.headers['content-encoding'] || 'identity' return Object.assign({}, options, { encoding: options.encoding || 'utf-8', limit: options.limit || '1mb', length: (len && encoding === 'identity') ? ~~len : options.length }, ...args) }
javascript
function setup (request, options, ...args) { const len = request.headers['content-length'] const encoding = request.headers['content-encoding'] || 'identity' return Object.assign({}, options, { encoding: options.encoding || 'utf-8', limit: options.limit || '1mb', length: (len && encoding === 'identity') ? ~~len : options.length }, ...args) }
[ "function", "setup", "(", "request", ",", "options", ",", "...", "args", ")", "{", "const", "len", "=", "request", ".", "headers", "[", "'content-length'", "]", "const", "encoding", "=", "request", ".", "headers", "[", "'content-encoding'", "]", "||", "'identity'", "return", "Object", ".", "assign", "(", "{", "}", ",", "options", ",", "{", "encoding", ":", "options", ".", "encoding", "||", "'utf-8'", ",", "limit", ":", "options", ".", "limit", "||", "'1mb'", ",", "length", ":", "(", "len", "&&", "encoding", "===", "'identity'", ")", "?", "~", "~", "len", ":", "options", ".", "length", "}", ",", "...", "args", ")", "}" ]
Clone and setup default options. @param {HttpIncomingMessage} request @param {Object} options @param {Object} mixin @return {Object} @api private
[ "Clone", "and", "setup", "default", "options", "." ]
f3a38bc78dcef21fa495e644c53fc532be6f8bfb
https://github.com/tether/request-text/blob/f3a38bc78dcef21fa495e644c53fc532be6f8bfb/index.js#L33-L41
54,957
blaugold/express-recaptcha-rest
index.js
getRecaptchaResponse
function getRecaptchaResponse(field, req) { return req.get(field) || (req.query && req.query[field]) || (req.body && req.body[field]) }
javascript
function getRecaptchaResponse(field, req) { return req.get(field) || (req.query && req.query[field]) || (req.body && req.body[field]) }
[ "function", "getRecaptchaResponse", "(", "field", ",", "req", ")", "{", "return", "req", ".", "get", "(", "field", ")", "||", "(", "req", ".", "query", "&&", "req", ".", "query", "[", "field", "]", ")", "||", "(", "req", ".", "body", "&&", "req", ".", "body", "[", "field", "]", ")", "}" ]
Gets recaptcha response from request. @private @param {string} field - Key to look for response. @param {express.req} req - Request object. @returns {string} - Recaptcha response.
[ "Gets", "recaptcha", "response", "from", "request", "." ]
3993ef63ca4a2bbea6e331dfe2a1acbc83564056
https://github.com/blaugold/express-recaptcha-rest/blob/3993ef63ca4a2bbea6e331dfe2a1acbc83564056/index.js#L141-L143
54,958
morulus/import-sub
resolve.js
resolveAsync
function resolveAsync(p, base, root) { if (!path.isAbsolute(p)) { return new Promise(function(r, j) { resolve(forceRelative(p), { basedir: path.resolve(root, base) }, function(err, res) { if (err) { j(err); } else { r(res); } }); }); } else { return Promise.resolve(p); } }
javascript
function resolveAsync(p, base, root) { if (!path.isAbsolute(p)) { return new Promise(function(r, j) { resolve(forceRelative(p), { basedir: path.resolve(root, base) }, function(err, res) { if (err) { j(err); } else { r(res); } }); }); } else { return Promise.resolve(p); } }
[ "function", "resolveAsync", "(", "p", ",", "base", ",", "root", ")", "{", "if", "(", "!", "path", ".", "isAbsolute", "(", "p", ")", ")", "{", "return", "new", "Promise", "(", "function", "(", "r", ",", "j", ")", "{", "resolve", "(", "forceRelative", "(", "p", ")", ",", "{", "basedir", ":", "path", ".", "resolve", "(", "root", ",", "base", ")", "}", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "j", "(", "err", ")", ";", "}", "else", "{", "r", "(", "res", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", "p", ")", ";", "}", "}" ]
Resolve path the same way ans postcss-import @return {Promise}
[ "Resolve", "path", "the", "same", "way", "ans", "postcss", "-", "import" ]
c5e33545bdc2b09714028ef6c44185a3ee59db3c
https://github.com/morulus/import-sub/blob/c5e33545bdc2b09714028ef6c44185a3ee59db3c/resolve.js#L81-L99
54,959
morulus/import-sub
resolve.js
object
function object(pairs) { let obj = {}; for (let i = 0;i<pairs.length;++i) { obj[pairs[i][0]] = pairs[i][1]; } return obj; }
javascript
function object(pairs) { let obj = {}; for (let i = 0;i<pairs.length;++i) { obj[pairs[i][0]] = pairs[i][1]; } return obj; }
[ "function", "object", "(", "pairs", ")", "{", "let", "obj", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "pairs", ".", "length", ";", "++", "i", ")", "{", "obj", "[", "pairs", "[", "i", "]", "[", "0", "]", "]", "=", "pairs", "[", "i", "]", "[", "1", "]", ";", "}", "return", "obj", ";", "}" ]
Object fn surrogate
[ "Object", "fn", "surrogate" ]
c5e33545bdc2b09714028ef6c44185a3ee59db3c
https://github.com/morulus/import-sub/blob/c5e33545bdc2b09714028ef6c44185a3ee59db3c/resolve.js#L112-L118
54,960
morulus/import-sub
resolve.js
matchToHolders
function matchToHolders(match, tag) { return object(match.map(function(val, index) { return [tag+":"+index, val]; })); }
javascript
function matchToHolders(match, tag) { return object(match.map(function(val, index) { return [tag+":"+index, val]; })); }
[ "function", "matchToHolders", "(", "match", ",", "tag", ")", "{", "return", "object", "(", "match", ".", "map", "(", "function", "(", "val", ",", "index", ")", "{", "return", "[", "tag", "+", "\":\"", "+", "index", ",", "val", "]", ";", "}", ")", ")", ";", "}" ]
Transform regExpr exec result to hashmap with tagged keys
[ "Transform", "regExpr", "exec", "result", "to", "hashmap", "with", "tagged", "keys" ]
c5e33545bdc2b09714028ef6c44185a3ee59db3c
https://github.com/morulus/import-sub/blob/c5e33545bdc2b09714028ef6c44185a3ee59db3c/resolve.js#L122-L126
54,961
morulus/import-sub
resolve.js
filterValidRule
function filterValidRule(rule) { return (rule.hasOwnProperty('match')&&typeof rule.match === "object") && (rule.hasOwnProperty('use') && ( typeof rule.use === "object" || typeof rule.use === "function" )) && ( (rule.match.hasOwnProperty('request')) || (rule.match.hasOwnProperty('base')) ) }
javascript
function filterValidRule(rule) { return (rule.hasOwnProperty('match')&&typeof rule.match === "object") && (rule.hasOwnProperty('use') && ( typeof rule.use === "object" || typeof rule.use === "function" )) && ( (rule.match.hasOwnProperty('request')) || (rule.match.hasOwnProperty('base')) ) }
[ "function", "filterValidRule", "(", "rule", ")", "{", "return", "(", "rule", ".", "hasOwnProperty", "(", "'match'", ")", "&&", "typeof", "rule", ".", "match", "===", "\"object\"", ")", "&&", "(", "rule", ".", "hasOwnProperty", "(", "'use'", ")", "&&", "(", "typeof", "rule", ".", "use", "===", "\"object\"", "||", "typeof", "rule", ".", "use", "===", "\"function\"", ")", ")", "&&", "(", "(", "rule", ".", "match", ".", "hasOwnProperty", "(", "'request'", ")", ")", "||", "(", "rule", ".", "match", ".", "hasOwnProperty", "(", "'base'", ")", ")", ")", "}" ]
Filter rules with `use` prop
[ "Filter", "rules", "with", "use", "prop" ]
c5e33545bdc2b09714028ef6c44185a3ee59db3c
https://github.com/morulus/import-sub/blob/c5e33545bdc2b09714028ef6c44185a3ee59db3c/resolve.js#L130-L140
54,962
morulus/import-sub
resolve.js
mapDefaults
function mapDefaults(rule) { return Object.assign({}, rule, { match: Object.assign({ request: defaultExpr, base: defaultExpr, module: defaultExpr }, rule.match), use: rule.use, }); }
javascript
function mapDefaults(rule) { return Object.assign({}, rule, { match: Object.assign({ request: defaultExpr, base: defaultExpr, module: defaultExpr }, rule.match), use: rule.use, }); }
[ "function", "mapDefaults", "(", "rule", ")", "{", "return", "Object", ".", "assign", "(", "{", "}", ",", "rule", ",", "{", "match", ":", "Object", ".", "assign", "(", "{", "request", ":", "defaultExpr", ",", "base", ":", "defaultExpr", ",", "module", ":", "defaultExpr", "}", ",", "rule", ".", "match", ")", ",", "use", ":", "rule", ".", "use", ",", "}", ")", ";", "}" ]
Merge with defaults
[ "Merge", "with", "defaults" ]
c5e33545bdc2b09714028ef6c44185a3ee59db3c
https://github.com/morulus/import-sub/blob/c5e33545bdc2b09714028ef6c44185a3ee59db3c/resolve.js#L144-L153
54,963
morulus/import-sub
resolve.js
wrapPlaceholders
function wrapPlaceholders(placeholders) { const keys = Object.keys(placeholders); const wrappedPlaceholders = {}; for (let i = 0; i < keys.length; i++) { wrappedPlaceholders['<'+keys[i]+'>'] = placeholders[keys[i]]; } return wrappedPlaceholders; }
javascript
function wrapPlaceholders(placeholders) { const keys = Object.keys(placeholders); const wrappedPlaceholders = {}; for (let i = 0; i < keys.length; i++) { wrappedPlaceholders['<'+keys[i]+'>'] = placeholders[keys[i]]; } return wrappedPlaceholders; }
[ "function", "wrapPlaceholders", "(", "placeholders", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "placeholders", ")", ";", "const", "wrappedPlaceholders", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "wrappedPlaceholders", "[", "'<'", "+", "keys", "[", "i", "]", "+", "'>'", "]", "=", "placeholders", "[", "keys", "[", "i", "]", "]", ";", "}", "return", "wrappedPlaceholders", ";", "}" ]
Wrap placeholders with scobes
[ "Wrap", "placeholders", "with", "scobes" ]
c5e33545bdc2b09714028ef6c44185a3ee59db3c
https://github.com/morulus/import-sub/blob/c5e33545bdc2b09714028ef6c44185a3ee59db3c/resolve.js#L157-L166
54,964
morulus/import-sub
resolve.js
isRequiresEarlyResolve
function isRequiresEarlyResolve(rules) { for (let i = 0; i < rules.length; ++i) { if ( Object.prototype.hasOwnProperty.call(rules[i], 'module') || (Object.prototype.hasOwnProperty.call(rules[i], 'append') && rules[i].append) ) { return true; } } return false; }
javascript
function isRequiresEarlyResolve(rules) { for (let i = 0; i < rules.length; ++i) { if ( Object.prototype.hasOwnProperty.call(rules[i], 'module') || (Object.prototype.hasOwnProperty.call(rules[i], 'append') && rules[i].append) ) { return true; } } return false; }
[ "function", "isRequiresEarlyResolve", "(", "rules", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rules", ".", "length", ";", "++", "i", ")", "{", "if", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "rules", "[", "i", "]", ",", "'module'", ")", "||", "(", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "rules", "[", "i", "]", ",", "'append'", ")", "&&", "rules", "[", "i", "]", ".", "append", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Search module in rules existing
[ "Search", "module", "in", "rules", "existing" ]
c5e33545bdc2b09714028ef6c44185a3ee59db3c
https://github.com/morulus/import-sub/blob/c5e33545bdc2b09714028ef6c44185a3ee59db3c/resolve.js#L177-L187
54,965
OctaveWealth/passy
lib/random.js
toArray
function toArray (id) { if (!isValid(id)) throw new Error('random#toArray: Need valid id'); // Decode var result = []; for (var i = 0; i < id.length; i++) { result.push(baseURL.ALPHABET.indexOf(id[i])); } return result; }
javascript
function toArray (id) { if (!isValid(id)) throw new Error('random#toArray: Need valid id'); // Decode var result = []; for (var i = 0; i < id.length; i++) { result.push(baseURL.ALPHABET.indexOf(id[i])); } return result; }
[ "function", "toArray", "(", "id", ")", "{", "if", "(", "!", "isValid", "(", "id", ")", ")", "throw", "new", "Error", "(", "'random#toArray: Need valid id'", ")", ";", "// Decode", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "id", ".", "length", ";", "i", "++", ")", "{", "result", ".", "push", "(", "baseURL", ".", "ALPHABET", ".", "indexOf", "(", "id", "[", "i", "]", ")", ")", ";", "}", "return", "result", ";", "}" ]
Convert a random id to Integer Array @param {string} id The id to convert. @return {Array.<number>} result
[ "Convert", "a", "random", "id", "to", "Integer", "Array" ]
6e357b018952f73e8570b89eda95393780328fab
https://github.com/OctaveWealth/passy/blob/6e357b018952f73e8570b89eda95393780328fab/lib/random.js#L56-L64
54,966
impomezia/sjmp-node
lib/sjmp.js
request
function request(packet, json) { return _create(packet, 1, (METHODS[packet.method] || '') + packet.resource, json); }
javascript
function request(packet, json) { return _create(packet, 1, (METHODS[packet.method] || '') + packet.resource, json); }
[ "function", "request", "(", "packet", ",", "json", ")", "{", "return", "_create", "(", "packet", ",", "1", ",", "(", "METHODS", "[", "packet", ".", "method", "]", "||", "''", ")", "+", "packet", ".", "resource", ",", "json", ")", ";", "}" ]
Serialize request to array or JSON. @param {Object} packet @param {String} packet.resource @param {String} packet.id @param {*} packet.body @param {Number|String} [packet.date] @param {Object} [packet.headers] @param {String} [packet.method] "get", "search", "post", "put", "delete", "sub", "unsub". @param {Boolean} [json] true to generate JSON instead of array. @returns {Array|String|null}
[ "Serialize", "request", "to", "array", "or", "JSON", "." ]
801a1bbdc8805b2e4c09721148684d43cae5a1e3
https://github.com/impomezia/sjmp-node/blob/801a1bbdc8805b2e4c09721148684d43cae5a1e3/lib/sjmp.js#L38-L40
54,967
impomezia/sjmp-node
lib/sjmp.js
reply
function reply(packet, json) { return _create(packet, packet.status || 500, (METHODS[packet.method] || '') + packet.resource, json); }
javascript
function reply(packet, json) { return _create(packet, packet.status || 500, (METHODS[packet.method] || '') + packet.resource, json); }
[ "function", "reply", "(", "packet", ",", "json", ")", "{", "return", "_create", "(", "packet", ",", "packet", ".", "status", "||", "500", ",", "(", "METHODS", "[", "packet", ".", "method", "]", "||", "''", ")", "+", "packet", ".", "resource", ",", "json", ")", ";", "}" ]
Serialize reply to array or JSON. @param {Object} packet @param {String} packet.method "get", "search", "post", "put", "delete", "sub", "unsub". @param {String} packet.resource @param {String} packet.id @param {*} packet.body @param {Number} [packet.status] @param {Number|String} [packet.date] @param {Object} [packet.headers] @param {Boolean} [json] true to generate JSON instead of array. @returns {Array|String|null}
[ "Serialize", "reply", "to", "array", "or", "JSON", "." ]
801a1bbdc8805b2e4c09721148684d43cae5a1e3
https://github.com/impomezia/sjmp-node/blob/801a1bbdc8805b2e4c09721148684d43cae5a1e3/lib/sjmp.js#L56-L58
54,968
frozzare/vecka
lib/vecka.js
function () { var date = new Date(); date.setHours(0, 0, 0); date.setDate(date.getDate() + 4 - (date.getDay() || 7)); return Math.ceil((((date - new Date(date.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7); }
javascript
function () { var date = new Date(); date.setHours(0, 0, 0); date.setDate(date.getDate() + 4 - (date.getDay() || 7)); return Math.ceil((((date - new Date(date.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7); }
[ "function", "(", ")", "{", "var", "date", "=", "new", "Date", "(", ")", ";", "date", ".", "setHours", "(", "0", ",", "0", ",", "0", ")", ";", "date", ".", "setDate", "(", "date", ".", "getDate", "(", ")", "+", "4", "-", "(", "date", ".", "getDay", "(", ")", "||", "7", ")", ")", ";", "return", "Math", ".", "ceil", "(", "(", "(", "(", "date", "-", "new", "Date", "(", "date", ".", "getFullYear", "(", ")", ",", "0", ",", "1", ")", ")", "/", "8.64e7", ")", "+", "1", ")", "/", "7", ")", ";", "}" ]
Get current week number. @return {Number}
[ "Get", "current", "week", "number", "." ]
b9dd4144536b9a29620e668ecbde99aeda1debc0
https://github.com/frozzare/vecka/blob/b9dd4144536b9a29620e668ecbde99aeda1debc0/lib/vecka.js#L11-L16
54,969
yaru22/co-couchbase
lib/util.js
methodQualified
function methodQualified(name, func) { var funcStr = func.toString(); // Only public methodds (i.e. methods that do not start with '_') which have // 'callback' as last parameter are qualified for thunkification. return (/^[^_]/.test(name) && /function.*\(.*,?.*callback\)/.test(funcStr)); }
javascript
function methodQualified(name, func) { var funcStr = func.toString(); // Only public methodds (i.e. methods that do not start with '_') which have // 'callback' as last parameter are qualified for thunkification. return (/^[^_]/.test(name) && /function.*\(.*,?.*callback\)/.test(funcStr)); }
[ "function", "methodQualified", "(", "name", ",", "func", ")", "{", "var", "funcStr", "=", "func", ".", "toString", "(", ")", ";", "// Only public methodds (i.e. methods that do not start with '_') which have", "// 'callback' as last parameter are qualified for thunkification.", "return", "(", "/", "^[^_]", "/", ".", "test", "(", "name", ")", "&&", "/", "function.*\\(.*,?.*callback\\)", "/", ".", "test", "(", "funcStr", ")", ")", ";", "}" ]
Given method name and its function, determine if it qualifies for thunkification. @param {String} name Method name. @param {Function} func Function object for the method. @return {Boolean} True if the method is qualified for thunkification.
[ "Given", "method", "name", "and", "its", "function", "determine", "if", "it", "qualifies", "for", "thunkification", "." ]
1937f289a18d4a7ea8cdeac03c245a6a56d9f590
https://github.com/yaru22/co-couchbase/blob/1937f289a18d4a7ea8cdeac03c245a6a56d9f590/lib/util.js#L9-L15
54,970
ValeriiVasin/grunt-node-deploy
tasks/deployHelper.js
registerUserTasks
function registerUserTasks() { var tasks = options.tasks, task = that.task.bind(that), before = that.before.bind(that), after = that.after.bind(that), taskName; // register user tasks for (taskName in tasks) { if ( tasks.hasOwnProperty(taskName) ) { task(taskName, tasks[taskName]); } } // register predefined user tasks order before('deploy', 'beforeDeploy'); before('updateCode', 'beforeUpdateCode'); after('updateCode', 'afterUpdateCode'); before('npm', 'beforeNpm'); after('npm', 'afterNpm'); before('createSymlink', 'beforeCreateSymlink'); after('createSymlink', 'afterCreateSymlink'); before('restart', 'beforeRestart'); after('restart', 'afterRestart'); after('deploy', 'afterDeploy'); }
javascript
function registerUserTasks() { var tasks = options.tasks, task = that.task.bind(that), before = that.before.bind(that), after = that.after.bind(that), taskName; // register user tasks for (taskName in tasks) { if ( tasks.hasOwnProperty(taskName) ) { task(taskName, tasks[taskName]); } } // register predefined user tasks order before('deploy', 'beforeDeploy'); before('updateCode', 'beforeUpdateCode'); after('updateCode', 'afterUpdateCode'); before('npm', 'beforeNpm'); after('npm', 'afterNpm'); before('createSymlink', 'beforeCreateSymlink'); after('createSymlink', 'afterCreateSymlink'); before('restart', 'beforeRestart'); after('restart', 'afterRestart'); after('deploy', 'afterDeploy'); }
[ "function", "registerUserTasks", "(", ")", "{", "var", "tasks", "=", "options", ".", "tasks", ",", "task", "=", "that", ".", "task", ".", "bind", "(", "that", ")", ",", "before", "=", "that", ".", "before", ".", "bind", "(", "that", ")", ",", "after", "=", "that", ".", "after", ".", "bind", "(", "that", ")", ",", "taskName", ";", "// register user tasks", "for", "(", "taskName", "in", "tasks", ")", "{", "if", "(", "tasks", ".", "hasOwnProperty", "(", "taskName", ")", ")", "{", "task", "(", "taskName", ",", "tasks", "[", "taskName", "]", ")", ";", "}", "}", "// register predefined user tasks order", "before", "(", "'deploy'", ",", "'beforeDeploy'", ")", ";", "before", "(", "'updateCode'", ",", "'beforeUpdateCode'", ")", ";", "after", "(", "'updateCode'", ",", "'afterUpdateCode'", ")", ";", "before", "(", "'npm'", ",", "'beforeNpm'", ")", ";", "after", "(", "'npm'", ",", "'afterNpm'", ")", ";", "before", "(", "'createSymlink'", ",", "'beforeCreateSymlink'", ")", ";", "after", "(", "'createSymlink'", ",", "'afterCreateSymlink'", ")", ";", "before", "(", "'restart'", ",", "'beforeRestart'", ")", ";", "after", "(", "'restart'", ",", "'afterRestart'", ")", ";", "after", "(", "'deploy'", ",", "'afterDeploy'", ")", ";", "}" ]
Register user-callbacks defined tasks
[ "Register", "user", "-", "callbacks", "defined", "tasks" ]
74304c4954732602494b555d98fe359c57b71887
https://github.com/ValeriiVasin/grunt-node-deploy/blob/74304c4954732602494b555d98fe359c57b71887/tasks/deployHelper.js#L149-L179
54,971
mrwest808/johan
src/object/proto.js
combine
function combine(...objects) { inv(Array.isArray(objects) && objects.length > 0, 'You must pass at least one object to instantiate' ); inv(objects.every(isObj), 'Expecting only plain objects as parameter(s)' ); return assign({}, ...objects); }
javascript
function combine(...objects) { inv(Array.isArray(objects) && objects.length > 0, 'You must pass at least one object to instantiate' ); inv(objects.every(isObj), 'Expecting only plain objects as parameter(s)' ); return assign({}, ...objects); }
[ "function", "combine", "(", "...", "objects", ")", "{", "inv", "(", "Array", ".", "isArray", "(", "objects", ")", "&&", "objects", ".", "length", ">", "0", ",", "'You must pass at least one object to instantiate'", ")", ";", "inv", "(", "objects", ".", "every", "(", "isObj", ")", ",", "'Expecting only plain objects as parameter(s)'", ")", ";", "return", "assign", "(", "{", "}", ",", "...", "objects", ")", ";", "}" ]
Assign one or more objects. @param {...Object} ...objects @return {Object}
[ "Assign", "one", "or", "more", "objects", "." ]
9e2bf0c1c924ec548d8f648e8a3a50e6fe3fa15b
https://github.com/mrwest808/johan/blob/9e2bf0c1c924ec548d8f648e8a3a50e6fe3fa15b/src/object/proto.js#L14-L24
54,972
Pocketbrain/native-ads-web-ad-library
src/adConfiguration/fetchConfiguration.js
fetchConfiguration
function fetchConfiguration(environment, applicationId, callback) { if(!applicationId) { logger.error("No application ID specified"); return; } var deviceDetails = deviceDetector.getDeviceDetails(); var pathname = environment.getPathname(); var formFactor = deviceDetails.formFactor; var requestUrl = ""; var queryParams = {}; if (appSettings.overrides && appSettings.overrides.configFileLocation) { requestUrl = appSettings.overrides.configFileLocation; }else{ requestUrl = appSettings.configurationsApiUrl; queryParams = { path: pathname, device: formFactor, "application_id":applicationId }; } ajax.get({ url: requestUrl, query: queryParams, success: function (data) { if (appSettings.overrides && appSettings.overrides.configFileLocation){ callback(null, data.adUnits); }else{ callback(null, data); } }, error: function (err) { callback(err, null); } }); }
javascript
function fetchConfiguration(environment, applicationId, callback) { if(!applicationId) { logger.error("No application ID specified"); return; } var deviceDetails = deviceDetector.getDeviceDetails(); var pathname = environment.getPathname(); var formFactor = deviceDetails.formFactor; var requestUrl = ""; var queryParams = {}; if (appSettings.overrides && appSettings.overrides.configFileLocation) { requestUrl = appSettings.overrides.configFileLocation; }else{ requestUrl = appSettings.configurationsApiUrl; queryParams = { path: pathname, device: formFactor, "application_id":applicationId }; } ajax.get({ url: requestUrl, query: queryParams, success: function (data) { if (appSettings.overrides && appSettings.overrides.configFileLocation){ callback(null, data.adUnits); }else{ callback(null, data); } }, error: function (err) { callback(err, null); } }); }
[ "function", "fetchConfiguration", "(", "environment", ",", "applicationId", ",", "callback", ")", "{", "if", "(", "!", "applicationId", ")", "{", "logger", ".", "error", "(", "\"No application ID specified\"", ")", ";", "return", ";", "}", "var", "deviceDetails", "=", "deviceDetector", ".", "getDeviceDetails", "(", ")", ";", "var", "pathname", "=", "environment", ".", "getPathname", "(", ")", ";", "var", "formFactor", "=", "deviceDetails", ".", "formFactor", ";", "var", "requestUrl", "=", "\"\"", ";", "var", "queryParams", "=", "{", "}", ";", "if", "(", "appSettings", ".", "overrides", "&&", "appSettings", ".", "overrides", ".", "configFileLocation", ")", "{", "requestUrl", "=", "appSettings", ".", "overrides", ".", "configFileLocation", ";", "}", "else", "{", "requestUrl", "=", "appSettings", ".", "configurationsApiUrl", ";", "queryParams", "=", "{", "path", ":", "pathname", ",", "device", ":", "formFactor", ",", "\"application_id\"", ":", "applicationId", "}", ";", "}", "ajax", ".", "get", "(", "{", "url", ":", "requestUrl", ",", "query", ":", "queryParams", ",", "success", ":", "function", "(", "data", ")", "{", "if", "(", "appSettings", ".", "overrides", "&&", "appSettings", ".", "overrides", ".", "configFileLocation", ")", "{", "callback", "(", "null", ",", "data", ".", "adUnits", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "data", ")", ";", "}", "}", ",", "error", ":", "function", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Fetch the ad configurations to load on the current page from the server @param environment - The environment specific implementations @param applicationId - The applicationId to fetch ad configurations for @param callback - The callback to execute when the configurations are retrieved
[ "Fetch", "the", "ad", "configurations", "to", "load", "on", "the", "current", "page", "from", "the", "server" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/adConfiguration/fetchConfiguration.js#L16-L55
54,973
evaisse/jsonconsole
jsonconsole.js
write
function write(src, lvl, obj) { var stack = null; var lvlInt = levels[lvl]; var msg; if ( typeof process.env.LOG_LEVEL == "string" && levels[process.env.LOG_LEVEL.toLowerCase()] > lvlInt) { return false; } if (process.env.JSONCONSOLE_DISABLE_JSON_OUTPUT) { return src.write(util.format(obj)+os.EOL); } if (lvlInt >= 40) { if (obj instanceof Error) { stack = obj.stack; } else { stack = new Error().stack.split("\n"); stack.splice(1, 4); // obfuscate the trace inside the logger. stack = stack.join('\n'); } } if (obj instanceof RawValue) { msg = util.inspect(obj.raw); } else if (typeof obj == "string") { msg = obj; } else { msg = util.inspect(obj); } var log = { name: options.name, hostname, pid: process.pid, level: lvlInt, msg: msg, time: options.localDate ? formatLocalDate() : new Date().toISOString(), src: getCaller3Info(), levelName: levelNames[lvlInt], }; if (obj instanceof RawValue) { log.raw = obj.raw; } stack = stack && options.root ? stack.replace(new RegExp(options.root, 'g'), '{root}') : stack; if (stack) { log.stack = stack; } log.v = options.v; log.src.r = options.root; return src.write(JSON.stringify(log) + os.EOL); }
javascript
function write(src, lvl, obj) { var stack = null; var lvlInt = levels[lvl]; var msg; if ( typeof process.env.LOG_LEVEL == "string" && levels[process.env.LOG_LEVEL.toLowerCase()] > lvlInt) { return false; } if (process.env.JSONCONSOLE_DISABLE_JSON_OUTPUT) { return src.write(util.format(obj)+os.EOL); } if (lvlInt >= 40) { if (obj instanceof Error) { stack = obj.stack; } else { stack = new Error().stack.split("\n"); stack.splice(1, 4); // obfuscate the trace inside the logger. stack = stack.join('\n'); } } if (obj instanceof RawValue) { msg = util.inspect(obj.raw); } else if (typeof obj == "string") { msg = obj; } else { msg = util.inspect(obj); } var log = { name: options.name, hostname, pid: process.pid, level: lvlInt, msg: msg, time: options.localDate ? formatLocalDate() : new Date().toISOString(), src: getCaller3Info(), levelName: levelNames[lvlInt], }; if (obj instanceof RawValue) { log.raw = obj.raw; } stack = stack && options.root ? stack.replace(new RegExp(options.root, 'g'), '{root}') : stack; if (stack) { log.stack = stack; } log.v = options.v; log.src.r = options.root; return src.write(JSON.stringify(log) + os.EOL); }
[ "function", "write", "(", "src", ",", "lvl", ",", "obj", ")", "{", "var", "stack", "=", "null", ";", "var", "lvlInt", "=", "levels", "[", "lvl", "]", ";", "var", "msg", ";", "if", "(", "typeof", "process", ".", "env", ".", "LOG_LEVEL", "==", "\"string\"", "&&", "levels", "[", "process", ".", "env", ".", "LOG_LEVEL", ".", "toLowerCase", "(", ")", "]", ">", "lvlInt", ")", "{", "return", "false", ";", "}", "if", "(", "process", ".", "env", ".", "JSONCONSOLE_DISABLE_JSON_OUTPUT", ")", "{", "return", "src", ".", "write", "(", "util", ".", "format", "(", "obj", ")", "+", "os", ".", "EOL", ")", ";", "}", "if", "(", "lvlInt", ">=", "40", ")", "{", "if", "(", "obj", "instanceof", "Error", ")", "{", "stack", "=", "obj", ".", "stack", ";", "}", "else", "{", "stack", "=", "new", "Error", "(", ")", ".", "stack", ".", "split", "(", "\"\\n\"", ")", ";", "stack", ".", "splice", "(", "1", ",", "4", ")", ";", "// obfuscate the trace inside the logger.", "stack", "=", "stack", ".", "join", "(", "'\\n'", ")", ";", "}", "}", "if", "(", "obj", "instanceof", "RawValue", ")", "{", "msg", "=", "util", ".", "inspect", "(", "obj", ".", "raw", ")", ";", "}", "else", "if", "(", "typeof", "obj", "==", "\"string\"", ")", "{", "msg", "=", "obj", ";", "}", "else", "{", "msg", "=", "util", ".", "inspect", "(", "obj", ")", ";", "}", "var", "log", "=", "{", "name", ":", "options", ".", "name", ",", "hostname", ",", "pid", ":", "process", ".", "pid", ",", "level", ":", "lvlInt", ",", "msg", ":", "msg", ",", "time", ":", "options", ".", "localDate", "?", "formatLocalDate", "(", ")", ":", "new", "Date", "(", ")", ".", "toISOString", "(", ")", ",", "src", ":", "getCaller3Info", "(", ")", ",", "levelName", ":", "levelNames", "[", "lvlInt", "]", ",", "}", ";", "if", "(", "obj", "instanceof", "RawValue", ")", "{", "log", ".", "raw", "=", "obj", ".", "raw", ";", "}", "stack", "=", "stack", "&&", "options", ".", "root", "?", "stack", ".", "replace", "(", "new", "RegExp", "(", "options", ".", "root", ",", "'g'", ")", ",", "'{root}'", ")", ":", "stack", ";", "if", "(", "stack", ")", "{", "log", ".", "stack", "=", "stack", ";", "}", "log", ".", "v", "=", "options", ".", "v", ";", "log", ".", "src", ".", "r", "=", "options", ".", "root", ";", "return", "src", ".", "write", "(", "JSON", ".", "stringify", "(", "log", ")", "+", "os", ".", "EOL", ")", ";", "}" ]
Write JSON log line to stderr & stdout @param {Stream} src stderr or stdout @param {String} lvl a given string level by calling console.{level}() @param {Object} obj Any object that will be filtered @return {Boolean} false if logging has aborted
[ "Write", "JSON", "log", "line", "to", "stderr", "&", "stdout" ]
d5b29d44542d4e276d1660fdda0c6b47436b5774
https://github.com/evaisse/jsonconsole/blob/d5b29d44542d4e276d1660fdda0c6b47436b5774/jsonconsole.js#L92-L151
54,974
evaisse/jsonconsole
jsonconsole.js
replace
function replace() { if (!isOriginal) return; else isOriginal = false; function replaceWith(fn) { return function() { /* eslint prefer-rest-params:0 */ // todo: once node v4 support dropped, use rest parameter instead fn.apply(logger, Array.from(arguments)); }; } ['log', 'debug', 'info', 'warn', 'error'].forEach((lvl) => { console[lvl] = function() { Array.prototype.slice.call(arguments).forEach((arg) => { write(lvl == "error" ? process.stderr : process.stdout, lvl, arg); }); }; }); }
javascript
function replace() { if (!isOriginal) return; else isOriginal = false; function replaceWith(fn) { return function() { /* eslint prefer-rest-params:0 */ // todo: once node v4 support dropped, use rest parameter instead fn.apply(logger, Array.from(arguments)); }; } ['log', 'debug', 'info', 'warn', 'error'].forEach((lvl) => { console[lvl] = function() { Array.prototype.slice.call(arguments).forEach((arg) => { write(lvl == "error" ? process.stderr : process.stdout, lvl, arg); }); }; }); }
[ "function", "replace", "(", ")", "{", "if", "(", "!", "isOriginal", ")", "return", ";", "else", "isOriginal", "=", "false", ";", "function", "replaceWith", "(", "fn", ")", "{", "return", "function", "(", ")", "{", "/* eslint prefer-rest-params:0 */", "// todo: once node v4 support dropped, use rest parameter instead", "fn", ".", "apply", "(", "logger", ",", "Array", ".", "from", "(", "arguments", ")", ")", ";", "}", ";", "}", "[", "'log'", ",", "'debug'", ",", "'info'", ",", "'warn'", ",", "'error'", "]", ".", "forEach", "(", "(", "lvl", ")", "=>", "{", "console", "[", "lvl", "]", "=", "function", "(", ")", "{", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ".", "forEach", "(", "(", "arg", ")", "=>", "{", "write", "(", "lvl", "==", "\"error\"", "?", "process", ".", "stderr", ":", "process", ".", "stdout", ",", "lvl", ",", "arg", ")", ";", "}", ")", ";", "}", ";", "}", ")", ";", "}" ]
Replace global console api
[ "Replace", "global", "console", "api" ]
d5b29d44542d4e276d1660fdda0c6b47436b5774
https://github.com/evaisse/jsonconsole/blob/d5b29d44542d4e276d1660fdda0c6b47436b5774/jsonconsole.js#L165-L186
54,975
evaisse/jsonconsole
jsonconsole.js
restore
function restore() { if (isOriginal) return; else isOriginal = true; ['log', 'debug', 'info', 'warn', 'error'].forEach((item) => { console[item] = originalConsoleFunctions[item]; }); }
javascript
function restore() { if (isOriginal) return; else isOriginal = true; ['log', 'debug', 'info', 'warn', 'error'].forEach((item) => { console[item] = originalConsoleFunctions[item]; }); }
[ "function", "restore", "(", ")", "{", "if", "(", "isOriginal", ")", "return", ";", "else", "isOriginal", "=", "true", ";", "[", "'log'", ",", "'debug'", ",", "'info'", ",", "'warn'", ",", "'error'", "]", ".", "forEach", "(", "(", "item", ")", "=>", "{", "console", "[", "item", "]", "=", "originalConsoleFunctions", "[", "item", "]", ";", "}", ")", ";", "}" ]
Restore original console api
[ "Restore", "original", "console", "api" ]
d5b29d44542d4e276d1660fdda0c6b47436b5774
https://github.com/evaisse/jsonconsole/blob/d5b29d44542d4e276d1660fdda0c6b47436b5774/jsonconsole.js#L191-L197
54,976
evaisse/jsonconsole
jsonconsole.js
setup
function setup(userOptions) { Object.assign(options, userOptions); /* Try to automatically grab the app name from the root directory */ if (!options.root) { try { var p = require(path.dirname(process.mainModule.filename) + '/package.json'); options.root = path.dirname(process.mainModule.filename); options.name = p.name; } catch (e) { options.root = null; } } if (options.root && !options.name) { try { var p = require(options.root + '/package.json'); options.name = p.name; } catch (e) { } } /* In production mode, define default log threshold to info */ if (process.env.LOG_LEVEL === undefined && process.env.NODE_ENV === "production") { process.env.LOG_LEVEL = "info"; } options.name = options.name || "."; replace(); return restore; }
javascript
function setup(userOptions) { Object.assign(options, userOptions); /* Try to automatically grab the app name from the root directory */ if (!options.root) { try { var p = require(path.dirname(process.mainModule.filename) + '/package.json'); options.root = path.dirname(process.mainModule.filename); options.name = p.name; } catch (e) { options.root = null; } } if (options.root && !options.name) { try { var p = require(options.root + '/package.json'); options.name = p.name; } catch (e) { } } /* In production mode, define default log threshold to info */ if (process.env.LOG_LEVEL === undefined && process.env.NODE_ENV === "production") { process.env.LOG_LEVEL = "info"; } options.name = options.name || "."; replace(); return restore; }
[ "function", "setup", "(", "userOptions", ")", "{", "Object", ".", "assign", "(", "options", ",", "userOptions", ")", ";", "/*\n Try to automatically grab the app name from the root directory\n */", "if", "(", "!", "options", ".", "root", ")", "{", "try", "{", "var", "p", "=", "require", "(", "path", ".", "dirname", "(", "process", ".", "mainModule", ".", "filename", ")", "+", "'/package.json'", ")", ";", "options", ".", "root", "=", "path", ".", "dirname", "(", "process", ".", "mainModule", ".", "filename", ")", ";", "options", ".", "name", "=", "p", ".", "name", ";", "}", "catch", "(", "e", ")", "{", "options", ".", "root", "=", "null", ";", "}", "}", "if", "(", "options", ".", "root", "&&", "!", "options", ".", "name", ")", "{", "try", "{", "var", "p", "=", "require", "(", "options", ".", "root", "+", "'/package.json'", ")", ";", "options", ".", "name", "=", "p", ".", "name", ";", "}", "catch", "(", "e", ")", "{", "}", "}", "/*\n In production mode, define default log threshold to info\n */", "if", "(", "process", ".", "env", ".", "LOG_LEVEL", "===", "undefined", "&&", "process", ".", "env", ".", "NODE_ENV", "===", "\"production\"", ")", "{", "process", ".", "env", ".", "LOG_LEVEL", "=", "\"info\"", ";", "}", "options", ".", "name", "=", "options", ".", "name", "||", "\".\"", ";", "replace", "(", ")", ";", "return", "restore", ";", "}" ]
Setup JSON console @param {Object} userOptions [description] @return {Function} a restore function that restore the behavior of classic console
[ "Setup", "JSON", "console" ]
d5b29d44542d4e276d1660fdda0c6b47436b5774
https://github.com/evaisse/jsonconsole/blob/d5b29d44542d4e276d1660fdda0c6b47436b5774/jsonconsole.js#L206-L241
54,977
phated/grunt-enyo
tasks/init/enyo/root/enyo/source/touch/TranslateScrollStrategy.js
function(inX, inY) { var o = inX + "px, " + inY + "px" + (this.accel ? ",0" : ""); enyo.dom.transformValue(this.$.client, this.translation, o); }
javascript
function(inX, inY) { var o = inX + "px, " + inY + "px" + (this.accel ? ",0" : ""); enyo.dom.transformValue(this.$.client, this.translation, o); }
[ "function", "(", "inX", ",", "inY", ")", "{", "var", "o", "=", "inX", "+", "\"px, \"", "+", "inY", "+", "\"px\"", "+", "(", "this", ".", "accel", "?", "\",0\"", ":", "\"\"", ")", ";", "enyo", ".", "dom", ".", "transformValue", "(", "this", ".", "$", ".", "client", ",", "this", ".", "translation", ",", "o", ")", ";", "}" ]
While moving, scroller uses translate.
[ "While", "moving", "scroller", "uses", "translate", "." ]
d2990ee4cd85eea8db4108c43086c6d8c3c90c30
https://github.com/phated/grunt-enyo/blob/d2990ee4cd85eea8db4108c43086c6d8c3c90c30/tasks/init/enyo/root/enyo/source/touch/TranslateScrollStrategy.js#L109-L112
54,978
bredele/deus
index.js
deus
function deus(one, two, fn) { var types = [one, two]; var type = function(args, arg) { var idx = index(types, typeof arg); if(idx > -1 && !args[idx]) args[idx] = arg; else if(arg) args.splice(args.length, 0, arg); }; return function() { var args = [,,]; for(var i = 0, l = arguments.length; i < l; i++) { type(args, arguments[i]); } return fn.apply(this, args); }; }
javascript
function deus(one, two, fn) { var types = [one, two]; var type = function(args, arg) { var idx = index(types, typeof arg); if(idx > -1 && !args[idx]) args[idx] = arg; else if(arg) args.splice(args.length, 0, arg); }; return function() { var args = [,,]; for(var i = 0, l = arguments.length; i < l; i++) { type(args, arguments[i]); } return fn.apply(this, args); }; }
[ "function", "deus", "(", "one", ",", "two", ",", "fn", ")", "{", "var", "types", "=", "[", "one", ",", "two", "]", ";", "var", "type", "=", "function", "(", "args", ",", "arg", ")", "{", "var", "idx", "=", "index", "(", "types", ",", "typeof", "arg", ")", ";", "if", "(", "idx", ">", "-", "1", "&&", "!", "args", "[", "idx", "]", ")", "args", "[", "idx", "]", "=", "arg", ";", "else", "if", "(", "arg", ")", "args", ".", "splice", "(", "args", ".", "length", ",", "0", ",", "arg", ")", ";", "}", ";", "return", "function", "(", ")", "{", "var", "args", "=", "[", ",", ",", "]", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "arguments", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "type", "(", "args", ",", "arguments", "[", "i", "]", ")", ";", "}", "return", "fn", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ";", "}" ]
Make two arguments function flexible. @param {String} one @param {String} two @return {Function} @api public
[ "Make", "two", "arguments", "function", "flexible", "." ]
4d6ff76f6e5d2b73361556ab93bbb186729974ea
https://github.com/bredele/deus/blob/4d6ff76f6e5d2b73361556ab93bbb186729974ea/index.js#L26-L41
54,979
wshager/l3n
lib/doc.js
ensureDoc
function ensureDoc($node) { // FIXME if isVNode(node) use cx on node var cx = (0, _vnode.getContext)(this, inode); return (0, _just.default)($node).pipe((0, _operators.concatMap)(function (node) { if (!(0, _vnode.isVNode)(node)) { var type = cx.getType(node); if (type == 9 || type == 11) { var root = cx.first(node); return (0, _just.default)(cx.vnode(root, cx.vnode(node), 1, 0)); } else { // create a document-fragment by default! var doc = t.bind(cx)(); var _root = cx.vnode(node, doc, 1, 0); return (0, _just.default)(doc).pipe((0, _operators.concatMap)(function (doc) { doc = doc.push([0, _root.node]); var next = doc.first(); return next ? (0, _just.default)(doc.vnode(next, doc, doc.depth + 1, 0)) : (0, _just.default)(); })); } } if (typeof node.node === "function") { // NOTE never bind to current node.cx, but purposely allow cross-binding return (0, _just.default)(t.bind(cx)(node)).pipe((0, _operators.concatMap)(function (node) { var next = node.first(); return next ? (0, _just.default)(node.vnode(next, node, node.depth + 1, 0)) : (0, _just.default)(); })); } return (0, _just.default)(node); })); }
javascript
function ensureDoc($node) { // FIXME if isVNode(node) use cx on node var cx = (0, _vnode.getContext)(this, inode); return (0, _just.default)($node).pipe((0, _operators.concatMap)(function (node) { if (!(0, _vnode.isVNode)(node)) { var type = cx.getType(node); if (type == 9 || type == 11) { var root = cx.first(node); return (0, _just.default)(cx.vnode(root, cx.vnode(node), 1, 0)); } else { // create a document-fragment by default! var doc = t.bind(cx)(); var _root = cx.vnode(node, doc, 1, 0); return (0, _just.default)(doc).pipe((0, _operators.concatMap)(function (doc) { doc = doc.push([0, _root.node]); var next = doc.first(); return next ? (0, _just.default)(doc.vnode(next, doc, doc.depth + 1, 0)) : (0, _just.default)(); })); } } if (typeof node.node === "function") { // NOTE never bind to current node.cx, but purposely allow cross-binding return (0, _just.default)(t.bind(cx)(node)).pipe((0, _operators.concatMap)(function (node) { var next = node.first(); return next ? (0, _just.default)(node.vnode(next, node, node.depth + 1, 0)) : (0, _just.default)(); })); } return (0, _just.default)(node); })); }
[ "function", "ensureDoc", "(", "$node", ")", "{", "// FIXME if isVNode(node) use cx on node", "var", "cx", "=", "(", "0", ",", "_vnode", ".", "getContext", ")", "(", "this", ",", "inode", ")", ";", "return", "(", "0", ",", "_just", ".", "default", ")", "(", "$node", ")", ".", "pipe", "(", "(", "0", ",", "_operators", ".", "concatMap", ")", "(", "function", "(", "node", ")", "{", "if", "(", "!", "(", "0", ",", "_vnode", ".", "isVNode", ")", "(", "node", ")", ")", "{", "var", "type", "=", "cx", ".", "getType", "(", "node", ")", ";", "if", "(", "type", "==", "9", "||", "type", "==", "11", ")", "{", "var", "root", "=", "cx", ".", "first", "(", "node", ")", ";", "return", "(", "0", ",", "_just", ".", "default", ")", "(", "cx", ".", "vnode", "(", "root", ",", "cx", ".", "vnode", "(", "node", ")", ",", "1", ",", "0", ")", ")", ";", "}", "else", "{", "// create a document-fragment by default!", "var", "doc", "=", "t", ".", "bind", "(", "cx", ")", "(", ")", ";", "var", "_root", "=", "cx", ".", "vnode", "(", "node", ",", "doc", ",", "1", ",", "0", ")", ";", "return", "(", "0", ",", "_just", ".", "default", ")", "(", "doc", ")", ".", "pipe", "(", "(", "0", ",", "_operators", ".", "concatMap", ")", "(", "function", "(", "doc", ")", "{", "doc", "=", "doc", ".", "push", "(", "[", "0", ",", "_root", ".", "node", "]", ")", ";", "var", "next", "=", "doc", ".", "first", "(", ")", ";", "return", "next", "?", "(", "0", ",", "_just", ".", "default", ")", "(", "doc", ".", "vnode", "(", "next", ",", "doc", ",", "doc", ".", "depth", "+", "1", ",", "0", ")", ")", ":", "(", "0", ",", "_just", ".", "default", ")", "(", ")", ";", "}", ")", ")", ";", "}", "}", "if", "(", "typeof", "node", ".", "node", "===", "\"function\"", ")", "{", "// NOTE never bind to current node.cx, but purposely allow cross-binding", "return", "(", "0", ",", "_just", ".", "default", ")", "(", "t", ".", "bind", "(", "cx", ")", "(", "node", ")", ")", ".", "pipe", "(", "(", "0", ",", "_operators", ".", "concatMap", ")", "(", "function", "(", "node", ")", "{", "var", "next", "=", "node", ".", "first", "(", ")", ";", "return", "next", "?", "(", "0", ",", "_just", ".", "default", ")", "(", "node", ".", "vnode", "(", "next", ",", "node", ",", "node", ".", "depth", "+", "1", ",", "0", ")", ")", ":", "(", "0", ",", "_just", ".", "default", ")", "(", ")", ";", "}", ")", ")", ";", "}", "return", "(", "0", ",", "_just", ".", "default", ")", "(", "node", ")", ";", "}", ")", ")", ";", "}" ]
Document-related functions @module doc Wraps a document into a document-fragment if it doesn't have a document root @param {any} $node Observable, VNode or any kind of node mathing the provided document implementation context @return {Observable} Observable yielding a single VNode
[ "Document", "-", "related", "functions" ]
700496b9172a29efb3864eae920744d08acb1dc8
https://github.com/wshager/l3n/blob/700496b9172a29efb3864eae920744d08acb1dc8/lib/doc.js#L35-L69
54,980
tjhart/broccoli-tree-to-json
index.js
Tree2Json
function Tree2Json(inputTree) { if (!(this instanceof Tree2Json)) return new Tree2Json(inputTree); this.inputTree = inputTree.replace(/\/$/, ''); this.walker = new TreeTraverser(inputTree, this); }
javascript
function Tree2Json(inputTree) { if (!(this instanceof Tree2Json)) return new Tree2Json(inputTree); this.inputTree = inputTree.replace(/\/$/, ''); this.walker = new TreeTraverser(inputTree, this); }
[ "function", "Tree2Json", "(", "inputTree", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Tree2Json", ")", ")", "return", "new", "Tree2Json", "(", "inputTree", ")", ";", "this", ".", "inputTree", "=", "inputTree", ".", "replace", "(", "/", "\\/$", "/", ",", "''", ")", ";", "this", ".", "walker", "=", "new", "TreeTraverser", "(", "inputTree", ",", "this", ")", ";", "}" ]
Take an input tree, and roll it up into a JSON document. The resulting document will be named `srcDir.json`. it will have key names associated with each of the file and directories that `srcDir` contains. If the key represents the file, then the stringified file contents will be the value of the key. If the key represents a directory, then the value of that key will be an `Object`, represented by the same algorithm @param inputTree {string} - relative path to source tree @return {Tree2Json} @constructor @alias module:index
[ "Take", "an", "input", "tree", "and", "roll", "it", "up", "into", "a", "JSON", "document", ".", "The", "resulting", "document", "will", "be", "named", "srcDir", ".", "json", ".", "it", "will", "have", "key", "names", "associated", "with", "each", "of", "the", "file", "and", "directories", "that", "srcDir", "contains", ".", "If", "the", "key", "represents", "the", "file", "then", "the", "stringified", "file", "contents", "will", "be", "the", "value", "of", "the", "key", ".", "If", "the", "key", "represents", "a", "directory", "then", "the", "value", "of", "that", "key", "will", "be", "an", "Object", "represented", "by", "the", "same", "algorithm" ]
d8e069f35d626a7c86d9857cc45462a7d5c72b97
https://github.com/tjhart/broccoli-tree-to-json/blob/d8e069f35d626a7c86d9857cc45462a7d5c72b97/index.js#L23-L28
54,981
pwstegman/pw-stat
index.js
cov
function cov(x) { // Useful variables let N = x.length; // Step 1: Find expected value for each variable (columns are variables, rows are samples) let E = []; for (let c = 0; c < x[0].length; c++) { let u = 0; for (let r = 0; r < N; r++) { u += x[r][c]; } E.push(u / N); } // Step 2: Center each variable at 0 let centered = []; for (let r = 0; r < N; r++) { centered.push([]); for (let c = 0; c < x[0].length; c++) { centered[r].push(x[r][c] - E[c]); } } // Step 3: Calculate covariance between each possible combination of variables let S = []; for (let i = 0; i < x[0].length; i++) { S.push([]); } for (let c1 = 0; c1 < x[0].length; c1++) { // Doing c2 = c1; because, for example, cov(1,2) = cov(2, 1) // so no need to recalculate for (let c2 = c1; c2 < x[0].length; c2++) { // Solve cov(c1, c2) = average of elementwise products of each variable sample let cov = 0; for (let r = 0; r < N; r++) { cov += centered[r][c1] * centered[r][c2]; } cov /= (N - 1); // N-1 for sample covariance, N for population. In this case, using sample covariance S[c1][c2] = cov; S[c2][c1] = cov; // Matrix is symmetric } } return S; }
javascript
function cov(x) { // Useful variables let N = x.length; // Step 1: Find expected value for each variable (columns are variables, rows are samples) let E = []; for (let c = 0; c < x[0].length; c++) { let u = 0; for (let r = 0; r < N; r++) { u += x[r][c]; } E.push(u / N); } // Step 2: Center each variable at 0 let centered = []; for (let r = 0; r < N; r++) { centered.push([]); for (let c = 0; c < x[0].length; c++) { centered[r].push(x[r][c] - E[c]); } } // Step 3: Calculate covariance between each possible combination of variables let S = []; for (let i = 0; i < x[0].length; i++) { S.push([]); } for (let c1 = 0; c1 < x[0].length; c1++) { // Doing c2 = c1; because, for example, cov(1,2) = cov(2, 1) // so no need to recalculate for (let c2 = c1; c2 < x[0].length; c2++) { // Solve cov(c1, c2) = average of elementwise products of each variable sample let cov = 0; for (let r = 0; r < N; r++) { cov += centered[r][c1] * centered[r][c2]; } cov /= (N - 1); // N-1 for sample covariance, N for population. In this case, using sample covariance S[c1][c2] = cov; S[c2][c1] = cov; // Matrix is symmetric } } return S; }
[ "function", "cov", "(", "x", ")", "{", "// Useful variables", "let", "N", "=", "x", ".", "length", ";", "// Step 1: Find expected value for each variable (columns are variables, rows are samples)", "let", "E", "=", "[", "]", ";", "for", "(", "let", "c", "=", "0", ";", "c", "<", "x", "[", "0", "]", ".", "length", ";", "c", "++", ")", "{", "let", "u", "=", "0", ";", "for", "(", "let", "r", "=", "0", ";", "r", "<", "N", ";", "r", "++", ")", "{", "u", "+=", "x", "[", "r", "]", "[", "c", "]", ";", "}", "E", ".", "push", "(", "u", "/", "N", ")", ";", "}", "// Step 2: Center each variable at 0", "let", "centered", "=", "[", "]", ";", "for", "(", "let", "r", "=", "0", ";", "r", "<", "N", ";", "r", "++", ")", "{", "centered", ".", "push", "(", "[", "]", ")", ";", "for", "(", "let", "c", "=", "0", ";", "c", "<", "x", "[", "0", "]", ".", "length", ";", "c", "++", ")", "{", "centered", "[", "r", "]", ".", "push", "(", "x", "[", "r", "]", "[", "c", "]", "-", "E", "[", "c", "]", ")", ";", "}", "}", "// Step 3: Calculate covariance between each possible combination of variables", "let", "S", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "x", "[", "0", "]", ".", "length", ";", "i", "++", ")", "{", "S", ".", "push", "(", "[", "]", ")", ";", "}", "for", "(", "let", "c1", "=", "0", ";", "c1", "<", "x", "[", "0", "]", ".", "length", ";", "c1", "++", ")", "{", "// Doing c2 = c1; because, for example, cov(1,2) = cov(2, 1)", "// so no need to recalculate", "for", "(", "let", "c2", "=", "c1", ";", "c2", "<", "x", "[", "0", "]", ".", "length", ";", "c2", "++", ")", "{", "// Solve cov(c1, c2) = average of elementwise products of each variable sample", "let", "cov", "=", "0", ";", "for", "(", "let", "r", "=", "0", ";", "r", "<", "N", ";", "r", "++", ")", "{", "cov", "+=", "centered", "[", "r", "]", "[", "c1", "]", "*", "centered", "[", "r", "]", "[", "c2", "]", ";", "}", "cov", "/=", "(", "N", "-", "1", ")", ";", "// N-1 for sample covariance, N for population. In this case, using sample covariance", "S", "[", "c1", "]", "[", "c2", "]", "=", "cov", ";", "S", "[", "c2", "]", "[", "c1", "]", "=", "cov", ";", "// Matrix is symmetric", "}", "}", "return", "S", ";", "}" ]
Returns the covariance matrix for a given matrix. @param {number[][]} x - A matrix where rows are samples and columns are variables.
[ "Returns", "the", "covariance", "matrix", "for", "a", "given", "matrix", "." ]
f0d75c54ae5d9484630b568b8077e8271f4caf38
https://github.com/pwstegman/pw-stat/blob/f0d75c54ae5d9484630b568b8077e8271f4caf38/index.js#L5-L51
54,982
pwstegman/pw-stat
index.js
mean
function mean(x) { let result = []; for(let c = 0; c<x[0].length; c++){ result.push(0); } for (let r = 0; r < x.length; r++) { for(let c = 0; c<x[r].length; c++){ result[c] += x[r][c]; } } for(let c = 0; c<x[0].length; c++){ result[c] /= x.length; } return result; }
javascript
function mean(x) { let result = []; for(let c = 0; c<x[0].length; c++){ result.push(0); } for (let r = 0; r < x.length; r++) { for(let c = 0; c<x[r].length; c++){ result[c] += x[r][c]; } } for(let c = 0; c<x[0].length; c++){ result[c] /= x.length; } return result; }
[ "function", "mean", "(", "x", ")", "{", "let", "result", "=", "[", "]", ";", "for", "(", "let", "c", "=", "0", ";", "c", "<", "x", "[", "0", "]", ".", "length", ";", "c", "++", ")", "{", "result", ".", "push", "(", "0", ")", ";", "}", "for", "(", "let", "r", "=", "0", ";", "r", "<", "x", ".", "length", ";", "r", "++", ")", "{", "for", "(", "let", "c", "=", "0", ";", "c", "<", "x", "[", "r", "]", ".", "length", ";", "c", "++", ")", "{", "result", "[", "c", "]", "+=", "x", "[", "r", "]", "[", "c", "]", ";", "}", "}", "for", "(", "let", "c", "=", "0", ";", "c", "<", "x", "[", "0", "]", ".", "length", ";", "c", "++", ")", "{", "result", "[", "c", "]", "/=", "x", ".", "length", ";", "}", "return", "result", ";", "}" ]
Returns the mean of each column in the provided matrix. @param {number[][]} x - Two-dimensional matrix.
[ "Returns", "the", "mean", "of", "each", "column", "in", "the", "provided", "matrix", "." ]
f0d75c54ae5d9484630b568b8077e8271f4caf38
https://github.com/pwstegman/pw-stat/blob/f0d75c54ae5d9484630b568b8077e8271f4caf38/index.js#L57-L75
54,983
changecoin/changetip-javascript
src/changetip.js
function (config) { config = config || {}; this.api_key = config.api_key; this.host = config.host || undefined; this.api_version = config.api_version || undefined; this.dev_mode = config.dev_mode || false; return this; }
javascript
function (config) { config = config || {}; this.api_key = config.api_key; this.host = config.host || undefined; this.api_version = config.api_version || undefined; this.dev_mode = config.dev_mode || false; return this; }
[ "function", "(", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "this", ".", "api_key", "=", "config", ".", "api_key", ";", "this", ".", "host", "=", "config", ".", "host", "||", "undefined", ";", "this", ".", "api_version", "=", "config", ".", "api_version", "||", "undefined", ";", "this", ".", "dev_mode", "=", "config", ".", "dev_mode", "||", "false", ";", "return", "this", ";", "}" ]
Initializes the class for remote API Calls @param {ChangeTipConfig} config @returns {ChangeTip}
[ "Initializes", "the", "class", "for", "remote", "API", "Calls" ]
093a7abedbdb69e7ffc08236cec001c1630cf5e1
https://github.com/changecoin/changetip-javascript/blob/093a7abedbdb69e7ffc08236cec001c1630cf5e1/src/changetip.js#L86-L93
54,984
changecoin/changetip-javascript
src/changetip.js
function (context_uid, sender, receiver, channel, message, meta) { if (!this.api_key) throw new ChangeTipException(300); if (!channel) throw new ChangeTipException(301); var deferred = Q.defer(), data; data = { context_uid: context_uid, sender: sender, receiver: receiver, channel: channel, message: message, meta: meta }; this._send_request(data, 'tips', null, Methods.POST, deferred); return deferred.promise; }
javascript
function (context_uid, sender, receiver, channel, message, meta) { if (!this.api_key) throw new ChangeTipException(300); if (!channel) throw new ChangeTipException(301); var deferred = Q.defer(), data; data = { context_uid: context_uid, sender: sender, receiver: receiver, channel: channel, message: message, meta: meta }; this._send_request(data, 'tips', null, Methods.POST, deferred); return deferred.promise; }
[ "function", "(", "context_uid", ",", "sender", ",", "receiver", ",", "channel", ",", "message", ",", "meta", ")", "{", "if", "(", "!", "this", ".", "api_key", ")", "throw", "new", "ChangeTipException", "(", "300", ")", ";", "if", "(", "!", "channel", ")", "throw", "new", "ChangeTipException", "(", "301", ")", ";", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ",", "data", ";", "data", "=", "{", "context_uid", ":", "context_uid", ",", "sender", ":", "sender", ",", "receiver", ":", "receiver", ",", "channel", ":", "channel", ",", "message", ":", "message", ",", "meta", ":", "meta", "}", ";", "this", ".", "_send_request", "(", "data", ",", "'tips'", ",", "null", ",", "Methods", ".", "POST", ",", "deferred", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Sends a tip via the ChangeTip API @param context_uid {number|string} Unique ID for this tip @param {number|string} sender username/identifier for the tip sender @param {number|string} receiver username/identifier for the tip receiever @param {string} channel Origin channel for this tip (twitter, github, slack, etc) @param {string} message Tip message. Includes amount or moniker. @param [meta] {Object} optional object to be sent back in result set @returns {promise.promise|jQuery.promise|promise|Q.promise|jQuery.ready.promise|l.promise}
[ "Sends", "a", "tip", "via", "the", "ChangeTip", "API" ]
093a7abedbdb69e7ffc08236cec001c1630cf5e1
https://github.com/changecoin/changetip-javascript/blob/093a7abedbdb69e7ffc08236cec001c1630cf5e1/src/changetip.js#L105-L123
54,985
changecoin/changetip-javascript
src/changetip.js
function (tips, channel) { if (!this.api_key) throw new ChangeTipException(300); var deferred = Q.defer(), params; params = { tips: tips instanceof Array ? tips.join(",") : tips, channel: channel || '' }; this._send_request({}, 'tips', params, Methods.GET, deferred); return deferred.promise; }
javascript
function (tips, channel) { if (!this.api_key) throw new ChangeTipException(300); var deferred = Q.defer(), params; params = { tips: tips instanceof Array ? tips.join(",") : tips, channel: channel || '' }; this._send_request({}, 'tips', params, Methods.GET, deferred); return deferred.promise; }
[ "function", "(", "tips", ",", "channel", ")", "{", "if", "(", "!", "this", ".", "api_key", ")", "throw", "new", "ChangeTipException", "(", "300", ")", ";", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ",", "params", ";", "params", "=", "{", "tips", ":", "tips", "instanceof", "Array", "?", "tips", ".", "join", "(", "\",\"", ")", ":", "tips", ",", "channel", ":", "channel", "||", "''", "}", ";", "this", ".", "_send_request", "(", "{", "}", ",", "'tips'", ",", "params", ",", "Methods", ".", "GET", ",", "deferred", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
Retrieve tips from the ChangeTip API @param {string|string[]} tips Single or collection of tip identifiers to retrieve @param {string} [channel] Channel to filter results. (github, twitter, slack, etc) @returns {promise.promise|jQuery.promise|promise|Q.promise|jQuery.ready.promise|l.promise}
[ "Retrieve", "tips", "from", "the", "ChangeTip", "API" ]
093a7abedbdb69e7ffc08236cec001c1630cf5e1
https://github.com/changecoin/changetip-javascript/blob/093a7abedbdb69e7ffc08236cec001c1630cf5e1/src/changetip.js#L131-L144
54,986
changecoin/changetip-javascript
src/changetip.js
function (data, path, params, method, deferred) { var options, query_params, req, dataString = JSON.stringify(data); query_params = querystring.stringify(params); options = { host: this.host, port: 443, path: '/v' + this.api_version + '/' + path + '/?api_key=' + this.api_key + (query_params ? ('&' + query_params) : ''), method: method, headers: { 'Content-Type': 'application/json', 'Content-Length': dataString.length } }; if (!this.dev_mode) { req = https.request(options, function (res) { res.setEncoding('utf-8'); var response = '', result; res.on('data', function (response_data) { response += response_data; }); res.on('end', function () { result = JSON.parse(response); deferred.resolve(result); }); }); req.write(dataString); req.end(); } else { deferred.resolve({status:"dev_mode", data: data, params: params, path: options.path}); } }
javascript
function (data, path, params, method, deferred) { var options, query_params, req, dataString = JSON.stringify(data); query_params = querystring.stringify(params); options = { host: this.host, port: 443, path: '/v' + this.api_version + '/' + path + '/?api_key=' + this.api_key + (query_params ? ('&' + query_params) : ''), method: method, headers: { 'Content-Type': 'application/json', 'Content-Length': dataString.length } }; if (!this.dev_mode) { req = https.request(options, function (res) { res.setEncoding('utf-8'); var response = '', result; res.on('data', function (response_data) { response += response_data; }); res.on('end', function () { result = JSON.parse(response); deferred.resolve(result); }); }); req.write(dataString); req.end(); } else { deferred.resolve({status:"dev_mode", data: data, params: params, path: options.path}); } }
[ "function", "(", "data", ",", "path", ",", "params", ",", "method", ",", "deferred", ")", "{", "var", "options", ",", "query_params", ",", "req", ",", "dataString", "=", "JSON", ".", "stringify", "(", "data", ")", ";", "query_params", "=", "querystring", ".", "stringify", "(", "params", ")", ";", "options", "=", "{", "host", ":", "this", ".", "host", ",", "port", ":", "443", ",", "path", ":", "'/v'", "+", "this", ".", "api_version", "+", "'/'", "+", "path", "+", "'/?api_key='", "+", "this", ".", "api_key", "+", "(", "query_params", "?", "(", "'&'", "+", "query_params", ")", ":", "''", ")", ",", "method", ":", "method", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/json'", ",", "'Content-Length'", ":", "dataString", ".", "length", "}", "}", ";", "if", "(", "!", "this", ".", "dev_mode", ")", "{", "req", "=", "https", ".", "request", "(", "options", ",", "function", "(", "res", ")", "{", "res", ".", "setEncoding", "(", "'utf-8'", ")", ";", "var", "response", "=", "''", ",", "result", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "response_data", ")", "{", "response", "+=", "response_data", ";", "}", ")", ";", "res", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "result", "=", "JSON", ".", "parse", "(", "response", ")", ";", "deferred", ".", "resolve", "(", "result", ")", ";", "}", ")", ";", "}", ")", ";", "req", ".", "write", "(", "dataString", ")", ";", "req", ".", "end", "(", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", "{", "status", ":", "\"dev_mode\"", ",", "data", ":", "data", ",", "params", ":", "params", ",", "path", ":", "options", ".", "path", "}", ")", ";", "}", "}" ]
Sends a request @param {Object} data JSON Object with data payload @param {String} path API Path @param {Object} params Query Parameters to be sent along with this request @param {Methods} method HTTP Method @param deferred Deferred Object @param deferred.promise Deferred Promise Object @param deferred.resolve Deferred success function @param deferred.reject Deferred rejection function @private
[ "Sends", "a", "request" ]
093a7abedbdb69e7ffc08236cec001c1630cf5e1
https://github.com/changecoin/changetip-javascript/blob/093a7abedbdb69e7ffc08236cec001c1630cf5e1/src/changetip.js#L158-L196
54,987
zouloux/grunt-deployer
tasks/gruntDeployer.js
quickTemplate
function quickTemplate (pTemplate, pValues) { return pTemplate.replace(templateRegex, function(i, pMatch) { return pValues[pMatch]; }); }
javascript
function quickTemplate (pTemplate, pValues) { return pTemplate.replace(templateRegex, function(i, pMatch) { return pValues[pMatch]; }); }
[ "function", "quickTemplate", "(", "pTemplate", ",", "pValues", ")", "{", "return", "pTemplate", ".", "replace", "(", "templateRegex", ",", "function", "(", "i", ",", "pMatch", ")", "{", "return", "pValues", "[", "pMatch", "]", ";", "}", ")", ";", "}" ]
Quick and dirty template method
[ "Quick", "and", "dirty", "template", "method" ]
e9877b8683c5c5344b1738677ad07699ee09d051
https://github.com/zouloux/grunt-deployer/blob/e9877b8683c5c5344b1738677ad07699ee09d051/tasks/gruntDeployer.js#L25-L30
54,988
hpcloud/hpcloud-js
lib/objectstorage/objectinfo.js
ObjectInfo
function ObjectInfo(name, contentType) { this._name = name; this._type = contentType || ObjectInfo.DEFAULT_CONTENT_TYPE; this._partial = false; }
javascript
function ObjectInfo(name, contentType) { this._name = name; this._type = contentType || ObjectInfo.DEFAULT_CONTENT_TYPE; this._partial = false; }
[ "function", "ObjectInfo", "(", "name", ",", "contentType", ")", "{", "this", ".", "_name", "=", "name", ";", "this", ".", "_type", "=", "contentType", "||", "ObjectInfo", ".", "DEFAULT_CONTENT_TYPE", ";", "this", ".", "_partial", "=", "false", ";", "}" ]
Build a new ObjectInfo instance. This represents the data about an object. It is used under the following circumstances: - SAVING: When creating a new object, you declare the object as ObjectInfo. When saving, you will save with an ObjectInfo and a Stream of data. See Container.save(). - LISTING: When calling Container.objects(), a list including ObjectInfo items will be returned. - FETCHING METADATA: Using Container.objectInfo(), you can get just the info about an object, without downloading the entire object. - FETCHING OBJECT: When you fetch the entire object, you will also get the ObjectInfo. See RemoteObject.info(). - UPATING METADATA: When updating just the metadata on an object, you will supply an ObjectInfo object. @class ObjectInfo @constructor @param {String} name The name of the object. @param {String} [contentType] (Optional) The type of content, defaults to Application/X-Octet-Stream.
[ "Build", "a", "new", "ObjectInfo", "instance", "." ]
c457ea3ee6a21e361d1af0af70d64622b6910208
https://github.com/hpcloud/hpcloud-js/blob/c457ea3ee6a21e361d1af0af70d64622b6910208/lib/objectstorage/objectinfo.js#L49-L53
54,989
mazaid/check
examples/functions.js
initCheckApi
function initCheckApi(logger, config) { return new Promise((resolve, reject) => { var check = new Check(logger, config); var promises = []; var checkers = require('mazaid-checkers'); for (var checker of checkers) { promises.push(check.add(checker)); } Promise.all(promises) .then(() => { return check.init(); }) .then(() => { checkApi = check; resolve(); }) .catch((error) => { reject(error); }); }); }
javascript
function initCheckApi(logger, config) { return new Promise((resolve, reject) => { var check = new Check(logger, config); var promises = []; var checkers = require('mazaid-checkers'); for (var checker of checkers) { promises.push(check.add(checker)); } Promise.all(promises) .then(() => { return check.init(); }) .then(() => { checkApi = check; resolve(); }) .catch((error) => { reject(error); }); }); }
[ "function", "initCheckApi", "(", "logger", ",", "config", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "check", "=", "new", "Check", "(", "logger", ",", "config", ")", ";", "var", "promises", "=", "[", "]", ";", "var", "checkers", "=", "require", "(", "'mazaid-checkers'", ")", ";", "for", "(", "var", "checker", "of", "checkers", ")", "{", "promises", ".", "push", "(", "check", ".", "add", "(", "checker", ")", ")", ";", "}", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "(", ")", "=>", "{", "return", "check", ".", "init", "(", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "{", "checkApi", "=", "check", ";", "resolve", "(", ")", ";", "}", ")", ".", "catch", "(", "(", "error", ")", "=>", "{", "reject", "(", "error", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
init check api, add ping checker @return {Promise}
[ "init", "check", "api", "add", "ping", "checker" ]
9bd0f7c5b44b1c996c2c805ae2a3c480c7009409
https://github.com/mazaid/check/blob/9bd0f7c5b44b1c996c2c805ae2a3c480c7009409/examples/functions.js#L19-L45
54,990
mazaid/check
examples/functions.js
runCheckTask
function runCheckTask(logger, checkTask) { return new Promise((resolve, reject) => { // create check task object // raw.id = uuid(); // var checkTask = new CheckTask(raw); // validate check task checkTask.validate(logger) .then((checkTask) => { // set check task status to queued checkTask.queued(); // prepare exec task by check task data return checkApi.prepare(checkTask); }) .then((execData) => { // create exec task and validate execData.id = uuid(); checkTask.execTaskId = execData.id; var execTask = new ExecTask(execData); return execTask.validate(); }) .then((execTask) => { // set check task to started checkTask.started(); // execute exec task return exec(logger, execTask); }) .then((execTask) => { // got exec task response and parse it return checkApi.parse(checkTask, execTask); }) .then((parsedResult) => { // got parsed response // set to check task checkTask.rawResult = parsedResult; // run analyze stage return checkApi.analyze(checkTask); }) .then((result) => { // got status and message result, and custom checker data in result // set result to check task and validate checkTask.result = result; checkTask.finished(); return checkTask.validate(); }) .then((task) => { resolve(task); }) .catch((error) => { checkTask.result = { status: 'fail', message: error.message }; error.checkTask = checkTask; reject(error); }); }); }
javascript
function runCheckTask(logger, checkTask) { return new Promise((resolve, reject) => { // create check task object // raw.id = uuid(); // var checkTask = new CheckTask(raw); // validate check task checkTask.validate(logger) .then((checkTask) => { // set check task status to queued checkTask.queued(); // prepare exec task by check task data return checkApi.prepare(checkTask); }) .then((execData) => { // create exec task and validate execData.id = uuid(); checkTask.execTaskId = execData.id; var execTask = new ExecTask(execData); return execTask.validate(); }) .then((execTask) => { // set check task to started checkTask.started(); // execute exec task return exec(logger, execTask); }) .then((execTask) => { // got exec task response and parse it return checkApi.parse(checkTask, execTask); }) .then((parsedResult) => { // got parsed response // set to check task checkTask.rawResult = parsedResult; // run analyze stage return checkApi.analyze(checkTask); }) .then((result) => { // got status and message result, and custom checker data in result // set result to check task and validate checkTask.result = result; checkTask.finished(); return checkTask.validate(); }) .then((task) => { resolve(task); }) .catch((error) => { checkTask.result = { status: 'fail', message: error.message }; error.checkTask = checkTask; reject(error); }); }); }
[ "function", "runCheckTask", "(", "logger", ",", "checkTask", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "// create check task object", "// raw.id = uuid();", "// var checkTask = new CheckTask(raw);", "// validate check task", "checkTask", ".", "validate", "(", "logger", ")", ".", "then", "(", "(", "checkTask", ")", "=>", "{", "// set check task status to queued", "checkTask", ".", "queued", "(", ")", ";", "// prepare exec task by check task data", "return", "checkApi", ".", "prepare", "(", "checkTask", ")", ";", "}", ")", ".", "then", "(", "(", "execData", ")", "=>", "{", "// create exec task and validate", "execData", ".", "id", "=", "uuid", "(", ")", ";", "checkTask", ".", "execTaskId", "=", "execData", ".", "id", ";", "var", "execTask", "=", "new", "ExecTask", "(", "execData", ")", ";", "return", "execTask", ".", "validate", "(", ")", ";", "}", ")", ".", "then", "(", "(", "execTask", ")", "=>", "{", "// set check task to started", "checkTask", ".", "started", "(", ")", ";", "// execute exec task", "return", "exec", "(", "logger", ",", "execTask", ")", ";", "}", ")", ".", "then", "(", "(", "execTask", ")", "=>", "{", "// got exec task response and parse it", "return", "checkApi", ".", "parse", "(", "checkTask", ",", "execTask", ")", ";", "}", ")", ".", "then", "(", "(", "parsedResult", ")", "=>", "{", "// got parsed response", "// set to check task", "checkTask", ".", "rawResult", "=", "parsedResult", ";", "// run analyze stage", "return", "checkApi", ".", "analyze", "(", "checkTask", ")", ";", "}", ")", ".", "then", "(", "(", "result", ")", "=>", "{", "// got status and message result, and custom checker data in result", "// set result to check task and validate", "checkTask", ".", "result", "=", "result", ";", "checkTask", ".", "finished", "(", ")", ";", "return", "checkTask", ".", "validate", "(", ")", ";", "}", ")", ".", "then", "(", "(", "task", ")", "=>", "{", "resolve", "(", "task", ")", ";", "}", ")", ".", "catch", "(", "(", "error", ")", "=>", "{", "checkTask", ".", "result", "=", "{", "status", ":", "'fail'", ",", "message", ":", "error", ".", "message", "}", ";", "error", ".", "checkTask", "=", "checkTask", ";", "reject", "(", "error", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
exec check task @param {Object} checkTask @return {Promise}
[ "exec", "check", "task" ]
9bd0f7c5b44b1c996c2c805ae2a3c480c7009409
https://github.com/mazaid/check/blob/9bd0f7c5b44b1c996c2c805ae2a3c480c7009409/examples/functions.js#L54-L123
54,991
peteromano/jetrunner
example/vendor/mocha/support/compile.js
parseRequires
function parseRequires(js) { return js .replace(/require\('events'\)/g, "require('browser/events')") .replace(/require\('debug'\)/g, "require('browser/debug')") .replace(/require\('path'\)/g, "require('browser/path')") .replace(/require\('diff'\)/g, "require('browser/diff')") .replace(/require\('tty'\)/g, "require('browser/tty')") .replace(/require\('fs'\)/g, "require('browser/fs')") }
javascript
function parseRequires(js) { return js .replace(/require\('events'\)/g, "require('browser/events')") .replace(/require\('debug'\)/g, "require('browser/debug')") .replace(/require\('path'\)/g, "require('browser/path')") .replace(/require\('diff'\)/g, "require('browser/diff')") .replace(/require\('tty'\)/g, "require('browser/tty')") .replace(/require\('fs'\)/g, "require('browser/fs')") }
[ "function", "parseRequires", "(", "js", ")", "{", "return", "js", ".", "replace", "(", "/", "require\\('events'\\)", "/", "g", ",", "\"require('browser/events')\"", ")", ".", "replace", "(", "/", "require\\('debug'\\)", "/", "g", ",", "\"require('browser/debug')\"", ")", ".", "replace", "(", "/", "require\\('path'\\)", "/", "g", ",", "\"require('browser/path')\"", ")", ".", "replace", "(", "/", "require\\('diff'\\)", "/", "g", ",", "\"require('browser/diff')\"", ")", ".", "replace", "(", "/", "require\\('tty'\\)", "/", "g", ",", "\"require('browser/tty')\"", ")", ".", "replace", "(", "/", "require\\('fs'\\)", "/", "g", ",", "\"require('browser/fs')\"", ")", "}" ]
Parse requires.
[ "Parse", "requires", "." ]
1882e0ee83d31fe1c799b42848c8c1357a62c995
https://github.com/peteromano/jetrunner/blob/1882e0ee83d31fe1c799b42848c8c1357a62c995/example/vendor/mocha/support/compile.js#L44-L52
54,992
jlindsey/grunt-reconfigure
tasks/reconfigure.js
function(obj, parts) { if (parts.length === 0) { return true; } var key = parts.shift(); if (!_(obj).has(key)) { return false; } else { return hasKeyPath(obj[key], parts); } }
javascript
function(obj, parts) { if (parts.length === 0) { return true; } var key = parts.shift(); if (!_(obj).has(key)) { return false; } else { return hasKeyPath(obj[key], parts); } }
[ "function", "(", "obj", ",", "parts", ")", "{", "if", "(", "parts", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "var", "key", "=", "parts", ".", "shift", "(", ")", ";", "if", "(", "!", "_", "(", "obj", ")", ".", "has", "(", "key", ")", ")", "{", "return", "false", ";", "}", "else", "{", "return", "hasKeyPath", "(", "obj", "[", "key", "]", ",", "parts", ")", ";", "}", "}" ]
Recursively step through the provided object and return whether it contains the provided keypath.
[ "Recursively", "step", "through", "the", "provided", "object", "and", "return", "whether", "it", "contains", "the", "provided", "keypath", "." ]
eebb9485eeeea39e3783b54a48792f5e6d956095
https://github.com/jlindsey/grunt-reconfigure/blob/eebb9485eeeea39e3783b54a48792f5e6d956095/tasks/reconfigure.js#L26-L36
54,993
jlindsey/grunt-reconfigure
tasks/reconfigure.js
function(obj, env, keypath) { if (!_.isObject(obj) || _.isArray(obj)) { return; } if (hasKeyPath(obj, ['options', 'reconfigureOverrides', env])) { var options = obj.options, overrides = obj.options.reconfigureOverrides[env]; for (var key in overrides) { var update = { key: keypath+'.options.'+key, oldVal: (typeof options[key] === 'undefined') ? 'undefined' : util.inspect(options[key]), }; if (_.isObject(options[key]) && _.isObject(overrides[key])) { var newVal = _.extend(options[key], overrides[key]); update.newVal = util.inspect(newVal); } else { options[key] = overrides[key]; update.newVal = util.inspect(overrides[key]); } updates.push(update); } } for (var objKey in obj) { updateOptions(obj[objKey], env, keypath+'.'+objKey); } }
javascript
function(obj, env, keypath) { if (!_.isObject(obj) || _.isArray(obj)) { return; } if (hasKeyPath(obj, ['options', 'reconfigureOverrides', env])) { var options = obj.options, overrides = obj.options.reconfigureOverrides[env]; for (var key in overrides) { var update = { key: keypath+'.options.'+key, oldVal: (typeof options[key] === 'undefined') ? 'undefined' : util.inspect(options[key]), }; if (_.isObject(options[key]) && _.isObject(overrides[key])) { var newVal = _.extend(options[key], overrides[key]); update.newVal = util.inspect(newVal); } else { options[key] = overrides[key]; update.newVal = util.inspect(overrides[key]); } updates.push(update); } } for (var objKey in obj) { updateOptions(obj[objKey], env, keypath+'.'+objKey); } }
[ "function", "(", "obj", ",", "env", ",", "keypath", ")", "{", "if", "(", "!", "_", ".", "isObject", "(", "obj", ")", "||", "_", ".", "isArray", "(", "obj", ")", ")", "{", "return", ";", "}", "if", "(", "hasKeyPath", "(", "obj", ",", "[", "'options'", ",", "'reconfigureOverrides'", ",", "env", "]", ")", ")", "{", "var", "options", "=", "obj", ".", "options", ",", "overrides", "=", "obj", ".", "options", ".", "reconfigureOverrides", "[", "env", "]", ";", "for", "(", "var", "key", "in", "overrides", ")", "{", "var", "update", "=", "{", "key", ":", "keypath", "+", "'.options.'", "+", "key", ",", "oldVal", ":", "(", "typeof", "options", "[", "key", "]", "===", "'undefined'", ")", "?", "'undefined'", ":", "util", ".", "inspect", "(", "options", "[", "key", "]", ")", ",", "}", ";", "if", "(", "_", ".", "isObject", "(", "options", "[", "key", "]", ")", "&&", "_", ".", "isObject", "(", "overrides", "[", "key", "]", ")", ")", "{", "var", "newVal", "=", "_", ".", "extend", "(", "options", "[", "key", "]", ",", "overrides", "[", "key", "]", ")", ";", "update", ".", "newVal", "=", "util", ".", "inspect", "(", "newVal", ")", ";", "}", "else", "{", "options", "[", "key", "]", "=", "overrides", "[", "key", "]", ";", "update", ".", "newVal", "=", "util", ".", "inspect", "(", "overrides", "[", "key", "]", ")", ";", "}", "updates", ".", "push", "(", "update", ")", ";", "}", "}", "for", "(", "var", "objKey", "in", "obj", ")", "{", "updateOptions", "(", "obj", "[", "objKey", "]", ",", "env", ",", "keypath", "+", "'.'", "+", "objKey", ")", ";", "}", "}" ]
Recursively step through the provided object, searching for an `options` object with `reconfigureOverrides` containing the provided `env`. If it finds one, it resets any keys and values found inside on the containing `options` object.
[ "Recursively", "step", "through", "the", "provided", "object", "searching", "for", "an", "options", "object", "with", "reconfigureOverrides", "containing", "the", "provided", "env", ".", "If", "it", "finds", "one", "it", "resets", "any", "keys", "and", "values", "found", "inside", "on", "the", "containing", "options", "object", "." ]
eebb9485eeeea39e3783b54a48792f5e6d956095
https://github.com/jlindsey/grunt-reconfigure/blob/eebb9485eeeea39e3783b54a48792f5e6d956095/tasks/reconfigure.js#L44-L72
54,994
Pocketbrain/native-ads-web-ad-library
src/util/logger.js
pushLogEntry
function pushLogEntry(logEntry) { var logger = window[appSettings.loggerVar]; if (logger) { logger.logs.push(logEntry); if (window.console) { if (typeof console.error === "function" && typeof console.warn === "function") { switch (logEntry.type) { case enumerations.logType.wtf: console.error(toFriendlyString(logEntry)); break; case enumerations.logType.error: if (appSettings.logLevel <= enumerations.logLevel.error && appSettings.logLevel > enumerations.logLevel.off) { console.error(toFriendlyString(logEntry)); } break; case enumerations.logType.warning: if (appSettings.logLevel <= enumerations.logLevel.warn && appSettings.logLevel > enumerations.logLevel.off) { console.warn(toFriendlyString(logEntry)); } break; default: if (appSettings.logLevel <= enumerations.logLevel.debug && appSettings.logLevel > enumerations.logLevel.off) { console.log(toFriendlyString(logEntry)); break; } } } else { console.log(toFriendlyString(logEntry)); } } } }
javascript
function pushLogEntry(logEntry) { var logger = window[appSettings.loggerVar]; if (logger) { logger.logs.push(logEntry); if (window.console) { if (typeof console.error === "function" && typeof console.warn === "function") { switch (logEntry.type) { case enumerations.logType.wtf: console.error(toFriendlyString(logEntry)); break; case enumerations.logType.error: if (appSettings.logLevel <= enumerations.logLevel.error && appSettings.logLevel > enumerations.logLevel.off) { console.error(toFriendlyString(logEntry)); } break; case enumerations.logType.warning: if (appSettings.logLevel <= enumerations.logLevel.warn && appSettings.logLevel > enumerations.logLevel.off) { console.warn(toFriendlyString(logEntry)); } break; default: if (appSettings.logLevel <= enumerations.logLevel.debug && appSettings.logLevel > enumerations.logLevel.off) { console.log(toFriendlyString(logEntry)); break; } } } else { console.log(toFriendlyString(logEntry)); } } } }
[ "function", "pushLogEntry", "(", "logEntry", ")", "{", "var", "logger", "=", "window", "[", "appSettings", ".", "loggerVar", "]", ";", "if", "(", "logger", ")", "{", "logger", ".", "logs", ".", "push", "(", "logEntry", ")", ";", "if", "(", "window", ".", "console", ")", "{", "if", "(", "typeof", "console", ".", "error", "===", "\"function\"", "&&", "typeof", "console", ".", "warn", "===", "\"function\"", ")", "{", "switch", "(", "logEntry", ".", "type", ")", "{", "case", "enumerations", ".", "logType", ".", "wtf", ":", "console", ".", "error", "(", "toFriendlyString", "(", "logEntry", ")", ")", ";", "break", ";", "case", "enumerations", ".", "logType", ".", "error", ":", "if", "(", "appSettings", ".", "logLevel", "<=", "enumerations", ".", "logLevel", ".", "error", "&&", "appSettings", ".", "logLevel", ">", "enumerations", ".", "logLevel", ".", "off", ")", "{", "console", ".", "error", "(", "toFriendlyString", "(", "logEntry", ")", ")", ";", "}", "break", ";", "case", "enumerations", ".", "logType", ".", "warning", ":", "if", "(", "appSettings", ".", "logLevel", "<=", "enumerations", ".", "logLevel", ".", "warn", "&&", "appSettings", ".", "logLevel", ">", "enumerations", ".", "logLevel", ".", "off", ")", "{", "console", ".", "warn", "(", "toFriendlyString", "(", "logEntry", ")", ")", ";", "}", "break", ";", "default", ":", "if", "(", "appSettings", ".", "logLevel", "<=", "enumerations", ".", "logLevel", ".", "debug", "&&", "appSettings", ".", "logLevel", ">", "enumerations", ".", "logLevel", ".", "off", ")", "{", "console", ".", "log", "(", "toFriendlyString", "(", "logEntry", ")", ")", ";", "break", ";", "}", "}", "}", "else", "{", "console", ".", "log", "(", "toFriendlyString", "(", "logEntry", ")", ")", ";", "}", "}", "}", "}" ]
Push a logEntry to the array of logs and output it to the console @param logEntry The logEntry to process
[ "Push", "a", "logEntry", "to", "the", "array", "of", "logs", "and", "output", "it", "to", "the", "console" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/util/logger.js#L50-L83
54,995
Pocketbrain/native-ads-web-ad-library
src/util/logger.js
getCurrentTimeString
function getCurrentTimeString() { var today = new Date(); var hh = today.getHours(); var mm = today.getMinutes(); //January is 0 var ss = today.getSeconds(); var ms = today.getMilliseconds(); if (hh < 10) { hh = '0' + hh; } if (mm < 10) { mm = '0' + mm; } if (ss < 10) { ss = '0' + ss; } if (ms < 10) { ms = '0' + ms; } return hh + ":" + mm + ":" + ss + ":" + ms; }
javascript
function getCurrentTimeString() { var today = new Date(); var hh = today.getHours(); var mm = today.getMinutes(); //January is 0 var ss = today.getSeconds(); var ms = today.getMilliseconds(); if (hh < 10) { hh = '0' + hh; } if (mm < 10) { mm = '0' + mm; } if (ss < 10) { ss = '0' + ss; } if (ms < 10) { ms = '0' + ms; } return hh + ":" + mm + ":" + ss + ":" + ms; }
[ "function", "getCurrentTimeString", "(", ")", "{", "var", "today", "=", "new", "Date", "(", ")", ";", "var", "hh", "=", "today", ".", "getHours", "(", ")", ";", "var", "mm", "=", "today", ".", "getMinutes", "(", ")", ";", "//January is 0", "var", "ss", "=", "today", ".", "getSeconds", "(", ")", ";", "var", "ms", "=", "today", ".", "getMilliseconds", "(", ")", ";", "if", "(", "hh", "<", "10", ")", "{", "hh", "=", "'0'", "+", "hh", ";", "}", "if", "(", "mm", "<", "10", ")", "{", "mm", "=", "'0'", "+", "mm", ";", "}", "if", "(", "ss", "<", "10", ")", "{", "ss", "=", "'0'", "+", "ss", ";", "}", "if", "(", "ms", "<", "10", ")", "{", "ms", "=", "'0'", "+", "ms", ";", "}", "return", "hh", "+", "\":\"", "+", "mm", "+", "\":\"", "+", "ss", "+", "\":\"", "+", "ms", ";", "}" ]
Get the current time as a string @returns {string} - the current time in a hh:mm:ss string
[ "Get", "the", "current", "time", "as", "a", "string" ]
aafee1c42e0569ee77f334fc2c4eb71eb146957e
https://github.com/Pocketbrain/native-ads-web-ad-library/blob/aafee1c42e0569ee77f334fc2c4eb71eb146957e/src/util/logger.js#L89-L113
54,996
darrencruse/sugarlisp-core
reader.js
read_from_source
function read_from_source(codestr, filenameOrLexer, options) { var lexer; if(typeof filenameOrLexer === 'string') { lexer = initLexerFor(codestr, filenameOrLexer, options); } else { lexer = filenameOrLexer; lexer.set_source_text(codestr, options); } // read the forms var forms = read(lexer); // it's useful to sometimes look "up" the lexical nesting of forms... // to make this easy/reliable - walk the form tree setting "parent" // I SHOULD TIME THIS? IF IT'S EXPENSIVE - I'M NOT SURE I EVEN NEED IT ANYMORE? if(options.setParents !== 'no' && forms.setParents) { forms.setParents(); } return forms; }
javascript
function read_from_source(codestr, filenameOrLexer, options) { var lexer; if(typeof filenameOrLexer === 'string') { lexer = initLexerFor(codestr, filenameOrLexer, options); } else { lexer = filenameOrLexer; lexer.set_source_text(codestr, options); } // read the forms var forms = read(lexer); // it's useful to sometimes look "up" the lexical nesting of forms... // to make this easy/reliable - walk the form tree setting "parent" // I SHOULD TIME THIS? IF IT'S EXPENSIVE - I'M NOT SURE I EVEN NEED IT ANYMORE? if(options.setParents !== 'no' && forms.setParents) { forms.setParents(); } return forms; }
[ "function", "read_from_source", "(", "codestr", ",", "filenameOrLexer", ",", "options", ")", "{", "var", "lexer", ";", "if", "(", "typeof", "filenameOrLexer", "===", "'string'", ")", "{", "lexer", "=", "initLexerFor", "(", "codestr", ",", "filenameOrLexer", ",", "options", ")", ";", "}", "else", "{", "lexer", "=", "filenameOrLexer", ";", "lexer", ".", "set_source_text", "(", "codestr", ",", "options", ")", ";", "}", "// read the forms", "var", "forms", "=", "read", "(", "lexer", ")", ";", "// it's useful to sometimes look \"up\" the lexical nesting of forms...", "// to make this easy/reliable - walk the form tree setting \"parent\"", "// I SHOULD TIME THIS? IF IT'S EXPENSIVE - I'M NOT SURE I EVEN NEED IT ANYMORE?", "if", "(", "options", ".", "setParents", "!==", "'no'", "&&", "forms", ".", "setParents", ")", "{", "forms", ".", "setParents", "(", ")", ";", "}", "return", "forms", ";", "}" ]
Read the expressions in the provided source code string. @param codestr = the source code as a string e.g. from reading a source file. @param filenameOrLexer = the name of source file (or the Lexer for the file) @return the list (see sl-types) of the expressions in codestr.
[ "Read", "the", "expressions", "in", "the", "provided", "source", "code", "string", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L55-L77
54,997
darrencruse/sugarlisp-core
reader.js
unuse_dialect
function unuse_dialect(dialectName, lexer, options) { options = options || {}; if(dialectName && options.validate && lexer.dialects[0].name !== dialectName) { lexer.error('Attempt to exit dialect "' + dialectName + '" while "' + lexer.dialects[0].name + '" was still active'); } slinfo('removing dialect', dialectName ? ": " + dialectName : ""); var removedDialect = lexer.pop_dialect(dialectName); if(!removedDialect) { lexer.error('The dialect ' + (dialectName ? '"' + dialectName + '"': '') + ' has never been used'); } }
javascript
function unuse_dialect(dialectName, lexer, options) { options = options || {}; if(dialectName && options.validate && lexer.dialects[0].name !== dialectName) { lexer.error('Attempt to exit dialect "' + dialectName + '" while "' + lexer.dialects[0].name + '" was still active'); } slinfo('removing dialect', dialectName ? ": " + dialectName : ""); var removedDialect = lexer.pop_dialect(dialectName); if(!removedDialect) { lexer.error('The dialect ' + (dialectName ? '"' + dialectName + '"': '') + ' has never been used'); } }
[ "function", "unuse_dialect", "(", "dialectName", ",", "lexer", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "dialectName", "&&", "options", ".", "validate", "&&", "lexer", ".", "dialects", "[", "0", "]", ".", "name", "!==", "dialectName", ")", "{", "lexer", ".", "error", "(", "'Attempt to exit dialect \"'", "+", "dialectName", "+", "'\" while \"'", "+", "lexer", ".", "dialects", "[", "0", "]", ".", "name", "+", "'\" was still active'", ")", ";", "}", "slinfo", "(", "'removing dialect'", ",", "dialectName", "?", "\": \"", "+", "dialectName", ":", "\"\"", ")", ";", "var", "removedDialect", "=", "lexer", ".", "pop_dialect", "(", "dialectName", ")", ";", "if", "(", "!", "removedDialect", ")", "{", "lexer", ".", "error", "(", "'The dialect '", "+", "(", "dialectName", "?", "'\"'", "+", "dialectName", "+", "'\"'", ":", "''", ")", "+", "' has never been used'", ")", ";", "}", "}" ]
stop using a dialect Whereas "use_dialect" enters the scope of a dialect, "unuse_dialect" exits that scope. @params dialectName = the name of the dialect to stop using, or if undefined the most recent dialect "used" in the one that's "unused" @params lexer = the lexer for the file being "unused" from. note: if options.validate is true, the function will *only* "unuse" the most recent dialect and it's name must match the name you've given, otherwise an error is thrown. This validates that you haven't (accidentally) failed to "unuse" an inner dialect nested inside another one, leaving the dialect stack in a different state than you think.
[ "stop", "using", "a", "dialect" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L354-L370
54,998
darrencruse/sugarlisp-core
reader.js
invokeInitDialectFunctions
function invokeInitDialectFunctions(dialect, lexer, options) { var initfnkey = "__init"; if(dialect[initfnkey]) { dialect[initfnkey](lexer, dialect, options); } if(dialect.lextab[initfnkey]) { dialect.lextab[initfnkey](lexer, dialect, options); } if(dialect.readtab[initfnkey]) { dialect.readtab[initfnkey](lexer, dialect, options); } if(dialect.gentab[initfnkey]) { dialect.gentab[initfnkey](lexer, dialect, options); } }
javascript
function invokeInitDialectFunctions(dialect, lexer, options) { var initfnkey = "__init"; if(dialect[initfnkey]) { dialect[initfnkey](lexer, dialect, options); } if(dialect.lextab[initfnkey]) { dialect.lextab[initfnkey](lexer, dialect, options); } if(dialect.readtab[initfnkey]) { dialect.readtab[initfnkey](lexer, dialect, options); } if(dialect.gentab[initfnkey]) { dialect.gentab[initfnkey](lexer, dialect, options); } }
[ "function", "invokeInitDialectFunctions", "(", "dialect", ",", "lexer", ",", "options", ")", "{", "var", "initfnkey", "=", "\"__init\"", ";", "if", "(", "dialect", "[", "initfnkey", "]", ")", "{", "dialect", "[", "initfnkey", "]", "(", "lexer", ",", "dialect", ",", "options", ")", ";", "}", "if", "(", "dialect", ".", "lextab", "[", "initfnkey", "]", ")", "{", "dialect", ".", "lextab", "[", "initfnkey", "]", "(", "lexer", ",", "dialect", ",", "options", ")", ";", "}", "if", "(", "dialect", ".", "readtab", "[", "initfnkey", "]", ")", "{", "dialect", ".", "readtab", "[", "initfnkey", "]", "(", "lexer", ",", "dialect", ",", "options", ")", ";", "}", "if", "(", "dialect", ".", "gentab", "[", "initfnkey", "]", ")", "{", "dialect", ".", "gentab", "[", "initfnkey", "]", "(", "lexer", ",", "dialect", ",", "options", ")", ";", "}", "}" ]
Init dialect functions can optionally be used to initialize things at the time a dialect is "used". They can be placed on the dialect, it's lextab, readtab, or gentab, under a key named "__init" (note we use two underscores). They receive as arguments the lexer, the dialect, and the overall options (as passed to "read_from_source".
[ "Init", "dialect", "functions", "can", "optionally", "be", "used", "to", "initialize", "things", "at", "the", "time", "a", "dialect", "is", "used", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L382-L396
54,999
darrencruse/sugarlisp-core
reader.js
read
function read(lexer, precedence) { precedence = precedence || 0; var form = read_via_closest_dialect(lexer); // are we a prefix unary operator? var leftForm = form; if(sl.isAtom(form)) { var opSpec = getOperatorSpecFor(form, lexer.dialects); if(opSpec && isEnabled(opSpec.prefix) && opSpec.prefix.transform && // "nospace" prefix ops must butt up against their arg so // "--i" not "-- i" this way we can't confuse e.g. (- x y) // with (-x y) (!opSpec.options || !opSpec.options.nospace || !lexer.onwhitespace(-1))) { leftForm = opSpec.prefix.transform(lexer, opSpec.prefix, form); } } // note flipped check below from < to > because our precedences // are currently as you see them here: http://www.scriptingmaster.com/javascript/operator-precedence.asp // not as you see them here: http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/ var token, opSpecObj; while(!lexer.eos() && (token = lexer.peek_token()) && (opSpecObj = getOperatorSpecFor(token.text, lexer.dialects)) && opSpecObj && (isEnabled(opSpecObj.infix) || isEnabled(opSpecObj.postfix))) { // make sure we don't misinterpet e.g. "(get ++i)" as "(get++ i)" if(opSpecObj.prefix && opSpecObj.postfix && (lexer.onwhitespace(-1) && !lexer.onwhitespace(token.text.length))) { break; // let it be prefix next time round } // we don't distinguish infix from postfix below: var opSpec = opSpecObj.infix || opSpecObj.postfix; // we only keep scanning if we're hitting *higher* precedence if((opSpec.precedence || 0) <= precedence) { trace("read of infix/postfix stopping because op precedence " + (opSpec.precedence || 0) + " is <= the current precendence of " + precedence); break; // stop scanning } token = lexer.next_token(); leftForm = opSpec.transform(lexer, opSpec, leftForm, sl.atom(token)); } if(sl.isList(leftForm)) { // now that we've finished reading the list, // pop any local dialects whose scope has ended pop_local_dialects(lexer, leftForm); } return leftForm; }
javascript
function read(lexer, precedence) { precedence = precedence || 0; var form = read_via_closest_dialect(lexer); // are we a prefix unary operator? var leftForm = form; if(sl.isAtom(form)) { var opSpec = getOperatorSpecFor(form, lexer.dialects); if(opSpec && isEnabled(opSpec.prefix) && opSpec.prefix.transform && // "nospace" prefix ops must butt up against their arg so // "--i" not "-- i" this way we can't confuse e.g. (- x y) // with (-x y) (!opSpec.options || !opSpec.options.nospace || !lexer.onwhitespace(-1))) { leftForm = opSpec.prefix.transform(lexer, opSpec.prefix, form); } } // note flipped check below from < to > because our precedences // are currently as you see them here: http://www.scriptingmaster.com/javascript/operator-precedence.asp // not as you see them here: http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/ var token, opSpecObj; while(!lexer.eos() && (token = lexer.peek_token()) && (opSpecObj = getOperatorSpecFor(token.text, lexer.dialects)) && opSpecObj && (isEnabled(opSpecObj.infix) || isEnabled(opSpecObj.postfix))) { // make sure we don't misinterpet e.g. "(get ++i)" as "(get++ i)" if(opSpecObj.prefix && opSpecObj.postfix && (lexer.onwhitespace(-1) && !lexer.onwhitespace(token.text.length))) { break; // let it be prefix next time round } // we don't distinguish infix from postfix below: var opSpec = opSpecObj.infix || opSpecObj.postfix; // we only keep scanning if we're hitting *higher* precedence if((opSpec.precedence || 0) <= precedence) { trace("read of infix/postfix stopping because op precedence " + (opSpec.precedence || 0) + " is <= the current precendence of " + precedence); break; // stop scanning } token = lexer.next_token(); leftForm = opSpec.transform(lexer, opSpec, leftForm, sl.atom(token)); } if(sl.isList(leftForm)) { // now that we've finished reading the list, // pop any local dialects whose scope has ended pop_local_dialects(lexer, leftForm); } return leftForm; }
[ "function", "read", "(", "lexer", ",", "precedence", ")", "{", "precedence", "=", "precedence", "||", "0", ";", "var", "form", "=", "read_via_closest_dialect", "(", "lexer", ")", ";", "// are we a prefix unary operator?", "var", "leftForm", "=", "form", ";", "if", "(", "sl", ".", "isAtom", "(", "form", ")", ")", "{", "var", "opSpec", "=", "getOperatorSpecFor", "(", "form", ",", "lexer", ".", "dialects", ")", ";", "if", "(", "opSpec", "&&", "isEnabled", "(", "opSpec", ".", "prefix", ")", "&&", "opSpec", ".", "prefix", ".", "transform", "&&", "// \"nospace\" prefix ops must butt up against their arg so", "// \"--i\" not \"-- i\" this way we can't confuse e.g. (- x y)", "// with (-x y)", "(", "!", "opSpec", ".", "options", "||", "!", "opSpec", ".", "options", ".", "nospace", "||", "!", "lexer", ".", "onwhitespace", "(", "-", "1", ")", ")", ")", "{", "leftForm", "=", "opSpec", ".", "prefix", ".", "transform", "(", "lexer", ",", "opSpec", ".", "prefix", ",", "form", ")", ";", "}", "}", "// note flipped check below from < to > because our precedences", "// are currently as you see them here: http://www.scriptingmaster.com/javascript/operator-precedence.asp", "// not as you see them here: http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/", "var", "token", ",", "opSpecObj", ";", "while", "(", "!", "lexer", ".", "eos", "(", ")", "&&", "(", "token", "=", "lexer", ".", "peek_token", "(", ")", ")", "&&", "(", "opSpecObj", "=", "getOperatorSpecFor", "(", "token", ".", "text", ",", "lexer", ".", "dialects", ")", ")", "&&", "opSpecObj", "&&", "(", "isEnabled", "(", "opSpecObj", ".", "infix", ")", "||", "isEnabled", "(", "opSpecObj", ".", "postfix", ")", ")", ")", "{", "// make sure we don't misinterpet e.g. \"(get ++i)\" as \"(get++ i)\"", "if", "(", "opSpecObj", ".", "prefix", "&&", "opSpecObj", ".", "postfix", "&&", "(", "lexer", ".", "onwhitespace", "(", "-", "1", ")", "&&", "!", "lexer", ".", "onwhitespace", "(", "token", ".", "text", ".", "length", ")", ")", ")", "{", "break", ";", "// let it be prefix next time round", "}", "// we don't distinguish infix from postfix below:", "var", "opSpec", "=", "opSpecObj", ".", "infix", "||", "opSpecObj", ".", "postfix", ";", "// we only keep scanning if we're hitting *higher* precedence", "if", "(", "(", "opSpec", ".", "precedence", "||", "0", ")", "<=", "precedence", ")", "{", "trace", "(", "\"read of infix/postfix stopping because op precedence \"", "+", "(", "opSpec", ".", "precedence", "||", "0", ")", "+", "\" is <= the current precendence of \"", "+", "precedence", ")", ";", "break", ";", "// stop scanning", "}", "token", "=", "lexer", ".", "next_token", "(", ")", ";", "leftForm", "=", "opSpec", ".", "transform", "(", "lexer", ",", "opSpec", ",", "leftForm", ",", "sl", ".", "atom", "(", "token", ")", ")", ";", "}", "if", "(", "sl", ".", "isList", "(", "leftForm", ")", ")", "{", "// now that we've finished reading the list,", "// pop any local dialects whose scope has ended", "pop_local_dialects", "(", "lexer", ",", "leftForm", ")", ";", "}", "return", "leftForm", ";", "}" ]
Read the form at the current position in the source. @param lexer = the lexer that is reading the source file. @param precedence = internal use only (don't pass) @return the list (see sl-types) for the expression that was read.
[ "Read", "the", "form", "at", "the", "current", "position", "in", "the", "source", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L404-L460