repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
imbo/imboclient-js
lib/url/imageurl.js
function(options) { options = options || {}; return this.append([ 'thumbnail:width=' + (options.width || 50), 'height=' + (options.height || 50), 'fit=' + (options.fit || 'outbound') ].join(',')); }
javascript
function(options) { options = options || {}; return this.append([ 'thumbnail:width=' + (options.width || 50), 'height=' + (options.height || 50), 'fit=' + (options.fit || 'outbound') ].join(',')); }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "return", "this", ".", "append", "(", "[", "'thumbnail:width='", "+", "(", "options", ".", "width", "||", "50", ")", ",", "'height='", "+", "(", "options", ".", "height", "||", "50", ")", ",", "'fit='", "+", "(", "options", ".", "fit", "||", "'outbound'", ")", "]", ".", "join", "(", "','", ")", ")", ";", "}" ]
Create a thumbnailed version of the image @param {Object} [options] @param {Number} [options.width=50] Width of the thumbnail @param {Number} [options.height=50] Height of the thumbnail @param {String} [options.fit=outbound] Fit mode: "outbound" or "inset" @return {Imbo.ImageUrl}
[ "Create", "a", "thumbnailed", "version", "of", "the", "image" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L481-L489
train
imbo/imboclient-js
lib/url/imageurl.js
function(options) { options = options || {}; var params = [ 'position=' + (options.position || 'top-left'), 'x=' + toInt(options.x || 0), 'y=' + toInt(options.y || 0) ]; if (options.imageIdentifier) { params.push('img=' + options.imageIdentifier); } if (options.width > 0) { params.push('width=' + toInt(options.width)); } if (options.height > 0) { params.push('height=' + toInt(options.height)); } return this.append('watermark:' + params.join(',')); }
javascript
function(options) { options = options || {}; var params = [ 'position=' + (options.position || 'top-left'), 'x=' + toInt(options.x || 0), 'y=' + toInt(options.y || 0) ]; if (options.imageIdentifier) { params.push('img=' + options.imageIdentifier); } if (options.width > 0) { params.push('width=' + toInt(options.width)); } if (options.height > 0) { params.push('height=' + toInt(options.height)); } return this.append('watermark:' + params.join(',')); }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "var", "params", "=", "[", "'position='", "+", "(", "options", ".", "position", "||", "'top-left'", ")", ",", "'x='", "+", "toInt", "(", "options", ".", "x", "||", "0", ")", ",", "'y='", "+", "toInt", "(", "options", ".", "y", "||", "0", ")", "]", ";", "if", "(", "options", ".", "imageIdentifier", ")", "{", "params", ".", "push", "(", "'img='", "+", "options", ".", "imageIdentifier", ")", ";", "}", "if", "(", "options", ".", "width", ">", "0", ")", "{", "params", ".", "push", "(", "'width='", "+", "toInt", "(", "options", ".", "width", ")", ")", ";", "}", "if", "(", "options", ".", "height", ">", "0", ")", "{", "params", ".", "push", "(", "'height='", "+", "toInt", "(", "options", ".", "height", ")", ")", ";", "}", "return", "this", ".", "append", "(", "'watermark:'", "+", "params", ".", "join", "(", "','", ")", ")", ";", "}" ]
Applies a watermark on top of the original image @param {Object} [options] @param {Number} [options.img] Image identifier of the image to apply as watermark @param {Number} [options.width] Width of the watermark, in pixels @param {Number} [options.height] Height of the watermark, in pixels @param {String} [options.position=top-left] Position of the watermark. Values: "top-left", "top-right", "bottom-left", "bottom-right" and "center" @param {Number} [options.x] Number of pixels in the X-axis the watermark image should be offset from the original position @param {Number} [options.y] Number of pixels in the Y-axis the watermark image should be offset from the original position @return {Imbo.ImageUrl}
[ "Applies", "a", "watermark", "on", "top", "of", "the", "original", "image" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L524-L546
train
imbo/imboclient-js
lib/url/imageurl.js
function() { return new ImageUrl({ transformations: this.transformations.slice(0), baseUrl: this.rootUrl, user: this.user, publicKey: this.publicKey, privateKey: this.privateKey, imageIdentifier: this.imageIdentifier, extension: this.extension, queryString: this.queryString, path: this.path }); }
javascript
function() { return new ImageUrl({ transformations: this.transformations.slice(0), baseUrl: this.rootUrl, user: this.user, publicKey: this.publicKey, privateKey: this.privateKey, imageIdentifier: this.imageIdentifier, extension: this.extension, queryString: this.queryString, path: this.path }); }
[ "function", "(", ")", "{", "return", "new", "ImageUrl", "(", "{", "transformations", ":", "this", ".", "transformations", ".", "slice", "(", "0", ")", ",", "baseUrl", ":", "this", ".", "rootUrl", ",", "user", ":", "this", ".", "user", ",", "publicKey", ":", "this", ".", "publicKey", ",", "privateKey", ":", "this", ".", "privateKey", ",", "imageIdentifier", ":", "this", ".", "imageIdentifier", ",", "extension", ":", "this", ".", "extension", ",", "queryString", ":", "this", ".", "queryString", ",", "path", ":", "this", ".", "path", "}", ")", ";", "}" ]
Clone this ImageUrl instance @return {Imbo.ImageUrl}
[ "Clone", "this", "ImageUrl", "instance" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L592-L604
train
imbo/imboclient-js
lib/url/imageurl.js
function(encode) { var query = this.queryString || '', transformations = this.transformations, transformationKey = encode ? 't%5B%5D=' : 't[]='; if (encode) { transformations = transformations.map(encodeURIComponent); } if (this.transformations.length) { query += query.length ? '&' : ''; query += transformationKey + transformations.join('&' + transformationKey); } return query; }
javascript
function(encode) { var query = this.queryString || '', transformations = this.transformations, transformationKey = encode ? 't%5B%5D=' : 't[]='; if (encode) { transformations = transformations.map(encodeURIComponent); } if (this.transformations.length) { query += query.length ? '&' : ''; query += transformationKey + transformations.join('&' + transformationKey); } return query; }
[ "function", "(", "encode", ")", "{", "var", "query", "=", "this", ".", "queryString", "||", "''", ",", "transformations", "=", "this", ".", "transformations", ",", "transformationKey", "=", "encode", "?", "'t%5B%5D='", ":", "'t[]='", ";", "if", "(", "encode", ")", "{", "transformations", "=", "transformations", ".", "map", "(", "encodeURIComponent", ")", ";", "}", "if", "(", "this", ".", "transformations", ".", "length", ")", "{", "query", "+=", "query", ".", "length", "?", "'&'", ":", "''", ";", "query", "+=", "transformationKey", "+", "transformations", ".", "join", "(", "'&'", "+", "transformationKey", ")", ";", "}", "return", "query", ";", "}" ]
Get the query string with all transformations applied @param {Boolean} [encode=false] @return {String}
[ "Get", "the", "query", "string", "with", "all", "transformations", "applied" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/url/imageurl.js#L650-L665
train
rootsdev/gedcomx-js
src/core/Identifiers.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Identifiers)){ return new Identifiers(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Identifiers.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Identifiers)){ return new Identifiers(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Identifiers.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Identifiers", ")", ")", "{", "return", "new", "Identifiers", "(", "json", ")", ";", "}", "if", "(", "Identifiers", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Manage the set of identifers for an object. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#identifier-type|GEDCOM X JSON Spec} @class @extends Base @param {Object} [json]
[ "Manage", "the", "set", "of", "identifers", "for", "an", "object", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Identifiers.js#L13-L26
train
blaxk/ixband
dist/ixBand_1.2.js
function ( value ) { if ( this.isObject(value) ) { //$('.touch_area').get(0).constructor.toString() return !!( value && value.nodeType === 1 && value.nodeName ); } else { return /HTML(?:.*)Element/.test( Object.prototype.toString.call(value) ); } }
javascript
function ( value ) { if ( this.isObject(value) ) { //$('.touch_area').get(0).constructor.toString() return !!( value && value.nodeType === 1 && value.nodeName ); } else { return /HTML(?:.*)Element/.test( Object.prototype.toString.call(value) ); } }
[ "function", "(", "value", ")", "{", "if", "(", "this", ".", "isObject", "(", "value", ")", ")", "{", "return", "!", "!", "(", "value", "&&", "value", ".", "nodeType", "===", "1", "&&", "value", ".", "nodeName", ")", ";", "}", "else", "{", "return", "/", "HTML(?:.*)Element", "/", ".", "test", "(", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "value", ")", ")", ";", "}", "}" ]
Element, HTMLElement, NodeElement check
[ "Element", "HTMLElement", "NodeElement", "check" ]
1f1ab638ea6dd633c31cf3f2bef97d121f63084f
https://github.com/blaxk/ixband/blob/1f1ab638ea6dd633c31cf3f2bef97d121f63084f/dist/ixBand_1.2.js#L507-L514
train
blaxk/ixband
dist/ixBand_1.2.js
function ( type ) { if ( /pointerdown/i.test(type) ) { type = 'touchstart'; } else if ( /pointermove/i.test(type) ) { type = 'touchmove'; } else if ( /pointerup/i.test(type) ) { type = 'touchend'; } else if ( /pointercancel/i.test(type) ) { type = 'touchcancel'; } return type; }
javascript
function ( type ) { if ( /pointerdown/i.test(type) ) { type = 'touchstart'; } else if ( /pointermove/i.test(type) ) { type = 'touchmove'; } else if ( /pointerup/i.test(type) ) { type = 'touchend'; } else if ( /pointercancel/i.test(type) ) { type = 'touchcancel'; } return type; }
[ "function", "(", "type", ")", "{", "if", "(", "/", "pointerdown", "/", "i", ".", "test", "(", "type", ")", ")", "{", "type", "=", "'touchstart'", ";", "}", "else", "if", "(", "/", "pointermove", "/", "i", ".", "test", "(", "type", ")", ")", "{", "type", "=", "'touchmove'", ";", "}", "else", "if", "(", "/", "pointerup", "/", "i", ".", "test", "(", "type", ")", ")", "{", "type", "=", "'touchend'", ";", "}", "else", "if", "(", "/", "pointercancel", "/", "i", ".", "test", "(", "type", ")", ")", "{", "type", "=", "'touchcancel'", ";", "}", "return", "type", ";", "}" ]
origin event type to cross event type
[ "origin", "event", "type", "to", "cross", "event", "type" ]
1f1ab638ea6dd633c31cf3f2bef97d121f63084f
https://github.com/blaxk/ixband/blob/1f1ab638ea6dd633c31cf3f2bef97d121f63084f/dist/ixBand_1.2.js#L5790-L5802
train
Hypermediaisobar-admin/node-any-db-mssql
index.js
function(anyConfig) { var result = {}; result.userName = anyConfig.user || anyConfig.userName || defaultConfig.userName; result.password = anyConfig.password || defaultConfig.password; result.server = anyConfig.host || anyConfig.server || defaultConfig.host; result.options = anyConfig.options || {}; result.options.database = anyConfig.database || result.options.database || defaultConfig.options.database; if (anyConfig.instanceName || result.options.instanceName) { result.options.instanceName = anyConfig.instanceName || result.options.instanceName; result.options.port = false; } else { result.options.port = anyConfig.port || result.options.port || defaultConfig.options.port; } return result; }
javascript
function(anyConfig) { var result = {}; result.userName = anyConfig.user || anyConfig.userName || defaultConfig.userName; result.password = anyConfig.password || defaultConfig.password; result.server = anyConfig.host || anyConfig.server || defaultConfig.host; result.options = anyConfig.options || {}; result.options.database = anyConfig.database || result.options.database || defaultConfig.options.database; if (anyConfig.instanceName || result.options.instanceName) { result.options.instanceName = anyConfig.instanceName || result.options.instanceName; result.options.port = false; } else { result.options.port = anyConfig.port || result.options.port || defaultConfig.options.port; } return result; }
[ "function", "(", "anyConfig", ")", "{", "var", "result", "=", "{", "}", ";", "result", ".", "userName", "=", "anyConfig", ".", "user", "||", "anyConfig", ".", "userName", "||", "defaultConfig", ".", "userName", ";", "result", ".", "password", "=", "anyConfig", ".", "password", "||", "defaultConfig", ".", "password", ";", "result", ".", "server", "=", "anyConfig", ".", "host", "||", "anyConfig", ".", "server", "||", "defaultConfig", ".", "host", ";", "result", ".", "options", "=", "anyConfig", ".", "options", "||", "{", "}", ";", "result", ".", "options", ".", "database", "=", "anyConfig", ".", "database", "||", "result", ".", "options", ".", "database", "||", "defaultConfig", ".", "options", ".", "database", ";", "if", "(", "anyConfig", ".", "instanceName", "||", "result", ".", "options", ".", "instanceName", ")", "{", "result", ".", "options", ".", "instanceName", "=", "anyConfig", ".", "instanceName", "||", "result", ".", "options", ".", "instanceName", ";", "result", ".", "options", ".", "port", "=", "false", ";", "}", "else", "{", "result", ".", "options", ".", "port", "=", "anyConfig", ".", "port", "||", "result", ".", "options", ".", "port", "||", "defaultConfig", ".", "options", ".", "port", ";", "}", "return", "result", ";", "}" ]
Any DB config. @external any-db~Config @see {@link https://github.com/grncdr/node-any-db-adapter-spec#adaptercreateconnection} Convert config provided by Any DB to the one used by Tedious. @private @param {any-db~Config} anyConfig @return {Tedious~Config}
[ "Any", "DB", "config", "." ]
325922af18554bc5db703034d966d666407671db
https://github.com/Hypermediaisobar-admin/node-any-db-mssql/blob/325922af18554bc5db703034d966d666407671db/index.js#L63-L81
train
Hypermediaisobar-admin/node-any-db-mssql
index.js
function(request, parameters) { if (!parameters) { return; } var keys = Object.keys(parameters); var type = false; var value = null; var options = null; for (var i = keys.length - 1; i >= 0; i--) { value = parameters[keys[i]]; options = null; if (value instanceof Object && value.type && value.hasOwnProperty('value')) { if (value.hasOwnProperty('options')) { options = value.options; } type = value.type; value = value.value; } else { type = exports.detectParameterType(value); } if (!(value instanceof Array)) { request.addParameter(keys[i], type, value, options); continue; } } }
javascript
function(request, parameters) { if (!parameters) { return; } var keys = Object.keys(parameters); var type = false; var value = null; var options = null; for (var i = keys.length - 1; i >= 0; i--) { value = parameters[keys[i]]; options = null; if (value instanceof Object && value.type && value.hasOwnProperty('value')) { if (value.hasOwnProperty('options')) { options = value.options; } type = value.type; value = value.value; } else { type = exports.detectParameterType(value); } if (!(value instanceof Array)) { request.addParameter(keys[i], type, value, options); continue; } } }
[ "function", "(", "request", ",", "parameters", ")", "{", "if", "(", "!", "parameters", ")", "{", "return", ";", "}", "var", "keys", "=", "Object", ".", "keys", "(", "parameters", ")", ";", "var", "type", "=", "false", ";", "var", "value", "=", "null", ";", "var", "options", "=", "null", ";", "for", "(", "var", "i", "=", "keys", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "value", "=", "parameters", "[", "keys", "[", "i", "]", "]", ";", "options", "=", "null", ";", "if", "(", "value", "instanceof", "Object", "&&", "value", ".", "type", "&&", "value", ".", "hasOwnProperty", "(", "'value'", ")", ")", "{", "if", "(", "value", ".", "hasOwnProperty", "(", "'options'", ")", ")", "{", "options", "=", "value", ".", "options", ";", "}", "type", "=", "value", ".", "type", ";", "value", "=", "value", ".", "value", ";", "}", "else", "{", "type", "=", "exports", ".", "detectParameterType", "(", "value", ")", ";", "}", "if", "(", "!", "(", "value", "instanceof", "Array", ")", ")", "{", "request", ".", "addParameter", "(", "keys", "[", "i", "]", ",", "type", ",", "value", ",", "options", ")", ";", "continue", ";", "}", "}", "}" ]
Tedious' Request object. @external Tedious~Request @see {@link http://pekim.github.io/tedious/api-request.html} Add parameters to the request. @private @param {Tedious~Request} request @param {namedParameters|positionalParameters} [parameters]
[ "Tedious", "Request", "object", "." ]
325922af18554bc5db703034d966d666407671db
https://github.com/Hypermediaisobar-admin/node-any-db-mssql/blob/325922af18554bc5db703034d966d666407671db/index.js#L292-L321
train
Hypermediaisobar-admin/node-any-db-mssql
index.js
function(target) { target.adapter = exports; target.query = execQuery.bind(target); // Tedious cannot execute more than one query at a time, so we have to // implement a queue for queries, just in case someone tries to set // multiple queries in a row (like node-any-db-adapter-spec tests do). target._queue = []; target._waitingForQueryToFinish = false; var _execNextInQueue = function(){ if (target._waitingForQueryToFinish) { return; } var query = target._queue.shift(); if (query) { target._waitingForQueryToFinish = true; target.emit('query', query); query.once('close', function(){ target._waitingForQueryToFinish = false; target.execNextInQueue(); }); target.execSql(query._request); } }; target.execNextInQueue = function(query){ if (query) { target._queue.push(query); } if (target._isConnected) { process.nextTick(_execNextInQueue); } }; return target; }
javascript
function(target) { target.adapter = exports; target.query = execQuery.bind(target); // Tedious cannot execute more than one query at a time, so we have to // implement a queue for queries, just in case someone tries to set // multiple queries in a row (like node-any-db-adapter-spec tests do). target._queue = []; target._waitingForQueryToFinish = false; var _execNextInQueue = function(){ if (target._waitingForQueryToFinish) { return; } var query = target._queue.shift(); if (query) { target._waitingForQueryToFinish = true; target.emit('query', query); query.once('close', function(){ target._waitingForQueryToFinish = false; target.execNextInQueue(); }); target.execSql(query._request); } }; target.execNextInQueue = function(query){ if (query) { target._queue.push(query); } if (target._isConnected) { process.nextTick(_execNextInQueue); } }; return target; }
[ "function", "(", "target", ")", "{", "target", ".", "adapter", "=", "exports", ";", "target", ".", "query", "=", "execQuery", ".", "bind", "(", "target", ")", ";", "target", ".", "_queue", "=", "[", "]", ";", "target", ".", "_waitingForQueryToFinish", "=", "false", ";", "var", "_execNextInQueue", "=", "function", "(", ")", "{", "if", "(", "target", ".", "_waitingForQueryToFinish", ")", "{", "return", ";", "}", "var", "query", "=", "target", ".", "_queue", ".", "shift", "(", ")", ";", "if", "(", "query", ")", "{", "target", ".", "_waitingForQueryToFinish", "=", "true", ";", "target", ".", "emit", "(", "'query'", ",", "query", ")", ";", "query", ".", "once", "(", "'close'", ",", "function", "(", ")", "{", "target", ".", "_waitingForQueryToFinish", "=", "false", ";", "target", ".", "execNextInQueue", "(", ")", ";", "}", ")", ";", "target", ".", "execSql", "(", "query", ".", "_request", ")", ";", "}", "}", ";", "target", ".", "execNextInQueue", "=", "function", "(", "query", ")", "{", "if", "(", "query", ")", "{", "target", ".", "_queue", ".", "push", "(", "query", ")", ";", "}", "if", "(", "target", ".", "_isConnected", ")", "{", "process", ".", "nextTick", "(", "_execNextInQueue", ")", ";", "}", "}", ";", "return", "target", ";", "}" ]
Inject Queryable API into object. @private @param {Object} target @return {any-db~Queryable} target object with Queryable API injected
[ "Inject", "Queryable", "API", "into", "object", "." ]
325922af18554bc5db703034d966d666407671db
https://github.com/Hypermediaisobar-admin/node-any-db-mssql/blob/325922af18554bc5db703034d966d666407671db/index.js#L535-L574
train
AckerApple/ack-node
js/modules/router.js
htmlCloseError
function htmlCloseError(options) { options = options || {}; options.debugLocalNetwork = options.debugLocalNetwork == null ? true : options.debugLocalNetwork; return function (err, req, res, next) { var msg = err.message || err.code; res.statusCode = err.status || err.statusCode || 500; res.statusMessage = msg; res.setHeader('Content-Type', 'text/html'); if (msg) res.setHeader('message', cleanStatusMessage(msg)); var output = '<h3>' + msg + '</h3>'; //message meat var isDebug = options.debug || (options.debugLocalNetwork && ack.reqres(req, res).req.isLocalNetwork()); var dump = null; if (isDebug) { dump = { Error: err }; var jErr = ack.error(err); if (err.stack) { output += jErr.getFirstTrace(); dump.stack = jErr.getStackArray(); } } else { dump = err; } output += ack(dump).dump('html'); res.end(output); }; }
javascript
function htmlCloseError(options) { options = options || {}; options.debugLocalNetwork = options.debugLocalNetwork == null ? true : options.debugLocalNetwork; return function (err, req, res, next) { var msg = err.message || err.code; res.statusCode = err.status || err.statusCode || 500; res.statusMessage = msg; res.setHeader('Content-Type', 'text/html'); if (msg) res.setHeader('message', cleanStatusMessage(msg)); var output = '<h3>' + msg + '</h3>'; //message meat var isDebug = options.debug || (options.debugLocalNetwork && ack.reqres(req, res).req.isLocalNetwork()); var dump = null; if (isDebug) { dump = { Error: err }; var jErr = ack.error(err); if (err.stack) { output += jErr.getFirstTrace(); dump.stack = jErr.getStackArray(); } } else { dump = err; } output += ack(dump).dump('html'); res.end(output); }; }
[ "function", "htmlCloseError", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "options", ".", "debugLocalNetwork", "=", "options", ".", "debugLocalNetwork", "==", "null", "?", "true", ":", "options", ".", "debugLocalNetwork", ";", "return", "function", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "var", "msg", "=", "err", ".", "message", "||", "err", ".", "code", ";", "res", ".", "statusCode", "=", "err", ".", "status", "||", "err", ".", "statusCode", "||", "500", ";", "res", ".", "statusMessage", "=", "msg", ";", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'text/html'", ")", ";", "if", "(", "msg", ")", "res", ".", "setHeader", "(", "'message'", ",", "cleanStatusMessage", "(", "msg", ")", ")", ";", "var", "output", "=", "'<h3>'", "+", "msg", "+", "'</h3>'", ";", "var", "isDebug", "=", "options", ".", "debug", "||", "(", "options", ".", "debugLocalNetwork", "&&", "ack", ".", "reqres", "(", "req", ",", "res", ")", ".", "req", ".", "isLocalNetwork", "(", ")", ")", ";", "var", "dump", "=", "null", ";", "if", "(", "isDebug", ")", "{", "dump", "=", "{", "Error", ":", "err", "}", ";", "var", "jErr", "=", "ack", ".", "error", "(", "err", ")", ";", "if", "(", "err", ".", "stack", ")", "{", "output", "+=", "jErr", ".", "getFirstTrace", "(", ")", ";", "dump", ".", "stack", "=", "jErr", ".", "getStackArray", "(", ")", ";", "}", "}", "else", "{", "dump", "=", "err", ";", "}", "output", "+=", "ack", "(", "dump", ")", ".", "dump", "(", "'html'", ")", ";", "res", ".", "end", "(", "output", ")", ";", "}", ";", "}" ]
Returns universal error handler middleware @options {debug:true/false, debugLocalNetwork:true}
[ "Returns", "universal", "error", "handler", "middleware" ]
c123d3fcbdd0195630fece6dc9ddee8910c9e115
https://github.com/AckerApple/ack-node/blob/c123d3fcbdd0195630fece6dc9ddee8910c9e115/js/modules/router.js#L572-L599
train
AckerApple/ack-node
js/modules/router.js
jsonCloseError
function jsonCloseError(options) { if (options === void 0) { options = {}; } options.debugLocalNetwork = options.debugLocalNetwork == null ? true : options.debugLocalNetwork; return function (err, req, res, next) { try { err = toError(err); var statusMessage = err.message || err.code; var statusCode = err.status || err.statusCode || 500; statusMessage = cleanStatusMessage(statusMessage); statusCode = statusCode.toString().replace(/[^0-9]/g, ''); res.statusMessage = statusMessage; res.statusCode = statusCode; var rtn = { error: { message: statusMessage, code: statusCode, "debug": { "stack": err.stack } } }; var isDebug = err.stack && (options.debug || (options.debugLocalNetwork && ack.reqres(req, res).req.isLocalNetwork())); if (isDebug) { rtn.error["stack"] = err.stack; //debug requests will get stack traces } /* if(res.json){ res.json(rtn) }else{ var output = JSON.stringify(rtn) res.setHeader('message', statusMessage) res.setHeader('Content-Type','application/json') res.setHeader('Content-Length', output.length.toString()) res.end( output ); } */ var output = JSON.stringify(rtn); res.setHeader('message', statusMessage); res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Length', output.length.toString()); res.end(output); } catch (e) { console.error('ack/modules/reqres/res.js jsonCloseError failed hard'); console.error(e); console.error('------ original error ------', statusMessage); console.error(err); if (next) { next(err); } else { throw err; } } }; }
javascript
function jsonCloseError(options) { if (options === void 0) { options = {}; } options.debugLocalNetwork = options.debugLocalNetwork == null ? true : options.debugLocalNetwork; return function (err, req, res, next) { try { err = toError(err); var statusMessage = err.message || err.code; var statusCode = err.status || err.statusCode || 500; statusMessage = cleanStatusMessage(statusMessage); statusCode = statusCode.toString().replace(/[^0-9]/g, ''); res.statusMessage = statusMessage; res.statusCode = statusCode; var rtn = { error: { message: statusMessage, code: statusCode, "debug": { "stack": err.stack } } }; var isDebug = err.stack && (options.debug || (options.debugLocalNetwork && ack.reqres(req, res).req.isLocalNetwork())); if (isDebug) { rtn.error["stack"] = err.stack; //debug requests will get stack traces } /* if(res.json){ res.json(rtn) }else{ var output = JSON.stringify(rtn) res.setHeader('message', statusMessage) res.setHeader('Content-Type','application/json') res.setHeader('Content-Length', output.length.toString()) res.end( output ); } */ var output = JSON.stringify(rtn); res.setHeader('message', statusMessage); res.setHeader('Content-Type', 'application/json'); res.setHeader('Content-Length', output.length.toString()); res.end(output); } catch (e) { console.error('ack/modules/reqres/res.js jsonCloseError failed hard'); console.error(e); console.error('------ original error ------', statusMessage); console.error(err); if (next) { next(err); } else { throw err; } } }; }
[ "function", "jsonCloseError", "(", "options", ")", "{", "if", "(", "options", "===", "void", "0", ")", "{", "options", "=", "{", "}", ";", "}", "options", ".", "debugLocalNetwork", "=", "options", ".", "debugLocalNetwork", "==", "null", "?", "true", ":", "options", ".", "debugLocalNetwork", ";", "return", "function", "(", "err", ",", "req", ",", "res", ",", "next", ")", "{", "try", "{", "err", "=", "toError", "(", "err", ")", ";", "var", "statusMessage", "=", "err", ".", "message", "||", "err", ".", "code", ";", "var", "statusCode", "=", "err", ".", "status", "||", "err", ".", "statusCode", "||", "500", ";", "statusMessage", "=", "cleanStatusMessage", "(", "statusMessage", ")", ";", "statusCode", "=", "statusCode", ".", "toString", "(", ")", ".", "replace", "(", "/", "[^0-9]", "/", "g", ",", "''", ")", ";", "res", ".", "statusMessage", "=", "statusMessage", ";", "res", ".", "statusCode", "=", "statusCode", ";", "var", "rtn", "=", "{", "error", ":", "{", "message", ":", "statusMessage", ",", "code", ":", "statusCode", ",", "\"debug\"", ":", "{", "\"stack\"", ":", "err", ".", "stack", "}", "}", "}", ";", "var", "isDebug", "=", "err", ".", "stack", "&&", "(", "options", ".", "debug", "||", "(", "options", ".", "debugLocalNetwork", "&&", "ack", ".", "reqres", "(", "req", ",", "res", ")", ".", "req", ".", "isLocalNetwork", "(", ")", ")", ")", ";", "if", "(", "isDebug", ")", "{", "rtn", ".", "error", "[", "\"stack\"", "]", "=", "err", ".", "stack", ";", "}", "var", "output", "=", "JSON", ".", "stringify", "(", "rtn", ")", ";", "res", ".", "setHeader", "(", "'message'", ",", "statusMessage", ")", ";", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'application/json'", ")", ";", "res", ".", "setHeader", "(", "'Content-Length'", ",", "output", ".", "length", ".", "toString", "(", ")", ")", ";", "res", ".", "end", "(", "output", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "'ack/modules/reqres/res.js jsonCloseError failed hard'", ")", ";", "console", ".", "error", "(", "e", ")", ";", "console", ".", "error", "(", "'------ original error ------'", ",", "statusMessage", ")", ";", "console", ".", "error", "(", "err", ")", ";", "if", "(", "next", ")", "{", "next", "(", "err", ")", ";", "}", "else", "{", "throw", "err", ";", "}", "}", "}", ";", "}" ]
returns middleware that handles errors with JSON style details @options {debug:true/false, debugLocalNetwork:true}
[ "returns", "middleware", "that", "handles", "errors", "with", "JSON", "style", "details" ]
c123d3fcbdd0195630fece6dc9ddee8910c9e115
https://github.com/AckerApple/ack-node/blob/c123d3fcbdd0195630fece6dc9ddee8910c9e115/js/modules/router.js#L615-L670
train
rootsdev/gedcomx-js
src/core/Attribution.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Attribution)){ return new Attribution(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Attribution.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Attribution)){ return new Attribution(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Attribution.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Attribution", ")", ")", "{", "return", "new", "Attribution", "(", "json", ")", ";", "}", "if", "(", "Attribution", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Define who is contributing information, when they contributed it, and why they are making the contribution. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#attribution|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json]
[ "Define", "who", "is", "contributing", "information", "when", "they", "contributed", "it", "and", "why", "they", "are", "making", "the", "contribution", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Attribution.js#L14-L27
train
ghepesdoru/babel-plugin-module-alias-rn
src/index.js
adaptModulePath
function adaptModulePath(modulePath, state) { // const fileName = state.file.opts.filename; const options = getStateOptions(state); const filesMap = createFilesMap(options); const rootPath = getRootPath(options); let module = determineContext(modulePath, options); // Do not generate infinite cyrcular references on empty nodes if (!module.file) { return null; } // Safeguard against circular calls if (lastIn === lastOut) { return null; } // Remove relative path prefix before replace const absoluteModule = path.isAbsolute(module.file); // Try to replace aliased module let found = false; let constantModulePart; filesMap.keys.filter((k) => { const d = filesMap.contents[k]; let idx = module.file.search(d.regexp); if (!found && idx > -1) { // throw `Found ${d} in ${module.file}` // constantModulePart = module.file.slice(0, idx) || './'; constantModulePart = './'; if (module.file[idx] === '/') { idx += 1; } const value = d.value[0] === '.' && idx > 0 ? d.value.slice(2) : d.value; // const value = d.value; // Replace the alias with it's path and continue module.file = `${module.file.slice(0, idx) || ''}${value}${module.file.slice(idx + d.expose.length) || ''}`; found = true; // Revaluate npm and react flags based on the new mapping module = determineContext(module.file, options); return true; } return false; }); // Leave NPM modules as resolved, do not remap and ignore wrongfully formatted strings of form require('npm:') if (module.npm) { return module.file || null; } // Do not touch direct requires to npm modules (non annotated) if (module.file.indexOf('./') !== 0 && module.file.indexOf('/') !== 0) { return null; } // Check if any substitution took place if (found) { // Module alias substituted if (!path.isAbsolute(module.file)) { if (!absoluteModule && module.file[0] !== '.') { // Add the relative notation back module.file = `./${module.file}`; } } } // Do not break node_modules required by name if (!found && module.file[0] !== '.') { if (reactOsFileInfer(options)) { const aux2 = mapForReact(module.file); if (aux2 !== module.file) { return aux2; } } return null; } // Enforce absolute paths on absolute mode if (rootPath) { if (!path.isAbsolute(module.file)) { module.file = path.join(rootPath, module.file); if (reactOsFileInfer(options)) { return mapForReact(module.file); } return module.file; } // After the node is replaced the visitor will be called again. // Without this condition these functions will generate a circular loop. return null; } // throw `Gets here: ${JSON.stringify(module.file)}`; // Do not bother with relative paths that are not aliased if (!found) { return null; } let moduleMapped = mapToRelative(module.file, constantModulePart, options); if (moduleMapped.indexOf('./') !== 0) { moduleMapped = `./${moduleMapped}`; } // throw JSON.stringify({ // moduleMapped, modulePath, module, constantModulePart // }, null, 2); return moduleMapped !== modulePath ? moduleMapped : null; }
javascript
function adaptModulePath(modulePath, state) { // const fileName = state.file.opts.filename; const options = getStateOptions(state); const filesMap = createFilesMap(options); const rootPath = getRootPath(options); let module = determineContext(modulePath, options); // Do not generate infinite cyrcular references on empty nodes if (!module.file) { return null; } // Safeguard against circular calls if (lastIn === lastOut) { return null; } // Remove relative path prefix before replace const absoluteModule = path.isAbsolute(module.file); // Try to replace aliased module let found = false; let constantModulePart; filesMap.keys.filter((k) => { const d = filesMap.contents[k]; let idx = module.file.search(d.regexp); if (!found && idx > -1) { // throw `Found ${d} in ${module.file}` // constantModulePart = module.file.slice(0, idx) || './'; constantModulePart = './'; if (module.file[idx] === '/') { idx += 1; } const value = d.value[0] === '.' && idx > 0 ? d.value.slice(2) : d.value; // const value = d.value; // Replace the alias with it's path and continue module.file = `${module.file.slice(0, idx) || ''}${value}${module.file.slice(idx + d.expose.length) || ''}`; found = true; // Revaluate npm and react flags based on the new mapping module = determineContext(module.file, options); return true; } return false; }); // Leave NPM modules as resolved, do not remap and ignore wrongfully formatted strings of form require('npm:') if (module.npm) { return module.file || null; } // Do not touch direct requires to npm modules (non annotated) if (module.file.indexOf('./') !== 0 && module.file.indexOf('/') !== 0) { return null; } // Check if any substitution took place if (found) { // Module alias substituted if (!path.isAbsolute(module.file)) { if (!absoluteModule && module.file[0] !== '.') { // Add the relative notation back module.file = `./${module.file}`; } } } // Do not break node_modules required by name if (!found && module.file[0] !== '.') { if (reactOsFileInfer(options)) { const aux2 = mapForReact(module.file); if (aux2 !== module.file) { return aux2; } } return null; } // Enforce absolute paths on absolute mode if (rootPath) { if (!path.isAbsolute(module.file)) { module.file = path.join(rootPath, module.file); if (reactOsFileInfer(options)) { return mapForReact(module.file); } return module.file; } // After the node is replaced the visitor will be called again. // Without this condition these functions will generate a circular loop. return null; } // throw `Gets here: ${JSON.stringify(module.file)}`; // Do not bother with relative paths that are not aliased if (!found) { return null; } let moduleMapped = mapToRelative(module.file, constantModulePart, options); if (moduleMapped.indexOf('./') !== 0) { moduleMapped = `./${moduleMapped}`; } // throw JSON.stringify({ // moduleMapped, modulePath, module, constantModulePart // }, null, 2); return moduleMapped !== modulePath ? moduleMapped : null; }
[ "function", "adaptModulePath", "(", "modulePath", ",", "state", ")", "{", "const", "options", "=", "getStateOptions", "(", "state", ")", ";", "const", "filesMap", "=", "createFilesMap", "(", "options", ")", ";", "const", "rootPath", "=", "getRootPath", "(", "options", ")", ";", "let", "module", "=", "determineContext", "(", "modulePath", ",", "options", ")", ";", "if", "(", "!", "module", ".", "file", ")", "{", "return", "null", ";", "}", "if", "(", "lastIn", "===", "lastOut", ")", "{", "return", "null", ";", "}", "const", "absoluteModule", "=", "path", ".", "isAbsolute", "(", "module", ".", "file", ")", ";", "let", "found", "=", "false", ";", "let", "constantModulePart", ";", "filesMap", ".", "keys", ".", "filter", "(", "(", "k", ")", "=>", "{", "const", "d", "=", "filesMap", ".", "contents", "[", "k", "]", ";", "let", "idx", "=", "module", ".", "file", ".", "search", "(", "d", ".", "regexp", ")", ";", "if", "(", "!", "found", "&&", "idx", ">", "-", "1", ")", "{", "constantModulePart", "=", "'./'", ";", "if", "(", "module", ".", "file", "[", "idx", "]", "===", "'/'", ")", "{", "idx", "+=", "1", ";", "}", "const", "value", "=", "d", ".", "value", "[", "0", "]", "===", "'.'", "&&", "idx", ">", "0", "?", "d", ".", "value", ".", "slice", "(", "2", ")", ":", "d", ".", "value", ";", "module", ".", "file", "=", "`", "${", "module", ".", "file", ".", "slice", "(", "0", ",", "idx", ")", "||", "''", "}", "${", "value", "}", "${", "module", ".", "file", ".", "slice", "(", "idx", "+", "d", ".", "expose", ".", "length", ")", "||", "''", "}", "`", ";", "found", "=", "true", ";", "module", "=", "determineContext", "(", "module", ".", "file", ",", "options", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "if", "(", "module", ".", "npm", ")", "{", "return", "module", ".", "file", "||", "null", ";", "}", "if", "(", "module", ".", "file", ".", "indexOf", "(", "'./'", ")", "!==", "0", "&&", "module", ".", "file", ".", "indexOf", "(", "'/'", ")", "!==", "0", ")", "{", "return", "null", ";", "}", "if", "(", "found", ")", "{", "if", "(", "!", "path", ".", "isAbsolute", "(", "module", ".", "file", ")", ")", "{", "if", "(", "!", "absoluteModule", "&&", "module", ".", "file", "[", "0", "]", "!==", "'.'", ")", "{", "module", ".", "file", "=", "`", "${", "module", ".", "file", "}", "`", ";", "}", "}", "}", "if", "(", "!", "found", "&&", "module", ".", "file", "[", "0", "]", "!==", "'.'", ")", "{", "if", "(", "reactOsFileInfer", "(", "options", ")", ")", "{", "const", "aux2", "=", "mapForReact", "(", "module", ".", "file", ")", ";", "if", "(", "aux2", "!==", "module", ".", "file", ")", "{", "return", "aux2", ";", "}", "}", "return", "null", ";", "}", "if", "(", "rootPath", ")", "{", "if", "(", "!", "path", ".", "isAbsolute", "(", "module", ".", "file", ")", ")", "{", "module", ".", "file", "=", "path", ".", "join", "(", "rootPath", ",", "module", ".", "file", ")", ";", "if", "(", "reactOsFileInfer", "(", "options", ")", ")", "{", "return", "mapForReact", "(", "module", ".", "file", ")", ";", "}", "return", "module", ".", "file", ";", "}", "return", "null", ";", "}", "if", "(", "!", "found", ")", "{", "return", "null", ";", "}", "let", "moduleMapped", "=", "mapToRelative", "(", "module", ".", "file", ",", "constantModulePart", ",", "options", ")", ";", "if", "(", "moduleMapped", ".", "indexOf", "(", "'./'", ")", "!==", "0", ")", "{", "moduleMapped", "=", "`", "${", "moduleMapped", "}", "`", ";", "}", "return", "moduleMapped", "!==", "modulePath", "?", "moduleMapped", ":", "null", ";", "}" ]
Adapts a module path to the context of caller
[ "Adapts", "a", "module", "path", "to", "the", "context", "of", "caller" ]
db516c8623c3f598237fab07d164126386140186
https://github.com/ghepesdoru/babel-plugin-module-alias-rn/blob/db516c8623c3f598237fab07d164126386140186/src/index.js#L201-L322
train
rootsdev/gedcomx-js
src/core/Conclusion.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Conclusion)){ return new Conclusion(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Conclusion.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Conclusion)){ return new Conclusion(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Conclusion.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Conclusion", ")", ")", "{", "return", "new", "Conclusion", "(", "json", ")", ";", "}", "if", "(", "Conclusion", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
An abstract concept for a basic genealogical data item. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#conclusion|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json]
[ "An", "abstract", "concept", "for", "a", "basic", "genealogical", "data", "item", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Conclusion.js#L13-L26
train
rootsdev/gedcomx-js
src/core/EventRole.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof EventRole)){ return new EventRole(json); } // If the given object is already an instance then just return it. DON'T copy it. if(GedcomX.Conclusion.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof EventRole)){ return new EventRole(json); } // If the given object is already an instance then just return it. DON'T copy it. if(GedcomX.Conclusion.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "EventRole", ")", ")", "{", "return", "new", "EventRole", "(", "json", ")", ";", "}", "if", "(", "GedcomX", ".", "Conclusion", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A role that a specific person plays in an event. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#conclusion-event-role|GEDCOM X JSON Spec} @class @extends Conclusion @param {Object} [json]
[ "A", "role", "that", "a", "specific", "person", "plays", "in", "an", "event", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/EventRole.js#L13-L26
train
Ubudu/uBeacon-uart-lib
node/uBeaconUARTController.js
function(finishedCallback){ self.getUARTProtocolVersion(function(data,error){ self.deviceData.uartProtocolVersion = data; finishedCallback(error); }); }
javascript
function(finishedCallback){ self.getUARTProtocolVersion(function(data,error){ self.deviceData.uartProtocolVersion = data; finishedCallback(error); }); }
[ "function", "(", "finishedCallback", ")", "{", "self", ".", "getUARTProtocolVersion", "(", "function", "(", "data", ",", "error", ")", "{", "self", ".", "deviceData", ".", "uartProtocolVersion", "=", "data", ";", "finishedCallback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Get uart protocol version
[ "Get", "uart", "protocol", "version" ]
a7436f3491f61ffabb34e2bc3b2441cc048f5dfa
https://github.com/Ubudu/uBeacon-uart-lib/blob/a7436f3491f61ffabb34e2bc3b2441cc048f5dfa/node/uBeaconUARTController.js#L207-L212
train
Ubudu/uBeacon-uart-lib
node/uBeaconUARTController.js
function(finishedCallback){ self.getHardwareModel(function(data,error){ self.deviceData.hardwareModel = data; finishedCallback(error); }); }
javascript
function(finishedCallback){ self.getHardwareModel(function(data,error){ self.deviceData.hardwareModel = data; finishedCallback(error); }); }
[ "function", "(", "finishedCallback", ")", "{", "self", ".", "getHardwareModel", "(", "function", "(", "data", ",", "error", ")", "{", "self", ".", "deviceData", ".", "hardwareModel", "=", "data", ";", "finishedCallback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Get hardware model
[ "Get", "hardware", "model" ]
a7436f3491f61ffabb34e2bc3b2441cc048f5dfa
https://github.com/Ubudu/uBeacon-uart-lib/blob/a7436f3491f61ffabb34e2bc3b2441cc048f5dfa/node/uBeaconUARTController.js#L214-L219
train
Ubudu/uBeacon-uart-lib
node/uBeaconUARTController.js
function(finishedCallback){ self.getHardwareVersion(function(data,error){ self.deviceData.hardwareVersion = data; finishedCallback(error); }); }
javascript
function(finishedCallback){ self.getHardwareVersion(function(data,error){ self.deviceData.hardwareVersion = data; finishedCallback(error); }); }
[ "function", "(", "finishedCallback", ")", "{", "self", ".", "getHardwareVersion", "(", "function", "(", "data", ",", "error", ")", "{", "self", ".", "deviceData", ".", "hardwareVersion", "=", "data", ";", "finishedCallback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Get hardware version
[ "Get", "hardware", "version" ]
a7436f3491f61ffabb34e2bc3b2441cc048f5dfa
https://github.com/Ubudu/uBeacon-uart-lib/blob/a7436f3491f61ffabb34e2bc3b2441cc048f5dfa/node/uBeaconUARTController.js#L221-L226
train
Ubudu/uBeacon-uart-lib
node/uBeaconUARTController.js
function(finishedCallback){ self.getFirmwareVersion(function(data,error){ self.deviceData.firmwareVersion = data; finishedCallback(error); }); }
javascript
function(finishedCallback){ self.getFirmwareVersion(function(data,error){ self.deviceData.firmwareVersion = data; finishedCallback(error); }); }
[ "function", "(", "finishedCallback", ")", "{", "self", ".", "getFirmwareVersion", "(", "function", "(", "data", ",", "error", ")", "{", "self", ".", "deviceData", ".", "firmwareVersion", "=", "data", ";", "finishedCallback", "(", "error", ")", ";", "}", ")", ";", "}" ]
Get firmware version
[ "Get", "firmware", "version" ]
a7436f3491f61ffabb34e2bc3b2441cc048f5dfa
https://github.com/Ubudu/uBeacon-uart-lib/blob/a7436f3491f61ffabb34e2bc3b2441cc048f5dfa/node/uBeaconUARTController.js#L228-L233
train
intel/grunt-zipup
tasks/grunt-zipup.js
function (path) { if (fs.existsSync(path) && fs.statSync(path).isDirectory()) { return true; } return false; }
javascript
function (path) { if (fs.existsSync(path) && fs.statSync(path).isDirectory()) { return true; } return false; }
[ "function", "(", "path", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "path", ")", "&&", "fs", ".", "statSync", "(", "path", ")", ".", "isDirectory", "(", ")", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
returns true if path exists and is a directory
[ "returns", "true", "if", "path", "exists", "and", "is", "a", "directory" ]
872e47cab6d111e7a61c69a042927fc6ffea0b79
https://github.com/intel/grunt-zipup/blob/872e47cab6d111e7a61c69a042927fc6ffea0b79/tasks/grunt-zipup.js#L45-L50
train
stylecow/stylecow-core
lib/tasks.js
needFix
function needFix (stylecowSupport, task, method) { const taskSupport = task[method]; if (!taskSupport || !stylecowSupport) { return true; } for (let browser in taskSupport) { if (stylecowSupport[browser] === false) { continue; } if (method === 'forBrowsersLowerThan' && (taskSupport[browser] === false || stylecowSupport[browser] < taskSupport[browser])) { return true; } if (method === 'forBrowsersUpperOrEqualTo') { if (taskSupport[browser] === false) { return false; } if (stylecowSupport[browser] >= taskSupport[browser]) { return true; } } } return false; }
javascript
function needFix (stylecowSupport, task, method) { const taskSupport = task[method]; if (!taskSupport || !stylecowSupport) { return true; } for (let browser in taskSupport) { if (stylecowSupport[browser] === false) { continue; } if (method === 'forBrowsersLowerThan' && (taskSupport[browser] === false || stylecowSupport[browser] < taskSupport[browser])) { return true; } if (method === 'forBrowsersUpperOrEqualTo') { if (taskSupport[browser] === false) { return false; } if (stylecowSupport[browser] >= taskSupport[browser]) { return true; } } } return false; }
[ "function", "needFix", "(", "stylecowSupport", ",", "task", ",", "method", ")", "{", "const", "taskSupport", "=", "task", "[", "method", "]", ";", "if", "(", "!", "taskSupport", "||", "!", "stylecowSupport", ")", "{", "return", "true", ";", "}", "for", "(", "let", "browser", "in", "taskSupport", ")", "{", "if", "(", "stylecowSupport", "[", "browser", "]", "===", "false", ")", "{", "continue", ";", "}", "if", "(", "method", "===", "'forBrowsersLowerThan'", "&&", "(", "taskSupport", "[", "browser", "]", "===", "false", "||", "stylecowSupport", "[", "browser", "]", "<", "taskSupport", "[", "browser", "]", ")", ")", "{", "return", "true", ";", "}", "if", "(", "method", "===", "'forBrowsersUpperOrEqualTo'", ")", "{", "if", "(", "taskSupport", "[", "browser", "]", "===", "false", ")", "{", "return", "false", ";", "}", "if", "(", "stylecowSupport", "[", "browser", "]", ">=", "taskSupport", "[", "browser", "]", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
check the browser support of a task
[ "check", "the", "browser", "support", "of", "a", "task" ]
8c22ec4cff21b10966d1e90fe870f037a8635976
https://github.com/stylecow/stylecow-core/blob/8c22ec4cff21b10966d1e90fe870f037a8635976/lib/tasks.js#L117-L145
train
rootsdev/gedcomx-js
src/atom/AtomSource.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomSource)){ return new AtomSource(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomSource.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomSource)){ return new AtomSource(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomSource.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AtomSource", ")", ")", "{", "return", "new", "AtomSource", "(", "json", ")", ";", "}", "if", "(", "AtomSource", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Information about the originating feed if an entry is copied or aggregated from another feed. @see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/atom-model-specification.md#atom-json-media-type|GEDCOM X Atom JSON Spec} @see {@link https://tools.ietf.org/html/rfc4287#section-4.2.11|RFC 4287} @class AtomSource @extends AtomCommon @param {Object} [json]
[ "Information", "about", "the", "originating", "feed", "if", "an", "entry", "is", "copied", "or", "aggregated", "from", "another", "feed", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/atom/AtomSource.js#L17-L30
train
stackr23/cssobjects-loader
lib/transformToNestedDomStyleObjects.js
transformPropertiesToCamelCase
function transformPropertiesToCamelCase (object) { var output = {} for (var _key in object) { if (typeof object === 'string') { return object.replace(' !important', '') } var key = _key var value = object[_key] if (~key.indexOf('-')) { var splittedKeys = key.split('-') splittedKeys = splittedKeys.map(function (v, i) { return i > 0 // UCFIRST if ! first element ? v.charAt(0).toUpperCase() + v.substr(1) : v }) key = splittedKeys.join('') } output[key] = transformPropertiesToCamelCase(value) } return output }
javascript
function transformPropertiesToCamelCase (object) { var output = {} for (var _key in object) { if (typeof object === 'string') { return object.replace(' !important', '') } var key = _key var value = object[_key] if (~key.indexOf('-')) { var splittedKeys = key.split('-') splittedKeys = splittedKeys.map(function (v, i) { return i > 0 // UCFIRST if ! first element ? v.charAt(0).toUpperCase() + v.substr(1) : v }) key = splittedKeys.join('') } output[key] = transformPropertiesToCamelCase(value) } return output }
[ "function", "transformPropertiesToCamelCase", "(", "object", ")", "{", "var", "output", "=", "{", "}", "for", "(", "var", "_key", "in", "object", ")", "{", "if", "(", "typeof", "object", "===", "'string'", ")", "{", "return", "object", ".", "replace", "(", "' !important'", ",", "''", ")", "}", "var", "key", "=", "_key", "var", "value", "=", "object", "[", "_key", "]", "if", "(", "~", "key", ".", "indexOf", "(", "'-'", ")", ")", "{", "var", "splittedKeys", "=", "key", ".", "split", "(", "'-'", ")", "splittedKeys", "=", "splittedKeys", ".", "map", "(", "function", "(", "v", ",", "i", ")", "{", "return", "i", ">", "0", "?", "v", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "v", ".", "substr", "(", "1", ")", ":", "v", "}", ")", "key", "=", "splittedKeys", ".", "join", "(", "''", ")", "}", "output", "[", "key", "]", "=", "transformPropertiesToCamelCase", "(", "value", ")", "}", "return", "output", "}" ]
f.e. font-family => fontFamily border-radius => borderRadius
[ "f", ".", "e", ".", "font", "-", "family", "=", ">", "fontFamily", "border", "-", "radius", "=", ">", "borderRadius" ]
eab363c1df302429b85d5b36d8b65cadf7318ba4
https://github.com/stackr23/cssobjects-loader/blob/eab363c1df302429b85d5b36d8b65cadf7318ba4/lib/transformToNestedDomStyleObjects.js#L8-L27
train
jaredhanson/junction-disco
lib/junction-disco/elements/item.js
Item
function Item(jid, node, name) { Element.call(this, 'item', 'http://jabber.org/protocol/disco#items'); this.jid = jid; this.node = node; this.displayName = name; }
javascript
function Item(jid, node, name) { Element.call(this, 'item', 'http://jabber.org/protocol/disco#items'); this.jid = jid; this.node = node; this.displayName = name; }
[ "function", "Item", "(", "jid", ",", "node", ",", "name", ")", "{", "Element", ".", "call", "(", "this", ",", "'item'", ",", "'http://jabber.org/protocol/disco#items'", ")", ";", "this", ".", "jid", "=", "jid", ";", "this", ".", "node", "=", "node", ";", "this", ".", "displayName", "=", "name", ";", "}" ]
Initialize a new `Item` element. @param {String} jid @param {String} node @param {String} name @api public
[ "Initialize", "a", "new", "Item", "element", "." ]
89f2d222518b3b0f282d54b25d6405b5e35c1383
https://github.com/jaredhanson/junction-disco/blob/89f2d222518b3b0f282d54b25d6405b5e35c1383/lib/junction-disco/elements/item.js#L15-L20
train
SamVerschueren/gulp-cordova-icon
index.js
copyIcon
function copyIcon() { var dest = path.join(process.env.PWD, 'res'); // Make sure the destination exists mkdir(dest); return pify(fs.copy.bind(fs), Promise)(src, path.join(dest, 'icon.' + mime.extension(mimetype))); }
javascript
function copyIcon() { var dest = path.join(process.env.PWD, 'res'); // Make sure the destination exists mkdir(dest); return pify(fs.copy.bind(fs), Promise)(src, path.join(dest, 'icon.' + mime.extension(mimetype))); }
[ "function", "copyIcon", "(", ")", "{", "var", "dest", "=", "path", ".", "join", "(", "process", ".", "env", ".", "PWD", ",", "'res'", ")", ";", "mkdir", "(", "dest", ")", ";", "return", "pify", "(", "fs", ".", "copy", ".", "bind", "(", "fs", ")", ",", "Promise", ")", "(", "src", ",", "path", ".", "join", "(", "dest", ",", "'icon.'", "+", "mime", ".", "extension", "(", "mimetype", ")", ")", ")", ";", "}" ]
Copy the icon to the res subdirectory of the cordova build.
[ "Copy", "the", "icon", "to", "the", "res", "subdirectory", "of", "the", "cordova", "build", "." ]
e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380
https://github.com/SamVerschueren/gulp-cordova-icon/blob/e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380/index.js#L33-L40
train
SamVerschueren/gulp-cordova-icon
index.js
copyHooks
function copyHooks() { var src = path.join(__dirname, 'hooks'); var dest = path.join(process.env.PWD, 'hooks'); return pify(fs.copy.bind(fs), Promise)(path.join(__dirname, 'platforms.json'), path.join(dest, 'platforms.json')) .then(function () { memFsEditor.copyTpl(src, dest, options); return pify(memFsEditor.commit.bind(memFsEditor))(); }) .then(function () { // Make all the scripts executable in the Cordova project fs.readdirSync(src).forEach(function (hook) { var hookPath = path.join(dest, hook); fs.readdirSync(hookPath).forEach(function (script) { fs.chmodSync(path.join(hookPath, script), '755'); }); }); }); }
javascript
function copyHooks() { var src = path.join(__dirname, 'hooks'); var dest = path.join(process.env.PWD, 'hooks'); return pify(fs.copy.bind(fs), Promise)(path.join(__dirname, 'platforms.json'), path.join(dest, 'platforms.json')) .then(function () { memFsEditor.copyTpl(src, dest, options); return pify(memFsEditor.commit.bind(memFsEditor))(); }) .then(function () { // Make all the scripts executable in the Cordova project fs.readdirSync(src).forEach(function (hook) { var hookPath = path.join(dest, hook); fs.readdirSync(hookPath).forEach(function (script) { fs.chmodSync(path.join(hookPath, script), '755'); }); }); }); }
[ "function", "copyHooks", "(", ")", "{", "var", "src", "=", "path", ".", "join", "(", "__dirname", ",", "'hooks'", ")", ";", "var", "dest", "=", "path", ".", "join", "(", "process", ".", "env", ".", "PWD", ",", "'hooks'", ")", ";", "return", "pify", "(", "fs", ".", "copy", ".", "bind", "(", "fs", ")", ",", "Promise", ")", "(", "path", ".", "join", "(", "__dirname", ",", "'platforms.json'", ")", ",", "path", ".", "join", "(", "dest", ",", "'platforms.json'", ")", ")", ".", "then", "(", "function", "(", ")", "{", "memFsEditor", ".", "copyTpl", "(", "src", ",", "dest", ",", "options", ")", ";", "return", "pify", "(", "memFsEditor", ".", "commit", ".", "bind", "(", "memFsEditor", ")", ")", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "fs", ".", "readdirSync", "(", "src", ")", ".", "forEach", "(", "function", "(", "hook", ")", "{", "var", "hookPath", "=", "path", ".", "join", "(", "dest", ",", "hook", ")", ";", "fs", ".", "readdirSync", "(", "hookPath", ")", ".", "forEach", "(", "function", "(", "script", ")", "{", "fs", ".", "chmodSync", "(", "path", ".", "join", "(", "hookPath", ",", "script", ")", ",", "'755'", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Copy all the hooks in the `hooks` directory to the `hooks` directory of the cordova project.
[ "Copy", "all", "the", "hooks", "in", "the", "hooks", "directory", "to", "the", "hooks", "directory", "of", "the", "cordova", "project", "." ]
e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380
https://github.com/SamVerschueren/gulp-cordova-icon/blob/e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380/index.js#L46-L66
train
SamVerschueren/gulp-cordova-icon
index.js
installHookDependencies
function installHookDependencies() { return Promise.all(hookDependencies.map(function (dependency) { return pify(npmi, Promise)({name: dependency, path: path.join(process.env.PWD, 'hooks')}); })); }
javascript
function installHookDependencies() { return Promise.all(hookDependencies.map(function (dependency) { return pify(npmi, Promise)({name: dependency, path: path.join(process.env.PWD, 'hooks')}); })); }
[ "function", "installHookDependencies", "(", ")", "{", "return", "Promise", ".", "all", "(", "hookDependencies", ".", "map", "(", "function", "(", "dependency", ")", "{", "return", "pify", "(", "npmi", ",", "Promise", ")", "(", "{", "name", ":", "dependency", ",", "path", ":", "path", ".", "join", "(", "process", ".", "env", ".", "PWD", ",", "'hooks'", ")", "}", ")", ";", "}", ")", ")", ";", "}" ]
Install all the dependencies that are used by the hooks.
[ "Install", "all", "the", "dependencies", "that", "are", "used", "by", "the", "hooks", "." ]
e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380
https://github.com/SamVerschueren/gulp-cordova-icon/blob/e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380/index.js#L71-L75
train
rootsdev/gedcomx-js
src/core/Note.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Note)){ return new Note(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Note.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Note)){ return new Note(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Note.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Note", ")", ")", "{", "return", "new", "Note", "(", "json", ")", ";", "}", "if", "(", "Note", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A note about a resource. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#note|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json]
[ "A", "note", "about", "a", "resource", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Note.js#L13-L26
train
mmalecki/seneca-loadbalance-transport
index.js
makeWorker
function makeWorker(worker) { return { seneca: Seneca().client(worker), id: worker.id, up: undefined, lastCallDuration: -1, meanCallDuration: -1, host: worker.host, port: worker.port, type: worker.type } }
javascript
function makeWorker(worker) { return { seneca: Seneca().client(worker), id: worker.id, up: undefined, lastCallDuration: -1, meanCallDuration: -1, host: worker.host, port: worker.port, type: worker.type } }
[ "function", "makeWorker", "(", "worker", ")", "{", "return", "{", "seneca", ":", "Seneca", "(", ")", ".", "client", "(", "worker", ")", ",", "id", ":", "worker", ".", "id", ",", "up", ":", "undefined", ",", "lastCallDuration", ":", "-", "1", ",", "meanCallDuration", ":", "-", "1", ",", "host", ":", "worker", ".", "host", ",", "port", ":", "worker", ".", "port", ",", "type", ":", "worker", ".", "type", "}", "}" ]
Make a worker and put it in our `workers` object
[ "Make", "a", "worker", "and", "put", "it", "in", "our", "workers", "object" ]
08d7e37370ace7768baaed5234054ec9db9d27a4
https://github.com/mmalecki/seneca-loadbalance-transport/blob/08d7e37370ace7768baaed5234054ec9db9d27a4/index.js#L37-L48
train
mmalecki/seneca-loadbalance-transport
index.js
nextWorker
function nextWorker(cb) { seneca.act('role:loadbalance,hook:balance', { workers: workers, lastWorker: lastWorker }, function (err, worker) { if (!worker) return cb(new Error('No up backend found')) lastWorker = worker cb(null, worker) }) }
javascript
function nextWorker(cb) { seneca.act('role:loadbalance,hook:balance', { workers: workers, lastWorker: lastWorker }, function (err, worker) { if (!worker) return cb(new Error('No up backend found')) lastWorker = worker cb(null, worker) }) }
[ "function", "nextWorker", "(", "cb", ")", "{", "seneca", ".", "act", "(", "'role:loadbalance,hook:balance'", ",", "{", "workers", ":", "workers", ",", "lastWorker", ":", "lastWorker", "}", ",", "function", "(", "err", ",", "worker", ")", "{", "if", "(", "!", "worker", ")", "return", "cb", "(", "new", "Error", "(", "'No up backend found'", ")", ")", "lastWorker", "=", "worker", "cb", "(", "null", ",", "worker", ")", "}", ")", "}" ]
Get the next worker by asking the `balance` hook for one. Default one is round robin, as implemented in `roundRobin`.
[ "Get", "the", "next", "worker", "by", "asking", "the", "balance", "hook", "for", "one", ".", "Default", "one", "is", "round", "robin", "as", "implemented", "in", "roundRobin", "." ]
08d7e37370ace7768baaed5234054ec9db9d27a4
https://github.com/mmalecki/seneca-loadbalance-transport/blob/08d7e37370ace7768baaed5234054ec9db9d27a4/index.js#L52-L61
train
mmalecki/seneca-loadbalance-transport
index.js
addWorker
function addWorker(worker, cb) { function ping() { // A thing to keep in mind that right now it can take very long // (I think default is 22222 ms) for a request to time out, even // in scenarios like remote side breaking the connection and // ECONNREFUSED on reconnect. madeWorker.seneca.act({ role: 'transport', cmd: 'ping' }, function (err) { worker.up = !isTaskTimeout(err) }) } if (!worker.id) worker.id = nid() var madeWorker = makeWorker(worker) madeWorker.pingInterval = setInterval(ping, opts.pingInterval || 1000) ping() workers.push(madeWorker) cb(null, madeWorker) }
javascript
function addWorker(worker, cb) { function ping() { // A thing to keep in mind that right now it can take very long // (I think default is 22222 ms) for a request to time out, even // in scenarios like remote side breaking the connection and // ECONNREFUSED on reconnect. madeWorker.seneca.act({ role: 'transport', cmd: 'ping' }, function (err) { worker.up = !isTaskTimeout(err) }) } if (!worker.id) worker.id = nid() var madeWorker = makeWorker(worker) madeWorker.pingInterval = setInterval(ping, opts.pingInterval || 1000) ping() workers.push(madeWorker) cb(null, madeWorker) }
[ "function", "addWorker", "(", "worker", ",", "cb", ")", "{", "function", "ping", "(", ")", "{", "madeWorker", ".", "seneca", ".", "act", "(", "{", "role", ":", "'transport'", ",", "cmd", ":", "'ping'", "}", ",", "function", "(", "err", ")", "{", "worker", ".", "up", "=", "!", "isTaskTimeout", "(", "err", ")", "}", ")", "}", "if", "(", "!", "worker", ".", "id", ")", "worker", ".", "id", "=", "nid", "(", ")", "var", "madeWorker", "=", "makeWorker", "(", "worker", ")", "madeWorker", ".", "pingInterval", "=", "setInterval", "(", "ping", ",", "opts", ".", "pingInterval", "||", "1000", ")", "ping", "(", ")", "workers", ".", "push", "(", "madeWorker", ")", "cb", "(", "null", ",", "madeWorker", ")", "}" ]
Add a new worker.
[ "Add", "a", "new", "worker", "." ]
08d7e37370ace7768baaed5234054ec9db9d27a4
https://github.com/mmalecki/seneca-loadbalance-transport/blob/08d7e37370ace7768baaed5234054ec9db9d27a4/index.js#L79-L96
train
BeLi4L/subz-hero
src/providers/subscene.js
getSubtitlesByFilename
async function getSubtitlesByFilename (filename) { // TODO: revamp this + add unit tests return getSubtitlesList(filename) .then(parseSearchResults) .then(getBestSearchResult(filename)) .then(getSubtitlesPage) .then(parseDownloadLink) .then(downloadZip) .then(extractSrt) }
javascript
async function getSubtitlesByFilename (filename) { // TODO: revamp this + add unit tests return getSubtitlesList(filename) .then(parseSearchResults) .then(getBestSearchResult(filename)) .then(getSubtitlesPage) .then(parseDownloadLink) .then(downloadZip) .then(extractSrt) }
[ "async", "function", "getSubtitlesByFilename", "(", "filename", ")", "{", "return", "getSubtitlesList", "(", "filename", ")", ".", "then", "(", "parseSearchResults", ")", ".", "then", "(", "getBestSearchResult", "(", "filename", ")", ")", ".", "then", "(", "getSubtitlesPage", ")", ".", "then", "(", "parseDownloadLink", ")", ".", "then", "(", "downloadZip", ")", ".", "then", "(", "extractSrt", ")", "}" ]
Get subtitles for the given filename. @param {string} filename @returns {Promise<string>} the subtitles, formatted as .srt
[ "Get", "subtitles", "for", "the", "given", "filename", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/providers/subscene.js#L34-L43
train
BeLi4L/subz-hero
src/providers/subscene.js
getSubtitlesList
async function getSubtitlesList (filename) { return request({ method: 'GET', uri: SUBSCENE_URL + '/subtitles/release', qs: { q: filename, // search query l: '', // language (english) r: true // released or whatever } }) }
javascript
async function getSubtitlesList (filename) { return request({ method: 'GET', uri: SUBSCENE_URL + '/subtitles/release', qs: { q: filename, // search query l: '', // language (english) r: true // released or whatever } }) }
[ "async", "function", "getSubtitlesList", "(", "filename", ")", "{", "return", "request", "(", "{", "method", ":", "'GET'", ",", "uri", ":", "SUBSCENE_URL", "+", "'/subtitles/release'", ",", "qs", ":", "{", "q", ":", "filename", ",", "l", ":", "''", ",", "r", ":", "true", "}", "}", ")", "}" ]
Search for the given file on SubScene. @param {string} filename @returns {Promise<string>} the HTML string, containing the search results
[ "Search", "for", "the", "given", "file", "on", "SubScene", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/providers/subscene.js#L51-L61
train
BeLi4L/subz-hero
src/providers/subscene.js
parseSearchResults
function parseSearchResults (html) { const $ = cheerio.load(html) return $('a') .filter(function (index, element) { const spans = $(element).find('span') return spans.length === 2 && spans.eq(0).text().trim() === 'English' }) .map(function (index, element) { const title = $(element).find('span').eq(1).text().trim() const url = $(element).attr('href') return new SearchResult({ title: title, url: url }) }) .get() }
javascript
function parseSearchResults (html) { const $ = cheerio.load(html) return $('a') .filter(function (index, element) { const spans = $(element).find('span') return spans.length === 2 && spans.eq(0).text().trim() === 'English' }) .map(function (index, element) { const title = $(element).find('span').eq(1).text().trim() const url = $(element).attr('href') return new SearchResult({ title: title, url: url }) }) .get() }
[ "function", "parseSearchResults", "(", "html", ")", "{", "const", "$", "=", "cheerio", ".", "load", "(", "html", ")", "return", "$", "(", "'a'", ")", ".", "filter", "(", "function", "(", "index", ",", "element", ")", "{", "const", "spans", "=", "$", "(", "element", ")", ".", "find", "(", "'span'", ")", "return", "spans", ".", "length", "===", "2", "&&", "spans", ".", "eq", "(", "0", ")", ".", "text", "(", ")", ".", "trim", "(", ")", "===", "'English'", "}", ")", ".", "map", "(", "function", "(", "index", ",", "element", ")", "{", "const", "title", "=", "$", "(", "element", ")", ".", "find", "(", "'span'", ")", ".", "eq", "(", "1", ")", ".", "text", "(", ")", ".", "trim", "(", ")", "const", "url", "=", "$", "(", "element", ")", ".", "attr", "(", "'href'", ")", "return", "new", "SearchResult", "(", "{", "title", ":", "title", ",", "url", ":", "url", "}", ")", "}", ")", ".", "get", "(", ")", "}" ]
Parse an HTML document that contains a list of SubScene search results. @param {string} html @returns {Array<SearchResult>} the list of search results
[ "Parse", "an", "HTML", "document", "that", "contains", "a", "list", "of", "SubScene", "search", "results", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/providers/subscene.js#L69-L85
train
BeLi4L/subz-hero
src/providers/subscene.js
downloadZip
async function downloadZip (href) { return request({ method: 'GET', uri: SUBSCENE_URL + href, encoding: null }) }
javascript
async function downloadZip (href) { return request({ method: 'GET', uri: SUBSCENE_URL + href, encoding: null }) }
[ "async", "function", "downloadZip", "(", "href", ")", "{", "return", "request", "(", "{", "method", ":", "'GET'", ",", "uri", ":", "SUBSCENE_URL", "+", "href", ",", "encoding", ":", "null", "}", ")", "}" ]
Download the subtitles based on the given link. @param {string} href @returns {Promise<Buffer>} the ZIP content
[ "Download", "the", "subtitles", "based", "on", "the", "given", "link", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/providers/subscene.js#L138-L144
train
BeLi4L/subz-hero
src/providers/subscene.js
extractSrt
function extractSrt (buffer) { const zip = new AdmZip(buffer) const srtZipEntry = zip .getEntries() .find(zipEntry => zipEntry.entryName.endsWith('.srt') ) return zip.readAsText(srtZipEntry) }
javascript
function extractSrt (buffer) { const zip = new AdmZip(buffer) const srtZipEntry = zip .getEntries() .find(zipEntry => zipEntry.entryName.endsWith('.srt') ) return zip.readAsText(srtZipEntry) }
[ "function", "extractSrt", "(", "buffer", ")", "{", "const", "zip", "=", "new", "AdmZip", "(", "buffer", ")", "const", "srtZipEntry", "=", "zip", ".", "getEntries", "(", ")", ".", "find", "(", "zipEntry", "=>", "zipEntry", ".", "entryName", ".", "endsWith", "(", "'.srt'", ")", ")", "return", "zip", ".", "readAsText", "(", "srtZipEntry", ")", "}" ]
Extract the first .srt file found in the given ZIP buffer. @param {Buffer} buffer @returns {string} the content of the first .srt file found in the given ZIP
[ "Extract", "the", "first", ".", "srt", "file", "found", "in", "the", "given", "ZIP", "buffer", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/providers/subscene.js#L152-L160
train
WRidder/backgrid-advanced-filter
src/filter-dropdown.js
function (e) { var self = this; if (e) { self.stopPropagation(e); } // Get current filter var currentFilter = self.filterStateModel.getActiveFilter(); if (currentFilter !== self.filter) { self.filterStateModel.setActiveFilter(self.filter); self.filterStateModel.trigger("filter:loaded"); } }
javascript
function (e) { var self = this; if (e) { self.stopPropagation(e); } // Get current filter var currentFilter = self.filterStateModel.getActiveFilter(); if (currentFilter !== self.filter) { self.filterStateModel.setActiveFilter(self.filter); self.filterStateModel.trigger("filter:loaded"); } }
[ "function", "(", "e", ")", "{", "var", "self", "=", "this", ";", "if", "(", "e", ")", "{", "self", ".", "stopPropagation", "(", "e", ")", ";", "}", "var", "currentFilter", "=", "self", ".", "filterStateModel", ".", "getActiveFilter", "(", ")", ";", "if", "(", "currentFilter", "!==", "self", ".", "filter", ")", "{", "self", ".", "filterStateModel", ".", "setActiveFilter", "(", "self", ".", "filter", ")", ";", "self", ".", "filterStateModel", ".", "trigger", "(", "\"filter:loaded\"", ")", ";", "}", "}" ]
Activates current filer @method setActiveFilter @param {object} e
[ "Activates", "current", "filer" ]
5b10216f091d0e4bad418398fb4ec4c4588f4475
https://github.com/WRidder/backgrid-advanced-filter/blob/5b10216f091d0e4bad418398fb4ec4c4588f4475/src/filter-dropdown.js#L49-L61
train
WRidder/backgrid-advanced-filter
src/filter-dropdown.js
function (e) { var self = this; if (self.isOpen !== true) { self.open(e); } else { self.close(e); } }
javascript
function (e) { var self = this; if (self.isOpen !== true) { self.open(e); } else { self.close(e); } }
[ "function", "(", "e", ")", "{", "var", "self", "=", "this", ";", "if", "(", "self", ".", "isOpen", "!==", "true", ")", "{", "self", ".", "open", "(", "e", ")", ";", "}", "else", "{", "self", ".", "close", "(", "e", ")", ";", "}", "}" ]
Toggle the dropdown visibility @method toggle @param {object} [e]
[ "Toggle", "the", "dropdown", "visibility" ]
5b10216f091d0e4bad418398fb4ec4c4588f4475
https://github.com/WRidder/backgrid-advanced-filter/blob/5b10216f091d0e4bad418398fb4ec4c4588f4475/src/filter-dropdown.js#L348-L356
train
WRidder/backgrid-advanced-filter
src/filter-dropdown.js
function (e) { var self = this; clearTimeout(self.closeTimeout); clearTimeout(self.deferCloseTimeout); if (e) { if (e.stopPropagation) { e.stopPropagation(); } if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; } // Don't do anything if already open if (self.isOpen) { return; } self.isOpen = true; self.$el.addClass("open"); // Notify child view self.dropdownContainerView.open(); }
javascript
function (e) { var self = this; clearTimeout(self.closeTimeout); clearTimeout(self.deferCloseTimeout); if (e) { if (e.stopPropagation) { e.stopPropagation(); } if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; } // Don't do anything if already open if (self.isOpen) { return; } self.isOpen = true; self.$el.addClass("open"); // Notify child view self.dropdownContainerView.open(); }
[ "function", "(", "e", ")", "{", "var", "self", "=", "this", ";", "clearTimeout", "(", "self", ".", "closeTimeout", ")", ";", "clearTimeout", "(", "self", ".", "deferCloseTimeout", ")", ";", "if", "(", "e", ")", "{", "if", "(", "e", ".", "stopPropagation", ")", "{", "e", ".", "stopPropagation", "(", ")", ";", "}", "if", "(", "e", ".", "preventDefault", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "}", "e", ".", "cancelBubble", "=", "true", ";", "}", "if", "(", "self", ".", "isOpen", ")", "{", "return", ";", "}", "self", ".", "isOpen", "=", "true", ";", "self", ".", "$el", ".", "addClass", "(", "\"open\"", ")", ";", "self", ".", "dropdownContainerView", ".", "open", "(", ")", ";", "}" ]
Open the dropdown @method open @param {object} [e]
[ "Open", "the", "dropdown" ]
5b10216f091d0e4bad418398fb4ec4c4588f4475
https://github.com/WRidder/backgrid-advanced-filter/blob/5b10216f091d0e4bad418398fb4ec4c4588f4475/src/filter-dropdown.js#L364-L390
train
WRidder/backgrid-advanced-filter
src/filter-dropdown.js
function (e) { var self = this; // Don't do anything if already closed if (!self.isOpen) { return; } self.isOpen = false; self.$el.removeClass("open"); // Notify child view self.dropdownContainerView.close(); }
javascript
function (e) { var self = this; // Don't do anything if already closed if (!self.isOpen) { return; } self.isOpen = false; self.$el.removeClass("open"); // Notify child view self.dropdownContainerView.close(); }
[ "function", "(", "e", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "self", ".", "isOpen", ")", "{", "return", ";", "}", "self", ".", "isOpen", "=", "false", ";", "self", ".", "$el", ".", "removeClass", "(", "\"open\"", ")", ";", "self", ".", "dropdownContainerView", ".", "close", "(", ")", ";", "}" ]
Close the dropdown @method close @param {object} [e]
[ "Close", "the", "dropdown" ]
5b10216f091d0e4bad418398fb4ec4c4588f4475
https://github.com/WRidder/backgrid-advanced-filter/blob/5b10216f091d0e4bad418398fb4ec4c4588f4475/src/filter-dropdown.js#L398-L411
train
rootsdev/gedcomx-js
src/core/Address.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Address)){ return new Address(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Address.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Address)){ return new Address(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Address.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Address", ")", ")", "{", "return", "new", "Address", "(", "json", ")", ";", "}", "if", "(", "Address", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
An address. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#address|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json]
[ "An", "address", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Address.js#L13-L26
train
greim/ng-falcor
src/index.js
function(...path) { path = pathify(path); return noUndef(path) ? model.getValueSync(path) : undefined; }
javascript
function(...path) { path = pathify(path); return noUndef(path) ? model.getValueSync(path) : undefined; }
[ "function", "(", "...", "path", ")", "{", "path", "=", "pathify", "(", "path", ")", ";", "return", "noUndef", "(", "path", ")", "?", "model", ".", "getValueSync", "(", "path", ")", ":", "undefined", ";", "}" ]
Retrieve a value. Path must reference a single node in the graph.
[ "Retrieve", "a", "value", ".", "Path", "must", "reference", "a", "single", "node", "in", "the", "graph", "." ]
bbdad2bcf63f9b3b7e0b5ead083f36b0454cccd3
https://github.com/greim/ng-falcor/blob/bbdad2bcf63f9b3b7e0b5ead083f36b0454cccd3/src/index.js#L31-L36
train
matterial/reckonjs
reckon.js
function(params) { /** * Reckon version * @type {String} */ this.version = '0.1.0'; /** * Define delimiter that marks beginning of interpolation * @type {String} */ this.delimStart = settings.delimStart; /** * Define delimiter that marks end of interpolation * @type {String} */ this.delimEnd = settings.delimEnd; /** * Get the text from params * @type {String} */ this.text = typeof params !=="undefined" && params.text !== "undefined" ? params.text : ''; /** * Get the scope from the params and ensure its an array, if not, make it one * @type {Array} */ this.scopes = typeof params !=="undefined" && typeof params.scope !== "undefined" ? [].concat(params.scope) : []; /** * Check if config needs to be applied from the global settings */ this.applyConfig(); /** * Compile the initial input */ if (typeof params !=="undefined" && typeof params.text !== "undefined") this.compile(); }
javascript
function(params) { /** * Reckon version * @type {String} */ this.version = '0.1.0'; /** * Define delimiter that marks beginning of interpolation * @type {String} */ this.delimStart = settings.delimStart; /** * Define delimiter that marks end of interpolation * @type {String} */ this.delimEnd = settings.delimEnd; /** * Get the text from params * @type {String} */ this.text = typeof params !=="undefined" && params.text !== "undefined" ? params.text : ''; /** * Get the scope from the params and ensure its an array, if not, make it one * @type {Array} */ this.scopes = typeof params !=="undefined" && typeof params.scope !== "undefined" ? [].concat(params.scope) : []; /** * Check if config needs to be applied from the global settings */ this.applyConfig(); /** * Compile the initial input */ if (typeof params !=="undefined" && typeof params.text !== "undefined") this.compile(); }
[ "function", "(", "params", ")", "{", "this", ".", "version", "=", "'0.1.0'", ";", "this", ".", "delimStart", "=", "settings", ".", "delimStart", ";", "this", ".", "delimEnd", "=", "settings", ".", "delimEnd", ";", "this", ".", "text", "=", "typeof", "params", "!==", "\"undefined\"", "&&", "params", ".", "text", "!==", "\"undefined\"", "?", "params", ".", "text", ":", "''", ";", "this", ".", "scopes", "=", "typeof", "params", "!==", "\"undefined\"", "&&", "typeof", "params", ".", "scope", "!==", "\"undefined\"", "?", "[", "]", ".", "concat", "(", "params", ".", "scope", ")", ":", "[", "]", ";", "this", ".", "applyConfig", "(", ")", ";", "if", "(", "typeof", "params", "!==", "\"undefined\"", "&&", "typeof", "params", ".", "text", "!==", "\"undefined\"", ")", "this", ".", "compile", "(", ")", ";", "}" ]
The actual Reckon implementation @param {Object} params Configuration and data
[ "The", "actual", "Reckon", "implementation" ]
39e1867886f50a2bd48eaeb15e24b24a09d22c24
https://github.com/matterial/reckonjs/blob/39e1867886f50a2bd48eaeb15e24b24a09d22c24/reckon.js#L28-L69
train
matterial/reckonjs
reckon.js
function(param) { /** * Reference the instance */ var rInstance = this; if (typeof param !== "undefined") { rInstance.text = param.text; rInstance.scopes = [].concat(param.scope); } /** * The required regexp computed using delims in settings * @type {RegExp} */ var re = new RegExp(['{%(.+?)%}|', this.delimStart, '(.+?)', this.delimEnd].join(''), 'g'); /** * Save the raw text * @type {String} */ rInstance.raw = rInstance.text; /** * Compute and assign to compiledText property of the same object * @param {String} _ Matched string * @param {String} $1 Content of first match group * @param {String} $2 Content of second match group * @return {String} Interpolated string */ rInstance.text = rInstance.text.replace(re, function(_, $1, $2) { var computed; /** * If escaped value is found, interpolation will not happen */ if ($1) { computed = $1; } /** * Matched content, let's interpolate */ if ($2) { /** * Break out scope variables out of scope's box and evaluate the expr expression */ var scopeBox = function(expr, localScope) { var variables = ''; /** * If scope is a window object, no need to scopebox it */ if (typeof window !== "undefined" ? localScope !== window : true) { for(var i in localScope) { variables += 'var ' + i + ' = localScope.' + i + '; '; } } var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()'; return eval(unbox); }; if (rInstance.scopes.length) { var numScopes = rInstance.scopes.length; for (var i=0;i<numScopes;i++) { /** * Current Scope * @type {String} */ var scope = rInstance.scopes[i]; /** * Get the computation * @type {Any} */ computed = scopeBox($2, scope); /** * If the computed property is a function, execute it in the context of the current scope * @type {Unknown} */ if (typeof computed === "function") { computed = computed.call(scope); } /** * If the computed property is an object, get the string */ if (typeof computed === "object") { computed = computed.toString(); } /** * Found what we were looking for, now break the loop */ if (computed !== undefined) break; } } else { /** * If no scope is passed, let us assume the global scope * @type {Any} */ computed = scopeBox($2, (typeof window !== "undefined" ? window : {})); } /** * If no computations were found, we return the raw matched value back * @type {String} */ computed = computed !== undefined ? computed : _; } /** * Final computed value returned */ return computed; }); /** * Return self for chaining */ return rInstance; }
javascript
function(param) { /** * Reference the instance */ var rInstance = this; if (typeof param !== "undefined") { rInstance.text = param.text; rInstance.scopes = [].concat(param.scope); } /** * The required regexp computed using delims in settings * @type {RegExp} */ var re = new RegExp(['{%(.+?)%}|', this.delimStart, '(.+?)', this.delimEnd].join(''), 'g'); /** * Save the raw text * @type {String} */ rInstance.raw = rInstance.text; /** * Compute and assign to compiledText property of the same object * @param {String} _ Matched string * @param {String} $1 Content of first match group * @param {String} $2 Content of second match group * @return {String} Interpolated string */ rInstance.text = rInstance.text.replace(re, function(_, $1, $2) { var computed; /** * If escaped value is found, interpolation will not happen */ if ($1) { computed = $1; } /** * Matched content, let's interpolate */ if ($2) { /** * Break out scope variables out of scope's box and evaluate the expr expression */ var scopeBox = function(expr, localScope) { var variables = ''; /** * If scope is a window object, no need to scopebox it */ if (typeof window !== "undefined" ? localScope !== window : true) { for(var i in localScope) { variables += 'var ' + i + ' = localScope.' + i + '; '; } } var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()'; return eval(unbox); }; if (rInstance.scopes.length) { var numScopes = rInstance.scopes.length; for (var i=0;i<numScopes;i++) { /** * Current Scope * @type {String} */ var scope = rInstance.scopes[i]; /** * Get the computation * @type {Any} */ computed = scopeBox($2, scope); /** * If the computed property is a function, execute it in the context of the current scope * @type {Unknown} */ if (typeof computed === "function") { computed = computed.call(scope); } /** * If the computed property is an object, get the string */ if (typeof computed === "object") { computed = computed.toString(); } /** * Found what we were looking for, now break the loop */ if (computed !== undefined) break; } } else { /** * If no scope is passed, let us assume the global scope * @type {Any} */ computed = scopeBox($2, (typeof window !== "undefined" ? window : {})); } /** * If no computations were found, we return the raw matched value back * @type {String} */ computed = computed !== undefined ? computed : _; } /** * Final computed value returned */ return computed; }); /** * Return self for chaining */ return rInstance; }
[ "function", "(", "param", ")", "{", "var", "rInstance", "=", "this", ";", "if", "(", "typeof", "param", "!==", "\"undefined\"", ")", "{", "rInstance", ".", "text", "=", "param", ".", "text", ";", "rInstance", ".", "scopes", "=", "[", "]", ".", "concat", "(", "param", ".", "scope", ")", ";", "}", "var", "re", "=", "new", "RegExp", "(", "[", "'{%(.+?)%}|'", ",", "this", ".", "delimStart", ",", "'(.+?)'", ",", "this", ".", "delimEnd", "]", ".", "join", "(", "''", ")", ",", "'g'", ")", ";", "rInstance", ".", "raw", "=", "rInstance", ".", "text", ";", "rInstance", ".", "text", "=", "rInstance", ".", "text", ".", "replace", "(", "re", ",", "function", "(", "_", ",", "$1", ",", "$2", ")", "{", "var", "computed", ";", "if", "(", "$1", ")", "{", "computed", "=", "$1", ";", "}", "if", "(", "$2", ")", "{", "var", "scopeBox", "=", "function", "(", "expr", ",", "localScope", ")", "{", "var", "variables", "=", "''", ";", "if", "(", "typeof", "window", "!==", "\"undefined\"", "?", "localScope", "!==", "window", ":", "true", ")", "{", "for", "(", "var", "i", "in", "localScope", ")", "{", "variables", "+=", "'var '", "+", "i", "+", "' = localScope.'", "+", "i", "+", "'; '", ";", "}", "}", "var", "unbox", "=", "'(function() { '", "+", "variables", "+", "' try { return eval(expr);} catch(e) {} })()'", ";", "return", "eval", "(", "unbox", ")", ";", "}", ";", "if", "(", "rInstance", ".", "scopes", ".", "length", ")", "{", "var", "numScopes", "=", "rInstance", ".", "scopes", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numScopes", ";", "i", "++", ")", "{", "var", "scope", "=", "rInstance", ".", "scopes", "[", "i", "]", ";", "computed", "=", "scopeBox", "(", "$2", ",", "scope", ")", ";", "if", "(", "typeof", "computed", "===", "\"function\"", ")", "{", "computed", "=", "computed", ".", "call", "(", "scope", ")", ";", "}", "if", "(", "typeof", "computed", "===", "\"object\"", ")", "{", "computed", "=", "computed", ".", "toString", "(", ")", ";", "}", "if", "(", "computed", "!==", "undefined", ")", "break", ";", "}", "}", "else", "{", "computed", "=", "scopeBox", "(", "$2", ",", "(", "typeof", "window", "!==", "\"undefined\"", "?", "window", ":", "{", "}", ")", ")", ";", "}", "computed", "=", "computed", "!==", "undefined", "?", "computed", ":", "_", ";", "}", "return", "computed", ";", "}", ")", ";", "return", "rInstance", ";", "}" ]
The function responsible for interpolation @return {Reckon} return self object for chaining
[ "The", "function", "responsible", "for", "interpolation" ]
39e1867886f50a2bd48eaeb15e24b24a09d22c24
https://github.com/matterial/reckonjs/blob/39e1867886f50a2bd48eaeb15e24b24a09d22c24/reckon.js#L81-L208
train
matterial/reckonjs
reckon.js
function(expr, localScope) { var variables = ''; /** * If scope is a window object, no need to scopebox it */ if (typeof window !== "undefined" ? localScope !== window : true) { for(var i in localScope) { variables += 'var ' + i + ' = localScope.' + i + '; '; } } var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()'; return eval(unbox); }
javascript
function(expr, localScope) { var variables = ''; /** * If scope is a window object, no need to scopebox it */ if (typeof window !== "undefined" ? localScope !== window : true) { for(var i in localScope) { variables += 'var ' + i + ' = localScope.' + i + '; '; } } var unbox = '(function() { ' + variables + ' try { return eval(expr);} catch(e) {} })()'; return eval(unbox); }
[ "function", "(", "expr", ",", "localScope", ")", "{", "var", "variables", "=", "''", ";", "if", "(", "typeof", "window", "!==", "\"undefined\"", "?", "localScope", "!==", "window", ":", "true", ")", "{", "for", "(", "var", "i", "in", "localScope", ")", "{", "variables", "+=", "'var '", "+", "i", "+", "' = localScope.'", "+", "i", "+", "'; '", ";", "}", "}", "var", "unbox", "=", "'(function() { '", "+", "variables", "+", "' try { return eval(expr);} catch(e) {} })()'", ";", "return", "eval", "(", "unbox", ")", ";", "}" ]
Break out scope variables out of scope's box and evaluate the expr expression
[ "Break", "out", "scope", "variables", "out", "of", "scope", "s", "box", "and", "evaluate", "the", "expr", "expression" ]
39e1867886f50a2bd48eaeb15e24b24a09d22c24
https://github.com/matterial/reckonjs/blob/39e1867886f50a2bd48eaeb15e24b24a09d22c24/reckon.js#L132-L145
train
matterial/reckonjs
reckon.js
function(setting) { if (typeof setting === "undefined") { if (typeof window !== "undefined") { if (typeof window.reckonSettings !== "undefined") { if (typeof window.reckonSettings.delimStart) { settings.delimStart = window.reckonSettings.delimStart; } if (typeof window.reckonSettings.delimEnd) { settings.delimEnd = window.reckonSettings.delimEnd; } } } } else { if (typeof setting.delimStart) { settings.delimStart = setting.delimStart; } if (typeof setting.delimEnd) { settings.delimEnd = setting.delimEnd; } } this.delimStart = settings.delimStart; this.delimEnd = settings.delimEnd; return this; }
javascript
function(setting) { if (typeof setting === "undefined") { if (typeof window !== "undefined") { if (typeof window.reckonSettings !== "undefined") { if (typeof window.reckonSettings.delimStart) { settings.delimStart = window.reckonSettings.delimStart; } if (typeof window.reckonSettings.delimEnd) { settings.delimEnd = window.reckonSettings.delimEnd; } } } } else { if (typeof setting.delimStart) { settings.delimStart = setting.delimStart; } if (typeof setting.delimEnd) { settings.delimEnd = setting.delimEnd; } } this.delimStart = settings.delimStart; this.delimEnd = settings.delimEnd; return this; }
[ "function", "(", "setting", ")", "{", "if", "(", "typeof", "setting", "===", "\"undefined\"", ")", "{", "if", "(", "typeof", "window", "!==", "\"undefined\"", ")", "{", "if", "(", "typeof", "window", ".", "reckonSettings", "!==", "\"undefined\"", ")", "{", "if", "(", "typeof", "window", ".", "reckonSettings", ".", "delimStart", ")", "{", "settings", ".", "delimStart", "=", "window", ".", "reckonSettings", ".", "delimStart", ";", "}", "if", "(", "typeof", "window", ".", "reckonSettings", ".", "delimEnd", ")", "{", "settings", ".", "delimEnd", "=", "window", ".", "reckonSettings", ".", "delimEnd", ";", "}", "}", "}", "}", "else", "{", "if", "(", "typeof", "setting", ".", "delimStart", ")", "{", "settings", ".", "delimStart", "=", "setting", ".", "delimStart", ";", "}", "if", "(", "typeof", "setting", ".", "delimEnd", ")", "{", "settings", ".", "delimEnd", "=", "setting", ".", "delimEnd", ";", "}", "}", "this", ".", "delimStart", "=", "settings", ".", "delimStart", ";", "this", ".", "delimEnd", "=", "settings", ".", "delimEnd", ";", "return", "this", ";", "}" ]
Modify in-built settings @param {Object} setting Delim settings @return {Object} Return self for chaining
[ "Modify", "in", "-", "built", "settings" ]
39e1867886f50a2bd48eaeb15e24b24a09d22c24
https://github.com/matterial/reckonjs/blob/39e1867886f50a2bd48eaeb15e24b24a09d22c24/reckon.js#L217-L241
train
BeLi4L/subz-hero
src/providers/subdb.js
hash
async function hash (file) { const filesize = await fileUtil.getFileSize(file) const chunkSize = 64 * 1024 const firstBytesPromise = fileUtil.readBytes({ file, chunkSize, start: 0 }) const lastBytesPromise = fileUtil.readBytes({ file, chunkSize, start: filesize - chunkSize }) const [ firstBytes, lastBytes ] = await Promise.all([firstBytesPromise, lastBytesPromise]) return crypto .createHash('md5') .update(firstBytes) .update(lastBytes) .digest('hex') }
javascript
async function hash (file) { const filesize = await fileUtil.getFileSize(file) const chunkSize = 64 * 1024 const firstBytesPromise = fileUtil.readBytes({ file, chunkSize, start: 0 }) const lastBytesPromise = fileUtil.readBytes({ file, chunkSize, start: filesize - chunkSize }) const [ firstBytes, lastBytes ] = await Promise.all([firstBytesPromise, lastBytesPromise]) return crypto .createHash('md5') .update(firstBytes) .update(lastBytes) .digest('hex') }
[ "async", "function", "hash", "(", "file", ")", "{", "const", "filesize", "=", "await", "fileUtil", ".", "getFileSize", "(", "file", ")", "const", "chunkSize", "=", "64", "*", "1024", "const", "firstBytesPromise", "=", "fileUtil", ".", "readBytes", "(", "{", "file", ",", "chunkSize", ",", "start", ":", "0", "}", ")", "const", "lastBytesPromise", "=", "fileUtil", ".", "readBytes", "(", "{", "file", ",", "chunkSize", ",", "start", ":", "filesize", "-", "chunkSize", "}", ")", "const", "[", "firstBytes", ",", "lastBytes", "]", "=", "await", "Promise", ".", "all", "(", "[", "firstBytesPromise", ",", "lastBytesPromise", "]", ")", "return", "crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "firstBytes", ")", ".", "update", "(", "lastBytes", ")", ".", "digest", "(", "'hex'", ")", "}" ]
Create the hash used to identify a file. @param {string} file - path to a file @returns {Promise<string>} a hex string representing the MD5 digest of the first 64kB and the last 64kB of the given file
[ "Create", "the", "hash", "used", "to", "identify", "a", "file", "." ]
c22c6df7c2d80c00685a9326043e1ceae3cbf53d
https://github.com/BeLi4L/subz-hero/blob/c22c6df7c2d80c00685a9326043e1ceae3cbf53d/src/providers/subdb.js#L47-L71
train
angie-framework/angie
src/services/$Response.js
controllerTemplateRouteResponse
function controllerTemplateRouteResponse() { if (this.template) { let match = this.template.toString().match(/!doctype ([a-z]+)/i), mime; // In the context where MIME type is not set, but we have a // DOCTYPE tag, we can force set the MIME // We want this here instead of the explicit template definition // in case the MIME failed earlier if (match && !this.response.$headers.hasOwnProperty('Content-Type')) { mime = this.response.$headers[ 'Content-Type' ] = $MimeType.$$(match[1].toLowerCase()); } // Check to see if this is an HTML template and has a DOCTYPE // and that the proper configuration options are set if ( mime === 'text/html' && config.loadDefaultScriptFile && ( this.route.hasOwnProperty('useDefaultScriptFile') || this.route.useDefaultScriptFile !== false ) ) { // Check that option is not true let scriptFile = config.loadDefaultScriptFile === true ? 'application.js' : config.loadDefaultScriptFile; $resourceLoader(scriptFile); } // Pull the response back in from wherever it was before this.content = this.response.content; // Render the template into the resoponse let me = this; return new Promise(function(resolve) { // $Compile to parse template strings and app.directives return $compile(me.template)( // In the context of the scope me.$scope ).then(function(template) { resolve(template); }); }).then(function(template) { me.response.content = me.content += template; me.response.write(me.content); }); } }
javascript
function controllerTemplateRouteResponse() { if (this.template) { let match = this.template.toString().match(/!doctype ([a-z]+)/i), mime; // In the context where MIME type is not set, but we have a // DOCTYPE tag, we can force set the MIME // We want this here instead of the explicit template definition // in case the MIME failed earlier if (match && !this.response.$headers.hasOwnProperty('Content-Type')) { mime = this.response.$headers[ 'Content-Type' ] = $MimeType.$$(match[1].toLowerCase()); } // Check to see if this is an HTML template and has a DOCTYPE // and that the proper configuration options are set if ( mime === 'text/html' && config.loadDefaultScriptFile && ( this.route.hasOwnProperty('useDefaultScriptFile') || this.route.useDefaultScriptFile !== false ) ) { // Check that option is not true let scriptFile = config.loadDefaultScriptFile === true ? 'application.js' : config.loadDefaultScriptFile; $resourceLoader(scriptFile); } // Pull the response back in from wherever it was before this.content = this.response.content; // Render the template into the resoponse let me = this; return new Promise(function(resolve) { // $Compile to parse template strings and app.directives return $compile(me.template)( // In the context of the scope me.$scope ).then(function(template) { resolve(template); }); }).then(function(template) { me.response.content = me.content += template; me.response.write(me.content); }); } }
[ "function", "controllerTemplateRouteResponse", "(", ")", "{", "if", "(", "this", ".", "template", ")", "{", "let", "match", "=", "this", ".", "template", ".", "toString", "(", ")", ".", "match", "(", "/", "!doctype ([a-z]+)", "/", "i", ")", ",", "mime", ";", "if", "(", "match", "&&", "!", "this", ".", "response", ".", "$headers", ".", "hasOwnProperty", "(", "'Content-Type'", ")", ")", "{", "mime", "=", "this", ".", "response", ".", "$headers", "[", "'Content-Type'", "]", "=", "$MimeType", ".", "$$", "(", "match", "[", "1", "]", ".", "toLowerCase", "(", ")", ")", ";", "}", "if", "(", "mime", "===", "'text/html'", "&&", "config", ".", "loadDefaultScriptFile", "&&", "(", "this", ".", "route", ".", "hasOwnProperty", "(", "'useDefaultScriptFile'", ")", "||", "this", ".", "route", ".", "useDefaultScriptFile", "!==", "false", ")", ")", "{", "let", "scriptFile", "=", "config", ".", "loadDefaultScriptFile", "===", "true", "?", "'application.js'", ":", "config", ".", "loadDefaultScriptFile", ";", "$resourceLoader", "(", "scriptFile", ")", ";", "}", "this", ".", "content", "=", "this", ".", "response", ".", "content", ";", "let", "me", "=", "this", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "return", "$compile", "(", "me", ".", "template", ")", "(", "me", ".", "$scope", ")", ".", "then", "(", "function", "(", "template", ")", "{", "resolve", "(", "template", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "template", ")", "{", "me", ".", "response", ".", "content", "=", "me", ".", "content", "+=", "template", ";", "me", ".", "response", ".", "write", "(", "me", ".", "content", ")", ";", "}", ")", ";", "}", "}" ]
Performs the templating inside of Controller Classes
[ "Performs", "the", "templating", "inside", "of", "Controller", "Classes" ]
7d0793f6125e60e0473b17ffd40305d6d6fdbc12
https://github.com/angie-framework/angie/blob/7d0793f6125e60e0473b17ffd40305d6d6fdbc12/src/services/$Response.js#L589-L640
train
rootsdev/gedcomx-js
src/core/Date.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof GDate)){ return new GDate(json); } // If the given object is already an instance then just return it. DON'T copy it. if(GDate.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof GDate)){ return new GDate(json); } // If the given object is already an instance then just return it. DON'T copy it. if(GDate.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "GDate", ")", ")", "{", "return", "new", "GDate", "(", "json", ")", ";", "}", "if", "(", "GDate", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A date. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#conclusion-date|GEDCOM X JSON Spec} @class @extends ExtensibleData @param {Object} [json] @alias Date
[ "A", "date", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/Date.js#L14-L27
train
SamVerschueren/gulp-cordova-icon
hooks/before_prepare/icon.js
loadProjectName
function loadProjectName(callback) { try { var contents = fs.readFileSync(path.join(__dirname, '../../config.xml'), 'utf-8'); if (contents) { // Windows is the BOM. Skip the Byte Order Mark. contents = contents.substring(contents.indexOf('<')); } var doc = new et.ElementTree(et.XML(contents)); var root = doc.getroot(); if (root.tag !== 'widget') { throw new Error('config.xml has incorrect root node name (expected "widget", was "' + root.tag + '")'); } var tag = root.find('./name'); if (!tag) { throw new Error('config.xml has no name tag.'); } return tag.text; } catch (e) { console.error('Could not loading config.xml'); throw e; } }
javascript
function loadProjectName(callback) { try { var contents = fs.readFileSync(path.join(__dirname, '../../config.xml'), 'utf-8'); if (contents) { // Windows is the BOM. Skip the Byte Order Mark. contents = contents.substring(contents.indexOf('<')); } var doc = new et.ElementTree(et.XML(contents)); var root = doc.getroot(); if (root.tag !== 'widget') { throw new Error('config.xml has incorrect root node name (expected "widget", was "' + root.tag + '")'); } var tag = root.find('./name'); if (!tag) { throw new Error('config.xml has no name tag.'); } return tag.text; } catch (e) { console.error('Could not loading config.xml'); throw e; } }
[ "function", "loadProjectName", "(", "callback", ")", "{", "try", "{", "var", "contents", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "__dirname", ",", "'../../config.xml'", ")", ",", "'utf-8'", ")", ";", "if", "(", "contents", ")", "{", "contents", "=", "contents", ".", "substring", "(", "contents", ".", "indexOf", "(", "'<'", ")", ")", ";", "}", "var", "doc", "=", "new", "et", ".", "ElementTree", "(", "et", ".", "XML", "(", "contents", ")", ")", ";", "var", "root", "=", "doc", ".", "getroot", "(", ")", ";", "if", "(", "root", ".", "tag", "!==", "'widget'", ")", "{", "throw", "new", "Error", "(", "'config.xml has incorrect root node name (expected \"widget\", was \"'", "+", "root", ".", "tag", "+", "'\")'", ")", ";", "}", "var", "tag", "=", "root", ".", "find", "(", "'./name'", ")", ";", "if", "(", "!", "tag", ")", "{", "throw", "new", "Error", "(", "'config.xml has no name tag.'", ")", ";", "}", "return", "tag", ".", "text", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "'Could not loading config.xml'", ")", ";", "throw", "e", ";", "}", "}" ]
Loads the project name from the config.xml file. @param {Function} callback Called when the name is retrieved.
[ "Loads", "the", "project", "name", "from", "the", "config", ".", "xml", "file", "." ]
e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380
https://github.com/SamVerschueren/gulp-cordova-icon/blob/e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380/hooks/before_prepare/icon.js#L33-L59
train
SamVerschueren/gulp-cordova-icon
hooks/before_prepare/icon.js
updateConfig
function updateConfig(target) { try { var contents = fs.readFileSync(path.join(__dirname, '../../config.xml'), 'utf-8'); if (contents) { // Windows is the BOM. Skip the Byte Order Mark. contents = contents.substring(contents.indexOf('<')); } var doc = new et.ElementTree(et.XML(contents)); var root = doc.getroot(); if (root.tag !== 'widget') { throw new Error('config.xml has incorrect root node name (expected "widget", was "' + root.tag + '")'); } var platformElement = doc.find('./platform/[@name="' + target + '"]'); if (platformElement) { var icons = platformElement.findall('./icon'); for (var i=0; i<icons.length; i++) { platformElement.remove(icons[i]); } } else { platformElement = new et.Element('platform'); platformElement.attrib.name = target; doc.getroot().append(platformElement); } // Add all the icons for(var i=0; i<platforms[target].icons.length; i++) { var iconElement = new et.Element('icon'); iconElement.attrib = { ...platforms[target].icons[i].attributes, src: 'res/' + target + '/' + platforms[target].icons[i].file }; platformElement.append(iconElement); } fs.writeFileSync(path.join(__dirname, '../../config.xml'), doc.write({indent: 4}), 'utf-8'); } catch (e) { console.error('Could not load config.xml'); throw e; } }
javascript
function updateConfig(target) { try { var contents = fs.readFileSync(path.join(__dirname, '../../config.xml'), 'utf-8'); if (contents) { // Windows is the BOM. Skip the Byte Order Mark. contents = contents.substring(contents.indexOf('<')); } var doc = new et.ElementTree(et.XML(contents)); var root = doc.getroot(); if (root.tag !== 'widget') { throw new Error('config.xml has incorrect root node name (expected "widget", was "' + root.tag + '")'); } var platformElement = doc.find('./platform/[@name="' + target + '"]'); if (platformElement) { var icons = platformElement.findall('./icon'); for (var i=0; i<icons.length; i++) { platformElement.remove(icons[i]); } } else { platformElement = new et.Element('platform'); platformElement.attrib.name = target; doc.getroot().append(platformElement); } // Add all the icons for(var i=0; i<platforms[target].icons.length; i++) { var iconElement = new et.Element('icon'); iconElement.attrib = { ...platforms[target].icons[i].attributes, src: 'res/' + target + '/' + platforms[target].icons[i].file }; platformElement.append(iconElement); } fs.writeFileSync(path.join(__dirname, '../../config.xml'), doc.write({indent: 4}), 'utf-8'); } catch (e) { console.error('Could not load config.xml'); throw e; } }
[ "function", "updateConfig", "(", "target", ")", "{", "try", "{", "var", "contents", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "__dirname", ",", "'../../config.xml'", ")", ",", "'utf-8'", ")", ";", "if", "(", "contents", ")", "{", "contents", "=", "contents", ".", "substring", "(", "contents", ".", "indexOf", "(", "'<'", ")", ")", ";", "}", "var", "doc", "=", "new", "et", ".", "ElementTree", "(", "et", ".", "XML", "(", "contents", ")", ")", ";", "var", "root", "=", "doc", ".", "getroot", "(", ")", ";", "if", "(", "root", ".", "tag", "!==", "'widget'", ")", "{", "throw", "new", "Error", "(", "'config.xml has incorrect root node name (expected \"widget\", was \"'", "+", "root", ".", "tag", "+", "'\")'", ")", ";", "}", "var", "platformElement", "=", "doc", ".", "find", "(", "'./platform/[@name=\"'", "+", "target", "+", "'\"]'", ")", ";", "if", "(", "platformElement", ")", "{", "var", "icons", "=", "platformElement", ".", "findall", "(", "'./icon'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "icons", ".", "length", ";", "i", "++", ")", "{", "platformElement", ".", "remove", "(", "icons", "[", "i", "]", ")", ";", "}", "}", "else", "{", "platformElement", "=", "new", "et", ".", "Element", "(", "'platform'", ")", ";", "platformElement", ".", "attrib", ".", "name", "=", "target", ";", "doc", ".", "getroot", "(", ")", ".", "append", "(", "platformElement", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "platforms", "[", "target", "]", ".", "icons", ".", "length", ";", "i", "++", ")", "{", "var", "iconElement", "=", "new", "et", ".", "Element", "(", "'icon'", ")", ";", "iconElement", ".", "attrib", "=", "{", "...", "platforms", "[", "target", "]", ".", "icons", "[", "i", "]", ".", "attributes", ",", "src", ":", "'res/'", "+", "target", "+", "'/'", "+", "platforms", "[", "target", "]", ".", "icons", "[", "i", "]", ".", "file", "}", ";", "platformElement", ".", "append", "(", "iconElement", ")", ";", "}", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "__dirname", ",", "'../../config.xml'", ")", ",", "doc", ".", "write", "(", "{", "indent", ":", "4", "}", ")", ",", "'utf-8'", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "'Could not load config.xml'", ")", ";", "throw", "e", ";", "}", "}" ]
This method will update the config.xml file for the target platform. It will add the icon tags to the config file.
[ "This", "method", "will", "update", "the", "config", ".", "xml", "file", "for", "the", "target", "platform", ".", "It", "will", "add", "the", "icon", "tags", "to", "the", "config", "file", "." ]
e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380
https://github.com/SamVerschueren/gulp-cordova-icon/blob/e228d4d4ccc4e3e9fbbf3f05f47a46015fc59380/hooks/before_prepare/icon.js#L65-L111
train
Globegitter/sails-hook-eslint
index.js
function (cb) { // If the hook has been deactivated, just return if (!sails.config[this.configKey].check) { sails.log.verbose('Eslint hook deactivated.'); return cb(); } else { var format = sails.config[this.configKey].formatter || 'stylish'; var patterns = sails.config[this.configKey].patterns || ['api', 'config']; patterns.forEach(function (pattern) { if (glob.hasMagic(pattern)) { glob.sync(pattern).forEach(function (file) { runLint(file, format); }); } else { runLint(pattern, format); } }); return cb(); } }
javascript
function (cb) { // If the hook has been deactivated, just return if (!sails.config[this.configKey].check) { sails.log.verbose('Eslint hook deactivated.'); return cb(); } else { var format = sails.config[this.configKey].formatter || 'stylish'; var patterns = sails.config[this.configKey].patterns || ['api', 'config']; patterns.forEach(function (pattern) { if (glob.hasMagic(pattern)) { glob.sync(pattern).forEach(function (file) { runLint(file, format); }); } else { runLint(pattern, format); } }); return cb(); } }
[ "function", "(", "cb", ")", "{", "if", "(", "!", "sails", ".", "config", "[", "this", ".", "configKey", "]", ".", "check", ")", "{", "sails", ".", "log", ".", "verbose", "(", "'Eslint hook deactivated.'", ")", ";", "return", "cb", "(", ")", ";", "}", "else", "{", "var", "format", "=", "sails", ".", "config", "[", "this", ".", "configKey", "]", ".", "formatter", "||", "'stylish'", ";", "var", "patterns", "=", "sails", ".", "config", "[", "this", ".", "configKey", "]", ".", "patterns", "||", "[", "'api'", ",", "'config'", "]", ";", "patterns", ".", "forEach", "(", "function", "(", "pattern", ")", "{", "if", "(", "glob", ".", "hasMagic", "(", "pattern", ")", ")", "{", "glob", ".", "sync", "(", "pattern", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "runLint", "(", "file", ",", "format", ")", ";", "}", ")", ";", "}", "else", "{", "runLint", "(", "pattern", ",", "format", ")", ";", "}", "}", ")", ";", "return", "cb", "(", ")", ";", "}", "}" ]
Initialize the hook @param {Function} cb Callback for when we're done initializing
[ "Initialize", "the", "hook" ]
0e3c91a234e8514313e33662620d0006836ec78d
https://github.com/Globegitter/sails-hook-eslint/blob/0e3c91a234e8514313e33662620d0006836ec78d/index.js#L58-L83
train
Bartvds/gruntfile-gtx
lib/lib.js
getParamAccessor
function getParamAccessor(id, params) { // easy access var paramGet = function (prop, alt, required) { if (arguments.length < 1) { throw (new Error('expected at least 1 argument')); } if (arguments.length < 2) { required = true; } if (params && hasOwnProp(params, prop)) { return params[prop]; } if (required) { if (!params) { throw (new Error('no params supplied for: ' + id)); } throw (new Error('missing param property: ' + prop + ' in: ' + id)); } return alt; }; paramGet.raw = params; return paramGet; }
javascript
function getParamAccessor(id, params) { // easy access var paramGet = function (prop, alt, required) { if (arguments.length < 1) { throw (new Error('expected at least 1 argument')); } if (arguments.length < 2) { required = true; } if (params && hasOwnProp(params, prop)) { return params[prop]; } if (required) { if (!params) { throw (new Error('no params supplied for: ' + id)); } throw (new Error('missing param property: ' + prop + ' in: ' + id)); } return alt; }; paramGet.raw = params; return paramGet; }
[ "function", "getParamAccessor", "(", "id", ",", "params", ")", "{", "var", "paramGet", "=", "function", "(", "prop", ",", "alt", ",", "required", ")", "{", "if", "(", "arguments", ".", "length", "<", "1", ")", "{", "throw", "(", "new", "Error", "(", "'expected at least 1 argument'", ")", ")", ";", "}", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "required", "=", "true", ";", "}", "if", "(", "params", "&&", "hasOwnProp", "(", "params", ",", "prop", ")", ")", "{", "return", "params", "[", "prop", "]", ";", "}", "if", "(", "required", ")", "{", "if", "(", "!", "params", ")", "{", "throw", "(", "new", "Error", "(", "'no params supplied for: '", "+", "id", ")", ")", ";", "}", "throw", "(", "new", "Error", "(", "'missing param property: '", "+", "prop", "+", "' in: '", "+", "id", ")", ")", ";", "}", "return", "alt", ";", "}", ";", "paramGet", ".", "raw", "=", "params", ";", "return", "paramGet", ";", "}" ]
return a parameter accessor
[ "return", "a", "parameter", "accessor" ]
90ac642769189ad6be7886b83f1e0c55d350e873
https://github.com/Bartvds/gruntfile-gtx/blob/90ac642769189ad6be7886b83f1e0c55d350e873/lib/lib.js#L6-L28
train
ember-cli/broccoli-es6modules
index.js
function(inDir, outDir){ var name = this.bundleOptions.name; var opts = this._generateEsperantoOptions(name); var transpilerName = formatToFunctionName[this.format]; var targetExtension = this.targetExtension; return esperanto.bundle({ base: inDir, entry: this.bundleOptions.entry }).then(function(bundle) { var compiledModule = bundle[transpilerName](opts); var fullOutputPath = path.join(outDir, name + '.' + targetExtension); return writeFile(fullOutputPath, compiledModule.code); }); }
javascript
function(inDir, outDir){ var name = this.bundleOptions.name; var opts = this._generateEsperantoOptions(name); var transpilerName = formatToFunctionName[this.format]; var targetExtension = this.targetExtension; return esperanto.bundle({ base: inDir, entry: this.bundleOptions.entry }).then(function(bundle) { var compiledModule = bundle[transpilerName](opts); var fullOutputPath = path.join(outDir, name + '.' + targetExtension); return writeFile(fullOutputPath, compiledModule.code); }); }
[ "function", "(", "inDir", ",", "outDir", ")", "{", "var", "name", "=", "this", ".", "bundleOptions", ".", "name", ";", "var", "opts", "=", "this", ".", "_generateEsperantoOptions", "(", "name", ")", ";", "var", "transpilerName", "=", "formatToFunctionName", "[", "this", ".", "format", "]", ";", "var", "targetExtension", "=", "this", ".", "targetExtension", ";", "return", "esperanto", ".", "bundle", "(", "{", "base", ":", "inDir", ",", "entry", ":", "this", ".", "bundleOptions", ".", "entry", "}", ")", ".", "then", "(", "function", "(", "bundle", ")", "{", "var", "compiledModule", "=", "bundle", "[", "transpilerName", "]", "(", "opts", ")", ";", "var", "fullOutputPath", "=", "path", ".", "join", "(", "outDir", ",", "name", "+", "'.'", "+", "targetExtension", ")", ";", "return", "writeFile", "(", "fullOutputPath", ",", "compiledModule", ".", "code", ")", ";", "}", ")", ";", "}" ]
A hook called if ES6Modules is being used in a n-to-1 bundle. Begins importing at an entry point and adds a single bundled module to the output tree.
[ "A", "hook", "called", "if", "ES6Modules", "is", "being", "used", "in", "a", "n", "-", "to", "-", "1", "bundle", "." ]
398d2e901687497a9eaab32a6ecb008b4e587230
https://github.com/ember-cli/broccoli-es6modules/blob/398d2e901687497a9eaab32a6ecb008b4e587230/index.js#L151-L166
train
ember-cli/broccoli-es6modules
index.js
function(inDir, outDir, relativePath, newCache) { var ext = this._matchingFileExtension(relativePath); var moduleName = relativePath.slice(0, relativePath.length - (ext.length + 1)); var fullInputPath = path.join(inDir, relativePath); var fullOutputPath = path.join(outDir, moduleName + '.' + this.targetExtension); var entry = this._transpileThroughCache( moduleName, fs.readFileSync(fullInputPath, 'utf-8'), newCache ); mkdirp.sync(path.dirname(fullOutputPath)); fs.writeFileSync(fullOutputPath, entry.output); }
javascript
function(inDir, outDir, relativePath, newCache) { var ext = this._matchingFileExtension(relativePath); var moduleName = relativePath.slice(0, relativePath.length - (ext.length + 1)); var fullInputPath = path.join(inDir, relativePath); var fullOutputPath = path.join(outDir, moduleName + '.' + this.targetExtension); var entry = this._transpileThroughCache( moduleName, fs.readFileSync(fullInputPath, 'utf-8'), newCache ); mkdirp.sync(path.dirname(fullOutputPath)); fs.writeFileSync(fullOutputPath, entry.output); }
[ "function", "(", "inDir", ",", "outDir", ",", "relativePath", ",", "newCache", ")", "{", "var", "ext", "=", "this", ".", "_matchingFileExtension", "(", "relativePath", ")", ";", "var", "moduleName", "=", "relativePath", ".", "slice", "(", "0", ",", "relativePath", ".", "length", "-", "(", "ext", ".", "length", "+", "1", ")", ")", ";", "var", "fullInputPath", "=", "path", ".", "join", "(", "inDir", ",", "relativePath", ")", ";", "var", "fullOutputPath", "=", "path", ".", "join", "(", "outDir", ",", "moduleName", "+", "'.'", "+", "this", ".", "targetExtension", ")", ";", "var", "entry", "=", "this", ".", "_transpileThroughCache", "(", "moduleName", ",", "fs", ".", "readFileSync", "(", "fullInputPath", ",", "'utf-8'", ")", ",", "newCache", ")", ";", "mkdirp", ".", "sync", "(", "path", ".", "dirname", "(", "fullOutputPath", ")", ")", ";", "fs", ".", "writeFileSync", "(", "fullOutputPath", ",", "entry", ".", "output", ")", ";", "}" ]
Normalizes module name, input path, and output path then calls transpileThroughCache to get a transpiled version of the ES6 source.
[ "Normalizes", "module", "name", "input", "path", "and", "output", "path", "then", "calls", "transpileThroughCache", "to", "get", "a", "transpiled", "version", "of", "the", "ES6", "source", "." ]
398d2e901687497a9eaab32a6ecb008b4e587230
https://github.com/ember-cli/broccoli-es6modules/blob/398d2e901687497a9eaab32a6ecb008b4e587230/index.js#L199-L213
train
ember-cli/broccoli-es6modules
index.js
function(moduleName, source, newCache) { var key = helpers.hashStrings([moduleName, source]); var entry = this._transpilerCache[key]; if (entry) { return newCache[key] = entry; } try { return newCache[key] = { output: this.toFormat( source, this._generateEsperantoOptions(moduleName) ).code }; } catch(err) { err.file = moduleName; throw err; } }
javascript
function(moduleName, source, newCache) { var key = helpers.hashStrings([moduleName, source]); var entry = this._transpilerCache[key]; if (entry) { return newCache[key] = entry; } try { return newCache[key] = { output: this.toFormat( source, this._generateEsperantoOptions(moduleName) ).code }; } catch(err) { err.file = moduleName; throw err; } }
[ "function", "(", "moduleName", ",", "source", ",", "newCache", ")", "{", "var", "key", "=", "helpers", ".", "hashStrings", "(", "[", "moduleName", ",", "source", "]", ")", ";", "var", "entry", "=", "this", ".", "_transpilerCache", "[", "key", "]", ";", "if", "(", "entry", ")", "{", "return", "newCache", "[", "key", "]", "=", "entry", ";", "}", "try", "{", "return", "newCache", "[", "key", "]", "=", "{", "output", ":", "this", ".", "toFormat", "(", "source", ",", "this", ".", "_generateEsperantoOptions", "(", "moduleName", ")", ")", ".", "code", "}", ";", "}", "catch", "(", "err", ")", "{", "err", ".", "file", "=", "moduleName", ";", "throw", "err", ";", "}", "}" ]
Called on every file in a tree when used in per-file mode. First this checks whether the file contents have been previously transpiled by checking the previous cache. If the file has been transpiled, adds the previous transpiled code into the new cache. If it has not been transpiled it adds passed the source code along to a transpiler and adds the resulting value to the new cache.
[ "Called", "on", "every", "file", "in", "a", "tree", "when", "used", "in", "per", "-", "file", "mode", "." ]
398d2e901687497a9eaab32a6ecb008b4e587230
https://github.com/ember-cli/broccoli-es6modules/blob/398d2e901687497a9eaab32a6ecb008b4e587230/index.js#L224-L242
train
blendsdk/blend-class-system
examples/hello-world/Hello/app/Greeter.js
function () { var me = this; me.callParent.apply(me, arguments); me.entity = me.entity || 'Someone'; }
javascript
function () { var me = this; me.callParent.apply(me, arguments); me.entity = me.entity || 'Someone'; }
[ "function", "(", ")", "{", "var", "me", "=", "this", ";", "me", ".", "callParent", ".", "apply", "(", "me", ",", "arguments", ")", ";", "me", ".", "entity", "=", "me", ".", "entity", "||", "'Someone'", ";", "}" ]
Constructor example. Don't forget to call the parent constructor
[ "Constructor", "example", ".", "Don", "t", "forget", "to", "call", "the", "parent", "constructor" ]
d6eb82c0305d8f4d17c925b8420654fe8271c590
https://github.com/blendsdk/blend-class-system/blob/d6eb82c0305d8f4d17c925b8420654fe8271c590/examples/hello-world/Hello/app/Greeter.js#L10-L14
train
rootsdev/gedcomx-js
src/core/TextValue.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof TextValue)){ return new TextValue(json); } // If the given object is already an instance then just return it. DON'T copy it. if(TextValue.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof TextValue)){ return new TextValue(json); } // If the given object is already an instance then just return it. DON'T copy it. if(TextValue.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "TextValue", ")", ")", "{", "return", "new", "TextValue", "(", "json", ")", ";", "}", "if", "(", "TextValue", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A text value in a specific language. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#text-value|GEDCOM X JSON Spec} @class @extends Base @apram {Object} [json]
[ "A", "text", "value", "in", "a", "specific", "language", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/TextValue.js#L13-L26
train
amrdraz/java-code-runner
index.js
runProc
function runProc(args, cb) { var stoutBuffer = '', sterrBuffer = ''; var proc = cp.spawn('java', args, { cwd: config.rootDir + '/bin' }); proc.stdout.on('data', function(data) { stoutBuffer += data; }); proc.stderr.on('data', function(data) { sterrBuffer += data; }); proc.on('close', function(code) { if (code === null) { cb(code); } else { cb(null, stoutBuffer, sterrBuffer); } running--; }); }
javascript
function runProc(args, cb) { var stoutBuffer = '', sterrBuffer = ''; var proc = cp.spawn('java', args, { cwd: config.rootDir + '/bin' }); proc.stdout.on('data', function(data) { stoutBuffer += data; }); proc.stderr.on('data', function(data) { sterrBuffer += data; }); proc.on('close', function(code) { if (code === null) { cb(code); } else { cb(null, stoutBuffer, sterrBuffer); } running--; }); }
[ "function", "runProc", "(", "args", ",", "cb", ")", "{", "var", "stoutBuffer", "=", "''", ",", "sterrBuffer", "=", "''", ";", "var", "proc", "=", "cp", ".", "spawn", "(", "'java'", ",", "args", ",", "{", "cwd", ":", "config", ".", "rootDir", "+", "'/bin'", "}", ")", ";", "proc", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "stoutBuffer", "+=", "data", ";", "}", ")", ";", "proc", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "sterrBuffer", "+=", "data", ";", "}", ")", ";", "proc", ".", "on", "(", "'close'", ",", "function", "(", "code", ")", "{", "if", "(", "code", "===", "null", ")", "{", "cb", "(", "code", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "stoutBuffer", ",", "sterrBuffer", ")", ";", "}", "running", "--", ";", "}", ")", ";", "}" ]
Spawn a java process and return callback @param {Array} args arguments to pass to java proc @param {Function} cb callback to be called with err, stout, sterr
[ "Spawn", "a", "java", "process", "and", "return", "callback" ]
b5d87b503076bf76a01d111b85c18a639e6f80c8
https://github.com/amrdraz/java-code-runner/blob/b5d87b503076bf76a01d111b85c18a639e6f80c8/index.js#L56-L76
train
amrdraz/java-code-runner
index.js
runCMD
function runCMD(options, cb) { if (options.cb) { cb = options.cb; } var args = ["-cp", ".", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1", "TerminalRunner"]; args.push(options.name); args.push(options.program); args.push(options.timeLimit); args.push(options.input); runProc(args, function() { observer.emit("runner.finished", options); cb.apply(this, arguments); }); }
javascript
function runCMD(options, cb) { if (options.cb) { cb = options.cb; } var args = ["-cp", ".", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1", "TerminalRunner"]; args.push(options.name); args.push(options.program); args.push(options.timeLimit); args.push(options.input); runProc(args, function() { observer.emit("runner.finished", options); cb.apply(this, arguments); }); }
[ "function", "runCMD", "(", "options", ",", "cb", ")", "{", "if", "(", "options", ".", "cb", ")", "{", "cb", "=", "options", ".", "cb", ";", "}", "var", "args", "=", "[", "\"-cp\"", ",", "\".\"", ",", "\"-XX:+TieredCompilation\"", ",", "\"-XX:TieredStopAtLevel=1\"", ",", "\"TerminalRunner\"", "]", ";", "args", ".", "push", "(", "options", ".", "name", ")", ";", "args", ".", "push", "(", "options", ".", "program", ")", ";", "args", ".", "push", "(", "options", ".", "timeLimit", ")", ";", "args", ".", "push", "(", "options", ".", "input", ")", ";", "runProc", "(", "args", ",", "function", "(", ")", "{", "observer", ".", "emit", "(", "\"runner.finished\"", ",", "options", ")", ";", "cb", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ")", ";", "}" ]
Run java program in TerminalRunner @param {Object} options an object containing all prgram needed configuration - {String} name name of class - {String} program source code of JavaClass with public class [name] - {String} input The program's input stream if needed @param {Function} cb callback when complete
[ "Run", "java", "program", "in", "TerminalRunner" ]
b5d87b503076bf76a01d111b85c18a639e6f80c8
https://github.com/amrdraz/java-code-runner/blob/b5d87b503076bf76a01d111b85c18a639e6f80c8/index.js#L86-L101
train
amrdraz/java-code-runner
index.js
runInServlet
function runInServlet(request, cb) { // log("waitingQueue:"+waitingQueue.length+", runningQueue:"+runningQueue.length); // log("pushed into running"); if (request.cb) { cb = request.cb; } // program to run var post_data = querystring.stringify({ 'name': request.name, 'code': request.program, 'input': request.input, 'timeLimit': request.timeLimit }); // An object of request to indicate where to post to var post_options = { host: '127.0.0.1', port: server.getPort(), path: '', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': post_data.length } }; var post_req = http.request(post_options, function(res) { res.setEncoding('utf8'); var responseString = ''; res.on('data', function(data) { // clearTimeout(request.timer); // log(data); // debugger; if (/An exception has occurred in the compiler/.test(data) || /RuntimeError: java.lang.ThreadDeath/.test(data)) { // log("ReWrote the folwoing as timout exception "+data); // queue.checkQueues(); request.timeOut(); } else { data = JSON.parse(data); request.setToDone(); observer.emit("runner.finished", request); // queue.clearRunning(); // queue.checkQueues(); cb(null, data.stout, data.sterr); } // log("finished with one"); }); // res.on('end', function() { // log('::-----end-----::'); // var data = JSON.parse(responseString); // log(responseString); // log('::-----end-----::'); // cb(null, data.stout, data.sterr); // }); }); post_req.on('error', function(e) { log("Error while waiting for server response ", e); request.timeOut(); // cb(e); }); // request.timer = setTimeout(function () { // cb(null, "","TimeoutException: Your program ran for more than "+timeLimit+"ms"); // },timeLimit+200); post_req.write(post_data); post_req.end(); }
javascript
function runInServlet(request, cb) { // log("waitingQueue:"+waitingQueue.length+", runningQueue:"+runningQueue.length); // log("pushed into running"); if (request.cb) { cb = request.cb; } // program to run var post_data = querystring.stringify({ 'name': request.name, 'code': request.program, 'input': request.input, 'timeLimit': request.timeLimit }); // An object of request to indicate where to post to var post_options = { host: '127.0.0.1', port: server.getPort(), path: '', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': post_data.length } }; var post_req = http.request(post_options, function(res) { res.setEncoding('utf8'); var responseString = ''; res.on('data', function(data) { // clearTimeout(request.timer); // log(data); // debugger; if (/An exception has occurred in the compiler/.test(data) || /RuntimeError: java.lang.ThreadDeath/.test(data)) { // log("ReWrote the folwoing as timout exception "+data); // queue.checkQueues(); request.timeOut(); } else { data = JSON.parse(data); request.setToDone(); observer.emit("runner.finished", request); // queue.clearRunning(); // queue.checkQueues(); cb(null, data.stout, data.sterr); } // log("finished with one"); }); // res.on('end', function() { // log('::-----end-----::'); // var data = JSON.parse(responseString); // log(responseString); // log('::-----end-----::'); // cb(null, data.stout, data.sterr); // }); }); post_req.on('error', function(e) { log("Error while waiting for server response ", e); request.timeOut(); // cb(e); }); // request.timer = setTimeout(function () { // cb(null, "","TimeoutException: Your program ran for more than "+timeLimit+"ms"); // },timeLimit+200); post_req.write(post_data); post_req.end(); }
[ "function", "runInServlet", "(", "request", ",", "cb", ")", "{", "if", "(", "request", ".", "cb", ")", "{", "cb", "=", "request", ".", "cb", ";", "}", "var", "post_data", "=", "querystring", ".", "stringify", "(", "{", "'name'", ":", "request", ".", "name", ",", "'code'", ":", "request", ".", "program", ",", "'input'", ":", "request", ".", "input", ",", "'timeLimit'", ":", "request", ".", "timeLimit", "}", ")", ";", "var", "post_options", "=", "{", "host", ":", "'127.0.0.1'", ",", "port", ":", "server", ".", "getPort", "(", ")", ",", "path", ":", "''", ",", "method", ":", "'POST'", ",", "headers", ":", "{", "'Content-Type'", ":", "'application/x-www-form-urlencoded'", ",", "'Content-Length'", ":", "post_data", ".", "length", "}", "}", ";", "var", "post_req", "=", "http", ".", "request", "(", "post_options", ",", "function", "(", "res", ")", "{", "res", ".", "setEncoding", "(", "'utf8'", ")", ";", "var", "responseString", "=", "''", ";", "res", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "if", "(", "/", "An exception has occurred in the compiler", "/", ".", "test", "(", "data", ")", "||", "/", "RuntimeError: java.lang.ThreadDeath", "/", ".", "test", "(", "data", ")", ")", "{", "request", ".", "timeOut", "(", ")", ";", "}", "else", "{", "data", "=", "JSON", ".", "parse", "(", "data", ")", ";", "request", ".", "setToDone", "(", ")", ";", "observer", ".", "emit", "(", "\"runner.finished\"", ",", "request", ")", ";", "cb", "(", "null", ",", "data", ".", "stout", ",", "data", ".", "sterr", ")", ";", "}", "}", ")", ";", "}", ")", ";", "post_req", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "log", "(", "\"Error while waiting for server response \"", ",", "e", ")", ";", "request", ".", "timeOut", "(", ")", ";", "}", ")", ";", "post_req", ".", "write", "(", "post_data", ")", ";", "post_req", ".", "end", "(", ")", ";", "}" ]
Run java program in server, which is singnificantly faster then CMD @param {Object} options an object containing all prgram needed configuration - {String} name name of class - {String} program source code of JavaClass with public class [name] - {String} input The program's input stream if needed @param {Function} cb callback when complete
[ "Run", "java", "program", "in", "server", "which", "is", "singnificantly", "faster", "then", "CMD" ]
b5d87b503076bf76a01d111b85c18a639e6f80c8
https://github.com/amrdraz/java-code-runner/blob/b5d87b503076bf76a01d111b85c18a639e6f80c8/index.js#L111-L179
train
amrdraz/java-code-runner
index.js
classCase
function classCase(input) { return input.toUpperCase().replace(/[\-\s](.)/g, function(match, group1) { return group1.toUpperCase(); }); }
javascript
function classCase(input) { return input.toUpperCase().replace(/[\-\s](.)/g, function(match, group1) { return group1.toUpperCase(); }); }
[ "function", "classCase", "(", "input", ")", "{", "return", "input", ".", "toUpperCase", "(", ")", ".", "replace", "(", "/", "[\\-\\s](.)", "/", "g", ",", "function", "(", "match", ",", "group1", ")", "{", "return", "group1", ".", "toUpperCase", "(", ")", ";", "}", ")", ";", "}" ]
Turn a sting to Java class style camel Case striping - and space chracters @param {[type]} input [description] @return {[type]} [description]
[ "Turn", "a", "sting", "to", "Java", "class", "style", "camel", "Case", "striping", "-", "and", "space", "chracters" ]
b5d87b503076bf76a01d111b85c18a639e6f80c8
https://github.com/amrdraz/java-code-runner/blob/b5d87b503076bf76a01d111b85c18a639e6f80c8/index.js#L380-L384
train
rootsdev/gedcomx-js
src/Base.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Base)){ return new Base(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Base.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof Base)){ return new Base(json); } // If the given object is already an instance then just return it. DON'T copy it. if(Base.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Base", ")", ")", "{", "return", "new", "Base", "(", "json", ")", ";", "}", "if", "(", "Base", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Base prototype that all other classes in this library extend @class @param {Object} [json]
[ "Base", "prototype", "that", "all", "other", "classes", "in", "this", "library", "extend" ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/Base.js#L9-L22
train
wrwrwr/babel-remove-props
dist/main.es5.js
enter
function enter(path, state) { regex = state.opts.regex; if (!regex) { throw new TypeError("A regex option is required."); } pure = function pure(n) { return (0, _sideEffectsSafe.pureBabylon)(n, state.opts); }; }
javascript
function enter(path, state) { regex = state.opts.regex; if (!regex) { throw new TypeError("A regex option is required."); } pure = function pure(n) { return (0, _sideEffectsSafe.pureBabylon)(n, state.opts); }; }
[ "function", "enter", "(", "path", ",", "state", ")", "{", "regex", "=", "state", ".", "opts", ".", "regex", ";", "if", "(", "!", "regex", ")", "{", "throw", "new", "TypeError", "(", "\"A regex option is required.\"", ")", ";", "}", "pure", "=", "function", "pure", "(", "n", ")", "{", "return", "(", "0", ",", "_sideEffectsSafe", ".", "pureBabylon", ")", "(", "n", ",", "state", ".", "opts", ")", ";", "}", ";", "}" ]
Preprocess options.
[ "Preprocess", "options", "." ]
37e0d759a9e6f2d4838f93231abe95f3dcb701ed
https://github.com/wrwrwr/babel-remove-props/blob/37e0d759a9e6f2d4838f93231abe95f3dcb701ed/dist/main.es5.js#L35-L43
train
fanout/node-fanoutpub
lib/fanoutpub.js
function(realm, key, ssl) { // Initialize with a specified realm, key, and a boolean indicating wther // SSL should be enabled or disabled. var scheme = 'https'; if (typeof ssl !== 'undefined' && !ssl) { scheme = 'http'; } var uri = scheme + '://api.fanout.io/realm/' + realm; var pubControl = new pubcontrol.PubControlClient(uri); pubControl.setAuthJwt({'iss': realm}, new Buffer(key, 'base64')); this.pubControl = pubControl; }
javascript
function(realm, key, ssl) { // Initialize with a specified realm, key, and a boolean indicating wther // SSL should be enabled or disabled. var scheme = 'https'; if (typeof ssl !== 'undefined' && !ssl) { scheme = 'http'; } var uri = scheme + '://api.fanout.io/realm/' + realm; var pubControl = new pubcontrol.PubControlClient(uri); pubControl.setAuthJwt({'iss': realm}, new Buffer(key, 'base64')); this.pubControl = pubControl; }
[ "function", "(", "realm", ",", "key", ",", "ssl", ")", "{", "var", "scheme", "=", "'https'", ";", "if", "(", "typeof", "ssl", "!==", "'undefined'", "&&", "!", "ssl", ")", "{", "scheme", "=", "'http'", ";", "}", "var", "uri", "=", "scheme", "+", "'://api.fanout.io/realm/'", "+", "realm", ";", "var", "pubControl", "=", "new", "pubcontrol", ".", "PubControlClient", "(", "uri", ")", ";", "pubControl", ".", "setAuthJwt", "(", "{", "'iss'", ":", "realm", "}", ",", "new", "Buffer", "(", "key", ",", "'base64'", ")", ")", ";", "this", ".", "pubControl", "=", "pubControl", ";", "}" ]
The Fanout class is used for publishing messages to Fanout.io and is configured with a Fanout.io realm and associated key. SSL can either be enabled or disabled.
[ "The", "Fanout", "class", "is", "used", "for", "publishing", "messages", "to", "Fanout", ".", "io", "and", "is", "configured", "with", "a", "Fanout", ".", "io", "realm", "and", "associated", "key", ".", "SSL", "can", "either", "be", "enabled", "or", "disabled", "." ]
726ca2f928385358ee095ea3ceb29c6cd32e80eb
https://github.com/fanout/node-fanoutpub/blob/726ca2f928385358ee095ea3ceb29c6cd32e80eb/lib/fanoutpub.js#L22-L34
train
keqingrong/react-iframe
packages/iframe-utils/src/index.js
buildOrigin
function buildOrigin(src, href) { try { const url = new URL(src, href || location.href); return url.origin; } catch (error) { return null; } }
javascript
function buildOrigin(src, href) { try { const url = new URL(src, href || location.href); return url.origin; } catch (error) { return null; } }
[ "function", "buildOrigin", "(", "src", ",", "href", ")", "{", "try", "{", "const", "url", "=", "new", "URL", "(", "src", ",", "href", "||", "location", ".", "href", ")", ";", "return", "url", ".", "origin", ";", "}", "catch", "(", "error", ")", "{", "return", "null", ";", "}", "}" ]
Build origin from URL string. @param {string} src - URL string @param {string} [href] - URL string @returns {string|null}
[ "Build", "origin", "from", "URL", "string", "." ]
9ebfa116fc97c9ecf8d4d5968ca5f851f21acb74
https://github.com/keqingrong/react-iframe/blob/9ebfa116fc97c9ecf8d4d5968ca5f851f21acb74/packages/iframe-utils/src/index.js#L13-L20
train
keqingrong/react-iframe
packages/iframe-utils/src/index.js
checkOlderIE
function checkOlderIE() { const ua = navigator.userAgent; const isIE = ua.indexOf('MSIE') !== -1 || ua.indexOf('Trident') !== -1; if (!isIE) { return false; } const version = ua.match(/(MSIE\s|Trident.*rv:)([\w.]+)/)[2]; const versionNumber = parseFloat(version); if (versionNumber < 10) { return true; } return false; }
javascript
function checkOlderIE() { const ua = navigator.userAgent; const isIE = ua.indexOf('MSIE') !== -1 || ua.indexOf('Trident') !== -1; if (!isIE) { return false; } const version = ua.match(/(MSIE\s|Trident.*rv:)([\w.]+)/)[2]; const versionNumber = parseFloat(version); if (versionNumber < 10) { return true; } return false; }
[ "function", "checkOlderIE", "(", ")", "{", "const", "ua", "=", "navigator", ".", "userAgent", ";", "const", "isIE", "=", "ua", ".", "indexOf", "(", "'MSIE'", ")", "!==", "-", "1", "||", "ua", ".", "indexOf", "(", "'Trident'", ")", "!==", "-", "1", ";", "if", "(", "!", "isIE", ")", "{", "return", "false", ";", "}", "const", "version", "=", "ua", ".", "match", "(", "/", "(MSIE\\s|Trident.*rv:)([\\w.]+)", "/", ")", "[", "2", "]", ";", "const", "versionNumber", "=", "parseFloat", "(", "version", ")", ";", "if", "(", "versionNumber", "<", "10", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Check if it is IE below 10. @returns {boolean}
[ "Check", "if", "it", "is", "IE", "below", "10", "." ]
9ebfa116fc97c9ecf8d4d5968ca5f851f21acb74
https://github.com/keqingrong/react-iframe/blob/9ebfa116fc97c9ecf8d4d5968ca5f851f21acb74/packages/iframe-utils/src/index.js#L47-L59
train
rootsdev/gedcomx-js
src/atom/AtomPerson.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomPerson)){ return new AtomPerson(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomPerson.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof AtomPerson)){ return new AtomPerson(json); } // If the given object is already an instance then just return it. DON'T copy it. if(AtomPerson.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AtomPerson", ")", ")", "{", "return", "new", "AtomPerson", "(", "json", ")", ";", "}", "if", "(", "AtomPerson", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
Common schema for atom authors and contributors. @see {@link https://github.com/FamilySearch/gedcomx-rs/blob/master/specifications/atom-model-specification.md#atom-json-media-type|GEDCOM X Atom JSON Spec} @see {@link https://tools.ietf.org/html/rfc4287#appendix-B|RFC 4287} @class AtomPerson @extends AtomCommon @param {Object} [json]
[ "Common", "schema", "for", "atom", "authors", "and", "contributors", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/atom/AtomPerson.js#L16-L29
train
mikolalysenko/poly-to-pslg
poly-to-pslg.js
polygonToPSLG
function polygonToPSLG(loops, options) { if(!Array.isArray(loops)) { throw new Error('poly-to-pslg: Error, invalid polygon') } if(loops.length === 0) { return { points: [], edges: [] } } options = options || {} var nested = true if('nested' in options) { nested = !!options.nested } else if(loops[0].length === 2 && typeof loops[0][0] === 'number') { //Hack: If use doesn't pass in a loop, then try to guess if it is nested nested = false } if(!nested) { loops = [loops] } //First we just unroll all the points in the dumb/obvious way var points = [] var edges = [] for(var i=0; i<loops.length; ++i) { var loop = loops[i] var offset = points.length for(var j=0; j<loop.length; ++j) { points.push(loop[j]) edges.push([ offset+j, offset+(j+1)%loop.length ]) } } //Then we run snap rounding to clean up self intersections and duplicate verts var clean = 'clean' in options ? true : !!options.clean if(clean) { cleanPSLG(points, edges) } //Finally, we return the resulting PSLG return { points: points, edges: edges } }
javascript
function polygonToPSLG(loops, options) { if(!Array.isArray(loops)) { throw new Error('poly-to-pslg: Error, invalid polygon') } if(loops.length === 0) { return { points: [], edges: [] } } options = options || {} var nested = true if('nested' in options) { nested = !!options.nested } else if(loops[0].length === 2 && typeof loops[0][0] === 'number') { //Hack: If use doesn't pass in a loop, then try to guess if it is nested nested = false } if(!nested) { loops = [loops] } //First we just unroll all the points in the dumb/obvious way var points = [] var edges = [] for(var i=0; i<loops.length; ++i) { var loop = loops[i] var offset = points.length for(var j=0; j<loop.length; ++j) { points.push(loop[j]) edges.push([ offset+j, offset+(j+1)%loop.length ]) } } //Then we run snap rounding to clean up self intersections and duplicate verts var clean = 'clean' in options ? true : !!options.clean if(clean) { cleanPSLG(points, edges) } //Finally, we return the resulting PSLG return { points: points, edges: edges } }
[ "function", "polygonToPSLG", "(", "loops", ",", "options", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "loops", ")", ")", "{", "throw", "new", "Error", "(", "'poly-to-pslg: Error, invalid polygon'", ")", "}", "if", "(", "loops", ".", "length", "===", "0", ")", "{", "return", "{", "points", ":", "[", "]", ",", "edges", ":", "[", "]", "}", "}", "options", "=", "options", "||", "{", "}", "var", "nested", "=", "true", "if", "(", "'nested'", "in", "options", ")", "{", "nested", "=", "!", "!", "options", ".", "nested", "}", "else", "if", "(", "loops", "[", "0", "]", ".", "length", "===", "2", "&&", "typeof", "loops", "[", "0", "]", "[", "0", "]", "===", "'number'", ")", "{", "nested", "=", "false", "}", "if", "(", "!", "nested", ")", "{", "loops", "=", "[", "loops", "]", "}", "var", "points", "=", "[", "]", "var", "edges", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "loops", ".", "length", ";", "++", "i", ")", "{", "var", "loop", "=", "loops", "[", "i", "]", "var", "offset", "=", "points", ".", "length", "for", "(", "var", "j", "=", "0", ";", "j", "<", "loop", ".", "length", ";", "++", "j", ")", "{", "points", ".", "push", "(", "loop", "[", "j", "]", ")", "edges", ".", "push", "(", "[", "offset", "+", "j", ",", "offset", "+", "(", "j", "+", "1", ")", "%", "loop", ".", "length", "]", ")", "}", "}", "var", "clean", "=", "'clean'", "in", "options", "?", "true", ":", "!", "!", "options", ".", "clean", "if", "(", "clean", ")", "{", "cleanPSLG", "(", "points", ",", "edges", ")", "}", "return", "{", "points", ":", "points", ",", "edges", ":", "edges", "}", "}" ]
Converts a polygon to a planar straight line graph
[ "Converts", "a", "polygon", "to", "a", "planar", "straight", "line", "graph" ]
186c2e164049009d2d89078d83065f3f7c86b182
https://github.com/mikolalysenko/poly-to-pslg/blob/186c2e164049009d2d89078d83065f3f7c86b182/poly-to-pslg.js#L8-L55
train
JS-DevTools/sourcemapify
lib/index.js
sourcemapify
function sourcemapify (browserify, options) { options = options || browserify._options || {}; function write (data) { if (options.base) { // Determine the relative path // from the bundle file's directory to the source file let base = path.resolve(process.cwd(), options.base); data.sourceFile = path.relative(base, data.file); } if (options.root) { // Prepend the root path to the file path data.sourceFile = joinURL(options.root, data.sourceFile); } // Output normalized URL paths data.sourceFile = normalizeSeparators(data.sourceFile); this.queue(data); } // Add our transform stream to Browserify's "debug" pipeline // https://github.com/substack/node-browserify#bpipeline configurePipeline(); browserify.on("reset", configurePipeline); function configurePipeline () { browserify.pipeline.get("debug").push(new Through(write)); } return this; }
javascript
function sourcemapify (browserify, options) { options = options || browserify._options || {}; function write (data) { if (options.base) { // Determine the relative path // from the bundle file's directory to the source file let base = path.resolve(process.cwd(), options.base); data.sourceFile = path.relative(base, data.file); } if (options.root) { // Prepend the root path to the file path data.sourceFile = joinURL(options.root, data.sourceFile); } // Output normalized URL paths data.sourceFile = normalizeSeparators(data.sourceFile); this.queue(data); } // Add our transform stream to Browserify's "debug" pipeline // https://github.com/substack/node-browserify#bpipeline configurePipeline(); browserify.on("reset", configurePipeline); function configurePipeline () { browserify.pipeline.get("debug").push(new Through(write)); } return this; }
[ "function", "sourcemapify", "(", "browserify", ",", "options", ")", "{", "options", "=", "options", "||", "browserify", ".", "_options", "||", "{", "}", ";", "function", "write", "(", "data", ")", "{", "if", "(", "options", ".", "base", ")", "{", "let", "base", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "options", ".", "base", ")", ";", "data", ".", "sourceFile", "=", "path", ".", "relative", "(", "base", ",", "data", ".", "file", ")", ";", "}", "if", "(", "options", ".", "root", ")", "{", "data", ".", "sourceFile", "=", "joinURL", "(", "options", ".", "root", ",", "data", ".", "sourceFile", ")", ";", "}", "data", ".", "sourceFile", "=", "normalizeSeparators", "(", "data", ".", "sourceFile", ")", ";", "this", ".", "queue", "(", "data", ")", ";", "}", "configurePipeline", "(", ")", ";", "browserify", ".", "on", "(", "\"reset\"", ",", "configurePipeline", ")", ";", "function", "configurePipeline", "(", ")", "{", "browserify", ".", "pipeline", ".", "get", "(", "\"debug\"", ")", ".", "push", "(", "new", "Through", "(", "write", ")", ")", ";", "}", "return", "this", ";", "}" ]
Transforms the browserify sourcemap @param {object} browserify - The Browserify instance @param {object} [options] - Plugin options
[ "Transforms", "the", "browserify", "sourcemap" ]
2e1d838ab6ff766a762c32097855125b3ed7bd80
https://github.com/JS-DevTools/sourcemapify/blob/2e1d838ab6ff766a762c32097855125b3ed7bd80/lib/index.js#L14-L45
train
JS-DevTools/sourcemapify
lib/index.js
joinURL
function joinURL (urlA, urlB) { urlA = urlA || ""; urlB = urlB || ""; let endsWithASlash = urlA.substr(-1) === "/" || urlA.substr(-1) === "\\"; let startsWithASlash = urlB[0] === "/" || urlB[0] === "\\"; if (endsWithASlash || startsWithASlash) { return urlA + urlB; } else { return urlA + "/" + urlB; } }
javascript
function joinURL (urlA, urlB) { urlA = urlA || ""; urlB = urlB || ""; let endsWithASlash = urlA.substr(-1) === "/" || urlA.substr(-1) === "\\"; let startsWithASlash = urlB[0] === "/" || urlB[0] === "\\"; if (endsWithASlash || startsWithASlash) { return urlA + urlB; } else { return urlA + "/" + urlB; } }
[ "function", "joinURL", "(", "urlA", ",", "urlB", ")", "{", "urlA", "=", "urlA", "||", "\"\"", ";", "urlB", "=", "urlB", "||", "\"\"", ";", "let", "endsWithASlash", "=", "urlA", ".", "substr", "(", "-", "1", ")", "===", "\"/\"", "||", "urlA", ".", "substr", "(", "-", "1", ")", "===", "\"\\\\\"", ";", "\\\\", "let", "startsWithASlash", "=", "urlB", "[", "0", "]", "===", "\"/\"", "||", "urlB", "[", "0", "]", "===", "\"\\\\\"", ";", "}" ]
Joins two URL paths, possibly adding a separator. @param {string} urlA @param {string} urlB @returns {string}
[ "Joins", "two", "URL", "paths", "possibly", "adding", "a", "separator", "." ]
2e1d838ab6ff766a762c32097855125b3ed7bd80
https://github.com/JS-DevTools/sourcemapify/blob/2e1d838ab6ff766a762c32097855125b3ed7bd80/lib/index.js#L54-L67
train
ragingwind/electron-togglify-window
index.js
ToggleAnimation
function ToggleAnimation(target, animation) { var preset = { hide: { hide: 'hide', focus: 'show', restore: 'show', blur: 'hide' }, scale: { hide: 'minimize', focus: 'focus', restore: 'restore', } }; this._preset = preset[animation]; this._target = target; if (!this._target) { throw new Error('Invalid BrowserWindow instance'); } else if (!this._preset) { throw new Error('Unknown type of animation for toggle'); } }
javascript
function ToggleAnimation(target, animation) { var preset = { hide: { hide: 'hide', focus: 'show', restore: 'show', blur: 'hide' }, scale: { hide: 'minimize', focus: 'focus', restore: 'restore', } }; this._preset = preset[animation]; this._target = target; if (!this._target) { throw new Error('Invalid BrowserWindow instance'); } else if (!this._preset) { throw new Error('Unknown type of animation for toggle'); } }
[ "function", "ToggleAnimation", "(", "target", ",", "animation", ")", "{", "var", "preset", "=", "{", "hide", ":", "{", "hide", ":", "'hide'", ",", "focus", ":", "'show'", ",", "restore", ":", "'show'", ",", "blur", ":", "'hide'", "}", ",", "scale", ":", "{", "hide", ":", "'minimize'", ",", "focus", ":", "'focus'", ",", "restore", ":", "'restore'", ",", "}", "}", ";", "this", ".", "_preset", "=", "preset", "[", "animation", "]", ";", "this", ".", "_target", "=", "target", ";", "if", "(", "!", "this", ".", "_target", ")", "{", "throw", "new", "Error", "(", "'Invalid BrowserWindow instance'", ")", ";", "}", "else", "if", "(", "!", "this", ".", "_preset", ")", "{", "throw", "new", "Error", "(", "'Unknown type of animation for toggle'", ")", ";", "}", "}" ]
Delegate function for animation of window set toggle
[ "Delegate", "function", "for", "animation", "of", "window", "set", "toggle" ]
e9781f67f79e8d2a082dba4cb31b29bdbb874df7
https://github.com/ragingwind/electron-togglify-window/blob/e9781f67f79e8d2a082dba4cb31b29bdbb874df7/index.js#L6-L29
train
ragingwind/electron-togglify-window
index.js
togglify
function togglify(win, opts) { // extend options for toggle window opts = oassign({ animation: 'hide' }, opts); win._toggleAction = new ToggleAnimation(win, opts.animation); // patch toggle function to window win.toggle = function () { if (this.isVisible() && this.isFocused()) { this._toggleAction.hide(); } else if (this.isVisible() && !this.isFocused()) { this._toggleAction.focus(); } else if (this.isMinimized() || !this.isVisible()) { this._toggleAction.restore(); } }; // bind event for default action win.on('blur', function () { if (win.isVisible()) { this._toggleAction.blur(); } }); return win; }
javascript
function togglify(win, opts) { // extend options for toggle window opts = oassign({ animation: 'hide' }, opts); win._toggleAction = new ToggleAnimation(win, opts.animation); // patch toggle function to window win.toggle = function () { if (this.isVisible() && this.isFocused()) { this._toggleAction.hide(); } else if (this.isVisible() && !this.isFocused()) { this._toggleAction.focus(); } else if (this.isMinimized() || !this.isVisible()) { this._toggleAction.restore(); } }; // bind event for default action win.on('blur', function () { if (win.isVisible()) { this._toggleAction.blur(); } }); return win; }
[ "function", "togglify", "(", "win", ",", "opts", ")", "{", "opts", "=", "oassign", "(", "{", "animation", ":", "'hide'", "}", ",", "opts", ")", ";", "win", ".", "_toggleAction", "=", "new", "ToggleAnimation", "(", "win", ",", "opts", ".", "animation", ")", ";", "win", ".", "toggle", "=", "function", "(", ")", "{", "if", "(", "this", ".", "isVisible", "(", ")", "&&", "this", ".", "isFocused", "(", ")", ")", "{", "this", ".", "_toggleAction", ".", "hide", "(", ")", ";", "}", "else", "if", "(", "this", ".", "isVisible", "(", ")", "&&", "!", "this", ".", "isFocused", "(", ")", ")", "{", "this", ".", "_toggleAction", ".", "focus", "(", ")", ";", "}", "else", "if", "(", "this", ".", "isMinimized", "(", ")", "||", "!", "this", ".", "isVisible", "(", ")", ")", "{", "this", ".", "_toggleAction", ".", "restore", "(", ")", ";", "}", "}", ";", "win", ".", "on", "(", "'blur'", ",", "function", "(", ")", "{", "if", "(", "win", ".", "isVisible", "(", ")", ")", "{", "this", ".", "_toggleAction", ".", "blur", "(", ")", ";", "}", "}", ")", ";", "return", "win", ";", "}" ]
Set window to be able to togggle
[ "Set", "window", "to", "be", "able", "to", "togggle" ]
e9781f67f79e8d2a082dba4cb31b29bdbb874df7
https://github.com/ragingwind/electron-togglify-window/blob/e9781f67f79e8d2a082dba4cb31b29bdbb874df7/index.js#L55-L82
train
rootsdev/gedcomx-js
src/core/SourceCitation.js
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SourceCitation)){ return new SourceCitation(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SourceCitation.isInstance(json)){ return json; } this.init(json); }
javascript
function(json){ // Protect against forgetting the new keyword when calling the constructor if(!(this instanceof SourceCitation)){ return new SourceCitation(json); } // If the given object is already an instance then just return it. DON'T copy it. if(SourceCitation.isInstance(json)){ return json; } this.init(json); }
[ "function", "(", "json", ")", "{", "if", "(", "!", "(", "this", "instanceof", "SourceCitation", ")", ")", "{", "return", "new", "SourceCitation", "(", "json", ")", ";", "}", "if", "(", "SourceCitation", ".", "isInstance", "(", "json", ")", ")", "{", "return", "json", ";", "}", "this", ".", "init", "(", "json", ")", ";", "}" ]
A source citation. @see {@link https://github.com/FamilySearch/gedcomx/blob/master/specifications/json-format-specification.md#source-citation|GEDCOM X JSON Spec} @class @extends ExtensibleData @apram {Object} [json]
[ "A", "source", "citation", "." ]
08b2fcde96f1e301c78561bfb7a8b0cac606e26e
https://github.com/rootsdev/gedcomx-js/blob/08b2fcde96f1e301c78561bfb7a8b0cac606e26e/src/core/SourceCitation.js#L13-L26
train
lroche/karma-jasmine-bridge
lib/Spec.js
wrapper
function wrapper(matcherName, legacyMatcher){ return function(util, customEqualityTesters){ return { compare: function(actual, expected){ var scope = {actual: actual}, message, result; result = legacyMatcher.call(scope, expected) message = scope.message && scope.message()[result ? 1 : 0]; return { pass:result, message : message } } } } }
javascript
function wrapper(matcherName, legacyMatcher){ return function(util, customEqualityTesters){ return { compare: function(actual, expected){ var scope = {actual: actual}, message, result; result = legacyMatcher.call(scope, expected) message = scope.message && scope.message()[result ? 1 : 0]; return { pass:result, message : message } } } } }
[ "function", "wrapper", "(", "matcherName", ",", "legacyMatcher", ")", "{", "return", "function", "(", "util", ",", "customEqualityTesters", ")", "{", "return", "{", "compare", ":", "function", "(", "actual", ",", "expected", ")", "{", "var", "scope", "=", "{", "actual", ":", "actual", "}", ",", "message", ",", "result", ";", "result", "=", "legacyMatcher", ".", "call", "(", "scope", ",", "expected", ")", "message", "=", "scope", ".", "message", "&&", "scope", ".", "message", "(", ")", "[", "result", "?", "1", ":", "0", "]", ";", "return", "{", "pass", ":", "result", ",", "message", ":", "message", "}", "}", "}", "}", "}" ]
Wraps Jasmine2 matcher to be compliant with Jasmine 1 API.
[ "Wraps", "Jasmine2", "matcher", "to", "be", "compliant", "with", "Jasmine", "1", "API", "." ]
eda799fab2bb09f7876d31420955583e6791d27c
https://github.com/lroche/karma-jasmine-bridge/blob/eda799fab2bb09f7876d31420955583e6791d27c/lib/Spec.js#L135-L151
train
rowanmanning/chic
lib/chic.js
applySuperMethod
function applySuperMethod (fn, sup) { return function () { var prev, result; prev = this.sup; this.sup = sup; result = fn.apply(this, arguments); this.sup = prev; if (typeof this.sup === 'undefined') { delete this.sup; } return result; }; }
javascript
function applySuperMethod (fn, sup) { return function () { var prev, result; prev = this.sup; this.sup = sup; result = fn.apply(this, arguments); this.sup = prev; if (typeof this.sup === 'undefined') { delete this.sup; } return result; }; }
[ "function", "applySuperMethod", "(", "fn", ",", "sup", ")", "{", "return", "function", "(", ")", "{", "var", "prev", ",", "result", ";", "prev", "=", "this", ".", "sup", ";", "this", ".", "sup", "=", "sup", ";", "result", "=", "fn", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "sup", "=", "prev", ";", "if", "(", "typeof", "this", ".", "sup", "===", "'undefined'", ")", "{", "delete", "this", ".", "sup", ";", "}", "return", "result", ";", "}", ";", "}" ]
Apply a super-method to a function. `this.sup` is set to `sup` inside calls to `fn`.
[ "Apply", "a", "super", "-", "method", "to", "a", "function", ".", "this", ".", "sup", "is", "set", "to", "sup", "inside", "calls", "to", "fn", "." ]
c5839c2e1e2be1cf13e86e828f5059c57954d5e8
https://github.com/rowanmanning/chic/blob/c5839c2e1e2be1cf13e86e828f5059c57954d5e8/lib/chic.js#L27-L39
train
ipanli/xlsxtojson
index.js
parseCommandLine
function parseCommandLine(args) { var parsed_cmds = []; if (args.length <= 2) { parsed_cmds.push(defaultCommand()); } else { var cli = args.slice(2); var pos = 0; var cmd; cli.forEach(function(element, index, array) { //replace alias name with real name. if (element.indexOf('--') === -1 && element.indexOf('-') === 0) { cli[index] = alias_map[element]; } //parse command and args if (cli[index].indexOf('--') === -1) { cmd.args.push(cli[index]); } else { if (keys[cli[index]] == "undefined") { throw new Error("not support command:" + cli[index]); }; pos = index; cmd = commands[cli[index]]; if (typeof cmd.args == 'undefined') { cmd.args = []; }; parsed_cmds.push(cmd); } }); }; return parsed_cmds; }
javascript
function parseCommandLine(args) { var parsed_cmds = []; if (args.length <= 2) { parsed_cmds.push(defaultCommand()); } else { var cli = args.slice(2); var pos = 0; var cmd; cli.forEach(function(element, index, array) { //replace alias name with real name. if (element.indexOf('--') === -1 && element.indexOf('-') === 0) { cli[index] = alias_map[element]; } //parse command and args if (cli[index].indexOf('--') === -1) { cmd.args.push(cli[index]); } else { if (keys[cli[index]] == "undefined") { throw new Error("not support command:" + cli[index]); }; pos = index; cmd = commands[cli[index]]; if (typeof cmd.args == 'undefined') { cmd.args = []; }; parsed_cmds.push(cmd); } }); }; return parsed_cmds; }
[ "function", "parseCommandLine", "(", "args", ")", "{", "var", "parsed_cmds", "=", "[", "]", ";", "if", "(", "args", ".", "length", "<=", "2", ")", "{", "parsed_cmds", ".", "push", "(", "defaultCommand", "(", ")", ")", ";", "}", "else", "{", "var", "cli", "=", "args", ".", "slice", "(", "2", ")", ";", "var", "pos", "=", "0", ";", "var", "cmd", ";", "cli", ".", "forEach", "(", "function", "(", "element", ",", "index", ",", "array", ")", "{", "if", "(", "element", ".", "indexOf", "(", "'--'", ")", "===", "-", "1", "&&", "element", ".", "indexOf", "(", "'-'", ")", "===", "0", ")", "{", "cli", "[", "index", "]", "=", "alias_map", "[", "element", "]", ";", "}", "if", "(", "cli", "[", "index", "]", ".", "indexOf", "(", "'--'", ")", "===", "-", "1", ")", "{", "cmd", ".", "args", ".", "push", "(", "cli", "[", "index", "]", ")", ";", "}", "else", "{", "if", "(", "keys", "[", "cli", "[", "index", "]", "]", "==", "\"undefined\"", ")", "{", "throw", "new", "Error", "(", "\"not support command:\"", "+", "cli", "[", "index", "]", ")", ";", "}", ";", "pos", "=", "index", ";", "cmd", "=", "commands", "[", "cli", "[", "index", "]", "]", ";", "if", "(", "typeof", "cmd", ".", "args", "==", "'undefined'", ")", "{", "cmd", ".", "args", "=", "[", "]", ";", "}", ";", "parsed_cmds", ".", "push", "(", "cmd", ")", ";", "}", "}", ")", ";", "}", ";", "return", "parsed_cmds", ";", "}" ]
parse command line args
[ "parse", "command", "line", "args" ]
7432f133d584d6f32eb2bf722de084e2416bc468
https://github.com/ipanli/xlsxtojson/blob/7432f133d584d6f32eb2bf722de084e2416bc468/index.js#L120-L160
train
ipanli/xlsxtojson
index.js
defaultCommand
function defaultCommand() { if (keys.length <= 0) { throw new Error("Error: there is no command at all!"); }; for (var p in commands) { if (commands[p]["default"]) { return commands[p]; }; }; if (keys["--help"]) { return commands["--help"]; } else { return commands[keys[0]]; }; }
javascript
function defaultCommand() { if (keys.length <= 0) { throw new Error("Error: there is no command at all!"); }; for (var p in commands) { if (commands[p]["default"]) { return commands[p]; }; }; if (keys["--help"]) { return commands["--help"]; } else { return commands[keys[0]]; }; }
[ "function", "defaultCommand", "(", ")", "{", "if", "(", "keys", ".", "length", "<=", "0", ")", "{", "throw", "new", "Error", "(", "\"Error: there is no command at all!\"", ")", ";", "}", ";", "for", "(", "var", "p", "in", "commands", ")", "{", "if", "(", "commands", "[", "p", "]", "[", "\"default\"", "]", ")", "{", "return", "commands", "[", "p", "]", ";", "}", ";", "}", ";", "if", "(", "keys", "[", "\"--help\"", "]", ")", "{", "return", "commands", "[", "\"--help\"", "]", ";", "}", "else", "{", "return", "commands", "[", "keys", "[", "0", "]", "]", ";", "}", ";", "}" ]
default command when no command line argas provided.
[ "default", "command", "when", "no", "command", "line", "argas", "provided", "." ]
7432f133d584d6f32eb2bf722de084e2416bc468
https://github.com/ipanli/xlsxtojson/blob/7432f133d584d6f32eb2bf722de084e2416bc468/index.js#L165-L181
train
smagch/simple-lru
simple-lru.js
Entry
function Entry(key, val, index) { this.key = key; this.val = val; this.index = index; }
javascript
function Entry(key, val, index) { this.key = key; this.val = val; this.index = index; }
[ "function", "Entry", "(", "key", ",", "val", ",", "index", ")", "{", "this", ".", "key", "=", "key", ";", "this", ".", "val", "=", "val", ";", "this", ".", "index", "=", "index", ";", "}" ]
Cache entry instance @param {String} @param {any} @param {Number} @api private
[ "Cache", "entry", "instance" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L92-L96
train
smagch/simple-lru
simple-lru.js
function (key, val) { var entry = this._byKey.get(key); // reuse entry if the key exists if (entry) { this._touch(entry); entry.val = val; return; } entry = new Entry(key, val, this._head++); this._byKey.set(key, entry); this._byOrder[entry.index] = entry; this._len++; this._trim(); }
javascript
function (key, val) { var entry = this._byKey.get(key); // reuse entry if the key exists if (entry) { this._touch(entry); entry.val = val; return; } entry = new Entry(key, val, this._head++); this._byKey.set(key, entry); this._byOrder[entry.index] = entry; this._len++; this._trim(); }
[ "function", "(", "key", ",", "val", ")", "{", "var", "entry", "=", "this", ".", "_byKey", ".", "get", "(", "key", ")", ";", "if", "(", "entry", ")", "{", "this", ".", "_touch", "(", "entry", ")", ";", "entry", ".", "val", "=", "val", ";", "return", ";", "}", "entry", "=", "new", "Entry", "(", "key", ",", "val", ",", "this", ".", "_head", "++", ")", ";", "this", ".", "_byKey", ".", "set", "(", "key", ",", "entry", ")", ";", "this", ".", "_byOrder", "[", "entry", ".", "index", "]", "=", "entry", ";", "this", ".", "_len", "++", ";", "this", ".", "_trim", "(", ")", ";", "}" ]
Set cache by key @param {String} unique string key @param {String|Object|Number} any value
[ "Set", "cache", "by", "key" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L126-L141
train
smagch/simple-lru
simple-lru.js
function (key) { var entry = this._byKey.del(key); if (!entry) return; delete this._byOrder[entry.index]; this._len--; if (this._len === 0) { this._head = this._tail = 0; } else { // update most index if it was most lecently used entry if (entry.index === this._head - 1) this._pop(); // update least index if it was least lecently used entry if (entry.index === this._tail) this._shift(); } return entry.val; }
javascript
function (key) { var entry = this._byKey.del(key); if (!entry) return; delete this._byOrder[entry.index]; this._len--; if (this._len === 0) { this._head = this._tail = 0; } else { // update most index if it was most lecently used entry if (entry.index === this._head - 1) this._pop(); // update least index if it was least lecently used entry if (entry.index === this._tail) this._shift(); } return entry.val; }
[ "function", "(", "key", ")", "{", "var", "entry", "=", "this", ".", "_byKey", ".", "del", "(", "key", ")", ";", "if", "(", "!", "entry", ")", "return", ";", "delete", "this", ".", "_byOrder", "[", "entry", ".", "index", "]", ";", "this", ".", "_len", "--", ";", "if", "(", "this", ".", "_len", "===", "0", ")", "{", "this", ".", "_head", "=", "this", ".", "_tail", "=", "0", ";", "}", "else", "{", "if", "(", "entry", ".", "index", "===", "this", ".", "_head", "-", "1", ")", "this", ".", "_pop", "(", ")", ";", "if", "(", "entry", ".", "index", "===", "this", ".", "_tail", ")", "this", ".", "_shift", "(", ")", ";", "}", "return", "entry", ".", "val", ";", "}" ]
delete cache by key @param {String} @return {String|Object|Number} cached value
[ "delete", "cache", "by", "key" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L149-L166
train
smagch/simple-lru
simple-lru.js
function (key) { var entry = this._byKey.get(key); if (entry) { this._touch(entry); return entry.val; } }
javascript
function (key) { var entry = this._byKey.get(key); if (entry) { this._touch(entry); return entry.val; } }
[ "function", "(", "key", ")", "{", "var", "entry", "=", "this", ".", "_byKey", ".", "get", "(", "key", ")", ";", "if", "(", "entry", ")", "{", "this", ".", "_touch", "(", "entry", ")", ";", "return", "entry", ".", "val", ";", "}", "}" ]
get cache by key @param {String} @return {any} cache if it exists
[ "get", "cache", "by", "key" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L174-L180
train
smagch/simple-lru
simple-lru.js
function (max) { if (typeof max !== 'number') return this._max; if (max < 1) throw new TypeError('max should be a positive number'); var shrink = (this._max || 0) > max; this._max = max; if (shrink) this._trim(); }
javascript
function (max) { if (typeof max !== 'number') return this._max; if (max < 1) throw new TypeError('max should be a positive number'); var shrink = (this._max || 0) > max; this._max = max; if (shrink) this._trim(); }
[ "function", "(", "max", ")", "{", "if", "(", "typeof", "max", "!==", "'number'", ")", "return", "this", ".", "_max", ";", "if", "(", "max", "<", "1", ")", "throw", "new", "TypeError", "(", "'max should be a positive number'", ")", ";", "var", "shrink", "=", "(", "this", ".", "_max", "||", "0", ")", ">", "max", ";", "this", ".", "_max", "=", "max", ";", "if", "(", "shrink", ")", "this", ".", "_trim", "(", ")", ";", "}" ]
Getter|Setter function of "max" option @param {Number} if setter
[ "Getter|Setter", "function", "of", "max", "option" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L222-L228
train
smagch/simple-lru
simple-lru.js
function () { var count = 0 , tail = this._tail , head = this._head , keys = new Array(this._len); for (var i = tail; i < head; i++) { var entry = this._byOrder[i]; if (entry) keys[count++] = entry.key; } return keys; }
javascript
function () { var count = 0 , tail = this._tail , head = this._head , keys = new Array(this._len); for (var i = tail; i < head; i++) { var entry = this._byOrder[i]; if (entry) keys[count++] = entry.key; } return keys; }
[ "function", "(", ")", "{", "var", "count", "=", "0", ",", "tail", "=", "this", ".", "_tail", ",", "head", "=", "this", ".", "_head", ",", "keys", "=", "new", "Array", "(", "this", ".", "_len", ")", ";", "for", "(", "var", "i", "=", "tail", ";", "i", "<", "head", ";", "i", "++", ")", "{", "var", "entry", "=", "this", ".", "_byOrder", "[", "i", "]", ";", "if", "(", "entry", ")", "keys", "[", "count", "++", "]", "=", "entry", ".", "key", ";", "}", "return", "keys", ";", "}" ]
return array of keys in least recently used order @return {Array}
[ "return", "array", "of", "keys", "in", "least", "recently", "used", "order" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L234-L246
train
smagch/simple-lru
simple-lru.js
function (entry) { // update most number to key if (entry.index !== this._head - 1) { var isTail = entry.index === this._tail; delete this._byOrder[entry.index]; entry.index = this._head++; this._byOrder[entry.index] = entry; if (isTail) this._shift(); } }
javascript
function (entry) { // update most number to key if (entry.index !== this._head - 1) { var isTail = entry.index === this._tail; delete this._byOrder[entry.index]; entry.index = this._head++; this._byOrder[entry.index] = entry; if (isTail) this._shift(); } }
[ "function", "(", "entry", ")", "{", "if", "(", "entry", ".", "index", "!==", "this", ".", "_head", "-", "1", ")", "{", "var", "isTail", "=", "entry", ".", "index", "===", "this", ".", "_tail", ";", "delete", "this", ".", "_byOrder", "[", "entry", ".", "index", "]", ";", "entry", ".", "index", "=", "this", ".", "_head", "++", ";", "this", ".", "_byOrder", "[", "entry", ".", "index", "]", "=", "entry", ";", "if", "(", "isTail", ")", "this", ".", "_shift", "(", ")", ";", "}", "}" ]
update least recently used index of an entry to "_head" @param {Entry} @api private
[ "update", "least", "recently", "used", "index", "of", "an", "entry", "to", "_head" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L254-L263
train
smagch/simple-lru
simple-lru.js
function () { var tail = this._tail , head = this._head; for (var i = tail; i < head; i++) { var entry = this._byOrder[i]; if (entry) { this._tail = i; return entry; } } }
javascript
function () { var tail = this._tail , head = this._head; for (var i = tail; i < head; i++) { var entry = this._byOrder[i]; if (entry) { this._tail = i; return entry; } } }
[ "function", "(", ")", "{", "var", "tail", "=", "this", ".", "_tail", ",", "head", "=", "this", ".", "_head", ";", "for", "(", "var", "i", "=", "tail", ";", "i", "<", "head", ";", "i", "++", ")", "{", "var", "entry", "=", "this", ".", "_byOrder", "[", "i", "]", ";", "if", "(", "entry", ")", "{", "this", ".", "_tail", "=", "i", ";", "return", "entry", ";", "}", "}", "}" ]
update tail index @return {Entry|undefined} @api private
[ "update", "tail", "index" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L282-L292
train
smagch/simple-lru
simple-lru.js
function () { var tail = this._tail , head = this._head; for (var i = head - 1; i >= tail; i--) { var headEntry = this._byOrder[i]; if (headEntry) { this._head = i + 1; return headEntry; } } }
javascript
function () { var tail = this._tail , head = this._head; for (var i = head - 1; i >= tail; i--) { var headEntry = this._byOrder[i]; if (headEntry) { this._head = i + 1; return headEntry; } } }
[ "function", "(", ")", "{", "var", "tail", "=", "this", ".", "_tail", ",", "head", "=", "this", ".", "_head", ";", "for", "(", "var", "i", "=", "head", "-", "1", ";", "i", ">=", "tail", ";", "i", "--", ")", "{", "var", "headEntry", "=", "this", ".", "_byOrder", "[", "i", "]", ";", "if", "(", "headEntry", ")", "{", "this", ".", "_head", "=", "i", "+", "1", ";", "return", "headEntry", ";", "}", "}", "}" ]
update head index @return {Entry|undefined} @api private
[ "update", "head", "index" ]
b32d8e55a190c969419d84669a1228c8705bfca2
https://github.com/smagch/simple-lru/blob/b32d8e55a190c969419d84669a1228c8705bfca2/simple-lru.js#L299-L309
train
futjs/fut-api
src/lib/mobile-login.js
generateMachineKey
async function generateMachineKey () { let parts = await Promise.all([ randomHex(8), randomHex(4), randomHex(4), randomHex(4), randomHex(12) ]) return `${parts[0]}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}` }
javascript
async function generateMachineKey () { let parts = await Promise.all([ randomHex(8), randomHex(4), randomHex(4), randomHex(4), randomHex(12) ]) return `${parts[0]}-${parts[1]}-${parts[2]}-${parts[3]}-${parts[4]}` }
[ "async", "function", "generateMachineKey", "(", ")", "{", "let", "parts", "=", "await", "Promise", ".", "all", "(", "[", "randomHex", "(", "8", ")", ",", "randomHex", "(", "4", ")", ",", "randomHex", "(", "4", ")", ",", "randomHex", "(", "4", ")", ",", "randomHex", "(", "12", ")", "]", ")", "return", "`", "${", "parts", "[", "0", "]", "}", "${", "parts", "[", "1", "]", "}", "${", "parts", "[", "2", "]", "}", "${", "parts", "[", "3", "]", "}", "${", "parts", "[", "4", "]", "}", "`", "}" ]
example EEA58055-E4E8-42E6-B89D-DFFBBD37AF57
[ "example", "EEA58055", "-", "E4E8", "-", "42E6", "-", "B89D", "-", "DFFBBD37AF57" ]
a26d3dfa93d62b4dd4755cb57b956c503182abc3
https://github.com/futjs/fut-api/blob/a26d3dfa93d62b4dd4755cb57b956c503182abc3/src/lib/mobile-login.js#L360-L369
train
imbo/imboclient-js
lib/browser/crypto.js
function() { if (typeof window.Worker === 'undefined' || typeof window.URL === 'undefined') { return false; } try { /* eslint-disable no-new */ new Worker(window.URL.createObjectURL( new Blob([''], { type: 'text/javascript' }) )); /* eslint-enable no-new */ } catch (e) { return false; } return true; }
javascript
function() { if (typeof window.Worker === 'undefined' || typeof window.URL === 'undefined') { return false; } try { /* eslint-disable no-new */ new Worker(window.URL.createObjectURL( new Blob([''], { type: 'text/javascript' }) )); /* eslint-enable no-new */ } catch (e) { return false; } return true; }
[ "function", "(", ")", "{", "if", "(", "typeof", "window", ".", "Worker", "===", "'undefined'", "||", "typeof", "window", ".", "URL", "===", "'undefined'", ")", "{", "return", "false", ";", "}", "try", "{", "new", "Worker", "(", "window", ".", "URL", ".", "createObjectURL", "(", "new", "Blob", "(", "[", "''", "]", ",", "{", "type", ":", "'text/javascript'", "}", ")", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Checks if webworkers are supported @return {Boolean}
[ "Checks", "if", "webworkers", "are", "supported" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/browser/crypto.js#L16-L32
train
imbo/imboclient-js
lib/browser/crypto.js
function(buffer, callback) { if (supportsWorkers) { // We have a worker queue, push an item into it and start processing workerQueue.push({ buffer: buffer, callback: callback }); nextMd5Task(); } else { // We don't have any Web Worker support, // queue an MD5 operation on the next tick process.nextTick(function() { callback(null, md5.ArrayBuffer.hash(buffer)); }); } }
javascript
function(buffer, callback) { if (supportsWorkers) { // We have a worker queue, push an item into it and start processing workerQueue.push({ buffer: buffer, callback: callback }); nextMd5Task(); } else { // We don't have any Web Worker support, // queue an MD5 operation on the next tick process.nextTick(function() { callback(null, md5.ArrayBuffer.hash(buffer)); }); } }
[ "function", "(", "buffer", ",", "callback", ")", "{", "if", "(", "supportsWorkers", ")", "{", "workerQueue", ".", "push", "(", "{", "buffer", ":", "buffer", ",", "callback", ":", "callback", "}", ")", ";", "nextMd5Task", "(", ")", ";", "}", "else", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "callback", "(", "null", ",", "md5", ".", "ArrayBuffer", ".", "hash", "(", "buffer", ")", ")", ";", "}", ")", ";", "}", "}" ]
Add a new MD5 task to the queue @param {ArrayBuffer} buffer - Buffer containing the file data @param {Function} callback - Callback to run when the MD5 task has been completed
[ "Add", "a", "new", "MD5", "task", "to", "the", "queue" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/browser/crypto.js#L64-L76
train
imbo/imboclient-js
lib/browser/crypto.js
function(key, data) { var shaObj = new Sha('SHA-256', 'TEXT'); shaObj.setHMACKey(key, 'TEXT'); shaObj.update(data); return shaObj.getHMAC('HEX'); }
javascript
function(key, data) { var shaObj = new Sha('SHA-256', 'TEXT'); shaObj.setHMACKey(key, 'TEXT'); shaObj.update(data); return shaObj.getHMAC('HEX'); }
[ "function", "(", "key", ",", "data", ")", "{", "var", "shaObj", "=", "new", "Sha", "(", "'SHA-256'", ",", "'TEXT'", ")", ";", "shaObj", ".", "setHMACKey", "(", "key", ",", "'TEXT'", ")", ";", "shaObj", ".", "update", "(", "data", ")", ";", "return", "shaObj", ".", "getHMAC", "(", "'HEX'", ")", ";", "}" ]
Generate a SHA256 HMAC hash from the given data @param {String} key @param {String} data @return {String}
[ "Generate", "a", "SHA256", "HMAC", "hash", "from", "the", "given", "data" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/browser/crypto.js#L98-L103
train
imbo/imboclient-js
lib/browser/crypto.js
function(buffer, callback, options) { if (options && options.type === 'url') { readers.getContentsFromUrl(buffer, function(err, data) { if (err) { return callback(err); } module.exports.md5(data, callback, { binary: true }); }); } else if (buffer instanceof window.File) { readers.getContentsFromFile(buffer, function(err, data) { if (err) { return callback(err); } module.exports.md5(data, callback, { binary: true }); }); } else { // ArrayBuffer, then. process.nextTick(function() { addMd5Task(buffer, callback); }); } }
javascript
function(buffer, callback, options) { if (options && options.type === 'url') { readers.getContentsFromUrl(buffer, function(err, data) { if (err) { return callback(err); } module.exports.md5(data, callback, { binary: true }); }); } else if (buffer instanceof window.File) { readers.getContentsFromFile(buffer, function(err, data) { if (err) { return callback(err); } module.exports.md5(data, callback, { binary: true }); }); } else { // ArrayBuffer, then. process.nextTick(function() { addMd5Task(buffer, callback); }); } }
[ "function", "(", "buffer", ",", "callback", ",", "options", ")", "{", "if", "(", "options", "&&", "options", ".", "type", "===", "'url'", ")", "{", "readers", ".", "getContentsFromUrl", "(", "buffer", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "module", ".", "exports", ".", "md5", "(", "data", ",", "callback", ",", "{", "binary", ":", "true", "}", ")", ";", "}", ")", ";", "}", "else", "if", "(", "buffer", "instanceof", "window", ".", "File", ")", "{", "readers", ".", "getContentsFromFile", "(", "buffer", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "module", ".", "exports", ".", "md5", "(", "data", ",", "callback", ",", "{", "binary", ":", "true", "}", ")", ";", "}", ")", ";", "}", "else", "{", "process", ".", "nextTick", "(", "function", "(", ")", "{", "addMd5Task", "(", "buffer", ",", "callback", ")", ";", "}", ")", ";", "}", "}" ]
Generate an MD5-sum of the given ArrayBuffer @param {ArrayBuffer} buffer @param {Function} callback @param {Object} [options]
[ "Generate", "an", "MD5", "-", "sum", "of", "the", "given", "ArrayBuffer" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/lib/browser/crypto.js#L112-L135
train
generate/generate-contributing
generator.js
template
function template(pattern) { return app.src(pattern, { cwd: path.join(__dirname, 'templates') }) .pipe(app.renderFile('*')).on('error', console.error) .pipe(app.conflicts(app.cwd)) .pipe(app.dest(app.options.dest || app.cwd)); }
javascript
function template(pattern) { return app.src(pattern, { cwd: path.join(__dirname, 'templates') }) .pipe(app.renderFile('*')).on('error', console.error) .pipe(app.conflicts(app.cwd)) .pipe(app.dest(app.options.dest || app.cwd)); }
[ "function", "template", "(", "pattern", ")", "{", "return", "app", ".", "src", "(", "pattern", ",", "{", "cwd", ":", "path", ".", "join", "(", "__dirname", ",", "'templates'", ")", "}", ")", ".", "pipe", "(", "app", ".", "renderFile", "(", "'*'", ")", ")", ".", "on", "(", "'error'", ",", "console", ".", "error", ")", ".", "pipe", "(", "app", ".", "conflicts", "(", "app", ".", "cwd", ")", ")", ".", "pipe", "(", "app", ".", "dest", "(", "app", ".", "options", ".", "dest", "||", "app", ".", "cwd", ")", ")", ";", "}" ]
Generate a file from the template that matches the given `pattern`
[ "Generate", "a", "file", "from", "the", "template", "that", "matches", "the", "given", "pattern" ]
e9becbfd164ede91246446200039cf6661d8ae1e
https://github.com/generate/generate-contributing/blob/e9becbfd164ede91246446200039cf6661d8ae1e/generator.js#L117-L122
train
angie-framework/angie
src/factories/$Compile.js
$$safeEvalFn
function $$safeEvalFn(str) { let keyStr = ''; // Perform any parsing that needs to be performed on the scope value for (let key in this) { let val = this[ key ]; if (!val && val !== 0 && val !== '') { continue; } else if ( typeof val === 'symbol' || typeof val === 'string' ) { val = `"${val}"`; } else if (typeof val === 'object') { val = JSON.stringify(val); } // I don't like having to use var here keyStr += `var ${key}=${val};`; } // Literal eval is executed in its own context here to reduce security issues /* eslint-disable */ return eval([ keyStr, str ].join('')); /* eslint-enable */ }
javascript
function $$safeEvalFn(str) { let keyStr = ''; // Perform any parsing that needs to be performed on the scope value for (let key in this) { let val = this[ key ]; if (!val && val !== 0 && val !== '') { continue; } else if ( typeof val === 'symbol' || typeof val === 'string' ) { val = `"${val}"`; } else if (typeof val === 'object') { val = JSON.stringify(val); } // I don't like having to use var here keyStr += `var ${key}=${val};`; } // Literal eval is executed in its own context here to reduce security issues /* eslint-disable */ return eval([ keyStr, str ].join('')); /* eslint-enable */ }
[ "function", "$$safeEvalFn", "(", "str", ")", "{", "let", "keyStr", "=", "''", ";", "for", "(", "let", "key", "in", "this", ")", "{", "let", "val", "=", "this", "[", "key", "]", ";", "if", "(", "!", "val", "&&", "val", "!==", "0", "&&", "val", "!==", "''", ")", "{", "continue", ";", "}", "else", "if", "(", "typeof", "val", "===", "'symbol'", "||", "typeof", "val", "===", "'string'", ")", "{", "val", "=", "`", "${", "val", "}", "`", ";", "}", "else", "if", "(", "typeof", "val", "===", "'object'", ")", "{", "val", "=", "JSON", ".", "stringify", "(", "val", ")", ";", "}", "keyStr", "+=", "`", "${", "key", "}", "${", "val", "}", "`", ";", "}", "return", "eval", "(", "[", "keyStr", ",", "str", "]", ".", "join", "(", "''", ")", ")", ";", "}" ]
A private function to evaluate the parsed template string in the context of `scope`
[ "A", "private", "function", "to", "evaluate", "the", "parsed", "template", "string", "in", "the", "context", "of", "scope" ]
7d0793f6125e60e0473b17ffd40305d6d6fdbc12
https://github.com/angie-framework/angie/blob/7d0793f6125e60e0473b17ffd40305d6d6fdbc12/src/factories/$Compile.js#L255-L281
train
Ubudu/uBeacon-uart-lib
node/examples/mesh-remote-management.js
function(callback){ var msg = ubeacon.getCommandString( false, ubeacon.uartCmd.led, new Buffer('03','hex') , false ); ubeacon.sendMeshRemoteManagementMessage( program.destinationAddress, msg.toString(), null); setTimeout(callback, 2000); }
javascript
function(callback){ var msg = ubeacon.getCommandString( false, ubeacon.uartCmd.led, new Buffer('03','hex') , false ); ubeacon.sendMeshRemoteManagementMessage( program.destinationAddress, msg.toString(), null); setTimeout(callback, 2000); }
[ "function", "(", "callback", ")", "{", "var", "msg", "=", "ubeacon", ".", "getCommandString", "(", "false", ",", "ubeacon", ".", "uartCmd", ".", "led", ",", "new", "Buffer", "(", "'03'", ",", "'hex'", ")", ",", "false", ")", ";", "ubeacon", ".", "sendMeshRemoteManagementMessage", "(", "program", ".", "destinationAddress", ",", "msg", ".", "toString", "(", ")", ",", "null", ")", ";", "setTimeout", "(", "callback", ",", "2000", ")", ";", "}" ]
Build LED-on message and send it
[ "Build", "LED", "-", "on", "message", "and", "send", "it" ]
a7436f3491f61ffabb34e2bc3b2441cc048f5dfa
https://github.com/Ubudu/uBeacon-uart-lib/blob/a7436f3491f61ffabb34e2bc3b2441cc048f5dfa/node/examples/mesh-remote-management.js#L31-L35
train
imbo/imboclient-js
examples/browser/resources/browser-demo.js
function(org) { var url = decodeURIComponent(org.toString()); urlOutput.empty().attr('href', url); url = url.replace(/.*?\/users\//g, '/users/'); url = url.replace(/Token=(.{10}).*/g, 'Token=$1...'); var parts = url.split('?'), param; var params = parts[1].replace(/t\[\]=maxSize.*?&/g, '').split('&'); // Base url $('<div />').text(parts[0]).appendTo(urlOutput); for (var i = 0, prefix; i < params.length; i++) { prefix = i > 0 ? '&' : '?'; parts = params[i].split(/t\[\]=/); param = prefix + parts[0]; if (parts.length > 1) { var args = [], trans = parts[1].split(':'); param = prefix + 't[]=<span class="transformation">' + trans[0] + '</span>'; if (trans.length > 1) { var items = trans[1].split(','); for (var t = 0; t < items.length; t++) { var c = items[t].split('='), x = ''; x += '<span class="param">' + c[0] + '</span>='; x += '<span class="value">' + c[1] + '</span>'; args.push(x); } param += ':' + args.join(','); } } param = param.replace(/(.*?=)/, '<strong>$1</strong>'); $('<div />').html(param).appendTo(urlOutput); } }
javascript
function(org) { var url = decodeURIComponent(org.toString()); urlOutput.empty().attr('href', url); url = url.replace(/.*?\/users\//g, '/users/'); url = url.replace(/Token=(.{10}).*/g, 'Token=$1...'); var parts = url.split('?'), param; var params = parts[1].replace(/t\[\]=maxSize.*?&/g, '').split('&'); // Base url $('<div />').text(parts[0]).appendTo(urlOutput); for (var i = 0, prefix; i < params.length; i++) { prefix = i > 0 ? '&' : '?'; parts = params[i].split(/t\[\]=/); param = prefix + parts[0]; if (parts.length > 1) { var args = [], trans = parts[1].split(':'); param = prefix + 't[]=<span class="transformation">' + trans[0] + '</span>'; if (trans.length > 1) { var items = trans[1].split(','); for (var t = 0; t < items.length; t++) { var c = items[t].split('='), x = ''; x += '<span class="param">' + c[0] + '</span>='; x += '<span class="value">' + c[1] + '</span>'; args.push(x); } param += ':' + args.join(','); } } param = param.replace(/(.*?=)/, '<strong>$1</strong>'); $('<div />').html(param).appendTo(urlOutput); } }
[ "function", "(", "org", ")", "{", "var", "url", "=", "decodeURIComponent", "(", "org", ".", "toString", "(", ")", ")", ";", "urlOutput", ".", "empty", "(", ")", ".", "attr", "(", "'href'", ",", "url", ")", ";", "url", "=", "url", ".", "replace", "(", "/", ".*?\\/users\\/", "/", "g", ",", "'/users/'", ")", ";", "url", "=", "url", ".", "replace", "(", "/", "Token=(.{10}).*", "/", "g", ",", "'Token=$1...'", ")", ";", "var", "parts", "=", "url", ".", "split", "(", "'?'", ")", ",", "param", ";", "var", "params", "=", "parts", "[", "1", "]", ".", "replace", "(", "/", "t\\[\\]=maxSize.*?&", "/", "g", ",", "''", ")", ".", "split", "(", "'&'", ")", ";", "$", "(", "'<div />'", ")", ".", "text", "(", "parts", "[", "0", "]", ")", ".", "appendTo", "(", "urlOutput", ")", ";", "for", "(", "var", "i", "=", "0", ",", "prefix", ";", "i", "<", "params", ".", "length", ";", "i", "++", ")", "{", "prefix", "=", "i", ">", "0", "?", "'&'", ":", "'?'", ";", "parts", "=", "params", "[", "i", "]", ".", "split", "(", "/", "t\\[\\]=", "/", ")", ";", "param", "=", "prefix", "+", "parts", "[", "0", "]", ";", "if", "(", "parts", ".", "length", ">", "1", ")", "{", "var", "args", "=", "[", "]", ",", "trans", "=", "parts", "[", "1", "]", ".", "split", "(", "':'", ")", ";", "param", "=", "prefix", "+", "'t[]=<span class=\"transformation\">'", "+", "trans", "[", "0", "]", "+", "'</span>'", ";", "if", "(", "trans", ".", "length", ">", "1", ")", "{", "var", "items", "=", "trans", "[", "1", "]", ".", "split", "(", "','", ")", ";", "for", "(", "var", "t", "=", "0", ";", "t", "<", "items", ".", "length", ";", "t", "++", ")", "{", "var", "c", "=", "items", "[", "t", "]", ".", "split", "(", "'='", ")", ",", "x", "=", "''", ";", "x", "+=", "'<span class=\"param\">'", "+", "c", "[", "0", "]", "+", "'</span>='", ";", "x", "+=", "'<span class=\"value\">'", "+", "c", "[", "1", "]", "+", "'</span>'", ";", "args", ".", "push", "(", "x", ")", ";", "}", "param", "+=", "':'", "+", "args", ".", "join", "(", "','", ")", ";", "}", "}", "param", "=", "param", ".", "replace", "(", "/", "(.*?=)", "/", ",", "'<strong>$1</strong>'", ")", ";", "$", "(", "'<div />'", ")", ".", "html", "(", "param", ")", ".", "appendTo", "(", "urlOutput", ")", ";", "}", "}" ]
Demonstrating the URL helper
[ "Demonstrating", "the", "URL", "helper" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/examples/browser/resources/browser-demo.js#L67-L105
train
imbo/imboclient-js
examples/browser/resources/browser-demo.js
function(err, imageIdentifier, res) { // Remove progress bar bar.css('width', '100%'); progress.animate({ opacity: 0}, { duration: 1000, complete: function() { $(this).remove(); } }); // Check for any XHR errors (200 means image already exists) if (err && res && res.headers && res.headers['X-Imbo-Error-Internalcode'] !== 200) { if (err === 'Signature mismatch') { err += ' (probably incorrect private key)'; } /* eslint no-alert: 0 */ return window.alert(err); } else if (err) { return window.alert(err); } // Build an Imbo-url var result = $('#result').removeClass('hidden'); var url = client.getImageUrl(imageIdentifier); $('#image-identifier').text(imageIdentifier).attr('href', url.toString()); result.find('img').attr('src', url.maxSize({ width: result.width() }).toString()); updateUrl(url); if (!active) { $('#controls [data-transformation="border"]').on('click', function() { url.border({ color: 'bf1942', width: 5, height: 5 }); }); $('#controls button').on('click', function() { var btn = $(this), transformation = btn.data('transformation'), args = btn.data('args'), pass = args ? (args + '').split(',') : []; url[transformation].apply(url, pass); if (transformation === 'reset') { url.maxSize({ width: result.width() }); } updateUrl(url); result.find('img').attr('src', url.toString()); }); } }
javascript
function(err, imageIdentifier, res) { // Remove progress bar bar.css('width', '100%'); progress.animate({ opacity: 0}, { duration: 1000, complete: function() { $(this).remove(); } }); // Check for any XHR errors (200 means image already exists) if (err && res && res.headers && res.headers['X-Imbo-Error-Internalcode'] !== 200) { if (err === 'Signature mismatch') { err += ' (probably incorrect private key)'; } /* eslint no-alert: 0 */ return window.alert(err); } else if (err) { return window.alert(err); } // Build an Imbo-url var result = $('#result').removeClass('hidden'); var url = client.getImageUrl(imageIdentifier); $('#image-identifier').text(imageIdentifier).attr('href', url.toString()); result.find('img').attr('src', url.maxSize({ width: result.width() }).toString()); updateUrl(url); if (!active) { $('#controls [data-transformation="border"]').on('click', function() { url.border({ color: 'bf1942', width: 5, height: 5 }); }); $('#controls button').on('click', function() { var btn = $(this), transformation = btn.data('transformation'), args = btn.data('args'), pass = args ? (args + '').split(',') : []; url[transformation].apply(url, pass); if (transformation === 'reset') { url.maxSize({ width: result.width() }); } updateUrl(url); result.find('img').attr('src', url.toString()); }); } }
[ "function", "(", "err", ",", "imageIdentifier", ",", "res", ")", "{", "bar", ".", "css", "(", "'width'", ",", "'100%'", ")", ";", "progress", ".", "animate", "(", "{", "opacity", ":", "0", "}", ",", "{", "duration", ":", "1000", ",", "complete", ":", "function", "(", ")", "{", "$", "(", "this", ")", ".", "remove", "(", ")", ";", "}", "}", ")", ";", "if", "(", "err", "&&", "res", "&&", "res", ".", "headers", "&&", "res", ".", "headers", "[", "'X-Imbo-Error-Internalcode'", "]", "!==", "200", ")", "{", "if", "(", "err", "===", "'Signature mismatch'", ")", "{", "err", "+=", "' (probably incorrect private key)'", ";", "}", "return", "window", ".", "alert", "(", "err", ")", ";", "}", "else", "if", "(", "err", ")", "{", "return", "window", ".", "alert", "(", "err", ")", ";", "}", "var", "result", "=", "$", "(", "'#result'", ")", ".", "removeClass", "(", "'hidden'", ")", ";", "var", "url", "=", "client", ".", "getImageUrl", "(", "imageIdentifier", ")", ";", "$", "(", "'#image-identifier'", ")", ".", "text", "(", "imageIdentifier", ")", ".", "attr", "(", "'href'", ",", "url", ".", "toString", "(", ")", ")", ";", "result", ".", "find", "(", "'img'", ")", ".", "attr", "(", "'src'", ",", "url", ".", "maxSize", "(", "{", "width", ":", "result", ".", "width", "(", ")", "}", ")", ".", "toString", "(", ")", ")", ";", "updateUrl", "(", "url", ")", ";", "if", "(", "!", "active", ")", "{", "$", "(", "'#controls [data-transformation=\"border\"]'", ")", ".", "on", "(", "'click'", ",", "function", "(", ")", "{", "url", ".", "border", "(", "{", "color", ":", "'bf1942'", ",", "width", ":", "5", ",", "height", ":", "5", "}", ")", ";", "}", ")", ";", "$", "(", "'#controls button'", ")", ".", "on", "(", "'click'", ",", "function", "(", ")", "{", "var", "btn", "=", "$", "(", "this", ")", ",", "transformation", "=", "btn", ".", "data", "(", "'transformation'", ")", ",", "args", "=", "btn", ".", "data", "(", "'args'", ")", ",", "pass", "=", "args", "?", "(", "args", "+", "''", ")", ".", "split", "(", "','", ")", ":", "[", "]", ";", "url", "[", "transformation", "]", ".", "apply", "(", "url", ",", "pass", ")", ";", "if", "(", "transformation", "===", "'reset'", ")", "{", "url", ".", "maxSize", "(", "{", "width", ":", "result", ".", "width", "(", ")", "}", ")", ";", "}", "updateUrl", "(", "url", ")", ";", "result", ".", "find", "(", "'img'", ")", ".", "attr", "(", "'src'", ",", "url", ".", "toString", "(", ")", ")", ";", "}", ")", ";", "}", "}" ]
Callback for when the image is uploaded
[ "Callback", "for", "when", "the", "image", "is", "uploaded" ]
809dcc489528dca9d67f49b03b612a99704339d0
https://github.com/imbo/imboclient-js/blob/809dcc489528dca9d67f49b03b612a99704339d0/examples/browser/resources/browser-demo.js#L108-L159
train
aefty/wireframe
lib/wireframe.js
function(data, callback) { var set = _assembleTask(data, workFlow[meth][url].merg); if (set.err) throw new Error('Invalid workflow: ' + set.tasks); async.series(set.tasks, function(err, results) { return callback(err, { 'sync': data.sync, 'async': data.async, 'merg': results }); }); }
javascript
function(data, callback) { var set = _assembleTask(data, workFlow[meth][url].merg); if (set.err) throw new Error('Invalid workflow: ' + set.tasks); async.series(set.tasks, function(err, results) { return callback(err, { 'sync': data.sync, 'async': data.async, 'merg': results }); }); }
[ "function", "(", "data", ",", "callback", ")", "{", "var", "set", "=", "_assembleTask", "(", "data", ",", "workFlow", "[", "meth", "]", "[", "url", "]", ".", "merg", ")", ";", "if", "(", "set", ".", "err", ")", "throw", "new", "Error", "(", "'Invalid workflow: '", "+", "set", ".", "tasks", ")", ";", "async", ".", "series", "(", "set", ".", "tasks", ",", "function", "(", "err", ",", "results", ")", "{", "return", "callback", "(", "err", ",", "{", "'sync'", ":", "data", ".", "sync", ",", "'async'", ":", "data", ".", "async", ",", "'merg'", ":", "results", "}", ")", ";", "}", ")", ";", "}" ]
Merg - Parallel process @param {Object} data - return values of sync and async @param {Function} callback
[ "Merg", "-", "Parallel", "process" ]
18b894fdf2591f390040a365b836fea87760332a
https://github.com/aefty/wireframe/blob/18b894fdf2591f390040a365b836fea87760332a/lib/wireframe.js#L54-L64
train
visionmedia/connect-render
lib/render.js
render
function render(view, options) { var self = this; options = options || {}; for (var name in settings._filters) { options[name] = settings._filters[name]; } if (settings.helpers) { for (var k in settings.helpers) { var helper = settings.helpers[k]; if (typeof helper === 'function') { helper = helper(self.req, self); } if (!options.hasOwnProperty(k)) { options[k] = helper; } } } if (settings.filters) { for (var name in settings.filters) { options[name] = settings.filters[name]; } } // add request to options if (!options.request) { options.request = self.req; } // render view template _render(view, options, function (err, str) { if (err) { return self.req.next(err); } var layout = typeof options.layout === 'string' ? options.layout : settings.layout; if (options.layout === false || !layout) { return send(self, str); } // render layout template, add view str to layout's locals.body; options.body = str; _render(layout, options, function (err, str) { if (err) { return self.req.next(err); } send(self, str); }); }); return this; }
javascript
function render(view, options) { var self = this; options = options || {}; for (var name in settings._filters) { options[name] = settings._filters[name]; } if (settings.helpers) { for (var k in settings.helpers) { var helper = settings.helpers[k]; if (typeof helper === 'function') { helper = helper(self.req, self); } if (!options.hasOwnProperty(k)) { options[k] = helper; } } } if (settings.filters) { for (var name in settings.filters) { options[name] = settings.filters[name]; } } // add request to options if (!options.request) { options.request = self.req; } // render view template _render(view, options, function (err, str) { if (err) { return self.req.next(err); } var layout = typeof options.layout === 'string' ? options.layout : settings.layout; if (options.layout === false || !layout) { return send(self, str); } // render layout template, add view str to layout's locals.body; options.body = str; _render(layout, options, function (err, str) { if (err) { return self.req.next(err); } send(self, str); }); }); return this; }
[ "function", "render", "(", "view", ",", "options", ")", "{", "var", "self", "=", "this", ";", "options", "=", "options", "||", "{", "}", ";", "for", "(", "var", "name", "in", "settings", ".", "_filters", ")", "{", "options", "[", "name", "]", "=", "settings", ".", "_filters", "[", "name", "]", ";", "}", "if", "(", "settings", ".", "helpers", ")", "{", "for", "(", "var", "k", "in", "settings", ".", "helpers", ")", "{", "var", "helper", "=", "settings", ".", "helpers", "[", "k", "]", ";", "if", "(", "typeof", "helper", "===", "'function'", ")", "{", "helper", "=", "helper", "(", "self", ".", "req", ",", "self", ")", ";", "}", "if", "(", "!", "options", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "options", "[", "k", "]", "=", "helper", ";", "}", "}", "}", "if", "(", "settings", ".", "filters", ")", "{", "for", "(", "var", "name", "in", "settings", ".", "filters", ")", "{", "options", "[", "name", "]", "=", "settings", ".", "filters", "[", "name", "]", ";", "}", "}", "if", "(", "!", "options", ".", "request", ")", "{", "options", ".", "request", "=", "self", ".", "req", ";", "}", "_render", "(", "view", ",", "options", ",", "function", "(", "err", ",", "str", ")", "{", "if", "(", "err", ")", "{", "return", "self", ".", "req", ".", "next", "(", "err", ")", ";", "}", "var", "layout", "=", "typeof", "options", ".", "layout", "===", "'string'", "?", "options", ".", "layout", ":", "settings", ".", "layout", ";", "if", "(", "options", ".", "layout", "===", "false", "||", "!", "layout", ")", "{", "return", "send", "(", "self", ",", "str", ")", ";", "}", "options", ".", "body", "=", "str", ";", "_render", "(", "layout", ",", "options", ",", "function", "(", "err", ",", "str", ")", "{", "if", "(", "err", ")", "{", "return", "self", ".", "req", ".", "next", "(", "err", ")", ";", "}", "send", "(", "self", ",", "str", ")", ";", "}", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Render the view fill with options @param {String} view, view name. @param {Object} [options=null] - {Boolean} layout, use layout or not, default is `true`. @return {HttpServerResponse} this
[ "Render", "the", "view", "fill", "with", "options" ]
bbd3b562aaafb8c3f3b0c536508db3fc2568e3ce
https://github.com/visionmedia/connect-render/blob/bbd3b562aaafb8c3f3b0c536508db3fc2568e3ce/lib/render.js#L123-L172
train