id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
48,700
dcodeIO/IntN.js
dist/IntN.js
IntN
function IntN(bytes, unsigned) { /** * Represented byte values, least significant first. * @type {!Array.<number>} * @expose */ this.bytes = new Array(nBytes); for (var i=0, k=Math.min(nBytes, bytes.length); i<k; ++i) this.bytes[i] = bytes[i] & 0xff; for (; i<nBytes; ++i) this.bytes[i] = 0; /** * Whether unsigned or otherwise signed. * @type {boolean} * @expose */ this.unsigned = !!unsigned; }
javascript
function IntN(bytes, unsigned) { /** * Represented byte values, least significant first. * @type {!Array.<number>} * @expose */ this.bytes = new Array(nBytes); for (var i=0, k=Math.min(nBytes, bytes.length); i<k; ++i) this.bytes[i] = bytes[i] & 0xff; for (; i<nBytes; ++i) this.bytes[i] = 0; /** * Whether unsigned or otherwise signed. * @type {boolean} * @expose */ this.unsigned = !!unsigned; }
[ "function", "IntN", "(", "bytes", ",", "unsigned", ")", "{", "/**\n * Represented byte values, least significant first.\n * @type {!Array.<number>}\n * @expose\n */", "this", ".", "bytes", "=", "new", "Array", "(", "nBytes", ")", ";", "for", "(", "var", "i", "=", "0", ",", "k", "=", "Math", ".", "min", "(", "nBytes", ",", "bytes", ".", "length", ")", ";", "i", "<", "k", ";", "++", "i", ")", "this", ".", "bytes", "[", "i", "]", "=", "bytes", "[", "i", "]", "&", "0xff", ";", "for", "(", ";", "i", "<", "nBytes", ";", "++", "i", ")", "this", ".", "bytes", "[", "i", "]", "=", "0", ";", "/**\n * Whether unsigned or otherwise signed.\n * @type {boolean}\n * @expose\n */", "this", ".", "unsigned", "=", "!", "!", "unsigned", ";", "}" ]
Constructs a new IntN, where N is the number of bits represented by this class. @class A class for representing arbitrary size integers, both signed and unsigned. @exports IntN @param {!Array.<number>|number} bytes Byte values, least significant first @param {boolean=} unsigned Whether unsigned or signed, defaults to `false` for signed @constructor
[ "Constructs", "a", "new", "IntN", "where", "N", "is", "the", "number", "of", "bits", "represented", "by", "this", "class", "." ]
d50a1323077a61c29460c5a267c2853e0b8ed0cf
https://github.com/dcodeIO/IntN.js/blob/d50a1323077a61c29460c5a267c2853e0b8ed0cf/dist/IntN.js#L81-L101
48,701
sagiegurari/js-project-commons
lib/grunt/config/init-config.js
createBuildConfig
function createBuildConfig(grunt, options, projectConfig) { var configType = 'grunt-web'; if (options.buildConfig.dualProject) { configType = 'grunt-dual'; } else if (options.buildConfig.nodeProject) { configType = 'grunt-node'; } var loader = require('./' + configType); return loader(grunt, options, projectConfig); }
javascript
function createBuildConfig(grunt, options, projectConfig) { var configType = 'grunt-web'; if (options.buildConfig.dualProject) { configType = 'grunt-dual'; } else if (options.buildConfig.nodeProject) { configType = 'grunt-node'; } var loader = require('./' + configType); return loader(grunt, options, projectConfig); }
[ "function", "createBuildConfig", "(", "grunt", ",", "options", ",", "projectConfig", ")", "{", "var", "configType", "=", "'grunt-web'", ";", "if", "(", "options", ".", "buildConfig", ".", "dualProject", ")", "{", "configType", "=", "'grunt-dual'", ";", "}", "else", "if", "(", "options", ".", "buildConfig", ".", "nodeProject", ")", "{", "configType", "=", "'grunt-node'", ";", "}", "var", "loader", "=", "require", "(", "'./'", "+", "configType", ")", ";", "return", "loader", "(", "grunt", ",", "options", ",", "projectConfig", ")", ";", "}" ]
Returns the build config object. @function @memberof! GruntInitConfig @private @param {Object} grunt - The grunt instance @param {Object} options - Any additional grunt config data @param {Object} [projectConfig] - Optional project specific config @returns {Object} Grunt config object
[ "Returns", "the", "build", "config", "object", "." ]
42dd07a8a3b2c49db71f489e08b94ac7279007a3
https://github.com/sagiegurari/js-project-commons/blob/42dd07a8a3b2c49db71f489e08b94ac7279007a3/lib/grunt/config/init-config.js#L18-L29
48,702
ThatDevCompany/that-build-library
src/utils/echo.js
echo
function echo(message) { return __awaiter(this, void 0, void 0, function* () { console.log('----------------'); console.log(message); console.log('----------------'); return Promise.resolve(); }); }
javascript
function echo(message) { return __awaiter(this, void 0, void 0, function* () { console.log('----------------'); console.log(message); console.log('----------------'); return Promise.resolve(); }); }
[ "function", "echo", "(", "message", ")", "{", "return", "__awaiter", "(", "this", ",", "void", "0", ",", "void", "0", ",", "function", "*", "(", ")", "{", "console", ".", "log", "(", "'----------------'", ")", ";", "console", ".", "log", "(", "message", ")", ";", "console", ".", "log", "(", "'----------------'", ")", ";", "return", "Promise", ".", "resolve", "(", ")", ";", "}", ")", ";", "}" ]
Echo a message to the console
[ "Echo", "a", "message", "to", "the", "console" ]
865aaac49531fa9793a055a4df8e9b1b41e71753
https://github.com/ThatDevCompany/that-build-library/blob/865aaac49531fa9793a055a4df8e9b1b41e71753/src/utils/echo.js#L14-L21
48,703
fatalxiao/js-markdown
src/lib/syntax/block/List.js
generateListItem
function generateListItem(result, hasBlankLine) { const content = [result[3]]; if (hasBlankLine) { content.unshift('\n'); } return { type: 'ListItem', checked: result[2] === '[x]' ? true : (result[2] === '[ ]' ? false : undefined), // true / false / undefined content, children: [] }; }
javascript
function generateListItem(result, hasBlankLine) { const content = [result[3]]; if (hasBlankLine) { content.unshift('\n'); } return { type: 'ListItem', checked: result[2] === '[x]' ? true : (result[2] === '[ ]' ? false : undefined), // true / false / undefined content, children: [] }; }
[ "function", "generateListItem", "(", "result", ",", "hasBlankLine", ")", "{", "const", "content", "=", "[", "result", "[", "3", "]", "]", ";", "if", "(", "hasBlankLine", ")", "{", "content", ".", "unshift", "(", "'\\n'", ")", ";", "}", "return", "{", "type", ":", "'ListItem'", ",", "checked", ":", "result", "[", "2", "]", "===", "'[x]'", "?", "true", ":", "(", "result", "[", "2", "]", "===", "'[ ]'", "?", "false", ":", "undefined", ")", ",", "// true / false / undefined", "content", ",", "children", ":", "[", "]", "}", ";", "}" ]
generate a list item node according to match result @param result @returns {{type: string, checked: boolean, content: [*], children: Array}}
[ "generate", "a", "list", "item", "node", "according", "to", "match", "result" ]
dffa23be561f50282e5ccc2f1595a51d18a81246
https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/syntax/block/List.js#L72-L87
48,704
3axap4eHko/yyf
src/undo-redo.js
getHistory
function getHistory(context) { if (!historyMap.has(context)) { clear(context); } return historyMap.get(context); }
javascript
function getHistory(context) { if (!historyMap.has(context)) { clear(context); } return historyMap.get(context); }
[ "function", "getHistory", "(", "context", ")", "{", "if", "(", "!", "historyMap", ".", "has", "(", "context", ")", ")", "{", "clear", "(", "context", ")", ";", "}", "return", "historyMap", ".", "get", "(", "context", ")", ";", "}" ]
Returns context history @param {Object} context @returns {Object}
[ "Returns", "context", "history" ]
0eddc236a3a5052b682ecc31dbb459772e653c14
https://github.com/3axap4eHko/yyf/blob/0eddc236a3a5052b682ecc31dbb459772e653c14/src/undo-redo.js#L30-L35
48,705
observing/fossa
lib/collection.js
constructor
function constructor(models, options) { if (!Array.isArray(models)) { options = models; models = []; } options = options || {}; // // Set the database name if it was provided in the options. // if (options.url) this.url = options.url; if (options.database) this.database = options.database; // // Define restricted non-enumerated properties. // predefine(this, fossa); // // Call original Backbone Model constructor. // backbone.Collection.call(this, models, options); }
javascript
function constructor(models, options) { if (!Array.isArray(models)) { options = models; models = []; } options = options || {}; // // Set the database name if it was provided in the options. // if (options.url) this.url = options.url; if (options.database) this.database = options.database; // // Define restricted non-enumerated properties. // predefine(this, fossa); // // Call original Backbone Model constructor. // backbone.Collection.call(this, models, options); }
[ "function", "constructor", "(", "models", ",", "options", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "models", ")", ")", "{", "options", "=", "models", ";", "models", "=", "[", "]", ";", "}", "options", "=", "options", "||", "{", "}", ";", "//", "// Set the database name if it was provided in the options.", "//", "if", "(", "options", ".", "url", ")", "this", ".", "url", "=", "options", ".", "url", ";", "if", "(", "options", ".", "database", ")", "this", ".", "database", "=", "options", ".", "database", ";", "//", "// Define restricted non-enumerated properties.", "//", "predefine", "(", "this", ",", "fossa", ")", ";", "//", "// Call original Backbone Model constructor.", "//", "backbone", ".", "Collection", ".", "call", "(", "this", ",", "models", ",", "options", ")", ";", "}" ]
Override default Collection Constructor. @param {Array} models @param {Object} options @api private
[ "Override", "default", "Collection", "Constructor", "." ]
29b3717ee10a13fb607f5bbddcb8b003faf008c6
https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/collection.js#L31-L54
48,706
observing/fossa
lib/collection.js
clone
function clone() { return new this.constructor(this.models, { url: 'function' === typeof this.url ? this.url() : this.url, model: this.model, database: this.database, comparator: this.comparator }); }
javascript
function clone() { return new this.constructor(this.models, { url: 'function' === typeof this.url ? this.url() : this.url, model: this.model, database: this.database, comparator: this.comparator }); }
[ "function", "clone", "(", ")", "{", "return", "new", "this", ".", "constructor", "(", "this", ".", "models", ",", "{", "url", ":", "'function'", "===", "typeof", "this", ".", "url", "?", "this", ".", "url", "(", ")", ":", "this", ".", "url", ",", "model", ":", "this", ".", "model", ",", "database", ":", "this", ".", "database", ",", "comparator", ":", "this", ".", "comparator", "}", ")", ";", "}" ]
Clone this Collection. @returns {Collection} @api public
[ "Clone", "this", "Collection", "." ]
29b3717ee10a13fb607f5bbddcb8b003faf008c6
https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/lib/collection.js#L73-L80
48,707
davidtucker/node-shutdown-manager
lib/shutdownManager.js
ShutdownManager
function ShutdownManager (params) { // Set State var that = this; this.isShuttingDown = false; this.actionChain = []; this.finalActionChain = []; // Set Parameters this.logger = (params && params.hasOwnProperty("logger")) ? params.logger : null; this.loggingPrefix = (params && params.hasOwnProperty("loggingPrefix")) ? params.loggingPrefix : DEFAULT_LOGGING_PREFIX; // Add Process Handlers process.on('SIGINT', function() { if (!that.emit('preShutdown', 'SIGINT')) { that._log("Received SIGINT, Beginning Shutdown Process"); } that._shutdown(128+2, params.timeout); }); process.on('SIGTERM', function() { if (!that.emit('preShutdown', 'SIGTERM')) { that._log("Received SIGTERM, Beginning Shutdown Process"); } that._shutdown(128+15, params.timeout); }); process.on('uncaughtException', function (err) { if (!that.emit('preShutdown', 'uncaughtException', err)) { that._log('Uncaught Exception Received, Beginning Shutdown Process'); that._log('Exception: '+err); } that._shutdown(255, params.timeout); }); process.on('exit', function() { // Just in case we are getting to exit without previous conditions being met // Not sure if this happens - will test. if(!that.isShuttingDown) { that.emit('preShutdown', 'exit'); that._log("Application Exiting for Undefined Reason, Beginning Shutdown Process"); that._shutdown(null, params.timeout); } }); EventEmitter.call(this); }
javascript
function ShutdownManager (params) { // Set State var that = this; this.isShuttingDown = false; this.actionChain = []; this.finalActionChain = []; // Set Parameters this.logger = (params && params.hasOwnProperty("logger")) ? params.logger : null; this.loggingPrefix = (params && params.hasOwnProperty("loggingPrefix")) ? params.loggingPrefix : DEFAULT_LOGGING_PREFIX; // Add Process Handlers process.on('SIGINT', function() { if (!that.emit('preShutdown', 'SIGINT')) { that._log("Received SIGINT, Beginning Shutdown Process"); } that._shutdown(128+2, params.timeout); }); process.on('SIGTERM', function() { if (!that.emit('preShutdown', 'SIGTERM')) { that._log("Received SIGTERM, Beginning Shutdown Process"); } that._shutdown(128+15, params.timeout); }); process.on('uncaughtException', function (err) { if (!that.emit('preShutdown', 'uncaughtException', err)) { that._log('Uncaught Exception Received, Beginning Shutdown Process'); that._log('Exception: '+err); } that._shutdown(255, params.timeout); }); process.on('exit', function() { // Just in case we are getting to exit without previous conditions being met // Not sure if this happens - will test. if(!that.isShuttingDown) { that.emit('preShutdown', 'exit'); that._log("Application Exiting for Undefined Reason, Beginning Shutdown Process"); that._shutdown(null, params.timeout); } }); EventEmitter.call(this); }
[ "function", "ShutdownManager", "(", "params", ")", "{", "// Set State", "var", "that", "=", "this", ";", "this", ".", "isShuttingDown", "=", "false", ";", "this", ".", "actionChain", "=", "[", "]", ";", "this", ".", "finalActionChain", "=", "[", "]", ";", "// Set Parameters", "this", ".", "logger", "=", "(", "params", "&&", "params", ".", "hasOwnProperty", "(", "\"logger\"", ")", ")", "?", "params", ".", "logger", ":", "null", ";", "this", ".", "loggingPrefix", "=", "(", "params", "&&", "params", ".", "hasOwnProperty", "(", "\"loggingPrefix\"", ")", ")", "?", "params", ".", "loggingPrefix", ":", "DEFAULT_LOGGING_PREFIX", ";", "// Add Process Handlers", "process", ".", "on", "(", "'SIGINT'", ",", "function", "(", ")", "{", "if", "(", "!", "that", ".", "emit", "(", "'preShutdown'", ",", "'SIGINT'", ")", ")", "{", "that", ".", "_log", "(", "\"Received SIGINT, Beginning Shutdown Process\"", ")", ";", "}", "that", ".", "_shutdown", "(", "128", "+", "2", ",", "params", ".", "timeout", ")", ";", "}", ")", ";", "process", ".", "on", "(", "'SIGTERM'", ",", "function", "(", ")", "{", "if", "(", "!", "that", ".", "emit", "(", "'preShutdown'", ",", "'SIGTERM'", ")", ")", "{", "that", ".", "_log", "(", "\"Received SIGTERM, Beginning Shutdown Process\"", ")", ";", "}", "that", ".", "_shutdown", "(", "128", "+", "15", ",", "params", ".", "timeout", ")", ";", "}", ")", ";", "process", ".", "on", "(", "'uncaughtException'", ",", "function", "(", "err", ")", "{", "if", "(", "!", "that", ".", "emit", "(", "'preShutdown'", ",", "'uncaughtException'", ",", "err", ")", ")", "{", "that", ".", "_log", "(", "'Uncaught Exception Received, Beginning Shutdown Process'", ")", ";", "that", ".", "_log", "(", "'Exception: '", "+", "err", ")", ";", "}", "that", ".", "_shutdown", "(", "255", ",", "params", ".", "timeout", ")", ";", "}", ")", ";", "process", ".", "on", "(", "'exit'", ",", "function", "(", ")", "{", "// Just in case we are getting to exit without previous conditions being met", "// Not sure if this happens - will test.", "if", "(", "!", "that", ".", "isShuttingDown", ")", "{", "that", ".", "emit", "(", "'preShutdown'", ",", "'exit'", ")", ";", "that", ".", "_log", "(", "\"Application Exiting for Undefined Reason, Beginning Shutdown Process\"", ")", ";", "that", ".", "_shutdown", "(", "null", ",", "params", ".", "timeout", ")", ";", "}", "}", ")", ";", "EventEmitter", ".", "call", "(", "this", ")", ";", "}" ]
The manager class which handles detecting the shutdown process as well as managing a chain of actions to be performed when the shutdown process has been detected. @param params [Object] * +logger+ - (<tt>Object</tt>) You can pass in a custom logger. If a custom logger is not passed in, the console will be used. * +loggingPrefix+ - (<tt>String</tt>) The classes uses a default prefix for all log messages. You can pass in your own prefix instead of the default. * +timeout+ - (<tt>Integer</tt>) If set, the timeout (in milliseconds) for waiting for the action promises to complete. Default is none (infinite wait)
[ "The", "manager", "class", "which", "handles", "detecting", "the", "shutdown", "process", "as", "well", "as", "managing", "a", "chain", "of", "actions", "to", "be", "performed", "when", "the", "shutdown", "process", "has", "been", "detected", "." ]
5106ba004f7351c4281d9f736de176126077e75a
https://github.com/davidtucker/node-shutdown-manager/blob/5106ba004f7351c4281d9f736de176126077e75a/lib/shutdownManager.js#L40-L85
48,708
maciejzasada/grunt-gae
tasks/gae.js
readAuth
function readAuth (path) { var auth; if (grunt.file.exists(path)) { auth = grunt.file.read(path).trim().split(/\s/); if (auth.length === 2 && auth[0].indexOf('@') !== -1) { return {email: auth[0], password: auth[1]}; } } return null; }
javascript
function readAuth (path) { var auth; if (grunt.file.exists(path)) { auth = grunt.file.read(path).trim().split(/\s/); if (auth.length === 2 && auth[0].indexOf('@') !== -1) { return {email: auth[0], password: auth[1]}; } } return null; }
[ "function", "readAuth", "(", "path", ")", "{", "var", "auth", ";", "if", "(", "grunt", ".", "file", ".", "exists", "(", "path", ")", ")", "{", "auth", "=", "grunt", ".", "file", ".", "read", "(", "path", ")", ".", "trim", "(", ")", ".", "split", "(", "/", "\\s", "/", ")", ";", "if", "(", "auth", ".", "length", "===", "2", "&&", "auth", "[", "0", "]", ".", "indexOf", "(", "'@'", ")", "!==", "-", "1", ")", "{", "return", "{", "email", ":", "auth", "[", "0", "]", ",", "password", ":", "auth", "[", "1", "]", "}", ";", "}", "}", "return", "null", ";", "}" ]
Reads authentication file. @param path @returns {null}
[ "Reads", "authentication", "file", "." ]
69371677a5c136981fb6f8618c2f9bb1cf6628f5
https://github.com/maciejzasada/grunt-gae/blob/69371677a5c136981fb6f8618c2f9bb1cf6628f5/tasks/gae.js#L37-L46
48,709
maciejzasada/grunt-gae
tasks/gae.js
run
function run(command, auth, options, async, done, msgSuccess, msgSuccessAsync, msgFailure) { var args, flags, field, i, childProcess; // Pass auth. command = command.replace('{auth}', auth ? format('--email=%s --passin ', auth.email) : ''); // Evaluate arguments to pass. args = ''; for (field in options.args) { args += format('--%s=%s ', field, options.args[field]); } // Evaluate flags to pass. flags = ''; for (i = 0; i < options.flags.length; ++i) { flags += format('--%s ', options.flags[i]); } command = command.replace('{args}', args).replace('{flags}', flags).replace('{path}', options.path); // Passin. if (auth) { command = format('echo %s | %s', auth.password, command); } // Run it asynchronously if (async) { command = COMMAND_ASYNC. replace('{command}', command). replace('{redirect}', options.asyncOutput ? '' : REDIRECT_DEVNULL); } grunt.log.debug(command); // Run the command. childProcess = exec(command, {}, function () {}); // Listen to output if (options.stdout) { childProcess.stdout.on('data', function (d) { grunt.log.write(d); }); } // Listen to errors. if (options.stderr) { childProcess.stderr.on('data', function (d) { grunt.log.error(d); }); } // Listen to exit. childProcess.on('exit', function (code) { if (options.stdout) { if (code === 0 && async) { grunt.log.subhead( msgSuccessAsync || options.asyncOutput && 'Output from asynchronous operation follows.' || 'Unable to determine success of asynchronous operation. For debugging please disable async mode or enable asyncOutput.' ); } else if (code === 0) { grunt.log.ok(msgSuccess || 'Action executed successfully.'); } } if (options.stderr && code !== 0) { grunt.log.error(msgFailure || 'Error executing the action.'); } done(); }); }
javascript
function run(command, auth, options, async, done, msgSuccess, msgSuccessAsync, msgFailure) { var args, flags, field, i, childProcess; // Pass auth. command = command.replace('{auth}', auth ? format('--email=%s --passin ', auth.email) : ''); // Evaluate arguments to pass. args = ''; for (field in options.args) { args += format('--%s=%s ', field, options.args[field]); } // Evaluate flags to pass. flags = ''; for (i = 0; i < options.flags.length; ++i) { flags += format('--%s ', options.flags[i]); } command = command.replace('{args}', args).replace('{flags}', flags).replace('{path}', options.path); // Passin. if (auth) { command = format('echo %s | %s', auth.password, command); } // Run it asynchronously if (async) { command = COMMAND_ASYNC. replace('{command}', command). replace('{redirect}', options.asyncOutput ? '' : REDIRECT_DEVNULL); } grunt.log.debug(command); // Run the command. childProcess = exec(command, {}, function () {}); // Listen to output if (options.stdout) { childProcess.stdout.on('data', function (d) { grunt.log.write(d); }); } // Listen to errors. if (options.stderr) { childProcess.stderr.on('data', function (d) { grunt.log.error(d); }); } // Listen to exit. childProcess.on('exit', function (code) { if (options.stdout) { if (code === 0 && async) { grunt.log.subhead( msgSuccessAsync || options.asyncOutput && 'Output from asynchronous operation follows.' || 'Unable to determine success of asynchronous operation. For debugging please disable async mode or enable asyncOutput.' ); } else if (code === 0) { grunt.log.ok(msgSuccess || 'Action executed successfully.'); } } if (options.stderr && code !== 0) { grunt.log.error(msgFailure || 'Error executing the action.'); } done(); }); }
[ "function", "run", "(", "command", ",", "auth", ",", "options", ",", "async", ",", "done", ",", "msgSuccess", ",", "msgSuccessAsync", ",", "msgFailure", ")", "{", "var", "args", ",", "flags", ",", "field", ",", "i", ",", "childProcess", ";", "// Pass auth.", "command", "=", "command", ".", "replace", "(", "'{auth}'", ",", "auth", "?", "format", "(", "'--email=%s --passin '", ",", "auth", ".", "email", ")", ":", "''", ")", ";", "// Evaluate arguments to pass.", "args", "=", "''", ";", "for", "(", "field", "in", "options", ".", "args", ")", "{", "args", "+=", "format", "(", "'--%s=%s '", ",", "field", ",", "options", ".", "args", "[", "field", "]", ")", ";", "}", "// Evaluate flags to pass.", "flags", "=", "''", ";", "for", "(", "i", "=", "0", ";", "i", "<", "options", ".", "flags", ".", "length", ";", "++", "i", ")", "{", "flags", "+=", "format", "(", "'--%s '", ",", "options", ".", "flags", "[", "i", "]", ")", ";", "}", "command", "=", "command", ".", "replace", "(", "'{args}'", ",", "args", ")", ".", "replace", "(", "'{flags}'", ",", "flags", ")", ".", "replace", "(", "'{path}'", ",", "options", ".", "path", ")", ";", "// Passin.", "if", "(", "auth", ")", "{", "command", "=", "format", "(", "'echo %s | %s'", ",", "auth", ".", "password", ",", "command", ")", ";", "}", "// Run it asynchronously", "if", "(", "async", ")", "{", "command", "=", "COMMAND_ASYNC", ".", "replace", "(", "'{command}'", ",", "command", ")", ".", "replace", "(", "'{redirect}'", ",", "options", ".", "asyncOutput", "?", "''", ":", "REDIRECT_DEVNULL", ")", ";", "}", "grunt", ".", "log", ".", "debug", "(", "command", ")", ";", "// Run the command.", "childProcess", "=", "exec", "(", "command", ",", "{", "}", ",", "function", "(", ")", "{", "}", ")", ";", "// Listen to output", "if", "(", "options", ".", "stdout", ")", "{", "childProcess", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "d", ")", "{", "grunt", ".", "log", ".", "write", "(", "d", ")", ";", "}", ")", ";", "}", "// Listen to errors.", "if", "(", "options", ".", "stderr", ")", "{", "childProcess", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "d", ")", "{", "grunt", ".", "log", ".", "error", "(", "d", ")", ";", "}", ")", ";", "}", "// Listen to exit.", "childProcess", ".", "on", "(", "'exit'", ",", "function", "(", "code", ")", "{", "if", "(", "options", ".", "stdout", ")", "{", "if", "(", "code", "===", "0", "&&", "async", ")", "{", "grunt", ".", "log", ".", "subhead", "(", "msgSuccessAsync", "||", "options", ".", "asyncOutput", "&&", "'Output from asynchronous operation follows.'", "||", "'Unable to determine success of asynchronous operation. For debugging please disable async mode or enable asyncOutput.'", ")", ";", "}", "else", "if", "(", "code", "===", "0", ")", "{", "grunt", ".", "log", ".", "ok", "(", "msgSuccess", "||", "'Action executed successfully.'", ")", ";", "}", "}", "if", "(", "options", ".", "stderr", "&&", "code", "!==", "0", ")", "{", "grunt", ".", "log", ".", "error", "(", "msgFailure", "||", "'Error executing the action.'", ")", ";", "}", "done", "(", ")", ";", "}", ")", ";", "}" ]
Runs GAE command. @param command @param auth @param options @param async @param done @param msgSuccess @param msgSuccessAsync @param msgFailure
[ "Runs", "GAE", "command", "." ]
69371677a5c136981fb6f8618c2f9bb1cf6628f5
https://github.com/maciejzasada/grunt-gae/blob/69371677a5c136981fb6f8618c2f9bb1cf6628f5/tasks/gae.js#L59-L136
48,710
viRingbells/easy-babel
lib/depends.js
depends
function depends (targets) { debug('Depends: start parse dependencies'); targets = prepare.targets(targets).filter(directories); debug('Depends: target : ' + targets); targets.forEach(parse_node_module); }
javascript
function depends (targets) { debug('Depends: start parse dependencies'); targets = prepare.targets(targets).filter(directories); debug('Depends: target : ' + targets); targets.forEach(parse_node_module); }
[ "function", "depends", "(", "targets", ")", "{", "debug", "(", "'Depends: start parse dependencies'", ")", ";", "targets", "=", "prepare", ".", "targets", "(", "targets", ")", ".", "filter", "(", "directories", ")", ";", "debug", "(", "'Depends: target : '", "+", "targets", ")", ";", "targets", ".", "forEach", "(", "parse_node_module", ")", ";", "}" ]
Parse all dependencies
[ "Parse", "all", "dependencies" ]
2cb332affc404304cfb01924aaefeac864c002bc
https://github.com/viRingbells/easy-babel/blob/2cb332affc404304cfb01924aaefeac864c002bc/lib/depends.js#L19-L24
48,711
alexindigo/executioner
lib/terminate.js
terminate
function terminate(control) { if (control && control._process && typeof control._process.kill == 'function') { control._process._executioner_killRequested = true; control._process.kill(); return true; } return false; }
javascript
function terminate(control) { if (control && control._process && typeof control._process.kill == 'function') { control._process._executioner_killRequested = true; control._process.kill(); return true; } return false; }
[ "function", "terminate", "(", "control", ")", "{", "if", "(", "control", "&&", "control", ".", "_process", "&&", "typeof", "control", ".", "_process", ".", "kill", "==", "'function'", ")", "{", "control", ".", "_process", ".", "_executioner_killRequested", "=", "true", ";", "control", ".", "_process", ".", "kill", "(", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Terminates currently executed job, if available @param {object} control - job control with reference to the executed process @returns {boolean} - true if there was a process to terminate, false otherwise
[ "Terminates", "currently", "executed", "job", "if", "available" ]
582f92897f47c13f4531e0b692aebb4a9f134eec
https://github.com/alexindigo/executioner/blob/582f92897f47c13f4531e0b692aebb4a9f134eec/lib/terminate.js#L11-L21
48,712
TMiguelT/node-mtg-json
index.js
getMtgJson
function getMtgJson(type, directory, opts) { //Setup input and output URIs const outFileName = getJsonFilename(type, opts); const url = `${BASE_URL}/${outFileName}`; const output = path.resolve(`${directory}/${outFileName}`); const outputStream = fs.createWriteStream(output); //Return a file path if they requested it, or it's a zip file const returnFile = !!(opts && (opts.returnFile || opts.zip)); //Return the json if it already exists try { //If it's a ZIP, it can't be json, throw an error to ensure we don't try require if (opts && opts.zip) throw new Error(); const json = require(output); return returnFile ? Promise.resolve(output) : Promise.resolve(json); } catch (ex) { //Pipe the downloaded file into the output file request(url) .pipe(outputStream); //Return a promise that's resolved when the file has downloaded return eventToPromise(outputStream, 'close') .then(()=> { //Return the new json file, parsed try { return returnFile ? Promise.resolve(output) : require(output); } catch (ex) { throw new Error(`Invalid json: ${ex.message}`); } }); } }
javascript
function getMtgJson(type, directory, opts) { //Setup input and output URIs const outFileName = getJsonFilename(type, opts); const url = `${BASE_URL}/${outFileName}`; const output = path.resolve(`${directory}/${outFileName}`); const outputStream = fs.createWriteStream(output); //Return a file path if they requested it, or it's a zip file const returnFile = !!(opts && (opts.returnFile || opts.zip)); //Return the json if it already exists try { //If it's a ZIP, it can't be json, throw an error to ensure we don't try require if (opts && opts.zip) throw new Error(); const json = require(output); return returnFile ? Promise.resolve(output) : Promise.resolve(json); } catch (ex) { //Pipe the downloaded file into the output file request(url) .pipe(outputStream); //Return a promise that's resolved when the file has downloaded return eventToPromise(outputStream, 'close') .then(()=> { //Return the new json file, parsed try { return returnFile ? Promise.resolve(output) : require(output); } catch (ex) { throw new Error(`Invalid json: ${ex.message}`); } }); } }
[ "function", "getMtgJson", "(", "type", ",", "directory", ",", "opts", ")", "{", "//Setup input and output URIs", "const", "outFileName", "=", "getJsonFilename", "(", "type", ",", "opts", ")", ";", "const", "url", "=", "`", "${", "BASE_URL", "}", "${", "outFileName", "}", "`", ";", "const", "output", "=", "path", ".", "resolve", "(", "`", "${", "directory", "}", "${", "outFileName", "}", "`", ")", ";", "const", "outputStream", "=", "fs", ".", "createWriteStream", "(", "output", ")", ";", "//Return a file path if they requested it, or it's a zip file", "const", "returnFile", "=", "!", "!", "(", "opts", "&&", "(", "opts", ".", "returnFile", "||", "opts", ".", "zip", ")", ")", ";", "//Return the json if it already exists", "try", "{", "//If it's a ZIP, it can't be json, throw an error to ensure we don't try require", "if", "(", "opts", "&&", "opts", ".", "zip", ")", "throw", "new", "Error", "(", ")", ";", "const", "json", "=", "require", "(", "output", ")", ";", "return", "returnFile", "?", "Promise", ".", "resolve", "(", "output", ")", ":", "Promise", ".", "resolve", "(", "json", ")", ";", "}", "catch", "(", "ex", ")", "{", "//Pipe the downloaded file into the output file", "request", "(", "url", ")", ".", "pipe", "(", "outputStream", ")", ";", "//Return a promise that's resolved when the file has downloaded", "return", "eventToPromise", "(", "outputStream", ",", "'close'", ")", ".", "then", "(", "(", ")", "=>", "{", "//Return the new json file, parsed", "try", "{", "return", "returnFile", "?", "Promise", ".", "resolve", "(", "output", ")", ":", "require", "(", "output", ")", ";", "}", "catch", "(", "ex", ")", "{", "throw", "new", "Error", "(", "`", "${", "ex", ".", "message", "}", "`", ")", ";", "}", "}", ")", ";", "}", "}" ]
Returns a promise of an MtG Json file @param type Either 'sets' or 'cards' - the type of file to download. @param directory The location to put the new json file (the filename is decided by the request) @param opts An object with the keys {extras : bool, zip : bool, returnFile: bool}
[ "Returns", "a", "promise", "of", "an", "MtG", "Json", "file" ]
f1e292c42b4d685a8acd05b2d80a6da59321b484
https://github.com/TMiguelT/node-mtg-json/blob/f1e292c42b4d685a8acd05b2d80a6da59321b484/index.js#L23-L59
48,713
AirDwing/airx-proto
dist/message.js
Data
function Data(properties) { this.custom = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Data(properties) { this.custom = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Data", "(", "properties", ")", "{", "this", ".", "custom", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Data. @exports IData @interface IData @property {IGateway} [gateway] Data gateway @property {IAttitude} [attitude] Data attitude @property {IBattery} [battery] Data battery @property {IBattery} [battery_controller] Data battery_controller @property {IDronestatus} [dronestatus] Data dronestatus @property {IGNSS} [gnss] Data gnss @property {ISignal} [signal] Data signal @property {ISignal} [signal_image] Data signal_image @property {IVelocity} [velocity] Data velocity @property {IAtmosphere} [atmosphere] Data atmosphere @property {Array.<ICustom>} [custom] Data custom Constructs a new Data. @exports Data @classdesc Represents a Data. @constructor @param {IData=} [properties] Properties to set
[ "Properties", "of", "a", "Data", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L279-L285
48,714
AirDwing/airx-proto
dist/message.js
Custom
function Custom(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Custom(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Custom", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Custom. @exports ICustom @interface ICustom @property {string} [key] Custom key @property {google.protobuf.IAny} [val] Custom val Constructs a new Custom. @exports Custom @classdesc Represents a Custom. @constructor @param {ICustom=} [properties] Properties to set
[ "Properties", "of", "a", "Custom", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L749-L754
48,715
AirDwing/airx-proto
dist/message.js
Gateway
function Gateway(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Gateway(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Gateway", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Gateway. @exports IGateway @interface IGateway @property {string} [name] Gateway name Constructs a new Gateway. @exports Gateway @classdesc Represents a Gateway. @constructor @param {IGateway=} [properties] Properties to set
[ "Properties", "of", "a", "Gateway", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L1421-L1426
48,716
AirDwing/airx-proto
dist/message.js
Attitude
function Attitude(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Attitude(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Attitude", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of an Attitude. @exports IAttitude @interface IAttitude @property {number} [pitch] 俯仰 desc: 俯仰角,绕x轴,对应欧拉角γ。抬头为正 unit: ° range: [-180, 180] @property {number} [roll] 横滚 desc: 翻滚角,绕z轴,对应欧拉角β。右滚为正 unit: ° range: [-180, 180] @property {number} [yaw] 偏航 desc: 方向/航向角,绕y轴,对应欧拉角α。0为指向真北,顺时针旋转增加数值 unit: ° range: [-180, 180] Constructs a new Attitude. @exports Attitude @classdesc Represents an Attitude. @constructor @param {IAttitude=} [properties] Properties to set
[ "Properties", "of", "an", "Attitude", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L1618-L1623
48,717
AirDwing/airx-proto
dist/message.js
Battery
function Battery(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Battery(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Battery", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Battery. @exports IBattery @interface IBattery @property {number} [percent] 电量 desc: 电量百分比 unit: % range: [0, 100] @property {boolean} [charging] 正在充电 desc: 是否正在充电 @property {number} [voltage] 电压 desc: 电池组总电压 unit: mV range: [0, +∞) @property {number} [current] 电流 desc: 正为放电,负为充电 unit: mA @property {number} [temperature] 温度 desc: 温度 range: (-∞, +∞) Constructs a new Battery. @exports Battery @classdesc Represents a Battery. @constructor @param {IBattery=} [properties] Properties to set
[ "Properties", "of", "a", "Battery", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L1871-L1876
48,718
AirDwing/airx-proto
dist/message.js
Dronestatus
function Dronestatus(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Dronestatus(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Dronestatus", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Dronestatus. @exports IDronestatus @interface IDronestatus @property {boolean} [motors] 电机状态 desc: 电机是否启动 @property {boolean} [flying] 飞行状态 desc: 是否正在飞行 Constructs a new Dronestatus. @exports Dronestatus @classdesc Represents a Dronestatus. @constructor @param {IDronestatus=} [properties] Properties to set
[ "Properties", "of", "a", "Dronestatus", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L2156-L2161
48,719
AirDwing/airx-proto
dist/message.js
GNSS
function GNSS(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function GNSS(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "GNSS", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a GNSS. @exports IGNSS @interface IGNSS @property {number} [satellite] 卫星数 desc: 3颗:2D定位,4颗:3D定位 range: [0, 65535] @property {number} [latitude] 纬度 desc: 纬度,十进制,北纬为正,南纬为负 unit: ° range: [-90, 90] @property {number} [longitude] 经度 desc: 经度,十进制,东经为正,西经为负 unit: ° range: [-90, 90] @property {number} [amsl] 海拔高度 desc: 海拔高度(AMSL) unit: m @property {number} [ato] 相对地面高度 desc: 相对起飞点高度(ATO),只有飞行器或潜艇需要此参数 unit: m @property {google.protobuf.ITimestamp} [timestamp] GPS 时间 desc: GPS 时间,可选参数 @property {number} [hdop] 水平定位精度 desc: 米 精确到小数点后2位,可选参数 Constructs a new GNSS. @exports GNSS @classdesc Represents a GNSS. @constructor @param {IGNSS=} [properties] Properties to set
[ "Properties", "of", "a", "GNSS", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L2386-L2391
48,720
AirDwing/airx-proto
dist/message.js
Signal
function Signal(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Signal(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Signal", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Signal. @exports ISignal @interface ISignal @property {number} [percent] 信号强度 desc: 信号强度百分比 unit: % range: [0, 100] @property {Signal.Type} [type] 类型 desc: 连接方式类型 range: [ UNDEFINED, OTHER, TELE2G, TELE3G, TELE4G, TELE5G, BAND24GHZ, BAND58GHZ] @property {string} [protocal] 协议 desc: 链路协议,大多数情况下仅当选择具体频率或Other时有效 examples: ["Lightbridge 2","NB-IoT","ZigBee"] @property {number} [rssi] RSSI desc: 接收信号强度指示 unit: dBm range: (-∞, 0] Constructs a new Signal. @exports Signal @classdesc Represents a Signal. @constructor @param {ISignal=} [properties] Properties to set
[ "Properties", "of", "a", "Signal", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L2731-L2736
48,721
AirDwing/airx-proto
dist/message.js
Velocity
function Velocity(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Velocity(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Velocity", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Velocity. @exports IVelocity @interface IVelocity @property {number} [x] x速度 desc: 载具在x方向上的速度,使用N-E-D (North-East-Down),以米为单位 unit: m @property {number} [y] y速度 desc: 载具在y方向上的速度,使用N-E-D (North-East-Down),以米为单位 unit: m @property {number} [z] z速度 desc: 载具在z方向上的速度,使用N-E-D (North-East-Down),以米为单位 unit: m @property {number} [gspeed] 地速 desc: 载具的地速,米/秒 精确到小数点后1位 unit: m Constructs a new Velocity. @exports Velocity @classdesc Represents a Velocity. @constructor @param {IVelocity=} [properties] Properties to set
[ "Properties", "of", "a", "Velocity", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L3078-L3083
48,722
AirDwing/airx-proto
dist/message.js
Atmosphere
function Atmosphere(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Atmosphere(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Atmosphere", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of an Atmosphere. @exports IAtmosphere @interface IAtmosphere @property {number} [pm25] PM2.5 desc: PM2.5浓度 range: [0, +∞) @property {number} [co] 一氧化碳 desc: 一氧化碳浓度 range: [0, +∞) @property {number} [so2] 二氧化硫 desc: 二氧化硫浓度 range: [0, +∞) @property {number} [no2] 二氧化氮 desc: 二氧化氮浓度 range: [0, +∞) @property {number} [o3] 臭氧 desc: 臭氧浓度 range: [0, +∞) @property {number} [temperature] 温度 desc: 温度 range: (-∞, +∞) @property {number} [humidity] 湿度 desc: 湿度 range: [0, 100] @property {number} [pm10] PM10 desc: PM1.0浓度 range: [0, +∞) Constructs a new Atmosphere. @exports Atmosphere @classdesc Represents an Atmosphere. @constructor @param {IAtmosphere=} [properties] Properties to set
[ "Properties", "of", "an", "Atmosphere", "." ]
028223a4c34e7ff078032da28532371052d0fa3b
https://github.com/AirDwing/airx-proto/blob/028223a4c34e7ff078032da28532371052d0fa3b/dist/message.js#L3359-L3364
48,723
kuno/neco
deps/npm/lib/utils/relativize.js
relativize
function relativize (dest, src) { // both of these are absolute paths. // find the shortest relative distance. src = src.split("/") var abs = dest dest = dest.split("/") var i = 0 while (src[i] === dest[i]) i++ if (i === 1) return abs // nothing in common, leave absolute src.splice(0, i + 1) var dots = [0, i, "."] for (var i = 0, l = src.length; i < l; i ++) dots.push("..") dest.splice.apply(dest, dots) dest = dest.join("/") return abs.length < dest.length ? abs : dest }
javascript
function relativize (dest, src) { // both of these are absolute paths. // find the shortest relative distance. src = src.split("/") var abs = dest dest = dest.split("/") var i = 0 while (src[i] === dest[i]) i++ if (i === 1) return abs // nothing in common, leave absolute src.splice(0, i + 1) var dots = [0, i, "."] for (var i = 0, l = src.length; i < l; i ++) dots.push("..") dest.splice.apply(dest, dots) dest = dest.join("/") return abs.length < dest.length ? abs : dest }
[ "function", "relativize", "(", "dest", ",", "src", ")", "{", "// both of these are absolute paths.", "// find the shortest relative distance.", "src", "=", "src", ".", "split", "(", "\"/\"", ")", "var", "abs", "=", "dest", "dest", "=", "dest", ".", "split", "(", "\"/\"", ")", "var", "i", "=", "0", "while", "(", "src", "[", "i", "]", "===", "dest", "[", "i", "]", ")", "i", "++", "if", "(", "i", "===", "1", ")", "return", "abs", "// nothing in common, leave absolute", "src", ".", "splice", "(", "0", ",", "i", "+", "1", ")", "var", "dots", "=", "[", "0", ",", "i", ",", "\".\"", "]", "for", "(", "var", "i", "=", "0", ",", "l", "=", "src", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "dots", ".", "push", "(", "\"..\"", ")", "dest", ".", "splice", ".", "apply", "(", "dest", ",", "dots", ")", "dest", "=", "dest", ".", "join", "(", "\"/\"", ")", "return", "abs", ".", "length", "<", "dest", ".", "length", "?", "abs", ":", "dest", "}" ]
return the shortest path between two folders.
[ "return", "the", "shortest", "path", "between", "two", "folders", "." ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/utils/relativize.js#L5-L20
48,724
observing/fossa
index.js
configure
function configure(obj, fossa) { function get(key, backup) { return key in obj ? obj[key] : backup; } // // Allow new options to be be merged in against the original object. // get.merge = function merge(properties) { return fossa.merge(obj, properties); }; return get; }
javascript
function configure(obj, fossa) { function get(key, backup) { return key in obj ? obj[key] : backup; } // // Allow new options to be be merged in against the original object. // get.merge = function merge(properties) { return fossa.merge(obj, properties); }; return get; }
[ "function", "configure", "(", "obj", ",", "fossa", ")", "{", "function", "get", "(", "key", ",", "backup", ")", "{", "return", "key", "in", "obj", "?", "obj", "[", "key", "]", ":", "backup", ";", "}", "//", "// Allow new options to be be merged in against the original object.", "//", "get", ".", "merge", "=", "function", "merge", "(", "properties", ")", "{", "return", "fossa", ".", "merge", "(", "obj", ",", "properties", ")", ";", "}", ";", "return", "get", ";", "}" ]
Queryable options with merge and fallback functionality. @param {Object} obj @param {Fossa} fossa instance @returns {Function} @api private
[ "Queryable", "options", "with", "merge", "and", "fallback", "functionality", "." ]
29b3717ee10a13fb607f5bbddcb8b003faf008c6
https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/index.js#L25-L38
48,725
observing/fossa
index.js
Fossa
function Fossa(options) { this.fuse(); // // Store the options. // this.writable('queue', []); this.writable('plugins', {}); this.writable('connecting', false); this.readable('options', configure(options || {}, this)); // // Prepare a default model and collection sprinkled with MongoDB proxy methods. // this.readable('Model', model(this)); this.readable('Collection', collection(this)); // // Provide reference to the orginal mongo module so it can be used easily. // this.readable('mongo', mongo); // // Prepare connection. // this.init( this.options('hostname', 'localhost'), this.options('port', 27017), this.options ); }
javascript
function Fossa(options) { this.fuse(); // // Store the options. // this.writable('queue', []); this.writable('plugins', {}); this.writable('connecting', false); this.readable('options', configure(options || {}, this)); // // Prepare a default model and collection sprinkled with MongoDB proxy methods. // this.readable('Model', model(this)); this.readable('Collection', collection(this)); // // Provide reference to the orginal mongo module so it can be used easily. // this.readable('mongo', mongo); // // Prepare connection. // this.init( this.options('hostname', 'localhost'), this.options('port', 27017), this.options ); }
[ "function", "Fossa", "(", "options", ")", "{", "this", ".", "fuse", "(", ")", ";", "//", "// Store the options.", "//", "this", ".", "writable", "(", "'queue'", ",", "[", "]", ")", ";", "this", ".", "writable", "(", "'plugins'", ",", "{", "}", ")", ";", "this", ".", "writable", "(", "'connecting'", ",", "false", ")", ";", "this", ".", "readable", "(", "'options'", ",", "configure", "(", "options", "||", "{", "}", ",", "this", ")", ")", ";", "//", "// Prepare a default model and collection sprinkled with MongoDB proxy methods.", "//", "this", ".", "readable", "(", "'Model'", ",", "model", "(", "this", ")", ")", ";", "this", ".", "readable", "(", "'Collection'", ",", "collection", "(", "this", ")", ")", ";", "//", "// Provide reference to the orginal mongo module so it can be used easily.", "//", "this", ".", "readable", "(", "'mongo'", ",", "mongo", ")", ";", "//", "// Prepare connection.", "//", "this", ".", "init", "(", "this", ".", "options", "(", "'hostname'", ",", "'localhost'", ")", ",", "this", ".", "options", "(", "'port'", ",", "27017", ")", ",", "this", ".", "options", ")", ";", "}" ]
Constructor of Fossa. @Constructor @param {Object} options @api public
[ "Constructor", "of", "Fossa", "." ]
29b3717ee10a13fb607f5bbddcb8b003faf008c6
https://github.com/observing/fossa/blob/29b3717ee10a13fb607f5bbddcb8b003faf008c6/index.js#L47-L77
48,726
alikhil/zaes-js
src/aes.js
expandKey
function expandKey(key) { let tempWord = new Array(WORD_LENGTH); let rounds = getRoundsCount(key); let wordsCount = key.length / WORD_LENGTH; let keySchedule = new Array(COLUMNS * (rounds + 1)); for (let i = 0; i < wordsCount; i++) { keySchedule[i] = key.slice(WORD_LENGTH * i, WORD_LENGTH * i + WORD_LENGTH); } for (let i = wordsCount; i < keySchedule.length; i++) { tempWord = keySchedule[i - 1]; if (i % wordsCount === 0) { tempWord = a_u.xorWords(a_u.subWord(a_u.rotWordLeft(tempWord)), a_u.R_CON[i / wordsCount]); } else if (wordsCount > 6 && i % wordsCount === 4) { tempWord = a_u.subWord(tempWord); } keySchedule[i] = a_u.xorWords(keySchedule[i - wordsCount], tempWord); } return keySchedule; }
javascript
function expandKey(key) { let tempWord = new Array(WORD_LENGTH); let rounds = getRoundsCount(key); let wordsCount = key.length / WORD_LENGTH; let keySchedule = new Array(COLUMNS * (rounds + 1)); for (let i = 0; i < wordsCount; i++) { keySchedule[i] = key.slice(WORD_LENGTH * i, WORD_LENGTH * i + WORD_LENGTH); } for (let i = wordsCount; i < keySchedule.length; i++) { tempWord = keySchedule[i - 1]; if (i % wordsCount === 0) { tempWord = a_u.xorWords(a_u.subWord(a_u.rotWordLeft(tempWord)), a_u.R_CON[i / wordsCount]); } else if (wordsCount > 6 && i % wordsCount === 4) { tempWord = a_u.subWord(tempWord); } keySchedule[i] = a_u.xorWords(keySchedule[i - wordsCount], tempWord); } return keySchedule; }
[ "function", "expandKey", "(", "key", ")", "{", "let", "tempWord", "=", "new", "Array", "(", "WORD_LENGTH", ")", ";", "let", "rounds", "=", "getRoundsCount", "(", "key", ")", ";", "let", "wordsCount", "=", "key", ".", "length", "/", "WORD_LENGTH", ";", "let", "keySchedule", "=", "new", "Array", "(", "COLUMNS", "*", "(", "rounds", "+", "1", ")", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "wordsCount", ";", "i", "++", ")", "{", "keySchedule", "[", "i", "]", "=", "key", ".", "slice", "(", "WORD_LENGTH", "*", "i", ",", "WORD_LENGTH", "*", "i", "+", "WORD_LENGTH", ")", ";", "}", "for", "(", "let", "i", "=", "wordsCount", ";", "i", "<", "keySchedule", ".", "length", ";", "i", "++", ")", "{", "tempWord", "=", "keySchedule", "[", "i", "-", "1", "]", ";", "if", "(", "i", "%", "wordsCount", "===", "0", ")", "{", "tempWord", "=", "a_u", ".", "xorWords", "(", "a_u", ".", "subWord", "(", "a_u", ".", "rotWordLeft", "(", "tempWord", ")", ")", ",", "a_u", ".", "R_CON", "[", "i", "/", "wordsCount", "]", ")", ";", "}", "else", "if", "(", "wordsCount", ">", "6", "&&", "i", "%", "wordsCount", "===", "4", ")", "{", "tempWord", "=", "a_u", ".", "subWord", "(", "tempWord", ")", ";", "}", "keySchedule", "[", "i", "]", "=", "a_u", ".", "xorWords", "(", "keySchedule", "[", "i", "-", "wordsCount", "]", ",", "tempWord", ")", ";", "}", "return", "keySchedule", ";", "}" ]
Generates keys for each round
[ "Generates", "keys", "for", "each", "round" ]
5887597a14d81b0ced3439f4ad1fd9457dc8a1c9
https://github.com/alikhil/zaes-js/blob/5887597a14d81b0ced3439f4ad1fd9457dc8a1c9/src/aes.js#L70-L89
48,727
alikhil/zaes-js
src/aes.js
encryptBlock
function encryptBlock(block, keySchedule) { let state = splitToMatrix(block); state = a_u.addRoundKey(state, keySchedule.slice(0, 4)); let rounds = keySchedule.length / COLUMNS; for (let round = 1; round < rounds; round++){ state = a_u.subBytes(state); state = a_u.shiftRows(state); state = a_u.mixColumns(state); state = a_u.addRoundKey(state, keySchedule.slice(round * COLUMNS, (round + 1) * COLUMNS)); } state = a_u.subBytes(state); state = a_u.shiftRows(state); state = a_u.addRoundKey(state, keySchedule.slice(COLUMNS * (rounds-1), COLUMNS * rounds)); return getBlockFromState(state); }
javascript
function encryptBlock(block, keySchedule) { let state = splitToMatrix(block); state = a_u.addRoundKey(state, keySchedule.slice(0, 4)); let rounds = keySchedule.length / COLUMNS; for (let round = 1; round < rounds; round++){ state = a_u.subBytes(state); state = a_u.shiftRows(state); state = a_u.mixColumns(state); state = a_u.addRoundKey(state, keySchedule.slice(round * COLUMNS, (round + 1) * COLUMNS)); } state = a_u.subBytes(state); state = a_u.shiftRows(state); state = a_u.addRoundKey(state, keySchedule.slice(COLUMNS * (rounds-1), COLUMNS * rounds)); return getBlockFromState(state); }
[ "function", "encryptBlock", "(", "block", ",", "keySchedule", ")", "{", "let", "state", "=", "splitToMatrix", "(", "block", ")", ";", "state", "=", "a_u", ".", "addRoundKey", "(", "state", ",", "keySchedule", ".", "slice", "(", "0", ",", "4", ")", ")", ";", "let", "rounds", "=", "keySchedule", ".", "length", "/", "COLUMNS", ";", "for", "(", "let", "round", "=", "1", ";", "round", "<", "rounds", ";", "round", "++", ")", "{", "state", "=", "a_u", ".", "subBytes", "(", "state", ")", ";", "state", "=", "a_u", ".", "shiftRows", "(", "state", ")", ";", "state", "=", "a_u", ".", "mixColumns", "(", "state", ")", ";", "state", "=", "a_u", ".", "addRoundKey", "(", "state", ",", "keySchedule", ".", "slice", "(", "round", "*", "COLUMNS", ",", "(", "round", "+", "1", ")", "*", "COLUMNS", ")", ")", ";", "}", "state", "=", "a_u", ".", "subBytes", "(", "state", ")", ";", "state", "=", "a_u", ".", "shiftRows", "(", "state", ")", ";", "state", "=", "a_u", ".", "addRoundKey", "(", "state", ",", "keySchedule", ".", "slice", "(", "COLUMNS", "*", "(", "rounds", "-", "1", ")", ",", "COLUMNS", "*", "rounds", ")", ")", ";", "return", "getBlockFromState", "(", "state", ")", ";", "}" ]
Encrypts given block
[ "Encrypts", "given", "block" ]
5887597a14d81b0ced3439f4ad1fd9457dc8a1c9
https://github.com/alikhil/zaes-js/blob/5887597a14d81b0ced3439f4ad1fd9457dc8a1c9/src/aes.js#L108-L124
48,728
terryweiss/grunt-bundles
tasks/bundles.js
function ( taskName ) { var task = grunt.config.get( "bundles" )[taskName]; var retVal = []; if ( task ) { var sources = task.modules; if ( !sys.isEmpty( sources ) && !sys.isEmpty( sources.src ) ) { grunt.log.writeln( "Adding sources for " + taskName ); retVal = sys.map( grunt.file.expand( sources, sources.src ), function ( item ) { return resolvePath( item ); } ); } } return retVal; }
javascript
function ( taskName ) { var task = grunt.config.get( "bundles" )[taskName]; var retVal = []; if ( task ) { var sources = task.modules; if ( !sys.isEmpty( sources ) && !sys.isEmpty( sources.src ) ) { grunt.log.writeln( "Adding sources for " + taskName ); retVal = sys.map( grunt.file.expand( sources, sources.src ), function ( item ) { return resolvePath( item ); } ); } } return retVal; }
[ "function", "(", "taskName", ")", "{", "var", "task", "=", "grunt", ".", "config", ".", "get", "(", "\"bundles\"", ")", "[", "taskName", "]", ";", "var", "retVal", "=", "[", "]", ";", "if", "(", "task", ")", "{", "var", "sources", "=", "task", ".", "modules", ";", "if", "(", "!", "sys", ".", "isEmpty", "(", "sources", ")", "&&", "!", "sys", ".", "isEmpty", "(", "sources", ".", "src", ")", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "\"Adding sources for \"", "+", "taskName", ")", ";", "retVal", "=", "sys", ".", "map", "(", "grunt", ".", "file", ".", "expand", "(", "sources", ",", "sources", ".", "src", ")", ",", "function", "(", "item", ")", "{", "return", "resolvePath", "(", "item", ")", ";", "}", ")", ";", "}", "}", "return", "retVal", ";", "}" ]
find another task's entries
[ "find", "another", "task", "s", "entries" ]
33133118e99ff9f42ad17023561f5c268a7307cd
https://github.com/terryweiss/grunt-bundles/blob/33133118e99ff9f42ad17023561f5c268a7307cd/tasks/bundles.js#L46-L59
48,729
terryweiss/grunt-bundles
tasks/bundles.js
function ( file ) { var resolved; var expanded = grunt.file.expand( file )[0]; if ( !expanded ) { resolved = require.resolve( file ); } else { resolved = "./" + expanded; } return resolved; }
javascript
function ( file ) { var resolved; var expanded = grunt.file.expand( file )[0]; if ( !expanded ) { resolved = require.resolve( file ); } else { resolved = "./" + expanded; } return resolved; }
[ "function", "(", "file", ")", "{", "var", "resolved", ";", "var", "expanded", "=", "grunt", ".", "file", ".", "expand", "(", "file", ")", "[", "0", "]", ";", "if", "(", "!", "expanded", ")", "{", "resolved", "=", "require", ".", "resolve", "(", "file", ")", ";", "}", "else", "{", "resolved", "=", "\"./\"", "+", "expanded", ";", "}", "return", "resolved", ";", "}" ]
Resolve modules paths
[ "Resolve", "modules", "paths" ]
33133118e99ff9f42ad17023561f5c268a7307cd
https://github.com/terryweiss/grunt-bundles/blob/33133118e99ff9f42ad17023561f5c268a7307cd/tasks/bundles.js#L62-L74
48,730
terryweiss/grunt-bundles
tasks/bundles.js
function ( pkg ) { grunt.verbose.writeln( "Populating compiler" ); var copts = { noParse : pkg.noParse, entries : pkg.modules, externalRequireName : options.externalRequireName, pack : options.pack, bundleExternal : options.bundleExternal, // builtins : options.builtins, fullPaths : options.fullPaths, commondir : options.commondir, basedir : options.basedir, extensions : options.extensions } if ( !sys.isEmpty( options.builtins ) ) { copts.builtins = options.builtins; } var compiler = browsCompiler( copts ); sys.each( pkg.exec, function ( item ) { compiler.add( item ); } ); sys.each( pkg.aliases, function ( item, name ) { compiler.require( item, {expose : name} ); } ); sys.each( pkg.publish, function ( item ) { compiler.require( item ); } ); sys.each( pkg.externals, function ( item ) { compiler.external( item ); } ); sys.each( pkg.ignore, function ( item ) { compiler.ignore( item ); } ); return compiler; }
javascript
function ( pkg ) { grunt.verbose.writeln( "Populating compiler" ); var copts = { noParse : pkg.noParse, entries : pkg.modules, externalRequireName : options.externalRequireName, pack : options.pack, bundleExternal : options.bundleExternal, // builtins : options.builtins, fullPaths : options.fullPaths, commondir : options.commondir, basedir : options.basedir, extensions : options.extensions } if ( !sys.isEmpty( options.builtins ) ) { copts.builtins = options.builtins; } var compiler = browsCompiler( copts ); sys.each( pkg.exec, function ( item ) { compiler.add( item ); } ); sys.each( pkg.aliases, function ( item, name ) { compiler.require( item, {expose : name} ); } ); sys.each( pkg.publish, function ( item ) { compiler.require( item ); } ); sys.each( pkg.externals, function ( item ) { compiler.external( item ); } ); sys.each( pkg.ignore, function ( item ) { compiler.ignore( item ); } ); return compiler; }
[ "function", "(", "pkg", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "\"Populating compiler\"", ")", ";", "var", "copts", "=", "{", "noParse", ":", "pkg", ".", "noParse", ",", "entries", ":", "pkg", ".", "modules", ",", "externalRequireName", ":", "options", ".", "externalRequireName", ",", "pack", ":", "options", ".", "pack", ",", "bundleExternal", ":", "options", ".", "bundleExternal", ",", "//\t\t\t\tbuiltins : options.builtins,", "fullPaths", ":", "options", ".", "fullPaths", ",", "commondir", ":", "options", ".", "commondir", ",", "basedir", ":", "options", ".", "basedir", ",", "extensions", ":", "options", ".", "extensions", "}", "if", "(", "!", "sys", ".", "isEmpty", "(", "options", ".", "builtins", ")", ")", "{", "copts", ".", "builtins", "=", "options", ".", "builtins", ";", "}", "var", "compiler", "=", "browsCompiler", "(", "copts", ")", ";", "sys", ".", "each", "(", "pkg", ".", "exec", ",", "function", "(", "item", ")", "{", "compiler", ".", "add", "(", "item", ")", ";", "}", ")", ";", "sys", ".", "each", "(", "pkg", ".", "aliases", ",", "function", "(", "item", ",", "name", ")", "{", "compiler", ".", "require", "(", "item", ",", "{", "expose", ":", "name", "}", ")", ";", "}", ")", ";", "sys", ".", "each", "(", "pkg", ".", "publish", ",", "function", "(", "item", ")", "{", "compiler", ".", "require", "(", "item", ")", ";", "}", ")", ";", "sys", ".", "each", "(", "pkg", ".", "externals", ",", "function", "(", "item", ")", "{", "compiler", ".", "external", "(", "item", ")", ";", "}", ")", ";", "sys", ".", "each", "(", "pkg", ".", "ignore", ",", "function", "(", "item", ")", "{", "compiler", ".", "ignore", "(", "item", ")", ";", "}", ")", ";", "return", "compiler", ";", "}" ]
Create the browserify instance and prep it
[ "Create", "the", "browserify", "instance", "and", "prep", "it" ]
33133118e99ff9f42ad17023561f5c268a7307cd
https://github.com/terryweiss/grunt-bundles/blob/33133118e99ff9f42ad17023561f5c268a7307cd/tasks/bundles.js#L217-L259
48,731
terryweiss/grunt-bundles
tasks/bundles.js
function ( pkg, compiler ) { if ( !sys.isEmpty( task.data.depends ) && options.resolveAliases && !sys.isEmpty( pkg.dependAliases ) ) { compiler.transform( function ( file ) { grunt.verbose.writeln( "Transforming " + file ); function write( buf ) { data += buf; } var data = ''; return through( write, function () { var __aliases = []; sys.each( pkg.dependAliases, function ( al ) { if ( data.indexOf( "'" + al + "'" ) !== -1 || data.indexOf( '"' + al + '"' ) !== -1 ) { __aliases.push( "'" + al + "' : '" + al + "'" ); data = data.replace( new RegExp( "'" + al + "'", "g" ), "__aliases['" + al + "']" ); data = data.replace( new RegExp( '"' + al + '"', "g" ), "__aliases['" + al + "']" ); } } ); if ( !sys.isEmpty( __aliases ) ) { var aliasDefinition = "var __aliases = {" + __aliases.join( ",\n" ) + "};\n"; data = aliasDefinition + data; } this.queue( data ); this.queue( null ); } ); } ); } }
javascript
function ( pkg, compiler ) { if ( !sys.isEmpty( task.data.depends ) && options.resolveAliases && !sys.isEmpty( pkg.dependAliases ) ) { compiler.transform( function ( file ) { grunt.verbose.writeln( "Transforming " + file ); function write( buf ) { data += buf; } var data = ''; return through( write, function () { var __aliases = []; sys.each( pkg.dependAliases, function ( al ) { if ( data.indexOf( "'" + al + "'" ) !== -1 || data.indexOf( '"' + al + '"' ) !== -1 ) { __aliases.push( "'" + al + "' : '" + al + "'" ); data = data.replace( new RegExp( "'" + al + "'", "g" ), "__aliases['" + al + "']" ); data = data.replace( new RegExp( '"' + al + '"', "g" ), "__aliases['" + al + "']" ); } } ); if ( !sys.isEmpty( __aliases ) ) { var aliasDefinition = "var __aliases = {" + __aliases.join( ",\n" ) + "};\n"; data = aliasDefinition + data; } this.queue( data ); this.queue( null ); } ); } ); } }
[ "function", "(", "pkg", ",", "compiler", ")", "{", "if", "(", "!", "sys", ".", "isEmpty", "(", "task", ".", "data", ".", "depends", ")", "&&", "options", ".", "resolveAliases", "&&", "!", "sys", ".", "isEmpty", "(", "pkg", ".", "dependAliases", ")", ")", "{", "compiler", ".", "transform", "(", "function", "(", "file", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "\"Transforming \"", "+", "file", ")", ";", "function", "write", "(", "buf", ")", "{", "data", "+=", "buf", ";", "}", "var", "data", "=", "''", ";", "return", "through", "(", "write", ",", "function", "(", ")", "{", "var", "__aliases", "=", "[", "]", ";", "sys", ".", "each", "(", "pkg", ".", "dependAliases", ",", "function", "(", "al", ")", "{", "if", "(", "data", ".", "indexOf", "(", "\"'\"", "+", "al", "+", "\"'\"", ")", "!==", "-", "1", "||", "data", ".", "indexOf", "(", "'\"'", "+", "al", "+", "'\"'", ")", "!==", "-", "1", ")", "{", "__aliases", ".", "push", "(", "\"'\"", "+", "al", "+", "\"' : '\"", "+", "al", "+", "\"'\"", ")", ";", "data", "=", "data", ".", "replace", "(", "new", "RegExp", "(", "\"'\"", "+", "al", "+", "\"'\"", ",", "\"g\"", ")", ",", "\"__aliases['\"", "+", "al", "+", "\"']\"", ")", ";", "data", "=", "data", ".", "replace", "(", "new", "RegExp", "(", "'\"'", "+", "al", "+", "'\"'", ",", "\"g\"", ")", ",", "\"__aliases['\"", "+", "al", "+", "\"']\"", ")", ";", "}", "}", ")", ";", "if", "(", "!", "sys", ".", "isEmpty", "(", "__aliases", ")", ")", "{", "var", "aliasDefinition", "=", "\"var __aliases = {\"", "+", "__aliases", ".", "join", "(", "\",\\n\"", ")", "+", "\"};\\n\"", ";", "data", "=", "aliasDefinition", "+", "data", ";", "}", "this", ".", "queue", "(", "data", ")", ";", "this", ".", "queue", "(", "null", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}" ]
transform dependencies while browserify runs
[ "transform", "dependencies", "while", "browserify", "runs" ]
33133118e99ff9f42ad17023561f5c268a7307cd
https://github.com/terryweiss/grunt-bundles/blob/33133118e99ff9f42ad17023561f5c268a7307cd/tasks/bundles.js#L262-L295
48,732
bholloway/browserify-debug-tools
lib/dump-to-file.js
dumpToFile
function dumpToFile(extension, regex) { return inspect(onComplete); function onComplete(filename, contents, done) { if (!regex || regex.test(filename)) { var newName = [filename, extension || 'gen'].join('.'); fs.writeFile(newName, contents, done); } else { done(); } } }
javascript
function dumpToFile(extension, regex) { return inspect(onComplete); function onComplete(filename, contents, done) { if (!regex || regex.test(filename)) { var newName = [filename, extension || 'gen'].join('.'); fs.writeFile(newName, contents, done); } else { done(); } } }
[ "function", "dumpToFile", "(", "extension", ",", "regex", ")", "{", "return", "inspect", "(", "onComplete", ")", ";", "function", "onComplete", "(", "filename", ",", "contents", ",", "done", ")", "{", "if", "(", "!", "regex", "||", "regex", ".", "test", "(", "filename", ")", ")", "{", "var", "newName", "=", "[", "filename", ",", "extension", "||", "'gen'", "]", ".", "join", "(", "'.'", ")", ";", "fs", ".", "writeFile", "(", "newName", ",", "contents", ",", "done", ")", ";", "}", "else", "{", "done", "(", ")", ";", "}", "}", "}" ]
Transform that writes out the current state of the transformed file next to the original source file. Particularly helpful for source map visualisation. @see http://sokra.github.io/source-map-visualization @param {string} [extension] An optionalextention to append to the file (defaults to 'gen' meaning generated) @param {RegExp} [regex] An optional filename filter @returns {function} Browserify transform
[ "Transform", "that", "writes", "out", "the", "current", "state", "of", "the", "transformed", "file", "next", "to", "the", "original", "source", "file", ".", "Particularly", "helpful", "for", "source", "map", "visualisation", "." ]
47aa05164d73ec7512bdd4a18db0e12fa6b96209
https://github.com/bholloway/browserify-debug-tools/blob/47aa05164d73ec7512bdd4a18db0e12fa6b96209/lib/dump-to-file.js#L14-L25
48,733
tianjianchn/midd
packages/midd-session-mysql-store/src/index.js
dbName
function dbName(str) { if (!str) return str; str = str.replace(/[A-Z]/g, $0 => `_${$0.toLowerCase()}`); if (str[0] === '_') return str.slice(1); return str; }
javascript
function dbName(str) { if (!str) return str; str = str.replace(/[A-Z]/g, $0 => `_${$0.toLowerCase()}`); if (str[0] === '_') return str.slice(1); return str; }
[ "function", "dbName", "(", "str", ")", "{", "if", "(", "!", "str", ")", "return", "str", ";", "str", "=", "str", ".", "replace", "(", "/", "[A-Z]", "/", "g", ",", "$0", "=>", "`", "${", "$0", ".", "toLowerCase", "(", ")", "}", "`", ")", ";", "if", "(", "str", "[", "0", "]", "===", "'_'", ")", "return", "str", ".", "slice", "(", "1", ")", ";", "return", "str", ";", "}" ]
convert the string to a underline-delimited string which will used in database
[ "convert", "the", "string", "to", "a", "underline", "-", "delimited", "string", "which", "will", "used", "in", "database" ]
849f07f68c30335a68be5e1e2b709eb930a560d7
https://github.com/tianjianchn/midd/blob/849f07f68c30335a68be5e1e2b709eb930a560d7/packages/midd-session-mysql-store/src/index.js#L115-L120
48,734
glayzzle/php-core
src/strings.js
function () { bytes = str.substr(u, 45).split('') for (i in bytes) { bytes[i] = bytes[i].charCodeAt(0) } return bytes.length || 0 }
javascript
function () { bytes = str.substr(u, 45).split('') for (i in bytes) { bytes[i] = bytes[i].charCodeAt(0) } return bytes.length || 0 }
[ "function", "(", ")", "{", "bytes", "=", "str", ".", "substr", "(", "u", ",", "45", ")", ".", "split", "(", "''", ")", "for", "(", "i", "in", "bytes", ")", "{", "bytes", "[", "i", "]", "=", "bytes", "[", "i", "]", ".", "charCodeAt", "(", "0", ")", "}", "return", "bytes", ".", "length", "||", "0", "}" ]
divide string into chunks of 45 characters
[ "divide", "string", "into", "chunks", "of", "45", "characters" ]
39b8e8f077d67517dbe8ae6dd52ad95e456f84cd
https://github.com/glayzzle/php-core/blob/39b8e8f077d67517dbe8ae6dd52ad95e456f84cd/src/strings.js#L2494-L2500
48,735
scttnlsn/nettle
lib/store.js
function(result, callback) { self.cache.put(result, function(err, doc) { if (err) return callback(err); callback(null, result, doc._id); }); }
javascript
function(result, callback) { self.cache.put(result, function(err, doc) { if (err) return callback(err); callback(null, result, doc._id); }); }
[ "function", "(", "result", ",", "callback", ")", "{", "self", ".", "cache", ".", "put", "(", "result", ",", "function", "(", "err", ",", "doc", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "result", ",", "doc", ".", "_id", ")", ";", "}", ")", ";", "}" ]
Cache the result
[ "Cache", "the", "result" ]
bfdb06b20f3b808e0b330f4d8235e40db24e48dd
https://github.com/scttnlsn/nettle/blob/bfdb06b20f3b808e0b330f4d8235e40db24e48dd/lib/store.js#L75-L80
48,736
scttnlsn/nettle
lib/store.js
function(result, cached, callback) { self.metacache.store(id, processor, cached, function(err) { if (err) return callback(err); callback(null, result); }); }
javascript
function(result, cached, callback) { self.metacache.store(id, processor, cached, function(err) { if (err) return callback(err); callback(null, result); }); }
[ "function", "(", "result", ",", "cached", ",", "callback", ")", "{", "self", ".", "metacache", ".", "store", "(", "id", ",", "processor", ",", "cached", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "callback", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}" ]
Update the metacache
[ "Update", "the", "metacache" ]
bfdb06b20f3b808e0b330f4d8235e40db24e48dd
https://github.com/scttnlsn/nettle/blob/bfdb06b20f3b808e0b330f4d8235e40db24e48dd/lib/store.js#L83-L88
48,737
scttnlsn/nettle
lib/store.js
function(metacache, callback) { var funcs = []; for (var processor in metacache) { if (processor !== '_id') { var cached = metacache[processor]; funcs.push(function(callback) { self.cache.delete(cached, callback); }); } } async.parallel(funcs, callback); }
javascript
function(metacache, callback) { var funcs = []; for (var processor in metacache) { if (processor !== '_id') { var cached = metacache[processor]; funcs.push(function(callback) { self.cache.delete(cached, callback); }); } } async.parallel(funcs, callback); }
[ "function", "(", "metacache", ",", "callback", ")", "{", "var", "funcs", "=", "[", "]", ";", "for", "(", "var", "processor", "in", "metacache", ")", "{", "if", "(", "processor", "!==", "'_id'", ")", "{", "var", "cached", "=", "metacache", "[", "processor", "]", ";", "funcs", ".", "push", "(", "function", "(", "callback", ")", "{", "self", ".", "cache", ".", "delete", "(", "cached", ",", "callback", ")", ";", "}", ")", ";", "}", "}", "async", ".", "parallel", "(", "funcs", ",", "callback", ")", ";", "}" ]
Delete all cached entities
[ "Delete", "all", "cached", "entities" ]
bfdb06b20f3b808e0b330f4d8235e40db24e48dd
https://github.com/scttnlsn/nettle/blob/bfdb06b20f3b808e0b330f4d8235e40db24e48dd/lib/store.js#L105-L118
48,738
MartinKolarik/ractive-render
lib/rvc.js
load
function load(file, options) { if (options.cache && rr.cache['rvc!' + file]) { return Promise.resolve(rr.cache['rvc!' + file]); } return requireJSAsync(file).then(function (Component) { // flush requireJS's cache _.forEach(requireJS.s.contexts._.defined, function (value, key, array) { if (key.substr(0, 4) === 'rvc!') { delete array[key]; } }); return utils.wrap(utils.selectTemplate(options, Component), options).then(function (template) { var basePath = path.relative(options.settings.views, path.dirname(file)); Component.defaults.template = options.template = template; return Promise.join(utils.buildComponentsRegistry(options), utils.buildPartialsRegistry(basePath, options), function (components, partials) { _.assign(Component.components, components); _.assign(Component.partials, partials); options.components = {}; options.partials = {}; if (options.cache) { rr.cache['rvc!' + file] = Component; } return Component; }); }); }); }
javascript
function load(file, options) { if (options.cache && rr.cache['rvc!' + file]) { return Promise.resolve(rr.cache['rvc!' + file]); } return requireJSAsync(file).then(function (Component) { // flush requireJS's cache _.forEach(requireJS.s.contexts._.defined, function (value, key, array) { if (key.substr(0, 4) === 'rvc!') { delete array[key]; } }); return utils.wrap(utils.selectTemplate(options, Component), options).then(function (template) { var basePath = path.relative(options.settings.views, path.dirname(file)); Component.defaults.template = options.template = template; return Promise.join(utils.buildComponentsRegistry(options), utils.buildPartialsRegistry(basePath, options), function (components, partials) { _.assign(Component.components, components); _.assign(Component.partials, partials); options.components = {}; options.partials = {}; if (options.cache) { rr.cache['rvc!' + file] = Component; } return Component; }); }); }); }
[ "function", "load", "(", "file", ",", "options", ")", "{", "if", "(", "options", ".", "cache", "&&", "rr", ".", "cache", "[", "'rvc!'", "+", "file", "]", ")", "{", "return", "Promise", ".", "resolve", "(", "rr", ".", "cache", "[", "'rvc!'", "+", "file", "]", ")", ";", "}", "return", "requireJSAsync", "(", "file", ")", ".", "then", "(", "function", "(", "Component", ")", "{", "// flush requireJS's cache", "_", ".", "forEach", "(", "requireJS", ".", "s", ".", "contexts", ".", "_", ".", "defined", ",", "function", "(", "value", ",", "key", ",", "array", ")", "{", "if", "(", "key", ".", "substr", "(", "0", ",", "4", ")", "===", "'rvc!'", ")", "{", "delete", "array", "[", "key", "]", ";", "}", "}", ")", ";", "return", "utils", ".", "wrap", "(", "utils", ".", "selectTemplate", "(", "options", ",", "Component", ")", ",", "options", ")", ".", "then", "(", "function", "(", "template", ")", "{", "var", "basePath", "=", "path", ".", "relative", "(", "options", ".", "settings", ".", "views", ",", "path", ".", "dirname", "(", "file", ")", ")", ";", "Component", ".", "defaults", ".", "template", "=", "options", ".", "template", "=", "template", ";", "return", "Promise", ".", "join", "(", "utils", ".", "buildComponentsRegistry", "(", "options", ")", ",", "utils", ".", "buildPartialsRegistry", "(", "basePath", ",", "options", ")", ",", "function", "(", "components", ",", "partials", ")", "{", "_", ".", "assign", "(", "Component", ".", "components", ",", "components", ")", ";", "_", ".", "assign", "(", "Component", ".", "partials", ",", "partials", ")", ";", "options", ".", "components", "=", "{", "}", ";", "options", ".", "partials", "=", "{", "}", ";", "if", "(", "options", ".", "cache", ")", "{", "rr", ".", "cache", "[", "'rvc!'", "+", "file", "]", "=", "Component", ";", "}", "return", "Component", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create a component from the given file using RVC @param {String} file @param {Object} options @returns {Promise} @public
[ "Create", "a", "component", "from", "the", "given", "file", "using", "RVC" ]
417a97c42de4b1ea6c1ab13803f5470b3cc6f75a
https://github.com/MartinKolarik/ractive-render/blob/417a97c42de4b1ea6c1ab13803f5470b3cc6f75a/lib/rvc.js#L31-L62
48,739
MartinKolarik/ractive-render
lib/rvc.js
requireJSAsync
function requireJSAsync (file) { return new Promise(function (resolve, reject) { requireJS([ 'rvc!' + requireJSPath(file, '.html') ], resolve, reject); }); }
javascript
function requireJSAsync (file) { return new Promise(function (resolve, reject) { requireJS([ 'rvc!' + requireJSPath(file, '.html') ], resolve, reject); }); }
[ "function", "requireJSAsync", "(", "file", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "requireJS", "(", "[", "'rvc!'", "+", "requireJSPath", "(", "file", ",", "'.html'", ")", "]", ",", "resolve", ",", "reject", ")", ";", "}", ")", ";", "}" ]
Wrapper for requireJS @param {String} file @returns {Promise} @private
[ "Wrapper", "for", "requireJS" ]
417a97c42de4b1ea6c1ab13803f5470b3cc6f75a
https://github.com/MartinKolarik/ractive-render/blob/417a97c42de4b1ea6c1ab13803f5470b3cc6f75a/lib/rvc.js#L71-L75
48,740
MartinKolarik/ractive-render
lib/rvc.js
requireJSPath
function requireJSPath(file, extension) { return path.join(path.dirname(file), path.basename(file, extension)).replace(/\\/g, '/'); }
javascript
function requireJSPath(file, extension) { return path.join(path.dirname(file), path.basename(file, extension)).replace(/\\/g, '/'); }
[ "function", "requireJSPath", "(", "file", ",", "extension", ")", "{", "return", "path", ".", "join", "(", "path", ".", "dirname", "(", "file", ")", ",", "path", ".", "basename", "(", "file", ",", "extension", ")", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ";", "}" ]
Get RequireJS path to the given file @param {String} file @param {String} [extension] @returns {string} @private
[ "Get", "RequireJS", "path", "to", "the", "given", "file" ]
417a97c42de4b1ea6c1ab13803f5470b3cc6f75a
https://github.com/MartinKolarik/ractive-render/blob/417a97c42de4b1ea6c1ab13803f5470b3cc6f75a/lib/rvc.js#L85-L87
48,741
ceddl/ceddl-aditional-inputs
src/heatmap.js
DetectMouseUser
function DetectMouseUser(event) { if(isMouseUser) { // collection throttle interval. setInterval(function() { trackData = true; }, 50); return true; } let current = movement; if(x && y){ movement = movement + Math.abs(x - event.pageX) + Math.abs(y - event.pageY); } x = event.pageX; y = event.pageY; if ((current + 10) > movement) { movementOkcount++; } if(movementOkcount > 5) { isMouseUser = true; } return false; }
javascript
function DetectMouseUser(event) { if(isMouseUser) { // collection throttle interval. setInterval(function() { trackData = true; }, 50); return true; } let current = movement; if(x && y){ movement = movement + Math.abs(x - event.pageX) + Math.abs(y - event.pageY); } x = event.pageX; y = event.pageY; if ((current + 10) > movement) { movementOkcount++; } if(movementOkcount > 5) { isMouseUser = true; } return false; }
[ "function", "DetectMouseUser", "(", "event", ")", "{", "if", "(", "isMouseUser", ")", "{", "// collection throttle interval.", "setInterval", "(", "function", "(", ")", "{", "trackData", "=", "true", ";", "}", ",", "50", ")", ";", "return", "true", ";", "}", "let", "current", "=", "movement", ";", "if", "(", "x", "&&", "y", ")", "{", "movement", "=", "movement", "+", "Math", ".", "abs", "(", "x", "-", "event", ".", "pageX", ")", "+", "Math", ".", "abs", "(", "y", "-", "event", ".", "pageY", ")", ";", "}", "x", "=", "event", ".", "pageX", ";", "y", "=", "event", ".", "pageY", ";", "if", "(", "(", "current", "+", "10", ")", ">", "movement", ")", "{", "movementOkcount", "++", ";", "}", "if", "(", "movementOkcount", ">", "5", ")", "{", "isMouseUser", "=", "true", ";", "}", "return", "false", ";", "}" ]
Only use the mousemove data if the user is actualy using a mouse. This can be hard to detect. If you have a inproved sollution please do not hesitate to contact ceddl-polyfill team or create a pull request.
[ "Only", "use", "the", "mousemove", "data", "if", "the", "user", "is", "actualy", "using", "a", "mouse", ".", "This", "can", "be", "hard", "to", "detect", ".", "If", "you", "have", "a", "inproved", "sollution", "please", "do", "not", "hesitate", "to", "contact", "ceddl", "-", "polyfill", "team", "or", "create", "a", "pull", "request", "." ]
0e018d463107a0b631c317d7bf372aa9e194b7da
https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/heatmap.js#L27-L48
48,742
ceddl/ceddl-aditional-inputs
src/heatmap.js
startIdle
function startIdle() { var idleCount = 0; function idle() { coordinates.push({ t: 1, x: lastX, y: lastY }); idleCount++; if (idleCount > 10) { clearInterval(idleInterval); } } idle(); idleInterval = setInterval(idle, 1000); }
javascript
function startIdle() { var idleCount = 0; function idle() { coordinates.push({ t: 1, x: lastX, y: lastY }); idleCount++; if (idleCount > 10) { clearInterval(idleInterval); } } idle(); idleInterval = setInterval(idle, 1000); }
[ "function", "startIdle", "(", ")", "{", "var", "idleCount", "=", "0", ";", "function", "idle", "(", ")", "{", "coordinates", ".", "push", "(", "{", "t", ":", "1", ",", "x", ":", "lastX", ",", "y", ":", "lastY", "}", ")", ";", "idleCount", "++", ";", "if", "(", "idleCount", ">", "10", ")", "{", "clearInterval", "(", "idleInterval", ")", ";", "}", "}", "idle", "(", ")", ";", "idleInterval", "=", "setInterval", "(", "idle", ",", "1000", ")", ";", "}" ]
As the mouse stops moving the stream of events stop. The user is deciding or reading text?! For 10 intervals continue to add the position to the coordinates.
[ "As", "the", "mouse", "stops", "moving", "the", "stream", "of", "events", "stop", ".", "The", "user", "is", "deciding", "or", "reading", "text?!", "For", "10", "intervals", "continue", "to", "add", "the", "position", "to", "the", "coordinates", "." ]
0e018d463107a0b631c317d7bf372aa9e194b7da
https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/heatmap.js#L55-L72
48,743
ceddl/ceddl-aditional-inputs
src/heatmap.js
emitHeatmapCoordinates
function emitHeatmapCoordinates() { if(coordinates.length > 0) { ceddl.emitEvent('heatmap:update', { width: windowWidth, coordinates: coordinates.splice(0, coordinates.length) }); } windowWidth = Math.round(parseInt(window.innerWidth, 10)); }
javascript
function emitHeatmapCoordinates() { if(coordinates.length > 0) { ceddl.emitEvent('heatmap:update', { width: windowWidth, coordinates: coordinates.splice(0, coordinates.length) }); } windowWidth = Math.round(parseInt(window.innerWidth, 10)); }
[ "function", "emitHeatmapCoordinates", "(", ")", "{", "if", "(", "coordinates", ".", "length", ">", "0", ")", "{", "ceddl", ".", "emitEvent", "(", "'heatmap:update'", ",", "{", "width", ":", "windowWidth", ",", "coordinates", ":", "coordinates", ".", "splice", "(", "0", ",", "coordinates", ".", "length", ")", "}", ")", ";", "}", "windowWidth", "=", "Math", ".", "round", "(", "parseInt", "(", "window", ".", "innerWidth", ",", "10", ")", ")", ";", "}" ]
Send data to ceddl and clear the current coordinates.
[ "Send", "data", "to", "ceddl", "and", "clear", "the", "current", "coordinates", "." ]
0e018d463107a0b631c317d7bf372aa9e194b7da
https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/heatmap.js#L77-L85
48,744
ceddl/ceddl-aditional-inputs
src/heatmap.js
isClickTarget
function isClickTarget(element) { return element.hasAttribute('ceddl-click') || (element.nodeType === 1 && element.tagName.toUpperCase() === 'BUTTON') || (element.nodeType === 1 && element.tagName.toUpperCase() === 'A'); }
javascript
function isClickTarget(element) { return element.hasAttribute('ceddl-click') || (element.nodeType === 1 && element.tagName.toUpperCase() === 'BUTTON') || (element.nodeType === 1 && element.tagName.toUpperCase() === 'A'); }
[ "function", "isClickTarget", "(", "element", ")", "{", "return", "element", ".", "hasAttribute", "(", "'ceddl-click'", ")", "||", "(", "element", ".", "nodeType", "===", "1", "&&", "element", ".", "tagName", ".", "toUpperCase", "(", ")", "===", "'BUTTON'", ")", "||", "(", "element", ".", "nodeType", "===", "1", "&&", "element", ".", "tagName", ".", "toUpperCase", "(", ")", "===", "'A'", ")", ";", "}" ]
Determines if the element is a valid element to stop the delegation loop and emit the coordinates dataset.
[ "Determines", "if", "the", "element", "is", "a", "valid", "element", "to", "stop", "the", "delegation", "loop", "and", "emit", "the", "coordinates", "dataset", "." ]
0e018d463107a0b631c317d7bf372aa9e194b7da
https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/heatmap.js#L91-L95
48,745
ceddl/ceddl-aditional-inputs
src/heatmap.js
delegate
function delegate(callback, el) { var currentElement = el; do { if (!isClickTarget(currentElement)) continue; callback(currentElement); return; } while(currentElement.nodeName.toUpperCase() !== 'BODY' && (currentElement = currentElement.parentNode)); }
javascript
function delegate(callback, el) { var currentElement = el; do { if (!isClickTarget(currentElement)) continue; callback(currentElement); return; } while(currentElement.nodeName.toUpperCase() !== 'BODY' && (currentElement = currentElement.parentNode)); }
[ "function", "delegate", "(", "callback", ",", "el", ")", "{", "var", "currentElement", "=", "el", ";", "do", "{", "if", "(", "!", "isClickTarget", "(", "currentElement", ")", ")", "continue", ";", "callback", "(", "currentElement", ")", ";", "return", ";", "}", "while", "(", "currentElement", ".", "nodeName", ".", "toUpperCase", "(", ")", "!==", "'BODY'", "&&", "(", "currentElement", "=", "currentElement", ".", "parentNode", ")", ")", ";", "}" ]
A deligation loop to find the clicked element and execute click callback with that element.
[ "A", "deligation", "loop", "to", "find", "the", "clicked", "element", "and", "execute", "click", "callback", "with", "that", "element", "." ]
0e018d463107a0b631c317d7bf372aa9e194b7da
https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/heatmap.js#L101-L109
48,746
rmdort/react-kitt
src/components/ButtonGroup/index.js
ButtonGroup
function ButtonGroup({ children, className, ...rest }) { const classes = cx(buttonGroupClassName, className) return ( <div className={classes} {...rest}> {children} </div> ) }
javascript
function ButtonGroup({ children, className, ...rest }) { const classes = cx(buttonGroupClassName, className) return ( <div className={classes} {...rest}> {children} </div> ) }
[ "function", "ButtonGroup", "(", "{", "children", ",", "className", ",", "...", "rest", "}", ")", "{", "const", "classes", "=", "cx", "(", "buttonGroupClassName", ",", "className", ")", "return", "(", "<", "div", "className", "=", "{", "classes", "}", "{", "...", "rest", "}", ">", "\n ", "{", "children", "}", "\n ", "<", "/", "div", ">", ")", "}" ]
Button groups arrange multiple buttons in a horizontal or vertical group.
[ "Button", "groups", "arrange", "multiple", "buttons", "in", "a", "horizontal", "or", "vertical", "group", "." ]
a3dc0ef1451a84b8f7bed1f86dd0f3db26e8ff31
https://github.com/rmdort/react-kitt/blob/a3dc0ef1451a84b8f7bed1f86dd0f3db26e8ff31/src/components/ButtonGroup/index.js#L10-L17
48,747
stefangordon/ethproof
dist/index.common.js
hashDocument
function hashDocument(document) { var words; if (Buffer.isBuffer(document)) { words = Base64.parse(document.toString('base64')); } else if (typeof document === 'string') { words = Base64.parse(document); } else { throw new TypeError('Expected document to be Buffer or String'); } var hash = sha256(words); return hash.toString(Hex); }
javascript
function hashDocument(document) { var words; if (Buffer.isBuffer(document)) { words = Base64.parse(document.toString('base64')); } else if (typeof document === 'string') { words = Base64.parse(document); } else { throw new TypeError('Expected document to be Buffer or String'); } var hash = sha256(words); return hash.toString(Hex); }
[ "function", "hashDocument", "(", "document", ")", "{", "var", "words", ";", "if", "(", "Buffer", ".", "isBuffer", "(", "document", ")", ")", "{", "words", "=", "Base64", ".", "parse", "(", "document", ".", "toString", "(", "'base64'", ")", ")", ";", "}", "else", "if", "(", "typeof", "document", "===", "'string'", ")", "{", "words", "=", "Base64", ".", "parse", "(", "document", ")", ";", "}", "else", "{", "throw", "new", "TypeError", "(", "'Expected document to be Buffer or String'", ")", ";", "}", "var", "hash", "=", "sha256", "(", "words", ")", ";", "return", "hash", ".", "toString", "(", "Hex", ")", ";", "}" ]
Generate hash of a document @param {string|buffer} document - The document as a string or buffer @return {string} Hex string representing hash
[ "Generate", "hash", "of", "a", "document" ]
5c0711b242dfe587d30fd57389222af635cd1dce
https://github.com/stefangordon/ethproof/blob/5c0711b242dfe587d30fd57389222af635cd1dce/dist/index.common.js#L21-L35
48,748
stefangordon/ethproof
dist/index.common.js
publishProof
function publishProof(privateKeyHex, toAddress, hash, rpcUri) { if (!EthereumUtil.isValidAddress(EthereumUtil.addHexPrefix(toAddress))) { throw new Error('Invalid destination address.'); } if (!rpcUri) { rpcUri = localDefault; } var web3 = new Web3( new Web3.providers.HttpProvider(rpcUri) ); var tx = buildTransaction(privateKeyHex, toAddress, hash, web3); var serializedTx = EthereumUtil.addHexPrefix(tx.serialize().toString('hex')); var txHash = web3.eth.sendRawTransaction(serializedTx); console.log('Transaction hash:' + txHash); return txHash; }
javascript
function publishProof(privateKeyHex, toAddress, hash, rpcUri) { if (!EthereumUtil.isValidAddress(EthereumUtil.addHexPrefix(toAddress))) { throw new Error('Invalid destination address.'); } if (!rpcUri) { rpcUri = localDefault; } var web3 = new Web3( new Web3.providers.HttpProvider(rpcUri) ); var tx = buildTransaction(privateKeyHex, toAddress, hash, web3); var serializedTx = EthereumUtil.addHexPrefix(tx.serialize().toString('hex')); var txHash = web3.eth.sendRawTransaction(serializedTx); console.log('Transaction hash:' + txHash); return txHash; }
[ "function", "publishProof", "(", "privateKeyHex", ",", "toAddress", ",", "hash", ",", "rpcUri", ")", "{", "if", "(", "!", "EthereumUtil", ".", "isValidAddress", "(", "EthereumUtil", ".", "addHexPrefix", "(", "toAddress", ")", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid destination address.'", ")", ";", "}", "if", "(", "!", "rpcUri", ")", "{", "rpcUri", "=", "localDefault", ";", "}", "var", "web3", "=", "new", "Web3", "(", "new", "Web3", ".", "providers", ".", "HttpProvider", "(", "rpcUri", ")", ")", ";", "var", "tx", "=", "buildTransaction", "(", "privateKeyHex", ",", "toAddress", ",", "hash", ",", "web3", ")", ";", "var", "serializedTx", "=", "EthereumUtil", ".", "addHexPrefix", "(", "tx", ".", "serialize", "(", ")", ".", "toString", "(", "'hex'", ")", ")", ";", "var", "txHash", "=", "web3", ".", "eth", ".", "sendRawTransaction", "(", "serializedTx", ")", ";", "console", ".", "log", "(", "'Transaction hash:'", "+", "txHash", ")", ";", "return", "txHash", ";", "}" ]
Publishes a proof of existence to the Ethereum chain @param {string} privateKeyHex - Private key as a hex string @param {string} toAddress - Destination address @param {string} hash - Hash as hex string @param {string} rpcUri - Optional RPC Uri. Defaults to http://localhost:8545 @return {string} Hex string representing hash
[ "Publishes", "a", "proof", "of", "existence", "to", "the", "Ethereum", "chain" ]
5c0711b242dfe587d30fd57389222af635cd1dce
https://github.com/stefangordon/ethproof/blob/5c0711b242dfe587d30fd57389222af635cd1dce/dist/index.common.js#L45-L64
48,749
stefangordon/ethproof
dist/index.common.js
buildTransaction
function buildTransaction(privateKeyHex, toAddress, hash, web3) { var privateKeyBuffer = Buffer.from(privateKeyHex, 'hex'); if (!EthereumUtil.isValidPrivate(privateKeyBuffer)) { throw new Error('Invalid private key.'); } var txParams = { nonce: '0x00', gasPrice: '0x09184e72a000', // How should we set this? gasLimit: '0x5A88', to: EthereumUtil.addHexPrefix(toAddress), value: '0x00', data: EthereumUtil.addHexPrefix(hash) }; if (web3 !== undefined) { var gas = web3.eth.estimateGas(txParams); var nonce = web3.eth.getTransactionCount( EthereumUtil.bufferToHex( EthereumUtil.privateToAddress(privateKeyBuffer) )); txParams.gasLimit = web3.toHex(gas); txParams.nonce = web3.toHex(nonce); txParams.gasPrice = web3.toHex(web3.eth.gasPrice); } var tx = new EthereumTx(txParams); tx.sign(privateKeyBuffer); return tx; }
javascript
function buildTransaction(privateKeyHex, toAddress, hash, web3) { var privateKeyBuffer = Buffer.from(privateKeyHex, 'hex'); if (!EthereumUtil.isValidPrivate(privateKeyBuffer)) { throw new Error('Invalid private key.'); } var txParams = { nonce: '0x00', gasPrice: '0x09184e72a000', // How should we set this? gasLimit: '0x5A88', to: EthereumUtil.addHexPrefix(toAddress), value: '0x00', data: EthereumUtil.addHexPrefix(hash) }; if (web3 !== undefined) { var gas = web3.eth.estimateGas(txParams); var nonce = web3.eth.getTransactionCount( EthereumUtil.bufferToHex( EthereumUtil.privateToAddress(privateKeyBuffer) )); txParams.gasLimit = web3.toHex(gas); txParams.nonce = web3.toHex(nonce); txParams.gasPrice = web3.toHex(web3.eth.gasPrice); } var tx = new EthereumTx(txParams); tx.sign(privateKeyBuffer); return tx; }
[ "function", "buildTransaction", "(", "privateKeyHex", ",", "toAddress", ",", "hash", ",", "web3", ")", "{", "var", "privateKeyBuffer", "=", "Buffer", ".", "from", "(", "privateKeyHex", ",", "'hex'", ")", ";", "if", "(", "!", "EthereumUtil", ".", "isValidPrivate", "(", "privateKeyBuffer", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid private key.'", ")", ";", "}", "var", "txParams", "=", "{", "nonce", ":", "'0x00'", ",", "gasPrice", ":", "'0x09184e72a000'", ",", "// How should we set this?", "gasLimit", ":", "'0x5A88'", ",", "to", ":", "EthereumUtil", ".", "addHexPrefix", "(", "toAddress", ")", ",", "value", ":", "'0x00'", ",", "data", ":", "EthereumUtil", ".", "addHexPrefix", "(", "hash", ")", "}", ";", "if", "(", "web3", "!==", "undefined", ")", "{", "var", "gas", "=", "web3", ".", "eth", ".", "estimateGas", "(", "txParams", ")", ";", "var", "nonce", "=", "web3", ".", "eth", ".", "getTransactionCount", "(", "EthereumUtil", ".", "bufferToHex", "(", "EthereumUtil", ".", "privateToAddress", "(", "privateKeyBuffer", ")", ")", ")", ";", "txParams", ".", "gasLimit", "=", "web3", ".", "toHex", "(", "gas", ")", ";", "txParams", ".", "nonce", "=", "web3", ".", "toHex", "(", "nonce", ")", ";", "txParams", ".", "gasPrice", "=", "web3", ".", "toHex", "(", "web3", ".", "eth", ".", "gasPrice", ")", ";", "}", "var", "tx", "=", "new", "EthereumTx", "(", "txParams", ")", ";", "tx", ".", "sign", "(", "privateKeyBuffer", ")", ";", "return", "tx", ";", "}" ]
Builds a signed transaction for transmitting, primarily used internally.
[ "Builds", "a", "signed", "transaction", "for", "transmitting", "primarily", "used", "internally", "." ]
5c0711b242dfe587d30fd57389222af635cd1dce
https://github.com/stefangordon/ethproof/blob/5c0711b242dfe587d30fd57389222af635cd1dce/dist/index.common.js#L70-L101
48,750
rgeraldporter/ebird-histogramr
src/lib/csv.js
toCsvValue
function toCsvValue(theValue, sDelimiter) { const t = typeof (theValue); let output, stringDelimiter ; if (typeof (sDelimiter) === "undefined" || sDelimiter === null) stringDelimiter = '"'; else stringDelimiter = sDelimiter; if (t === "undefined" || t === null) output = ''; else if (t === 'string') output = sDelimiter + theValue + sDelimiter; else output = String(theValue); return output; }
javascript
function toCsvValue(theValue, sDelimiter) { const t = typeof (theValue); let output, stringDelimiter ; if (typeof (sDelimiter) === "undefined" || sDelimiter === null) stringDelimiter = '"'; else stringDelimiter = sDelimiter; if (t === "undefined" || t === null) output = ''; else if (t === 'string') output = sDelimiter + theValue + sDelimiter; else output = String(theValue); return output; }
[ "function", "toCsvValue", "(", "theValue", ",", "sDelimiter", ")", "{", "const", "t", "=", "typeof", "(", "theValue", ")", ";", "let", "output", ",", "stringDelimiter", ";", "if", "(", "typeof", "(", "sDelimiter", ")", "===", "\"undefined\"", "||", "sDelimiter", "===", "null", ")", "stringDelimiter", "=", "'\"'", ";", "else", "stringDelimiter", "=", "sDelimiter", ";", "if", "(", "t", "===", "\"undefined\"", "||", "t", "===", "null", ")", "output", "=", "''", ";", "else", "if", "(", "t", "===", "'string'", ")", "output", "=", "sDelimiter", "+", "theValue", "+", "sDelimiter", ";", "else", "output", "=", "String", "(", "theValue", ")", ";", "return", "output", ";", "}" ]
Converts a value to a string appropriate for entry into a CSV table. E.g., a string value will be surrounded by quotes. @param {string|number|object} theValue @param {string} sDelimiter The string delimiter. Defaults to a double quote (") if omitted.
[ "Converts", "a", "value", "to", "a", "string", "appropriate", "for", "entry", "into", "a", "CSV", "table", ".", "E", ".", "g", ".", "a", "string", "value", "will", "be", "surrounded", "by", "quotes", "." ]
a8c47f3bf28fb21e8ced613c19168879deb55aef
https://github.com/rgeraldporter/ebird-histogramr/blob/a8c47f3bf28fb21e8ced613c19168879deb55aef/src/lib/csv.js#L6-L25
48,751
heroqu/node-content-store
index.js
taskMinus
function taskMinus() { taskCounter-- if (taskCounter === 0) { // Time to respond if (files.length === 0) { res.send(200, { result: 'no files to upload', files }) } else { res.send(201, { result: 'upload OK', files }) } next() } }
javascript
function taskMinus() { taskCounter-- if (taskCounter === 0) { // Time to respond if (files.length === 0) { res.send(200, { result: 'no files to upload', files }) } else { res.send(201, { result: 'upload OK', files }) } next() } }
[ "function", "taskMinus", "(", ")", "{", "taskCounter", "--", "if", "(", "taskCounter", "===", "0", ")", "{", "// Time to respond", "if", "(", "files", ".", "length", "===", "0", ")", "{", "res", ".", "send", "(", "200", ",", "{", "result", ":", "'no files to upload'", ",", "files", "}", ")", "}", "else", "{", "res", ".", "send", "(", "201", ",", "{", "result", ":", "'upload OK'", ",", "files", "}", ")", "}", "next", "(", ")", "}", "}" ]
call this one after any subtask is finished
[ "call", "this", "one", "after", "any", "subtask", "is", "finished" ]
0100814bfd988d60ad94cdf5a441eff328208a6a
https://github.com/heroqu/node-content-store/blob/0100814bfd988d60ad94cdf5a441eff328208a6a/index.js#L97-L114
48,752
thinkkoa/think_trace
index.js
function (tmr, timeout) { return new Promise((resolve, reject) => { /*eslint-disable no-return-assign */ return tmr = setTimeout(reject, timeout, httpError(408)); }); }
javascript
function (tmr, timeout) { return new Promise((resolve, reject) => { /*eslint-disable no-return-assign */ return tmr = setTimeout(reject, timeout, httpError(408)); }); }
[ "function", "(", "tmr", ",", "timeout", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "/*eslint-disable no-return-assign */", "return", "tmr", "=", "setTimeout", "(", "reject", ",", "timeout", ",", "httpError", "(", "408", ")", ")", ";", "}", ")", ";", "}" ]
http timeout timer @param {any} tmr @param {any} timeout @returns
[ "http", "timeout", "timer" ]
b9b6838a7287281b3585995faf60e5531eab435e
https://github.com/thinkkoa/think_trace/blob/b9b6838a7287281b3585995faf60e5531eab435e/index.js#L60-L65
48,753
owstack/ows-common
lib/util/js.js
defineImmutable
function defineImmutable(target, values) { Object.keys(values).forEach(function(key){ Object.defineProperty(target, key, { configurable: false, enumerable: true, value: values[key] }); }); return target; }
javascript
function defineImmutable(target, values) { Object.keys(values).forEach(function(key){ Object.defineProperty(target, key, { configurable: false, enumerable: true, value: values[key] }); }); return target; }
[ "function", "defineImmutable", "(", "target", ",", "values", ")", "{", "Object", ".", "keys", "(", "values", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "Object", ".", "defineProperty", "(", "target", ",", "key", ",", "{", "configurable", ":", "false", ",", "enumerable", ":", "true", ",", "value", ":", "values", "[", "key", "]", "}", ")", ";", "}", ")", ";", "return", "target", ";", "}" ]
Define immutable properties on a target object @param {Object} target - An object to be extended @param {Object} values - An object of properties @return {Object} The target object
[ "Define", "immutable", "properties", "on", "a", "target", "object" ]
aa2a7970547cf451c06e528472ee965d3b4cac36
https://github.com/owstack/ows-common/blob/aa2a7970547cf451c06e528472ee965d3b4cac36/lib/util/js.js#L62-L71
48,754
motionbank/piecemaker-api-client
src-js/api.js
function ( data ) { if ( !data ) return data; if ( typeof data !== 'object' ) return data; if ( 'entrySet' in data && typeof data.entrySet === 'function' ) { //var allowed_long_keys = ['utc_timestamp', 'duration', 'type', 'token']; var set = data.entrySet(); if ( !set ) return data; var obj = {}; var iter = set.iterator(); while ( iter.hasNext() ) { var entry = iter.next(); var val = entry.getValue(); if ( val && typeof val === 'object' && 'entrySet' in val && typeof val.entrySet === 'function' ) val = convertData(val); var key = entry.getKey(); if ( !key ) { throw( "Field key is not valid: " + key ); } obj[entry.getKey()] = val; } return obj; } else { if ( 'utc_timestamp' in data ) data.utc_timestamp = jsDateToTs(data.utc_timestamp); if ( 'created_at' in data ) data.created_at = jsDateToTs(data.created_at); } return data; }
javascript
function ( data ) { if ( !data ) return data; if ( typeof data !== 'object' ) return data; if ( 'entrySet' in data && typeof data.entrySet === 'function' ) { //var allowed_long_keys = ['utc_timestamp', 'duration', 'type', 'token']; var set = data.entrySet(); if ( !set ) return data; var obj = {}; var iter = set.iterator(); while ( iter.hasNext() ) { var entry = iter.next(); var val = entry.getValue(); if ( val && typeof val === 'object' && 'entrySet' in val && typeof val.entrySet === 'function' ) val = convertData(val); var key = entry.getKey(); if ( !key ) { throw( "Field key is not valid: " + key ); } obj[entry.getKey()] = val; } return obj; } else { if ( 'utc_timestamp' in data ) data.utc_timestamp = jsDateToTs(data.utc_timestamp); if ( 'created_at' in data ) data.created_at = jsDateToTs(data.created_at); } return data; }
[ "function", "(", "data", ")", "{", "if", "(", "!", "data", ")", "return", "data", ";", "if", "(", "typeof", "data", "!==", "'object'", ")", "return", "data", ";", "if", "(", "'entrySet'", "in", "data", "&&", "typeof", "data", ".", "entrySet", "===", "'function'", ")", "{", "//var allowed_long_keys = ['utc_timestamp', 'duration', 'type', 'token'];", "var", "set", "=", "data", ".", "entrySet", "(", ")", ";", "if", "(", "!", "set", ")", "return", "data", ";", "var", "obj", "=", "{", "}", ";", "var", "iter", "=", "set", ".", "iterator", "(", ")", ";", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "var", "entry", "=", "iter", ".", "next", "(", ")", ";", "var", "val", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "val", "&&", "typeof", "val", "===", "'object'", "&&", "'entrySet'", "in", "val", "&&", "typeof", "val", ".", "entrySet", "===", "'function'", ")", "val", "=", "convertData", "(", "val", ")", ";", "var", "key", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "!", "key", ")", "{", "throw", "(", "\"Field key is not valid: \"", "+", "key", ")", ";", "}", "obj", "[", "entry", ".", "getKey", "(", ")", "]", "=", "val", ";", "}", "return", "obj", ";", "}", "else", "{", "if", "(", "'utc_timestamp'", "in", "data", ")", "data", ".", "utc_timestamp", "=", "jsDateToTs", "(", "data", ".", "utc_timestamp", ")", ";", "if", "(", "'created_at'", "in", "data", ")", "data", ".", "created_at", "=", "jsDateToTs", "(", "data", ".", "created_at", ")", ";", "}", "return", "data", ";", "}" ]
Convert Processing.js HashMaps to JavaScript objects
[ "Convert", "Processing", ".", "js", "HashMaps", "to", "JavaScript", "objects" ]
6d0a3ab7d603fa7e21303433d099aaa36b09f7c4
https://github.com/motionbank/piecemaker-api-client/blob/6d0a3ab7d603fa7e21303433d099aaa36b09f7c4/src-js/api.js#L1238-L1265
48,755
amida-tech/blue-button-pim
lib/evaluator.js
evaluate
function evaluate(score, at, mt) { var automaticThreshold = at || 17.73; var manualThreshold = mt || 15.957; var result = "no match"; if (score >= automaticThreshold) { result = "automatic"; } else if (score >= manualThreshold) { result = "manual"; } return result; }
javascript
function evaluate(score, at, mt) { var automaticThreshold = at || 17.73; var manualThreshold = mt || 15.957; var result = "no match"; if (score >= automaticThreshold) { result = "automatic"; } else if (score >= manualThreshold) { result = "manual"; } return result; }
[ "function", "evaluate", "(", "score", ",", "at", ",", "mt", ")", "{", "var", "automaticThreshold", "=", "at", "||", "17.73", ";", "var", "manualThreshold", "=", "mt", "||", "15.957", ";", "var", "result", "=", "\"no match\"", ";", "if", "(", "score", ">=", "automaticThreshold", ")", "{", "result", "=", "\"automatic\"", ";", "}", "else", "if", "(", "score", ">=", "manualThreshold", ")", "{", "result", "=", "\"manual\"", ";", "}", "return", "result", ";", "}" ]
evaluates matching score
[ "evaluates", "matching", "score" ]
329dcc5fa5f3d877c2b675e8e0d689a8ef25a895
https://github.com/amida-tech/blue-button-pim/blob/329dcc5fa5f3d877c2b675e8e0d689a8ef25a895/lib/evaluator.js#L4-L17
48,756
wzrdtales/seneca-mesh-ng
mesh.js
function(seneca, options, bases, next) { var add = []; var host = options.host; if (0 === bases.length) { if (null != host && host !== DEFAULT_HOST) { add.push(host + ":" + DEFAULT_PORT); } add.push(DEFAULT_HOST + ":" + DEFAULT_PORT); } next(add); }
javascript
function(seneca, options, bases, next) { var add = []; var host = options.host; if (0 === bases.length) { if (null != host && host !== DEFAULT_HOST) { add.push(host + ":" + DEFAULT_PORT); } add.push(DEFAULT_HOST + ":" + DEFAULT_PORT); } next(add); }
[ "function", "(", "seneca", ",", "options", ",", "bases", ",", "next", ")", "{", "var", "add", "=", "[", "]", ";", "var", "host", "=", "options", ".", "host", ";", "if", "(", "0", "===", "bases", ".", "length", ")", "{", "if", "(", "null", "!=", "host", "&&", "host", "!==", "DEFAULT_HOST", ")", "{", "add", ".", "push", "(", "host", "+", "\":\"", "+", "DEFAULT_PORT", ")", ";", "}", "add", ".", "push", "(", "DEFAULT_HOST", "+", "\":\"", "+", "DEFAULT_PORT", ")", ";", "}", "next", "(", "add", ")", ";", "}" ]
order significant! depends on defined as uses bases.length
[ "order", "significant!", "depends", "on", "defined", "as", "uses", "bases", ".", "length" ]
25ffc2a53b83bf9575086ce7b8c35d88c188e760
https://github.com/wzrdtales/seneca-mesh-ng/blob/25ffc2a53b83bf9575086ce7b8c35d88c188e760/mesh.js#L522-L534
48,757
kuno/neco
deps/npm/lib/utils/semver.js
maxSatisfying
function maxSatisfying (versions, range) { return versions .filter(function (v) { return satisfies(v, range) }) .sort(compare) .pop() }
javascript
function maxSatisfying (versions, range) { return versions .filter(function (v) { return satisfies(v, range) }) .sort(compare) .pop() }
[ "function", "maxSatisfying", "(", "versions", ",", "range", ")", "{", "return", "versions", ".", "filter", "(", "function", "(", "v", ")", "{", "return", "satisfies", "(", "v", ",", "range", ")", "}", ")", ".", "sort", "(", "compare", ")", ".", "pop", "(", ")", "}" ]
returns the highest satisfying version in the list, or undefined
[ "returns", "the", "highest", "satisfying", "version", "in", "the", "list", "or", "undefined" ]
cf6361c1fcb9466c6b2ab3b127b5d0160ca50735
https://github.com/kuno/neco/blob/cf6361c1fcb9466c6b2ab3b127b5d0160ca50735/deps/npm/lib/utils/semver.js#L145-L150
48,758
mrmlnc/grunt-puglint
lib/formatter.js
function(item) { // Drop newline symbol in error string item.msg = (Array.isArray(item.msg) ? item.msg.join(' ') : item.msg).replace('\n', ''); // Using zero instead of undefined item.column = (item.column === undefined) ? 0 : item.column; // Drop `PUG:LINT_` prefix in error code item.code = chalk.grey(item.code.replace(/(PUG:|LINT_)/g, '')); // Formatting output var position = chalk.grey(item.line + ':' + item.column); return ['', position, chalk.red('error'), item.msg, item.code]; }
javascript
function(item) { // Drop newline symbol in error string item.msg = (Array.isArray(item.msg) ? item.msg.join(' ') : item.msg).replace('\n', ''); // Using zero instead of undefined item.column = (item.column === undefined) ? 0 : item.column; // Drop `PUG:LINT_` prefix in error code item.code = chalk.grey(item.code.replace(/(PUG:|LINT_)/g, '')); // Formatting output var position = chalk.grey(item.line + ':' + item.column); return ['', position, chalk.red('error'), item.msg, item.code]; }
[ "function", "(", "item", ")", "{", "// Drop newline symbol in error string", "item", ".", "msg", "=", "(", "Array", ".", "isArray", "(", "item", ".", "msg", ")", "?", "item", ".", "msg", ".", "join", "(", "' '", ")", ":", "item", ".", "msg", ")", ".", "replace", "(", "'\\n'", ",", "''", ")", ";", "// Using zero instead of undefined", "item", ".", "column", "=", "(", "item", ".", "column", "===", "undefined", ")", "?", "0", ":", "item", ".", "column", ";", "// Drop `PUG:LINT_` prefix in error code", "item", ".", "code", "=", "chalk", ".", "grey", "(", "item", ".", "code", ".", "replace", "(", "/", "(PUG:|LINT_)", "/", "g", ",", "''", ")", ")", ";", "// Formatting output", "var", "position", "=", "chalk", ".", "grey", "(", "item", ".", "line", "+", "':'", "+", "item", ".", "column", ")", ";", "return", "[", "''", ",", "position", ",", "chalk", ".", "red", "(", "'error'", ")", ",", "item", ".", "msg", ",", "item", ".", "code", "]", ";", "}" ]
Formatting string for the table @param {Object} item
[ "Formatting", "string", "for", "the", "table" ]
cc890d96ea328f78302d9006f65c7a9c9083ebfd
https://github.com/mrmlnc/grunt-puglint/blob/cc890d96ea328f78302d9006f65c7a9c9083ebfd/lib/formatter.js#L13-L23
48,759
jeanamarante/catena
tasks/dev/watch.js
readFile
function readFile (file) { if (!isFileRegistered(file)) { return undefined; } fileRegistry[file].content = gruntIsFile(file) ? gruntRead(file) + '\x0A' : ''; }
javascript
function readFile (file) { if (!isFileRegistered(file)) { return undefined; } fileRegistry[file].content = gruntIsFile(file) ? gruntRead(file) + '\x0A' : ''; }
[ "function", "readFile", "(", "file", ")", "{", "if", "(", "!", "isFileRegistered", "(", "file", ")", ")", "{", "return", "undefined", ";", "}", "fileRegistry", "[", "file", "]", ".", "content", "=", "gruntIsFile", "(", "file", ")", "?", "gruntRead", "(", "file", ")", "+", "'\\x0A'", ":", "''", ";", "}" ]
Read registered file's contents and store them into writeArray. @function readFile @param {String} file @return {String} @api private
[ "Read", "registered", "file", "s", "contents", "and", "store", "them", "into", "writeArray", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/dev/watch.js#L57-L61
48,760
jeanamarante/catena
tasks/dev/watch.js
renameFile
function renameFile (oldFile, newFile) { if (!isFileRegistered(oldFile) || isFileRegistered(newFile)) { return undefined; } let item = fileRegistry[oldFile]; item.file = newFile; fileRegistry[newFile] = item; delete fileRegistry[oldFile]; }
javascript
function renameFile (oldFile, newFile) { if (!isFileRegistered(oldFile) || isFileRegistered(newFile)) { return undefined; } let item = fileRegistry[oldFile]; item.file = newFile; fileRegistry[newFile] = item; delete fileRegistry[oldFile]; }
[ "function", "renameFile", "(", "oldFile", ",", "newFile", ")", "{", "if", "(", "!", "isFileRegistered", "(", "oldFile", ")", "||", "isFileRegistered", "(", "newFile", ")", ")", "{", "return", "undefined", ";", "}", "let", "item", "=", "fileRegistry", "[", "oldFile", "]", ";", "item", ".", "file", "=", "newFile", ";", "fileRegistry", "[", "newFile", "]", "=", "item", ";", "delete", "fileRegistry", "[", "oldFile", "]", ";", "}" ]
Unregister old file and register new one. @function renameFile @param {String} oldFile @param {String} newFile @api private
[ "Unregister", "old", "file", "and", "register", "new", "one", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/dev/watch.js#L116-L126
48,761
jeanamarante/catena
tasks/dev/watch.js
onEvent
function onEvent (watcher) { // Wait for write stream to end if write has been delayed. if (writeDelayed) { return undefined; } // If any watch events occur while writing to dest then restart // write stream with new changes. if (stream.isWriting()) { writeDelayed = true; stream.endWriteStream(); // Initial write of files to dest. } else { writeStartTime = Date.now(); writeFiles(); } }
javascript
function onEvent (watcher) { // Wait for write stream to end if write has been delayed. if (writeDelayed) { return undefined; } // If any watch events occur while writing to dest then restart // write stream with new changes. if (stream.isWriting()) { writeDelayed = true; stream.endWriteStream(); // Initial write of files to dest. } else { writeStartTime = Date.now(); writeFiles(); } }
[ "function", "onEvent", "(", "watcher", ")", "{", "// Wait for write stream to end if write has been delayed.", "if", "(", "writeDelayed", ")", "{", "return", "undefined", ";", "}", "// If any watch events occur while writing to dest then restart", "// write stream with new changes.", "if", "(", "stream", ".", "isWriting", "(", ")", ")", "{", "writeDelayed", "=", "true", ";", "stream", ".", "endWriteStream", "(", ")", ";", "// Initial write of files to dest.", "}", "else", "{", "writeStartTime", "=", "Date", ".", "now", "(", ")", ";", "writeFiles", "(", ")", ";", "}", "}" ]
Write files whenever a watch event happens. @function onEvent @param {Watcher} watcher @api private
[ "Write", "files", "whenever", "a", "watch", "event", "happens", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/dev/watch.js#L176-L192
48,762
alexindigo/executioner
index.js
executioner
function executioner(commands, params, options, callback) { var keys, execOptions, collector = []; // optional options :) if (typeof options == 'function') { callback = options; options = {}; } // clone params, to mess with them without side effects params = extend(params); // copy options and with specified shell execOptions = extend(executioner.options || {}, options || {}); // use it as array if (typeof commands == 'string') { commands = [ commands ]; } // assume commands that aren't array are objects if (!Array.isArray(commands)) { keys = Object.keys(commands); } run(collector, commands, keys, params, execOptions, function(err, results) { // output single command result as a string callback(err, (results && results.length == 1) ? results[0] : results); }); return collector; }
javascript
function executioner(commands, params, options, callback) { var keys, execOptions, collector = []; // optional options :) if (typeof options == 'function') { callback = options; options = {}; } // clone params, to mess with them without side effects params = extend(params); // copy options and with specified shell execOptions = extend(executioner.options || {}, options || {}); // use it as array if (typeof commands == 'string') { commands = [ commands ]; } // assume commands that aren't array are objects if (!Array.isArray(commands)) { keys = Object.keys(commands); } run(collector, commands, keys, params, execOptions, function(err, results) { // output single command result as a string callback(err, (results && results.length == 1) ? results[0] : results); }); return collector; }
[ "function", "executioner", "(", "commands", ",", "params", ",", "options", ",", "callback", ")", "{", "var", "keys", ",", "execOptions", ",", "collector", "=", "[", "]", ";", "// optional options :)", "if", "(", "typeof", "options", "==", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "// clone params, to mess with them without side effects", "params", "=", "extend", "(", "params", ")", ";", "// copy options and with specified shell", "execOptions", "=", "extend", "(", "executioner", ".", "options", "||", "{", "}", ",", "options", "||", "{", "}", ")", ";", "// use it as array", "if", "(", "typeof", "commands", "==", "'string'", ")", "{", "commands", "=", "[", "commands", "]", ";", "}", "// assume commands that aren't array are objects", "if", "(", "!", "Array", ".", "isArray", "(", "commands", ")", ")", "{", "keys", "=", "Object", ".", "keys", "(", "commands", ")", ";", "}", "run", "(", "collector", ",", "commands", ",", "keys", ",", "params", ",", "execOptions", ",", "function", "(", "err", ",", "results", ")", "{", "// output single command result as a string", "callback", "(", "err", ",", "(", "results", "&&", "results", ".", "length", "==", "1", ")", "?", "results", "[", "0", "]", ":", "results", ")", ";", "}", ")", ";", "return", "collector", ";", "}" ]
Executes provided command with supplied arguments @param {string|array|object} commands - command to execute, optionally with parameter placeholders @param {object} params - parameters to pass to the command @param {object} [options] - command execution options like `cwd` @param {function} callback - `callback(err, output)`, will be invoked after all commands is finished @returns {object} - execution control object
[ "Executes", "provided", "command", "with", "supplied", "arguments" ]
582f92897f47c13f4531e0b692aebb4a9f134eec
https://github.com/alexindigo/executioner/blob/582f92897f47c13f4531e0b692aebb4a9f134eec/index.js#L24-L59
48,763
viRingbells/easy-babel
lib/parse.js
parse
function parse (targets) { debug('Parse: start parsing'); targets = prepare.targets(targets); prepare_babelrc(); parse_targets(targets); }
javascript
function parse (targets) { debug('Parse: start parsing'); targets = prepare.targets(targets); prepare_babelrc(); parse_targets(targets); }
[ "function", "parse", "(", "targets", ")", "{", "debug", "(", "'Parse: start parsing'", ")", ";", "targets", "=", "prepare", ".", "targets", "(", "targets", ")", ";", "prepare_babelrc", "(", ")", ";", "parse_targets", "(", "targets", ")", ";", "}" ]
Parse targets with babel. @param {string|Array} targets @return {undefined} no return
[ "Parse", "targets", "with", "babel", "." ]
2cb332affc404304cfb01924aaefeac864c002bc
https://github.com/viRingbells/easy-babel/blob/2cb332affc404304cfb01924aaefeac864c002bc/lib/parse.js#L29-L34
48,764
viRingbells/easy-babel
lib/parse.js
parse_targets
function parse_targets (targets) { debug('Parse: parse targets'); for (let i = 0; i < targets.length; i++) { const target = targets[i]; const name = path.basename(target); if (is_special(name)) { special_targets.push(target); continue; } parse_target(target); } }
javascript
function parse_targets (targets) { debug('Parse: parse targets'); for (let i = 0; i < targets.length; i++) { const target = targets[i]; const name = path.basename(target); if (is_special(name)) { special_targets.push(target); continue; } parse_target(target); } }
[ "function", "parse_targets", "(", "targets", ")", "{", "debug", "(", "'Parse: parse targets'", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "targets", ".", "length", ";", "i", "++", ")", "{", "const", "target", "=", "targets", "[", "i", "]", ";", "const", "name", "=", "path", ".", "basename", "(", "target", ")", ";", "if", "(", "is_special", "(", "name", ")", ")", "{", "special_targets", ".", "push", "(", "target", ")", ";", "continue", ";", "}", "parse_target", "(", "target", ")", ";", "}", "}" ]
parse the target
[ "parse", "the", "target" ]
2cb332affc404304cfb01924aaefeac864c002bc
https://github.com/viRingbells/easy-babel/blob/2cb332affc404304cfb01924aaefeac864c002bc/lib/parse.js#L104-L115
48,765
yneves/grunt-html-generator
tasks/html_generator.js
expand
function expand(file, root){ var items = file.orig.src; var category = file.dest; _debug("Expanding "+category+": ",items,"\n"); var expanded; switch(category){ case 'meta': //bypass expanding that would break expanded = items; break; case 'head': case 'body': //expand + retrieve file content expanded = grunt.file.expand({cwd:root,nonull:true},items); expanded = expanded.map(function(item){ var filePath = path.join(root,item); if(isFile(filePath)){ return grunt.file.read(filePath,{encoding:'utf8'}); } else{ _debug("File ",filePath," does not exist"); return item; } }); break; default: //expand expanded = grunt.file.expand({cwd:root,nonull:true},items); break; } _debug("Expanded "+category+": ",expanded,"\n"); return expanded; }
javascript
function expand(file, root){ var items = file.orig.src; var category = file.dest; _debug("Expanding "+category+": ",items,"\n"); var expanded; switch(category){ case 'meta': //bypass expanding that would break expanded = items; break; case 'head': case 'body': //expand + retrieve file content expanded = grunt.file.expand({cwd:root,nonull:true},items); expanded = expanded.map(function(item){ var filePath = path.join(root,item); if(isFile(filePath)){ return grunt.file.read(filePath,{encoding:'utf8'}); } else{ _debug("File ",filePath," does not exist"); return item; } }); break; default: //expand expanded = grunt.file.expand({cwd:root,nonull:true},items); break; } _debug("Expanded "+category+": ",expanded,"\n"); return expanded; }
[ "function", "expand", "(", "file", ",", "root", ")", "{", "var", "items", "=", "file", ".", "orig", ".", "src", ";", "var", "category", "=", "file", ".", "dest", ";", "_debug", "(", "\"Expanding \"", "+", "category", "+", "\": \"", ",", "items", ",", "\"\\n\"", ")", ";", "var", "expanded", ";", "switch", "(", "category", ")", "{", "case", "'meta'", ":", "//bypass expanding that would break", "expanded", "=", "items", ";", "break", ";", "case", "'head'", ":", "case", "'body'", ":", "//expand + retrieve file content", "expanded", "=", "grunt", ".", "file", ".", "expand", "(", "{", "cwd", ":", "root", ",", "nonull", ":", "true", "}", ",", "items", ")", ";", "expanded", "=", "expanded", ".", "map", "(", "function", "(", "item", ")", "{", "var", "filePath", "=", "path", ".", "join", "(", "root", ",", "item", ")", ";", "if", "(", "isFile", "(", "filePath", ")", ")", "{", "return", "grunt", ".", "file", ".", "read", "(", "filePath", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "}", "else", "{", "_debug", "(", "\"File \"", ",", "filePath", ",", "\" does not exist\"", ")", ";", "return", "item", ";", "}", "}", ")", ";", "break", ";", "default", ":", "//expand", "expanded", "=", "grunt", ".", "file", ".", "expand", "(", "{", "cwd", ":", "root", ",", "nonull", ":", "true", "}", ",", "items", ")", ";", "break", ";", "}", "_debug", "(", "\"Expanded \"", "+", "category", "+", "\": \"", ",", "expanded", ",", "\"\\n\"", ")", ";", "return", "expanded", ";", "}" ]
Expand file, by converting in an array of strings @param file Object as returned by task.files @param root String root directory where paths refer to @return Array of strings
[ "Expand", "file", "by", "converting", "in", "an", "array", "of", "strings" ]
325553623706660886bc3e1c85e07a7582950a91
https://github.com/yneves/grunt-html-generator/blob/325553623706660886bc3e1c85e07a7582950a91/tasks/html_generator.js#L172-L204
48,766
ceddl/ceddl-aditional-inputs
src/performance-timing.js
getPerformanceTimingData
function getPerformanceTimingData() { var PerformanceObj = { 'redirecting': performance.timing.fetchStart - performance.timing.navigationStart, 'dnsconnect': performance.timing.requestStart - performance.timing.fetchStart, 'request': performance.timing.responseStart - performance.timing.requestStart, 'response': performance.timing.responseEnd - performance.timing.responseStart, 'domprocessing': performance.timing.domComplete - performance.timing.responseEnd, 'load': performance.timing.loadEventEnd - performance.timing.loadEventStart }; /** * Obtaining the transferred kb of resources inluding estimated document size. */ if (window.performance && window.performance.getEntriesByType) { var resource; var resources = window.performance.getEntriesByType('resource'); var documentSize = unescape(encodeURIComponent(document.documentElement.innerHTML)).length / 4.2; var byteTotal = 0; for (var i = 0; i < resources.length; i++) { resource = resources[i]; byteTotal = byteTotal + resource.transferSize; } PerformanceObj.transferbytes = byteTotal + Math.round(documentSize); PerformanceObj.transferrequests = resources.length + 1; } return PerformanceObj; }
javascript
function getPerformanceTimingData() { var PerformanceObj = { 'redirecting': performance.timing.fetchStart - performance.timing.navigationStart, 'dnsconnect': performance.timing.requestStart - performance.timing.fetchStart, 'request': performance.timing.responseStart - performance.timing.requestStart, 'response': performance.timing.responseEnd - performance.timing.responseStart, 'domprocessing': performance.timing.domComplete - performance.timing.responseEnd, 'load': performance.timing.loadEventEnd - performance.timing.loadEventStart }; /** * Obtaining the transferred kb of resources inluding estimated document size. */ if (window.performance && window.performance.getEntriesByType) { var resource; var resources = window.performance.getEntriesByType('resource'); var documentSize = unescape(encodeURIComponent(document.documentElement.innerHTML)).length / 4.2; var byteTotal = 0; for (var i = 0; i < resources.length; i++) { resource = resources[i]; byteTotal = byteTotal + resource.transferSize; } PerformanceObj.transferbytes = byteTotal + Math.round(documentSize); PerformanceObj.transferrequests = resources.length + 1; } return PerformanceObj; }
[ "function", "getPerformanceTimingData", "(", ")", "{", "var", "PerformanceObj", "=", "{", "'redirecting'", ":", "performance", ".", "timing", ".", "fetchStart", "-", "performance", ".", "timing", ".", "navigationStart", ",", "'dnsconnect'", ":", "performance", ".", "timing", ".", "requestStart", "-", "performance", ".", "timing", ".", "fetchStart", ",", "'request'", ":", "performance", ".", "timing", ".", "responseStart", "-", "performance", ".", "timing", ".", "requestStart", ",", "'response'", ":", "performance", ".", "timing", ".", "responseEnd", "-", "performance", ".", "timing", ".", "responseStart", ",", "'domprocessing'", ":", "performance", ".", "timing", ".", "domComplete", "-", "performance", ".", "timing", ".", "responseEnd", ",", "'load'", ":", "performance", ".", "timing", ".", "loadEventEnd", "-", "performance", ".", "timing", ".", "loadEventStart", "}", ";", "/**\n * Obtaining the transferred kb of resources inluding estimated document size.\n */", "if", "(", "window", ".", "performance", "&&", "window", ".", "performance", ".", "getEntriesByType", ")", "{", "var", "resource", ";", "var", "resources", "=", "window", ".", "performance", ".", "getEntriesByType", "(", "'resource'", ")", ";", "var", "documentSize", "=", "unescape", "(", "encodeURIComponent", "(", "document", ".", "documentElement", ".", "innerHTML", ")", ")", ".", "length", "/", "4.2", ";", "var", "byteTotal", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "resources", ".", "length", ";", "i", "++", ")", "{", "resource", "=", "resources", "[", "i", "]", ";", "byteTotal", "=", "byteTotal", "+", "resource", ".", "transferSize", ";", "}", "PerformanceObj", ".", "transferbytes", "=", "byteTotal", "+", "Math", ".", "round", "(", "documentSize", ")", ";", "PerformanceObj", ".", "transferrequests", "=", "resources", ".", "length", "+", "1", ";", "}", "return", "PerformanceObj", ";", "}" ]
Calculating steps in the page loading pipeline. @return {Object} PerformanceObj containg performance metrics
[ "Calculating", "steps", "in", "the", "page", "loading", "pipeline", "." ]
0e018d463107a0b631c317d7bf372aa9e194b7da
https://github.com/ceddl/ceddl-aditional-inputs/blob/0e018d463107a0b631c317d7bf372aa9e194b7da/src/performance-timing.js#L24-L51
48,767
fatalxiao/js-markdown
src/lib/utils/Str.js
at
function at(index) { if (!this) { throw TypeError(); } const str = '' + this, len = str.length; if (index >= len) { return; } if (index < 0) { index = len - index; } let i = 0; for (let item of str) { if (i === index) { return item; } } return; }
javascript
function at(index) { if (!this) { throw TypeError(); } const str = '' + this, len = str.length; if (index >= len) { return; } if (index < 0) { index = len - index; } let i = 0; for (let item of str) { if (i === index) { return item; } } return; }
[ "function", "at", "(", "index", ")", "{", "if", "(", "!", "this", ")", "{", "throw", "TypeError", "(", ")", ";", "}", "const", "str", "=", "''", "+", "this", ",", "len", "=", "str", ".", "length", ";", "if", "(", "index", ">=", "len", ")", "{", "return", ";", "}", "if", "(", "index", "<", "0", ")", "{", "index", "=", "len", "-", "index", ";", "}", "let", "i", "=", "0", ";", "for", "(", "let", "item", "of", "str", ")", "{", "if", "(", "i", "===", "index", ")", "{", "return", "item", ";", "}", "}", "return", ";", "}" ]
String.at polyfill @param index @returns {*}
[ "String", ".", "at", "polyfill" ]
dffa23be561f50282e5ccc2f1595a51d18a81246
https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/utils/Str.js#L10-L35
48,768
fatalxiao/js-markdown
src/lib/utils/Str.js
trimHandle
function trimHandle(str, chars = ' ', position) { if (typeof str !== 'string') { return; } let cs = chars; if (Valid.isArray(chars)) { cs = chars.join(''); } const startReg = new RegExp(`^[${cs}]*`, 'g'), endReg = new RegExp(`[${cs}]*$`, 'g'); if (position === 'start') { return str.replace(startReg, ''); } else if (position === 'end') { return str.replace(endReg, ''); } return str.replace(startReg, '').replace(endReg, ''); }
javascript
function trimHandle(str, chars = ' ', position) { if (typeof str !== 'string') { return; } let cs = chars; if (Valid.isArray(chars)) { cs = chars.join(''); } const startReg = new RegExp(`^[${cs}]*`, 'g'), endReg = new RegExp(`[${cs}]*$`, 'g'); if (position === 'start') { return str.replace(startReg, ''); } else if (position === 'end') { return str.replace(endReg, ''); } return str.replace(startReg, '').replace(endReg, ''); }
[ "function", "trimHandle", "(", "str", ",", "chars", "=", "' '", ",", "position", ")", "{", "if", "(", "typeof", "str", "!==", "'string'", ")", "{", "return", ";", "}", "let", "cs", "=", "chars", ";", "if", "(", "Valid", ".", "isArray", "(", "chars", ")", ")", "{", "cs", "=", "chars", ".", "join", "(", "''", ")", ";", "}", "const", "startReg", "=", "new", "RegExp", "(", "`", "${", "cs", "}", "`", ",", "'g'", ")", ",", "endReg", "=", "new", "RegExp", "(", "`", "${", "cs", "}", "`", ",", "'g'", ")", ";", "if", "(", "position", "===", "'start'", ")", "{", "return", "str", ".", "replace", "(", "startReg", ",", "''", ")", ";", "}", "else", "if", "(", "position", "===", "'end'", ")", "{", "return", "str", ".", "replace", "(", "endReg", ",", "''", ")", ";", "}", "return", "str", ".", "replace", "(", "startReg", ",", "''", ")", ".", "replace", "(", "endReg", ",", "''", ")", ";", "}" ]
string trim handle method @param str @param chars @param position
[ "string", "trim", "handle", "method" ]
dffa23be561f50282e5ccc2f1595a51d18a81246
https://github.com/fatalxiao/js-markdown/blob/dffa23be561f50282e5ccc2f1595a51d18a81246/src/lib/utils/Str.js#L43-L66
48,769
clauswitt/affirm
lib/affirm.js
function(a, length, msg) { return assert((this.assertIsArray(a, msg) && a.length <= length), msg); }
javascript
function(a, length, msg) { return assert((this.assertIsArray(a, msg) && a.length <= length), msg); }
[ "function", "(", "a", ",", "length", ",", "msg", ")", "{", "return", "assert", "(", "(", "this", ".", "assertIsArray", "(", "a", ",", "msg", ")", "&&", "a", ".", "length", "<=", "length", ")", ",", "msg", ")", ";", "}" ]
Assert that the array length is less than or equal to length
[ "Assert", "that", "the", "array", "length", "is", "less", "than", "or", "equal", "to", "length" ]
5eb49ec115896ce195c888bbcf6cf5a5bb17713b
https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L60-L62
48,770
clauswitt/affirm
lib/affirm.js
function(a, length, allowNumbers, msg) { allowNumbers = allowNumbers || true; return assert((this.assertIsString(a, allowNumbers) && a.length <= length), msg); }
javascript
function(a, length, allowNumbers, msg) { allowNumbers = allowNumbers || true; return assert((this.assertIsString(a, allowNumbers) && a.length <= length), msg); }
[ "function", "(", "a", ",", "length", ",", "allowNumbers", ",", "msg", ")", "{", "allowNumbers", "=", "allowNumbers", "||", "true", ";", "return", "assert", "(", "(", "this", ".", "assertIsString", "(", "a", ",", "allowNumbers", ")", "&&", "a", ".", "length", "<=", "length", ")", ",", "msg", ")", ";", "}" ]
Assert that the string length is less than or equal to max
[ "Assert", "that", "the", "string", "length", "is", "less", "than", "or", "equal", "to", "max" ]
5eb49ec115896ce195c888bbcf6cf5a5bb17713b
https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L79-L82
48,771
clauswitt/affirm
lib/affirm.js
function(a, min, max, allowNumbers, msg) { return assert((this.assertStringMinLength(a, min, allowNumbers, msg)&&this.assertStringMaxLength(a, max, allowNumbers, msg)), msg); }
javascript
function(a, min, max, allowNumbers, msg) { return assert((this.assertStringMinLength(a, min, allowNumbers, msg)&&this.assertStringMaxLength(a, max, allowNumbers, msg)), msg); }
[ "function", "(", "a", ",", "min", ",", "max", ",", "allowNumbers", ",", "msg", ")", "{", "return", "assert", "(", "(", "this", ".", "assertStringMinLength", "(", "a", ",", "min", ",", "allowNumbers", ",", "msg", ")", "&&", "this", ".", "assertStringMaxLength", "(", "a", ",", "max", ",", "allowNumbers", ",", "msg", ")", ")", ",", "msg", ")", ";", "}" ]
Assert that the string length is within the range
[ "Assert", "that", "the", "string", "length", "is", "within", "the", "range" ]
5eb49ec115896ce195c888bbcf6cf5a5bb17713b
https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L91-L93
48,772
clauswitt/affirm
lib/affirm.js
function(a, start, msg) { return assert((this.assertIsString(a, msg) && a.indexOf(start)===0), msg); }
javascript
function(a, start, msg) { return assert((this.assertIsString(a, msg) && a.indexOf(start)===0), msg); }
[ "function", "(", "a", ",", "start", ",", "msg", ")", "{", "return", "assert", "(", "(", "this", ".", "assertIsString", "(", "a", ",", "msg", ")", "&&", "a", ".", "indexOf", "(", "start", ")", "===", "0", ")", ",", "msg", ")", ";", "}" ]
Assert that the string string starts with the substring
[ "Assert", "that", "the", "string", "string", "starts", "with", "the", "substring" ]
5eb49ec115896ce195c888bbcf6cf5a5bb17713b
https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L96-L98
48,773
clauswitt/affirm
lib/affirm.js
function(a, end, msg) { return assert((this.assertIsString(a, msg) && a.indexOf(end, a.length - end.length) !== -1), msg); }
javascript
function(a, end, msg) { return assert((this.assertIsString(a, msg) && a.indexOf(end, a.length - end.length) !== -1), msg); }
[ "function", "(", "a", ",", "end", ",", "msg", ")", "{", "return", "assert", "(", "(", "this", ".", "assertIsString", "(", "a", ",", "msg", ")", "&&", "a", ".", "indexOf", "(", "end", ",", "a", ".", "length", "-", "end", ".", "length", ")", "!==", "-", "1", ")", ",", "msg", ")", ";", "}" ]
Assert that the string string ends with the substring
[ "Assert", "that", "the", "string", "string", "ends", "with", "the", "substring" ]
5eb49ec115896ce195c888bbcf6cf5a5bb17713b
https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L101-L103
48,774
clauswitt/affirm
lib/affirm.js
function(value, assertionObject) { for(var name in assertionObject) { if (assertionObject.hasOwnProperty(name)) { args = [value]; args = args.concat(assertionObject[name]); this[name].apply(this, args); } } }
javascript
function(value, assertionObject) { for(var name in assertionObject) { if (assertionObject.hasOwnProperty(name)) { args = [value]; args = args.concat(assertionObject[name]); this[name].apply(this, args); } } }
[ "function", "(", "value", ",", "assertionObject", ")", "{", "for", "(", "var", "name", "in", "assertionObject", ")", "{", "if", "(", "assertionObject", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "args", "=", "[", "value", "]", ";", "args", "=", "args", ".", "concat", "(", "assertionObject", "[", "name", "]", ")", ";", "this", "[", "name", "]", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "}", "}" ]
Run a series of assertions
[ "Run", "a", "series", "of", "assertions" ]
5eb49ec115896ce195c888bbcf6cf5a5bb17713b
https://github.com/clauswitt/affirm/blob/5eb49ec115896ce195c888bbcf6cf5a5bb17713b/lib/affirm.js#L116-L124
48,775
deliciousinsights/fb-flo-brunch
index.js
FbFloBrunch
function FbFloBrunch(config) { this.setOptions(config); // This plugin only makes sense if we're in watcher mode // (`config.persistent`). Also, we honor the plugin-specific `enabled` // setting, so users don't need to strip the plugin or its config to // disable it: just set `enabled` to `false`. if (!config || !config.persistent || false === this.config.enabled) { return; } this.resolver = this.resolver.bind(this); this.startServer(); }
javascript
function FbFloBrunch(config) { this.setOptions(config); // This plugin only makes sense if we're in watcher mode // (`config.persistent`). Also, we honor the plugin-specific `enabled` // setting, so users don't need to strip the plugin or its config to // disable it: just set `enabled` to `false`. if (!config || !config.persistent || false === this.config.enabled) { return; } this.resolver = this.resolver.bind(this); this.startServer(); }
[ "function", "FbFloBrunch", "(", "config", ")", "{", "this", ".", "setOptions", "(", "config", ")", ";", "// This plugin only makes sense if we're in watcher mode", "// (`config.persistent`). Also, we honor the plugin-specific `enabled`", "// setting, so users don't need to strip the plugin or its config to", "// disable it: just set `enabled` to `false`.", "if", "(", "!", "config", "||", "!", "config", ".", "persistent", "||", "false", "===", "this", ".", "config", ".", "enabled", ")", "{", "return", ";", "}", "this", ".", "resolver", "=", "this", ".", "resolver", ".", "bind", "(", "this", ")", ";", "this", ".", "startServer", "(", ")", ";", "}" ]
Plugin constructor. Takes Brunch's complete config as argument.
[ "Plugin", "constructor", ".", "Takes", "Brunch", "s", "complete", "config", "as", "argument", "." ]
88249d1b1c40fd2df69714ab01a77ab26a010581
https://github.com/deliciousinsights/fb-flo-brunch/blob/88249d1b1c40fd2df69714ab01a77ab26a010581/index.js#L19-L32
48,776
deliciousinsights/fb-flo-brunch
index.js
resolver
function resolver(filePath, callback) { var fullPath = path.join(this.config.publicPath, filePath); var options = { resourceURL: filePath, contents: fs.readFileSync(fullPath).toString() }; // If we defined a custom browser-side message system, use it. if (this.update) { options.update = this.update; } // If we specified a `match` option for fb-flo notifications, use it. if (this.config.resolverMatch) { options.match = this.config.resolverMatch; } // If we defined an advanced reload mechanism (fb-flo only has true/false, // we also allow anymatch sets), use it. if (this.config.resolverReload) { options.reload = this.config.resolverReload(filePath); } // Hand the notification over to the fb-flo server. callback(options); }
javascript
function resolver(filePath, callback) { var fullPath = path.join(this.config.publicPath, filePath); var options = { resourceURL: filePath, contents: fs.readFileSync(fullPath).toString() }; // If we defined a custom browser-side message system, use it. if (this.update) { options.update = this.update; } // If we specified a `match` option for fb-flo notifications, use it. if (this.config.resolverMatch) { options.match = this.config.resolverMatch; } // If we defined an advanced reload mechanism (fb-flo only has true/false, // we also allow anymatch sets), use it. if (this.config.resolverReload) { options.reload = this.config.resolverReload(filePath); } // Hand the notification over to the fb-flo server. callback(options); }
[ "function", "resolver", "(", "filePath", ",", "callback", ")", "{", "var", "fullPath", "=", "path", ".", "join", "(", "this", ".", "config", ".", "publicPath", ",", "filePath", ")", ";", "var", "options", "=", "{", "resourceURL", ":", "filePath", ",", "contents", ":", "fs", ".", "readFileSync", "(", "fullPath", ")", ".", "toString", "(", ")", "}", ";", "// If we defined a custom browser-side message system, use it.", "if", "(", "this", ".", "update", ")", "{", "options", ".", "update", "=", "this", ".", "update", ";", "}", "// If we specified a `match` option for fb-flo notifications, use it.", "if", "(", "this", ".", "config", ".", "resolverMatch", ")", "{", "options", ".", "match", "=", "this", ".", "config", ".", "resolverMatch", ";", "}", "// If we defined an advanced reload mechanism (fb-flo only has true/false,", "// we also allow anymatch sets), use it.", "if", "(", "this", ".", "config", ".", "resolverReload", ")", "{", "options", ".", "reload", "=", "this", ".", "config", ".", "resolverReload", "(", "filePath", ")", ";", "}", "// Hand the notification over to the fb-flo server.", "callback", "(", "options", ")", ";", "}" ]
The fb-flo resolver, triggered everytime fb-flo wants to send a change notification to connected browser extensions.
[ "The", "fb", "-", "flo", "resolver", "triggered", "everytime", "fb", "-", "flo", "wants", "to", "send", "a", "change", "notification", "to", "connected", "browser", "extensions", "." ]
88249d1b1c40fd2df69714ab01a77ab26a010581
https://github.com/deliciousinsights/fb-flo-brunch/blob/88249d1b1c40fd2df69714ab01a77ab26a010581/index.js#L62-L85
48,777
deliciousinsights/fb-flo-brunch
index.js
startServer
function startServer() { this._flo = flo( // The path to watch (see `setOptions(…)`). this.config.publicPath, // The config-provided fb-flo options + a generic watch glob // (all JS/CSS, at any depth) inside the watched path. extend( pick(this.config, FB_FLO_OPTIONS), { glob: ['**/*.js', '**/*.css'] } ), // Our resolver method (it was properly bound upon construction). this.resolver ); }
javascript
function startServer() { this._flo = flo( // The path to watch (see `setOptions(…)`). this.config.publicPath, // The config-provided fb-flo options + a generic watch glob // (all JS/CSS, at any depth) inside the watched path. extend( pick(this.config, FB_FLO_OPTIONS), { glob: ['**/*.js', '**/*.css'] } ), // Our resolver method (it was properly bound upon construction). this.resolver ); }
[ "function", "startServer", "(", ")", "{", "this", ".", "_flo", "=", "flo", "(", "// The path to watch (see `setOptions(…)`).", "this", ".", "config", ".", "publicPath", ",", "// The config-provided fb-flo options + a generic watch glob", "// (all JS/CSS, at any depth) inside the watched path.", "extend", "(", "pick", "(", "this", ".", "config", ",", "FB_FLO_OPTIONS", ")", ",", "{", "glob", ":", "[", "'**/*.js'", ",", "'**/*.css'", "]", "}", ")", ",", "// Our resolver method (it was properly bound upon construction).", "this", ".", "resolver", ")", ";", "}" ]
Starts the fb-flo server. Launched from the constructor unless the plugin is disabled.
[ "Starts", "the", "fb", "-", "flo", "server", ".", "Launched", "from", "the", "constructor", "unless", "the", "plugin", "is", "disabled", "." ]
88249d1b1c40fd2df69714ab01a77ab26a010581
https://github.com/deliciousinsights/fb-flo-brunch/blob/88249d1b1c40fd2df69714ab01a77ab26a010581/index.js#L137-L150
48,778
yashprit/is-float
index.js
isFloat
function isFloat (n, shouldCoerce) { if (shouldCoerce) { if (typeof n === "string") { n = parseFloat(n); } } return n === +n && n !== (n|0); }
javascript
function isFloat (n, shouldCoerce) { if (shouldCoerce) { if (typeof n === "string") { n = parseFloat(n); } } return n === +n && n !== (n|0); }
[ "function", "isFloat", "(", "n", ",", "shouldCoerce", ")", "{", "if", "(", "shouldCoerce", ")", "{", "if", "(", "typeof", "n", "===", "\"string\"", ")", "{", "n", "=", "parseFloat", "(", "n", ")", ";", "}", "}", "return", "n", "===", "+", "n", "&&", "n", "!==", "(", "n", "|", "0", ")", ";", "}" ]
Check argument is float or not @param {number} n @param {Boolean} shouldCoerce @return {Boolean} true if it's a float
[ "Check", "argument", "is", "float", "or", "not" ]
8e22fbeaa4913dae87918064b6f03eafdd36eff8
https://github.com/yashprit/is-float/blob/8e22fbeaa4913dae87918064b6f03eafdd36eff8/index.js#L9-L17
48,779
jeanamarante/catena
tasks/deploy/minify.js
writeExterns
function writeExterns (grunt, fileData, options) { let content = ''; // Default externs. content += 'var require = function () {};'; for (let i = 0, max = options.externs.length; i < max; i++) { content += `var ${options.externs[i]} = {};`; } grunt.file.write(fileData.tmpExterns, content); }
javascript
function writeExterns (grunt, fileData, options) { let content = ''; // Default externs. content += 'var require = function () {};'; for (let i = 0, max = options.externs.length; i < max; i++) { content += `var ${options.externs[i]} = {};`; } grunt.file.write(fileData.tmpExterns, content); }
[ "function", "writeExterns", "(", "grunt", ",", "fileData", ",", "options", ")", "{", "let", "content", "=", "''", ";", "// Default externs.", "content", "+=", "'var require = function () {};'", ";", "for", "(", "let", "i", "=", "0", ",", "max", "=", "options", ".", "externs", ".", "length", ";", "i", "<", "max", ";", "i", "++", ")", "{", "content", "+=", "`", "${", "options", ".", "externs", "[", "i", "]", "}", "`", ";", "}", "grunt", ".", "file", ".", "write", "(", "fileData", ".", "tmpExterns", ",", "content", ")", ";", "}" ]
Concatenate each extern as a variable declaration that points to an empty object. Externs are used to prevent the closure compiler from complaining about undeclared variables and renaming those variables. @function writeExterns @param {Object} grunt @param {Object} fileData @param {Object} options @api private
[ "Concatenate", "each", "extern", "as", "a", "variable", "declaration", "that", "points", "to", "an", "empty", "object", ".", "Externs", "are", "used", "to", "prevent", "the", "closure", "compiler", "from", "complaining", "about", "undeclared", "variables", "and", "renaming", "those", "variables", "." ]
c7762332f71c0fd7cfafba8d1e3cd66053529954
https://github.com/jeanamarante/catena/blob/c7762332f71c0fd7cfafba8d1e3cd66053529954/tasks/deploy/minify.js#L21-L32
48,780
Chris911/mocha-http-detect
src/index.js
printHostnames
function printHostnames() { console.log(chalk.yellow.bold(`${indent(2)} Hostnames requested: `)); if (Object.keys(hostnames).length === 0) { console.log(chalk.yellow(`${indent(4)}none`)); return; } for (const key in hostnames) { if (!hostnames[key]) return; console.log(chalk.yellow(`${indent(4)}${key}: ${hostnames[key]}`)); } }
javascript
function printHostnames() { console.log(chalk.yellow.bold(`${indent(2)} Hostnames requested: `)); if (Object.keys(hostnames).length === 0) { console.log(chalk.yellow(`${indent(4)}none`)); return; } for (const key in hostnames) { if (!hostnames[key]) return; console.log(chalk.yellow(`${indent(4)}${key}: ${hostnames[key]}`)); } }
[ "function", "printHostnames", "(", ")", "{", "console", ".", "log", "(", "chalk", ".", "yellow", ".", "bold", "(", "`", "${", "indent", "(", "2", ")", "}", "`", ")", ")", ";", "if", "(", "Object", ".", "keys", "(", "hostnames", ")", ".", "length", "===", "0", ")", "{", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "`", "${", "indent", "(", "4", ")", "}", "`", ")", ")", ";", "return", ";", "}", "for", "(", "const", "key", "in", "hostnames", ")", "{", "if", "(", "!", "hostnames", "[", "key", "]", ")", "return", ";", "console", ".", "log", "(", "chalk", ".", "yellow", "(", "`", "${", "indent", "(", "4", ")", "}", "${", "key", "}", "${", "hostnames", "[", "key", "]", "}", "`", ")", ")", ";", "}", "}" ]
Print requested hostnames summary.
[ "Print", "requested", "hostnames", "summary", "." ]
61e90d5d9478255844452bef0fe1a957cd2abdab
https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L39-L51
48,781
Chris911/mocha-http-detect
src/index.js
patchMocha
function patchMocha() { const _testRun = Mocha.Test.prototype.run; Mocha.Test.prototype.run = function (fn) { function done(ctx) { fn.call(this, ctx); if (testRequests.length) { printTestRequest(testRequests); testRequests = []; } } return _testRun.call(this, done); }; const _run = Mocha.prototype.run; Mocha.prototype.run = function(fn) { function done(failures) { printHostnames(hostnames); fn.call(this, failures); } return _run.call(this, done); }; }
javascript
function patchMocha() { const _testRun = Mocha.Test.prototype.run; Mocha.Test.prototype.run = function (fn) { function done(ctx) { fn.call(this, ctx); if (testRequests.length) { printTestRequest(testRequests); testRequests = []; } } return _testRun.call(this, done); }; const _run = Mocha.prototype.run; Mocha.prototype.run = function(fn) { function done(failures) { printHostnames(hostnames); fn.call(this, failures); } return _run.call(this, done); }; }
[ "function", "patchMocha", "(", ")", "{", "const", "_testRun", "=", "Mocha", ".", "Test", ".", "prototype", ".", "run", ";", "Mocha", ".", "Test", ".", "prototype", ".", "run", "=", "function", "(", "fn", ")", "{", "function", "done", "(", "ctx", ")", "{", "fn", ".", "call", "(", "this", ",", "ctx", ")", ";", "if", "(", "testRequests", ".", "length", ")", "{", "printTestRequest", "(", "testRequests", ")", ";", "testRequests", "=", "[", "]", ";", "}", "}", "return", "_testRun", ".", "call", "(", "this", ",", "done", ")", ";", "}", ";", "const", "_run", "=", "Mocha", ".", "prototype", ".", "run", ";", "Mocha", ".", "prototype", ".", "run", "=", "function", "(", "fn", ")", "{", "function", "done", "(", "failures", ")", "{", "printHostnames", "(", "hostnames", ")", ";", "fn", ".", "call", "(", "this", ",", "failures", ")", ";", "}", "return", "_run", ".", "call", "(", "this", ",", "done", ")", ";", "}", ";", "}" ]
Patch mocha to display recording requests during individual tests and at the end of the test suite.
[ "Patch", "mocha", "to", "display", "recording", "requests", "during", "individual", "tests", "and", "at", "the", "end", "of", "the", "test", "suite", "." ]
61e90d5d9478255844452bef0fe1a957cd2abdab
https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L57-L83
48,782
Chris911/mocha-http-detect
src/index.js
getHostname
function getHostname(httpOptions) { if (httpOptions.uri && httpOptions.uri.hostname) { return httpOptions.uri.hostname; } else if (httpOptions.hostname) { return httpOptions.hostname; } else if (httpOptions.host) { return httpOptions.host; } return 'Unknown'; }
javascript
function getHostname(httpOptions) { if (httpOptions.uri && httpOptions.uri.hostname) { return httpOptions.uri.hostname; } else if (httpOptions.hostname) { return httpOptions.hostname; } else if (httpOptions.host) { return httpOptions.host; } return 'Unknown'; }
[ "function", "getHostname", "(", "httpOptions", ")", "{", "if", "(", "httpOptions", ".", "uri", "&&", "httpOptions", ".", "uri", ".", "hostname", ")", "{", "return", "httpOptions", ".", "uri", ".", "hostname", ";", "}", "else", "if", "(", "httpOptions", ".", "hostname", ")", "{", "return", "httpOptions", ".", "hostname", ";", "}", "else", "if", "(", "httpOptions", ".", "host", ")", "{", "return", "httpOptions", ".", "host", ";", "}", "return", "'Unknown'", ";", "}" ]
Get the hostname from an HTTP options object. Supports multiple types of options. @param {object} httpOptions @return {string} the hostname or "Unknown" if not found.
[ "Get", "the", "hostname", "from", "an", "HTTP", "options", "object", ".", "Supports", "multiple", "types", "of", "options", "." ]
61e90d5d9478255844452bef0fe1a957cd2abdab
https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L91-L100
48,783
Chris911/mocha-http-detect
src/index.js
getHref
function getHref(httpOptions) { if (httpOptions.uri && httpOptions.uri.href) { return httpOptions.uri.href; } else if (httpOptions.hostname && httpOptions.path) { return httpOptions.hostname + httpOptions.path; } else if (httpOptions.host && httpOptions.path) { return httpOptions.host + httpOptions.path; } return 'Unknown'; }
javascript
function getHref(httpOptions) { if (httpOptions.uri && httpOptions.uri.href) { return httpOptions.uri.href; } else if (httpOptions.hostname && httpOptions.path) { return httpOptions.hostname + httpOptions.path; } else if (httpOptions.host && httpOptions.path) { return httpOptions.host + httpOptions.path; } return 'Unknown'; }
[ "function", "getHref", "(", "httpOptions", ")", "{", "if", "(", "httpOptions", ".", "uri", "&&", "httpOptions", ".", "uri", ".", "href", ")", "{", "return", "httpOptions", ".", "uri", ".", "href", ";", "}", "else", "if", "(", "httpOptions", ".", "hostname", "&&", "httpOptions", ".", "path", ")", "{", "return", "httpOptions", ".", "hostname", "+", "httpOptions", ".", "path", ";", "}", "else", "if", "(", "httpOptions", ".", "host", "&&", "httpOptions", ".", "path", ")", "{", "return", "httpOptions", ".", "host", "+", "httpOptions", ".", "path", ";", "}", "return", "'Unknown'", ";", "}" ]
Get the href from an HTTP options objet. Supports multiple types of options. @param {object} httpOptions @return {string} the hostname or "Unknown" if not found.
[ "Get", "the", "href", "from", "an", "HTTP", "options", "objet", ".", "Supports", "multiple", "types", "of", "options", "." ]
61e90d5d9478255844452bef0fe1a957cd2abdab
https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L108-L117
48,784
Chris911/mocha-http-detect
src/index.js
patchHttpClient
function patchHttpClient() { const _ClientRequest = http.ClientRequest; function patchedHttpClient(options, done) { if (http.OutgoingMessage) http.OutgoingMessage.call(this); const hostname = getHostname(options); // Ignore localhost requests if (hostname.indexOf('127.0.0.1') === -1 && hostname.indexOf('localhost') === -1) { if (hostnames[hostname]) { hostnames[hostname]++; } else { hostnames[hostname] = 1; } testRequests.push(getHref(options)); } _ClientRequest.call(this, options, done); } if (http.ClientRequest) { inherits(patchedHttpClient, _ClientRequest); } else { inherits(patchedHttpClient, EventEmitter); } http.ClientRequest = patchedHttpClient; http.request = function(options, done) { return new http.ClientRequest(options, done); }; }
javascript
function patchHttpClient() { const _ClientRequest = http.ClientRequest; function patchedHttpClient(options, done) { if (http.OutgoingMessage) http.OutgoingMessage.call(this); const hostname = getHostname(options); // Ignore localhost requests if (hostname.indexOf('127.0.0.1') === -1 && hostname.indexOf('localhost') === -1) { if (hostnames[hostname]) { hostnames[hostname]++; } else { hostnames[hostname] = 1; } testRequests.push(getHref(options)); } _ClientRequest.call(this, options, done); } if (http.ClientRequest) { inherits(patchedHttpClient, _ClientRequest); } else { inherits(patchedHttpClient, EventEmitter); } http.ClientRequest = patchedHttpClient; http.request = function(options, done) { return new http.ClientRequest(options, done); }; }
[ "function", "patchHttpClient", "(", ")", "{", "const", "_ClientRequest", "=", "http", ".", "ClientRequest", ";", "function", "patchedHttpClient", "(", "options", ",", "done", ")", "{", "if", "(", "http", ".", "OutgoingMessage", ")", "http", ".", "OutgoingMessage", ".", "call", "(", "this", ")", ";", "const", "hostname", "=", "getHostname", "(", "options", ")", ";", "// Ignore localhost requests", "if", "(", "hostname", ".", "indexOf", "(", "'127.0.0.1'", ")", "===", "-", "1", "&&", "hostname", ".", "indexOf", "(", "'localhost'", ")", "===", "-", "1", ")", "{", "if", "(", "hostnames", "[", "hostname", "]", ")", "{", "hostnames", "[", "hostname", "]", "++", ";", "}", "else", "{", "hostnames", "[", "hostname", "]", "=", "1", ";", "}", "testRequests", ".", "push", "(", "getHref", "(", "options", ")", ")", ";", "}", "_ClientRequest", ".", "call", "(", "this", ",", "options", ",", "done", ")", ";", "}", "if", "(", "http", ".", "ClientRequest", ")", "{", "inherits", "(", "patchedHttpClient", ",", "_ClientRequest", ")", ";", "}", "else", "{", "inherits", "(", "patchedHttpClient", ",", "EventEmitter", ")", ";", "}", "http", ".", "ClientRequest", "=", "patchedHttpClient", ";", "http", ".", "request", "=", "function", "(", "options", ",", "done", ")", "{", "return", "new", "http", ".", "ClientRequest", "(", "options", ",", "done", ")", ";", "}", ";", "}" ]
Patch Node's HTTP client to record external HTTP calls. - All hostnames are stored in `hostname` with their count for the whole test suite. - Full request URLs are stores in `testRequests` and used to display recorded requests for individual tests. - Requests to localhost are ignored.
[ "Patch", "Node", "s", "HTTP", "client", "to", "record", "external", "HTTP", "calls", ".", "-", "All", "hostnames", "are", "stored", "in", "hostname", "with", "their", "count", "for", "the", "whole", "test", "suite", ".", "-", "Full", "request", "URLs", "are", "stores", "in", "testRequests", "and", "used", "to", "display", "recorded", "requests", "for", "individual", "tests", ".", "-", "Requests", "to", "localhost", "are", "ignored", "." ]
61e90d5d9478255844452bef0fe1a957cd2abdab
https://github.com/Chris911/mocha-http-detect/blob/61e90d5d9478255844452bef0fe1a957cd2abdab/src/index.js#L127-L160
48,785
anseki/pre-proc
lib/pre-proc.js
isTargetPath
function isTargetPath(srcPath, pathTest) { return !srcPath || (Array.isArray(pathTest) ? pathTest : [pathTest]).some(function(test) { return test && (test instanceof RegExp ? test.test(srcPath) : srcPath.indexOf(test) === 0); }); }
javascript
function isTargetPath(srcPath, pathTest) { return !srcPath || (Array.isArray(pathTest) ? pathTest : [pathTest]).some(function(test) { return test && (test instanceof RegExp ? test.test(srcPath) : srcPath.indexOf(test) === 0); }); }
[ "function", "isTargetPath", "(", "srcPath", ",", "pathTest", ")", "{", "return", "!", "srcPath", "||", "(", "Array", ".", "isArray", "(", "pathTest", ")", "?", "pathTest", ":", "[", "pathTest", "]", ")", ".", "some", "(", "function", "(", "test", ")", "{", "return", "test", "&&", "(", "test", "instanceof", "RegExp", "?", "test", ".", "test", "(", "srcPath", ")", ":", "srcPath", ".", "indexOf", "(", "test", ")", "===", "0", ")", ";", "}", ")", ";", "}" ]
Test whether a path is target. @param {string} [srcPath] - A full path. @param {(string|RegExp|Array)} [pathTest] - A string which must be at the start, a RegExp which tests or an array. @returns {boolean} `true` if the `srcPath` is target, or `srcPath` is omitted.
[ "Test", "whether", "a", "path", "is", "target", "." ]
7b6814bd50df64cce98048736cba2eade755fad5
https://github.com/anseki/pre-proc/blob/7b6814bd50df64cce98048736cba2eade755fad5/lib/pre-proc.js#L17-L22
48,786
bernardodiasc/filestojson
examples/config.js
posts
function posts (content, contentType) { let output = {} const allFiles = content.filter(each => each.dir.includes(`/${contentType}`)) const index = allFiles.filter(each => each.base === 'index.md')[0] index.attr.forEach(each => { allFiles.forEach(file => { if (file.name === each) { output[each] = file } }) }) return output }
javascript
function posts (content, contentType) { let output = {} const allFiles = content.filter(each => each.dir.includes(`/${contentType}`)) const index = allFiles.filter(each => each.base === 'index.md')[0] index.attr.forEach(each => { allFiles.forEach(file => { if (file.name === each) { output[each] = file } }) }) return output }
[ "function", "posts", "(", "content", ",", "contentType", ")", "{", "let", "output", "=", "{", "}", "const", "allFiles", "=", "content", ".", "filter", "(", "each", "=>", "each", ".", "dir", ".", "includes", "(", "`", "${", "contentType", "}", "`", ")", ")", "const", "index", "=", "allFiles", ".", "filter", "(", "each", "=>", "each", ".", "base", "===", "'index.md'", ")", "[", "0", "]", "index", ".", "attr", ".", "forEach", "(", "each", "=>", "{", "allFiles", ".", "forEach", "(", "file", "=>", "{", "if", "(", "file", ".", "name", "===", "each", ")", "{", "output", "[", "each", "]", "=", "file", "}", "}", ")", "}", ")", "return", "output", "}" ]
Posts content type translation @param {Array} content List of files @param {String} contentType Content type name @return {Object} The posts content type data object
[ "Posts", "content", "type", "translation" ]
4ccd4454d1fe0408001b1f9f57ed89d19e38256e
https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/examples/config.js#L9-L21
48,787
bernardodiasc/filestojson
examples/config.js
gallery
function gallery (content, contentType) { let output = {} const allFiles = content.filter(each => each.dir.includes(`/${contentType}`)) const index = allFiles.filter(each => each.base === 'index.md')[0] index.attr.forEach(each => { Object.keys(each).forEach(key => { output[key] = Object.assign({ title: each[key] }, allFiles.filter(file => file.name === key)[0]) }) }) return output }
javascript
function gallery (content, contentType) { let output = {} const allFiles = content.filter(each => each.dir.includes(`/${contentType}`)) const index = allFiles.filter(each => each.base === 'index.md')[0] index.attr.forEach(each => { Object.keys(each).forEach(key => { output[key] = Object.assign({ title: each[key] }, allFiles.filter(file => file.name === key)[0]) }) }) return output }
[ "function", "gallery", "(", "content", ",", "contentType", ")", "{", "let", "output", "=", "{", "}", "const", "allFiles", "=", "content", ".", "filter", "(", "each", "=>", "each", ".", "dir", ".", "includes", "(", "`", "${", "contentType", "}", "`", ")", ")", "const", "index", "=", "allFiles", ".", "filter", "(", "each", "=>", "each", ".", "base", "===", "'index.md'", ")", "[", "0", "]", "index", ".", "attr", ".", "forEach", "(", "each", "=>", "{", "Object", ".", "keys", "(", "each", ")", ".", "forEach", "(", "key", "=>", "{", "output", "[", "key", "]", "=", "Object", ".", "assign", "(", "{", "title", ":", "each", "[", "key", "]", "}", ",", "allFiles", ".", "filter", "(", "file", "=>", "file", ".", "name", "===", "key", ")", "[", "0", "]", ")", "}", ")", "}", ")", "return", "output", "}" ]
Gallery content type translation @param {Array} content List of files @param {String} contentType Content type name @return {Object} The gallery content type data object
[ "Gallery", "content", "type", "translation" ]
4ccd4454d1fe0408001b1f9f57ed89d19e38256e
https://github.com/bernardodiasc/filestojson/blob/4ccd4454d1fe0408001b1f9f57ed89d19e38256e/examples/config.js#L29-L39
48,788
tianjianchn/javascript-packages
packages/frm/src/builder.js
activateField
function activateField(model, fields) { let activeFields = []; if (fields === true) { // activate all return Object.keys(model.def.fields); } else if (Array.isArray(fields)) { activeFields = fields; } else if (typeof fields === 'string') { if (fields.indexOf('*') >= 0) { // activate all activeFields = Object.keys(model.def.fields); } else { activeFields = fields.trim().split(/\s*,\s*/); } } if (activeFields.length <= 0) throw new QueryError(model.name, 'fields required in find'); // activate the related fields return Object.keys(activateRelatedFields(model, activeFields)); }
javascript
function activateField(model, fields) { let activeFields = []; if (fields === true) { // activate all return Object.keys(model.def.fields); } else if (Array.isArray(fields)) { activeFields = fields; } else if (typeof fields === 'string') { if (fields.indexOf('*') >= 0) { // activate all activeFields = Object.keys(model.def.fields); } else { activeFields = fields.trim().split(/\s*,\s*/); } } if (activeFields.length <= 0) throw new QueryError(model.name, 'fields required in find'); // activate the related fields return Object.keys(activateRelatedFields(model, activeFields)); }
[ "function", "activateField", "(", "model", ",", "fields", ")", "{", "let", "activeFields", "=", "[", "]", ";", "if", "(", "fields", "===", "true", ")", "{", "// activate all", "return", "Object", ".", "keys", "(", "model", ".", "def", ".", "fields", ")", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "fields", ")", ")", "{", "activeFields", "=", "fields", ";", "}", "else", "if", "(", "typeof", "fields", "===", "'string'", ")", "{", "if", "(", "fields", ".", "indexOf", "(", "'*'", ")", ">=", "0", ")", "{", "// activate all", "activeFields", "=", "Object", ".", "keys", "(", "model", ".", "def", ".", "fields", ")", ";", "}", "else", "{", "activeFields", "=", "fields", ".", "trim", "(", ")", ".", "split", "(", "/", "\\s*,\\s*", "/", ")", ";", "}", "}", "if", "(", "activeFields", ".", "length", "<=", "0", ")", "throw", "new", "QueryError", "(", "model", ".", "name", ",", "'fields required in find'", ")", ";", "// activate the related fields", "return", "Object", ".", "keys", "(", "activateRelatedFields", "(", "model", ",", "activeFields", ")", ")", ";", "}" ]
parse the active fields, which will be used as select field list in sql statement
[ "parse", "the", "active", "fields", "which", "will", "be", "used", "as", "select", "field", "list", "in", "sql", "statement" ]
3abe85edbfe323939c84c1d02128d74d6374bcde
https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/frm/src/builder.js#L217-L234
48,789
tianjianchn/javascript-packages
packages/frm/src/builder.js
cfv
function cfv(model, set) { const cvs = {};// column values for (const fieldName in set) { const field = model.def.fields[fieldName]; if (!field || field.props.category !== 'entity') continue; const value = set[fieldName]; cvs[field.props.column] = value; } return cvs; }
javascript
function cfv(model, set) { const cvs = {};// column values for (const fieldName in set) { const field = model.def.fields[fieldName]; if (!field || field.props.category !== 'entity') continue; const value = set[fieldName]; cvs[field.props.column] = value; } return cvs; }
[ "function", "cfv", "(", "model", ",", "set", ")", "{", "const", "cvs", "=", "{", "}", ";", "// column values", "for", "(", "const", "fieldName", "in", "set", ")", "{", "const", "field", "=", "model", ".", "def", ".", "fields", "[", "fieldName", "]", ";", "if", "(", "!", "field", "||", "field", ".", "props", ".", "category", "!==", "'entity'", ")", "continue", ";", "const", "value", "=", "set", "[", "fieldName", "]", ";", "cvs", "[", "field", ".", "props", ".", "column", "]", "=", "value", ";", "}", "return", "cvs", ";", "}" ]
convert the field to table column
[ "convert", "the", "field", "to", "table", "column" ]
3abe85edbfe323939c84c1d02128d74d6374bcde
https://github.com/tianjianchn/javascript-packages/blob/3abe85edbfe323939c84c1d02128d74d6374bcde/packages/frm/src/builder.js#L460-L470
48,790
krzystof/possible-states
lib/index.js
zip
function zip(keys, values) { if (keys.length !== values.length) { throw Error(`Incorrect number of arguments, expected: ${keys.length}, arguments received: ${values.join(', ')}`) } return keys.reduce((all, key, idx) => ({...all, [key]: values[idx]}), {}) }
javascript
function zip(keys, values) { if (keys.length !== values.length) { throw Error(`Incorrect number of arguments, expected: ${keys.length}, arguments received: ${values.join(', ')}`) } return keys.reduce((all, key, idx) => ({...all, [key]: values[idx]}), {}) }
[ "function", "zip", "(", "keys", ",", "values", ")", "{", "if", "(", "keys", ".", "length", "!==", "values", ".", "length", ")", "{", "throw", "Error", "(", "`", "${", "keys", ".", "length", "}", "${", "values", ".", "join", "(", "', '", ")", "}", "`", ")", "}", "return", "keys", ".", "reduce", "(", "(", "all", ",", "key", ",", "idx", ")", "=>", "(", "{", "...", "all", ",", "[", "key", "]", ":", "values", "[", "idx", "]", "}", ")", ",", "{", "}", ")", "}" ]
Zip two arrays together, combining the keys of the first with the values of the second one.
[ "Zip", "two", "arrays", "together", "combining", "the", "keys", "of", "the", "first", "with", "the", "values", "of", "the", "second", "one", "." ]
f7248da30dbec056447f11c2e9c5bc36526afaac
https://github.com/krzystof/possible-states/blob/f7248da30dbec056447f11c2e9c5bc36526afaac/lib/index.js#L5-L11
48,791
krzystof/possible-states
lib/index.js
PossibleStatesContainer
function PossibleStatesContainer({current, allStates, data}) { return { caseOf(clauses) { const casesCovered = Object.keys(clauses) const notCovered = allStates.map(({name}) => name).filter(state => !casesCovered.includes(state)) if (notCovered.length > 0 && !casesCovered.includes('_')) { throw Error('All cases are not covered in a "caseOf" clause') } const cb = clauses[current.name] || clauses['_'] return cb instanceof Function ? cb(data) : cb }, current() { return current.name }, data() { return {...data} }, ...generateTransitionHelpers(current, allStates), ...generateWhenAndNotHelpers(current, data, allStates), } }
javascript
function PossibleStatesContainer({current, allStates, data}) { return { caseOf(clauses) { const casesCovered = Object.keys(clauses) const notCovered = allStates.map(({name}) => name).filter(state => !casesCovered.includes(state)) if (notCovered.length > 0 && !casesCovered.includes('_')) { throw Error('All cases are not covered in a "caseOf" clause') } const cb = clauses[current.name] || clauses['_'] return cb instanceof Function ? cb(data) : cb }, current() { return current.name }, data() { return {...data} }, ...generateTransitionHelpers(current, allStates), ...generateWhenAndNotHelpers(current, data, allStates), } }
[ "function", "PossibleStatesContainer", "(", "{", "current", ",", "allStates", ",", "data", "}", ")", "{", "return", "{", "caseOf", "(", "clauses", ")", "{", "const", "casesCovered", "=", "Object", ".", "keys", "(", "clauses", ")", "const", "notCovered", "=", "allStates", ".", "map", "(", "(", "{", "name", "}", ")", "=>", "name", ")", ".", "filter", "(", "state", "=>", "!", "casesCovered", ".", "includes", "(", "state", ")", ")", "if", "(", "notCovered", ".", "length", ">", "0", "&&", "!", "casesCovered", ".", "includes", "(", "'_'", ")", ")", "{", "throw", "Error", "(", "'All cases are not covered in a \"caseOf\" clause'", ")", "}", "const", "cb", "=", "clauses", "[", "current", ".", "name", "]", "||", "clauses", "[", "'_'", "]", "return", "cb", "instanceof", "Function", "?", "cb", "(", "data", ")", ":", "cb", "}", ",", "current", "(", ")", "{", "return", "current", ".", "name", "}", ",", "data", "(", ")", "{", "return", "{", "...", "data", "}", "}", ",", "...", "generateTransitionHelpers", "(", "current", ",", "allStates", ")", ",", "...", "generateWhenAndNotHelpers", "(", "current", ",", "data", ",", "allStates", ")", ",", "}", "}" ]
The main data structure passed to the clients.
[ "The", "main", "data", "structure", "passed", "to", "the", "clients", "." ]
f7248da30dbec056447f11c2e9c5bc36526afaac
https://github.com/krzystof/possible-states/blob/f7248da30dbec056447f11c2e9c5bc36526afaac/lib/index.js#L68-L94
48,792
krzystof/possible-states
lib/index.js
PossibleStates
function PossibleStates(...allStates) { if (!allStates.length === 0) { throw Error('No values passed when constructing a new PossibleStates') } const containsData = typeDefinition => typeDefinition.match(/<.*>/) if (allStates[0].match(/<.*>/)) { throw Error('The initial state cannot contain data') } const parsedStates = allStates.map(state => { if (!containsData(state)) { return {name: state, data: []} } const [name, typeDefs] = state.match(/^(.*)<(.*)>$/).slice(1) return {name, data: typeDefs.split(',').map(def => def.trim())} }) return PossibleStatesContainer({current: parsedStates[0], allStates: parsedStates}) }
javascript
function PossibleStates(...allStates) { if (!allStates.length === 0) { throw Error('No values passed when constructing a new PossibleStates') } const containsData = typeDefinition => typeDefinition.match(/<.*>/) if (allStates[0].match(/<.*>/)) { throw Error('The initial state cannot contain data') } const parsedStates = allStates.map(state => { if (!containsData(state)) { return {name: state, data: []} } const [name, typeDefs] = state.match(/^(.*)<(.*)>$/).slice(1) return {name, data: typeDefs.split(',').map(def => def.trim())} }) return PossibleStatesContainer({current: parsedStates[0], allStates: parsedStates}) }
[ "function", "PossibleStates", "(", "...", "allStates", ")", "{", "if", "(", "!", "allStates", ".", "length", "===", "0", ")", "{", "throw", "Error", "(", "'No values passed when constructing a new PossibleStates'", ")", "}", "const", "containsData", "=", "typeDefinition", "=>", "typeDefinition", ".", "match", "(", "/", "<.*>", "/", ")", "if", "(", "allStates", "[", "0", "]", ".", "match", "(", "/", "<.*>", "/", ")", ")", "{", "throw", "Error", "(", "'The initial state cannot contain data'", ")", "}", "const", "parsedStates", "=", "allStates", ".", "map", "(", "state", "=>", "{", "if", "(", "!", "containsData", "(", "state", ")", ")", "{", "return", "{", "name", ":", "state", ",", "data", ":", "[", "]", "}", "}", "const", "[", "name", ",", "typeDefs", "]", "=", "state", ".", "match", "(", "/", "^(.*)<(.*)>$", "/", ")", ".", "slice", "(", "1", ")", "return", "{", "name", ",", "data", ":", "typeDefs", ".", "split", "(", "','", ")", ".", "map", "(", "def", "=>", "def", ".", "trim", "(", ")", ")", "}", "}", ")", "return", "PossibleStatesContainer", "(", "{", "current", ":", "parsedStates", "[", "0", "]", ",", "allStates", ":", "parsedStates", "}", ")", "}" ]
A function to parse the users definition and create the corresponding Container. The only exposed function to users.
[ "A", "function", "to", "parse", "the", "users", "definition", "and", "create", "the", "corresponding", "Container", ".", "The", "only", "exposed", "function", "to", "users", "." ]
f7248da30dbec056447f11c2e9c5bc36526afaac
https://github.com/krzystof/possible-states/blob/f7248da30dbec056447f11c2e9c5bc36526afaac/lib/index.js#L101-L123
48,793
adekom/decitectural
index.js
function(architectural, units, precision) { if (typeof architectural !== "string" && !(architectural instanceof String)) return false; if(architectural.match(/^(([0-9]+)\')?([-\s])*((([0-9]+\")([-\s])*|([0-9]*)([-\s]*)([0-9]+)(\/{1})([0-9]+\")))?$/g) === null) return false; if(["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision) < 0) return false; if(["inches", "feet"].indexOf(units) < 0) return false; var decimal = 0; var feet = architectural.match(/^([0-9]+)\'[-\s]*/); if(feet !== null) decimal += parseInt(feet[1]) * 12; var inches = architectural.match(/([-\s\']+([0-9]+)|^([0-9]+))[-\s\"]+/); if(inches !== null) { if(feet !== null) decimal += parseInt(inches[2]); else decimal += parseInt(inches[3]); } var fraction = architectural.match(/([-\s\']+([0-9]+\/[0-9]+)|(^[0-9]+\/[0-9]+))\"/); if(fraction !== null) { if(feet !== null || inches !== null) decimal += divideFraction(fraction[2]); else decimal += divideFraction(fraction[3]); } if(units !== "inches") decimal = decimal / 12; decimal = roundNumber(decimal, ["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision)); return decimal; }
javascript
function(architectural, units, precision) { if (typeof architectural !== "string" && !(architectural instanceof String)) return false; if(architectural.match(/^(([0-9]+)\')?([-\s])*((([0-9]+\")([-\s])*|([0-9]*)([-\s]*)([0-9]+)(\/{1})([0-9]+\")))?$/g) === null) return false; if(["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision) < 0) return false; if(["inches", "feet"].indexOf(units) < 0) return false; var decimal = 0; var feet = architectural.match(/^([0-9]+)\'[-\s]*/); if(feet !== null) decimal += parseInt(feet[1]) * 12; var inches = architectural.match(/([-\s\']+([0-9]+)|^([0-9]+))[-\s\"]+/); if(inches !== null) { if(feet !== null) decimal += parseInt(inches[2]); else decimal += parseInt(inches[3]); } var fraction = architectural.match(/([-\s\']+([0-9]+\/[0-9]+)|(^[0-9]+\/[0-9]+))\"/); if(fraction !== null) { if(feet !== null || inches !== null) decimal += divideFraction(fraction[2]); else decimal += divideFraction(fraction[3]); } if(units !== "inches") decimal = decimal / 12; decimal = roundNumber(decimal, ["1", "1/10", "1/100", "1/1000", "1/10000", "1/100000", "1/1000000", "1/10000000"].indexOf(precision)); return decimal; }
[ "function", "(", "architectural", ",", "units", ",", "precision", ")", "{", "if", "(", "typeof", "architectural", "!==", "\"string\"", "&&", "!", "(", "architectural", "instanceof", "String", ")", ")", "return", "false", ";", "if", "(", "architectural", ".", "match", "(", "/", "^(([0-9]+)\\')?([-\\s])*((([0-9]+\\\")([-\\s])*|([0-9]*)([-\\s]*)([0-9]+)(\\/{1})([0-9]+\\\")))?$", "/", "g", ")", "===", "null", ")", "return", "false", ";", "if", "(", "[", "\"1\"", ",", "\"1/10\"", ",", "\"1/100\"", ",", "\"1/1000\"", ",", "\"1/10000\"", ",", "\"1/100000\"", ",", "\"1/1000000\"", ",", "\"1/10000000\"", "]", ".", "indexOf", "(", "precision", ")", "<", "0", ")", "return", "false", ";", "if", "(", "[", "\"inches\"", ",", "\"feet\"", "]", ".", "indexOf", "(", "units", ")", "<", "0", ")", "return", "false", ";", "var", "decimal", "=", "0", ";", "var", "feet", "=", "architectural", ".", "match", "(", "/", "^([0-9]+)\\'[-\\s]*", "/", ")", ";", "if", "(", "feet", "!==", "null", ")", "decimal", "+=", "parseInt", "(", "feet", "[", "1", "]", ")", "*", "12", ";", "var", "inches", "=", "architectural", ".", "match", "(", "/", "([-\\s\\']+([0-9]+)|^([0-9]+))[-\\s\\\"]+", "/", ")", ";", "if", "(", "inches", "!==", "null", ")", "{", "if", "(", "feet", "!==", "null", ")", "decimal", "+=", "parseInt", "(", "inches", "[", "2", "]", ")", ";", "else", "decimal", "+=", "parseInt", "(", "inches", "[", "3", "]", ")", ";", "}", "var", "fraction", "=", "architectural", ".", "match", "(", "/", "([-\\s\\']+([0-9]+\\/[0-9]+)|(^[0-9]+\\/[0-9]+))\\\"", "/", ")", ";", "if", "(", "fraction", "!==", "null", ")", "{", "if", "(", "feet", "!==", "null", "||", "inches", "!==", "null", ")", "decimal", "+=", "divideFraction", "(", "fraction", "[", "2", "]", ")", ";", "else", "decimal", "+=", "divideFraction", "(", "fraction", "[", "3", "]", ")", ";", "}", "if", "(", "units", "!==", "\"inches\"", ")", "decimal", "=", "decimal", "/", "12", ";", "decimal", "=", "roundNumber", "(", "decimal", ",", "[", "\"1\"", ",", "\"1/10\"", ",", "\"1/100\"", ",", "\"1/1000\"", ",", "\"1/10000\"", ",", "\"1/100000\"", ",", "\"1/1000000\"", ",", "\"1/10000000\"", "]", ".", "indexOf", "(", "precision", ")", ")", ";", "return", "decimal", ";", "}" ]
Convert architectural measurement to decimal notation. @param {String} architectural @param {String} units @param {String} precision @return {Number}
[ "Convert", "architectural", "measurement", "to", "decimal", "notation", "." ]
3aa94c2c09bc23dd76ea2238021ede750b3e123e
https://github.com/adekom/decitectural/blob/3aa94c2c09bc23dd76ea2238021ede750b3e123e/index.js#L11-L49
48,794
adekom/decitectural
index.js
function(decimal, units, precision) { if(typeof decimal !== "number" || isNaN(decimal) || !isFinite(decimal)) return false; if(["inches", "feet"].indexOf(units) < 0) return false; if(["1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256"].indexOf(precision) < 0) return false; var architectural = ""; var precision = parseFloat(precision.replace("1/", "")); if(units !== "inches") decimal = decimal * 12; if(decimal < 0) { decimal = Math.abs(decimal); architectural += "-"; } var feet = Math.floor(decimal / 12); architectural += feet + "' "; var inches = Math.floor(decimal - (feet * 12)); architectural += inches + "\""; var fraction = Math.floor((decimal - (feet * 12) - inches) * precision); if(fraction > 0) architectural = architectural.replace("\"", " " + reduceFraction(fraction, precision) + "\""); return architectural; }
javascript
function(decimal, units, precision) { if(typeof decimal !== "number" || isNaN(decimal) || !isFinite(decimal)) return false; if(["inches", "feet"].indexOf(units) < 0) return false; if(["1/2", "1/4", "1/8", "1/16", "1/32", "1/64", "1/128", "1/256"].indexOf(precision) < 0) return false; var architectural = ""; var precision = parseFloat(precision.replace("1/", "")); if(units !== "inches") decimal = decimal * 12; if(decimal < 0) { decimal = Math.abs(decimal); architectural += "-"; } var feet = Math.floor(decimal / 12); architectural += feet + "' "; var inches = Math.floor(decimal - (feet * 12)); architectural += inches + "\""; var fraction = Math.floor((decimal - (feet * 12) - inches) * precision); if(fraction > 0) architectural = architectural.replace("\"", " " + reduceFraction(fraction, precision) + "\""); return architectural; }
[ "function", "(", "decimal", ",", "units", ",", "precision", ")", "{", "if", "(", "typeof", "decimal", "!==", "\"number\"", "||", "isNaN", "(", "decimal", ")", "||", "!", "isFinite", "(", "decimal", ")", ")", "return", "false", ";", "if", "(", "[", "\"inches\"", ",", "\"feet\"", "]", ".", "indexOf", "(", "units", ")", "<", "0", ")", "return", "false", ";", "if", "(", "[", "\"1/2\"", ",", "\"1/4\"", ",", "\"1/8\"", ",", "\"1/16\"", ",", "\"1/32\"", ",", "\"1/64\"", ",", "\"1/128\"", ",", "\"1/256\"", "]", ".", "indexOf", "(", "precision", ")", "<", "0", ")", "return", "false", ";", "var", "architectural", "=", "\"\"", ";", "var", "precision", "=", "parseFloat", "(", "precision", ".", "replace", "(", "\"1/\"", ",", "\"\"", ")", ")", ";", "if", "(", "units", "!==", "\"inches\"", ")", "decimal", "=", "decimal", "*", "12", ";", "if", "(", "decimal", "<", "0", ")", "{", "decimal", "=", "Math", ".", "abs", "(", "decimal", ")", ";", "architectural", "+=", "\"-\"", ";", "}", "var", "feet", "=", "Math", ".", "floor", "(", "decimal", "/", "12", ")", ";", "architectural", "+=", "feet", "+", "\"' \"", ";", "var", "inches", "=", "Math", ".", "floor", "(", "decimal", "-", "(", "feet", "*", "12", ")", ")", ";", "architectural", "+=", "inches", "+", "\"\\\"\"", ";", "var", "fraction", "=", "Math", ".", "floor", "(", "(", "decimal", "-", "(", "feet", "*", "12", ")", "-", "inches", ")", "*", "precision", ")", ";", "if", "(", "fraction", ">", "0", ")", "architectural", "=", "architectural", ".", "replace", "(", "\"\\\"\"", ",", "\" \"", "+", "reduceFraction", "(", "fraction", ",", "precision", ")", "+", "\"\\\"\"", ")", ";", "return", "architectural", ";", "}" ]
Convert decimal measurement to architectural notation. @param {Number} decimal @param {String} units @param {String} precision @return {String}
[ "Convert", "decimal", "measurement", "to", "architectural", "notation", "." ]
3aa94c2c09bc23dd76ea2238021ede750b3e123e
https://github.com/adekom/decitectural/blob/3aa94c2c09bc23dd76ea2238021ede750b3e123e/index.js#L60-L91
48,795
seeden/maglev
src/models/user.js
createByFacebook
function createByFacebook(profile, callback) { if (!profile.id) { return callback(new Error('Profile id is undefined')); } this.findByFacebookID(profile.id, ok(callback, (user) => { if (user) { return updateUserByFacebookProfile(user, profile, callback); } this.create({ username: profile.username || null, firstName: profile.first_name, lastName: profile.last_name, name: profile.name, email: profile.email, locale: profile.locale, }, ok(callback, (newUser) => { newUser.addProvider('facebook', profile.id, profile, ok(callback, () => { callback(null, newUser); })); })); })); }
javascript
function createByFacebook(profile, callback) { if (!profile.id) { return callback(new Error('Profile id is undefined')); } this.findByFacebookID(profile.id, ok(callback, (user) => { if (user) { return updateUserByFacebookProfile(user, profile, callback); } this.create({ username: profile.username || null, firstName: profile.first_name, lastName: profile.last_name, name: profile.name, email: profile.email, locale: profile.locale, }, ok(callback, (newUser) => { newUser.addProvider('facebook', profile.id, profile, ok(callback, () => { callback(null, newUser); })); })); })); }
[ "function", "createByFacebook", "(", "profile", ",", "callback", ")", "{", "if", "(", "!", "profile", ".", "id", ")", "{", "return", "callback", "(", "new", "Error", "(", "'Profile id is undefined'", ")", ")", ";", "}", "this", ".", "findByFacebookID", "(", "profile", ".", "id", ",", "ok", "(", "callback", ",", "(", "user", ")", "=>", "{", "if", "(", "user", ")", "{", "return", "updateUserByFacebookProfile", "(", "user", ",", "profile", ",", "callback", ")", ";", "}", "this", ".", "create", "(", "{", "username", ":", "profile", ".", "username", "||", "null", ",", "firstName", ":", "profile", ".", "first_name", ",", "lastName", ":", "profile", ".", "last_name", ",", "name", ":", "profile", ".", "name", ",", "email", ":", "profile", ".", "email", ",", "locale", ":", "profile", ".", "locale", ",", "}", ",", "ok", "(", "callback", ",", "(", "newUser", ")", "=>", "{", "newUser", ".", "addProvider", "(", "'facebook'", ",", "profile", ".", "id", ",", "profile", ",", "ok", "(", "callback", ",", "(", ")", "=>", "{", "callback", "(", "null", ",", "newUser", ")", ";", "}", ")", ")", ";", "}", ")", ")", ";", "}", ")", ")", ";", "}" ]
Create user by user profile from facebook @param {Object} profile Profile from facebook @param {Function} callback Callback with created user
[ "Create", "user", "by", "user", "profile", "from", "facebook" ]
e291675fed963ccf5d50bab24ec9d9bf745ad5a3
https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L96-L119
48,796
seeden/maglev
src/models/user.js
createByTwitter
function createByTwitter(profile, callback) { if (!profile.id) { return callback(new Error('Profile id is undefined')); } this.findByTwitterID(profile.id, ok(callback, (user) => { if (user) { return callback(null, user); } this.create({ username: profile.username || null, name: profile.displayName, }, ok(callback, (newUser) => { newUser.addProvider('twitter', profile.id, profile, ok(callback, () => { callback(null, newUser); })); })); })); }
javascript
function createByTwitter(profile, callback) { if (!profile.id) { return callback(new Error('Profile id is undefined')); } this.findByTwitterID(profile.id, ok(callback, (user) => { if (user) { return callback(null, user); } this.create({ username: profile.username || null, name: profile.displayName, }, ok(callback, (newUser) => { newUser.addProvider('twitter', profile.id, profile, ok(callback, () => { callback(null, newUser); })); })); })); }
[ "function", "createByTwitter", "(", "profile", ",", "callback", ")", "{", "if", "(", "!", "profile", ".", "id", ")", "{", "return", "callback", "(", "new", "Error", "(", "'Profile id is undefined'", ")", ")", ";", "}", "this", ".", "findByTwitterID", "(", "profile", ".", "id", ",", "ok", "(", "callback", ",", "(", "user", ")", "=>", "{", "if", "(", "user", ")", "{", "return", "callback", "(", "null", ",", "user", ")", ";", "}", "this", ".", "create", "(", "{", "username", ":", "profile", ".", "username", "||", "null", ",", "name", ":", "profile", ".", "displayName", ",", "}", ",", "ok", "(", "callback", ",", "(", "newUser", ")", "=>", "{", "newUser", ".", "addProvider", "(", "'twitter'", ",", "profile", ".", "id", ",", "profile", ",", "ok", "(", "callback", ",", "(", ")", "=>", "{", "callback", "(", "null", ",", "newUser", ")", ";", "}", ")", ")", ";", "}", ")", ")", ";", "}", ")", ")", ";", "}" ]
Create user by user profile from twitter @param {Object} profile Profile from twitter @param {Function} callback Callback with created user
[ "Create", "user", "by", "user", "profile", "from", "twitter" ]
e291675fed963ccf5d50bab24ec9d9bf745ad5a3
https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L126-L145
48,797
seeden/maglev
src/models/user.js
generateBearerToken
function generateBearerToken(tokenSecret, expiresInMinutes = 60 * 24 * 14, scope = []) { if (!tokenSecret) { throw new Error('Token secret is undefined'); } const data = { user: this._id.toString(), }; if (scope.length) { data.scope = scope; } const token = jwt.sign(data, tokenSecret, { expiresInMinutes, }); return { type: 'Bearer', value: token, }; }
javascript
function generateBearerToken(tokenSecret, expiresInMinutes = 60 * 24 * 14, scope = []) { if (!tokenSecret) { throw new Error('Token secret is undefined'); } const data = { user: this._id.toString(), }; if (scope.length) { data.scope = scope; } const token = jwt.sign(data, tokenSecret, { expiresInMinutes, }); return { type: 'Bearer', value: token, }; }
[ "function", "generateBearerToken", "(", "tokenSecret", ",", "expiresInMinutes", "=", "60", "*", "24", "*", "14", ",", "scope", "=", "[", "]", ")", "{", "if", "(", "!", "tokenSecret", ")", "{", "throw", "new", "Error", "(", "'Token secret is undefined'", ")", ";", "}", "const", "data", "=", "{", "user", ":", "this", ".", "_id", ".", "toString", "(", ")", ",", "}", ";", "if", "(", "scope", ".", "length", ")", "{", "data", ".", "scope", "=", "scope", ";", "}", "const", "token", "=", "jwt", ".", "sign", "(", "data", ",", "tokenSecret", ",", "{", "expiresInMinutes", ",", "}", ")", ";", "return", "{", "type", ":", "'Bearer'", ",", "value", ":", "token", ",", "}", ";", "}" ]
Generate access token for actual user @param {String} Secret for generating of token @param {[Number]} expiresInMinutes @param {[Array]} scope List of scopes @return {Object} Access token of user
[ "Generate", "access", "token", "for", "actual", "user" ]
e291675fed963ccf5d50bab24ec9d9bf745ad5a3
https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L154-L175
48,798
seeden/maglev
src/models/user.js
comparePassword
function comparePassword(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { if (err) { return callback(err); } callback(null, isMatch); }); }
javascript
function comparePassword(candidatePassword, callback) { bcrypt.compare(candidatePassword, this.password, (err, isMatch) => { if (err) { return callback(err); } callback(null, isMatch); }); }
[ "function", "comparePassword", "(", "candidatePassword", ",", "callback", ")", "{", "bcrypt", ".", "compare", "(", "candidatePassword", ",", "this", ".", "password", ",", "(", "err", ",", "isMatch", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "isMatch", ")", ";", "}", ")", ";", "}" ]
Compare user entered password with stored user's password @param {String} candidatePassword @param {Function} callback
[ "Compare", "user", "entered", "password", "with", "stored", "user", "s", "password" ]
e291675fed963ccf5d50bab24ec9d9bf745ad5a3
https://github.com/seeden/maglev/blob/e291675fed963ccf5d50bab24ec9d9bf745ad5a3/src/models/user.js#L318-L326
48,799
switer/chainjs
chain.js
pushNode
function pushNode( /*handler1, handler2, ..., handlerN*/ ) { var node = { items: utils.slice(arguments), state: {} } var id = this.props._nodes.add(node) node.id = id return node }
javascript
function pushNode( /*handler1, handler2, ..., handlerN*/ ) { var node = { items: utils.slice(arguments), state: {} } var id = this.props._nodes.add(node) node.id = id return node }
[ "function", "pushNode", "(", "/*handler1, handler2, ..., handlerN*/", ")", "{", "var", "node", "=", "{", "items", ":", "utils", ".", "slice", "(", "arguments", ")", ",", "state", ":", "{", "}", "}", "var", "id", "=", "this", ".", "props", ".", "_nodes", ".", "add", "(", "node", ")", "node", ".", "id", "=", "id", "return", "node", "}" ]
Push a step node to LinkNodes
[ "Push", "a", "step", "node", "to", "LinkNodes" ]
7b5c0ceb55135df7b7a621a891cf59f49cc67d6c
https://github.com/switer/chainjs/blob/7b5c0ceb55135df7b7a621a891cf59f49cc67d6c/chain.js#L263-L271