id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
55,000
darrencruse/sugarlisp-core
reader.js
read_via_closest_dialect
function read_via_closest_dialect(lexer, options) { trace(lexer.message_src_loc("", lexer, {file:false})); // options allow this function to be used when a readtab // handler needs to read by invoking a handler that it's // overridden, without knowing what dialect was overridden. // (see invoke_readfn_overridden_by below) options = options || {}; // normally we start with the close dialect (0) var startingDialect = options.startingDialect || 0; // And normally we read the source text under the current position // unless they give us a token that's already been read) var token = options.token; if(!token) { // we *peek* when determining which readtab read function to call, // so the read functions can consume the *entire* form, including the // first token (which makes the design of the read functions easier // easier to understand and test in isolation). token = lexer.peek_token(); } debug('reading expression starting "' + token.text + '"'); var form = retry; var readfn; // try the dialects from beginning (inner scope) to end (outer scope)... for(var i = startingDialect; isretry(form) && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; debug('looking for "' + token.text + '" in ' + dialect.name + ' readtab'); readfn = findReadfn(dialect.readtab, token) if(readfn) { form = read_via_readfn(readfn, lexer, token.text); if(!form) { lexer.error('Invalid response from "' + token.text + '" readtab function in "' + dialect.name + '"'); } } } // if we've tried all the dialects and either didn't find a match, // or found a match that returned "reader.retry"... if(isretry(form)) { // try all the dialects again, this time looking for "__default" // note: most likely this will get all the way to core's __default, // but dialect's *can* override __default if they need to, and // could e.g. "selectively" override it by returning reader.retry in // cases where they want core's __default to handle it instead. for(var i = startingDialect; isretry(form) && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; debug('looking for "__default" in ' + dialect.name + ' readtab'); readfn = dialect.readtab !== undefined ? dialect.readtab['__default'] : undefined; if(readfn) { form = read_via_readfn(readfn, lexer, token.text); if(!form) { lexer.error('Invalid response for "' + token.text + '" returned by __default function in "' + dialect.name + '"'); } } } } // this should never happen (because of __default) but JIC: if(!form || isretry(form)) { lexer.error('No dialect handled the text starting "' + lexer.snoop(10) + '...'); } return form; }
javascript
function read_via_closest_dialect(lexer, options) { trace(lexer.message_src_loc("", lexer, {file:false})); // options allow this function to be used when a readtab // handler needs to read by invoking a handler that it's // overridden, without knowing what dialect was overridden. // (see invoke_readfn_overridden_by below) options = options || {}; // normally we start with the close dialect (0) var startingDialect = options.startingDialect || 0; // And normally we read the source text under the current position // unless they give us a token that's already been read) var token = options.token; if(!token) { // we *peek* when determining which readtab read function to call, // so the read functions can consume the *entire* form, including the // first token (which makes the design of the read functions easier // easier to understand and test in isolation). token = lexer.peek_token(); } debug('reading expression starting "' + token.text + '"'); var form = retry; var readfn; // try the dialects from beginning (inner scope) to end (outer scope)... for(var i = startingDialect; isretry(form) && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; debug('looking for "' + token.text + '" in ' + dialect.name + ' readtab'); readfn = findReadfn(dialect.readtab, token) if(readfn) { form = read_via_readfn(readfn, lexer, token.text); if(!form) { lexer.error('Invalid response from "' + token.text + '" readtab function in "' + dialect.name + '"'); } } } // if we've tried all the dialects and either didn't find a match, // or found a match that returned "reader.retry"... if(isretry(form)) { // try all the dialects again, this time looking for "__default" // note: most likely this will get all the way to core's __default, // but dialect's *can* override __default if they need to, and // could e.g. "selectively" override it by returning reader.retry in // cases where they want core's __default to handle it instead. for(var i = startingDialect; isretry(form) && i < lexer.dialects.length; i++) { var dialect = lexer.dialects[i]; debug('looking for "__default" in ' + dialect.name + ' readtab'); readfn = dialect.readtab !== undefined ? dialect.readtab['__default'] : undefined; if(readfn) { form = read_via_readfn(readfn, lexer, token.text); if(!form) { lexer.error('Invalid response for "' + token.text + '" returned by __default function in "' + dialect.name + '"'); } } } } // this should never happen (because of __default) but JIC: if(!form || isretry(form)) { lexer.error('No dialect handled the text starting "' + lexer.snoop(10) + '...'); } return form; }
[ "function", "read_via_closest_dialect", "(", "lexer", ",", "options", ")", "{", "trace", "(", "lexer", ".", "message_src_loc", "(", "\"\"", ",", "lexer", ",", "{", "file", ":", "false", "}", ")", ")", ";", "// options allow this function to be used when a readtab", "// handler needs to read by invoking a handler that it's", "// overridden, without knowing what dialect was overridden.", "// (see invoke_readfn_overridden_by below)", "options", "=", "options", "||", "{", "}", ";", "// normally we start with the close dialect (0)", "var", "startingDialect", "=", "options", ".", "startingDialect", "||", "0", ";", "// And normally we read the source text under the current position", "// unless they give us a token that's already been read)", "var", "token", "=", "options", ".", "token", ";", "if", "(", "!", "token", ")", "{", "// we *peek* when determining which readtab read function to call,", "// so the read functions can consume the *entire* form, including the", "// first token (which makes the design of the read functions easier", "// easier to understand and test in isolation).", "token", "=", "lexer", ".", "peek_token", "(", ")", ";", "}", "debug", "(", "'reading expression starting \"'", "+", "token", ".", "text", "+", "'\"'", ")", ";", "var", "form", "=", "retry", ";", "var", "readfn", ";", "// try the dialects from beginning (inner scope) to end (outer scope)...", "for", "(", "var", "i", "=", "startingDialect", ";", "isretry", "(", "form", ")", "&&", "i", "<", "lexer", ".", "dialects", ".", "length", ";", "i", "++", ")", "{", "var", "dialect", "=", "lexer", ".", "dialects", "[", "i", "]", ";", "debug", "(", "'looking for \"'", "+", "token", ".", "text", "+", "'\" in '", "+", "dialect", ".", "name", "+", "' readtab'", ")", ";", "readfn", "=", "findReadfn", "(", "dialect", ".", "readtab", ",", "token", ")", "if", "(", "readfn", ")", "{", "form", "=", "read_via_readfn", "(", "readfn", ",", "lexer", ",", "token", ".", "text", ")", ";", "if", "(", "!", "form", ")", "{", "lexer", ".", "error", "(", "'Invalid response from \"'", "+", "token", ".", "text", "+", "'\" readtab function in \"'", "+", "dialect", ".", "name", "+", "'\"'", ")", ";", "}", "}", "}", "// if we've tried all the dialects and either didn't find a match,", "// or found a match that returned \"reader.retry\"...", "if", "(", "isretry", "(", "form", ")", ")", "{", "// try all the dialects again, this time looking for \"__default\"", "// note: most likely this will get all the way to core's __default,", "// but dialect's *can* override __default if they need to, and", "// could e.g. \"selectively\" override it by returning reader.retry in", "// cases where they want core's __default to handle it instead.", "for", "(", "var", "i", "=", "startingDialect", ";", "isretry", "(", "form", ")", "&&", "i", "<", "lexer", ".", "dialects", ".", "length", ";", "i", "++", ")", "{", "var", "dialect", "=", "lexer", ".", "dialects", "[", "i", "]", ";", "debug", "(", "'looking for \"__default\" in '", "+", "dialect", ".", "name", "+", "' readtab'", ")", ";", "readfn", "=", "dialect", ".", "readtab", "!==", "undefined", "?", "dialect", ".", "readtab", "[", "'__default'", "]", ":", "undefined", ";", "if", "(", "readfn", ")", "{", "form", "=", "read_via_readfn", "(", "readfn", ",", "lexer", ",", "token", ".", "text", ")", ";", "if", "(", "!", "form", ")", "{", "lexer", ".", "error", "(", "'Invalid response for \"'", "+", "token", ".", "text", "+", "'\" returned by __default function in \"'", "+", "dialect", ".", "name", "+", "'\"'", ")", ";", "}", "}", "}", "}", "// this should never happen (because of __default) but JIC:", "if", "(", "!", "form", "||", "isretry", "(", "form", ")", ")", "{", "lexer", ".", "error", "(", "'No dialect handled the text starting \"'", "+", "lexer", ".", "snoop", "(", "10", ")", "+", "'...'", ")", ";", "}", "return", "form", ";", "}" ]
Read the form under the current position, using the closest scoped dialect that contains a matching entry in it's readtab. If such an entry returns "reader.retry", try the *next* closest dialect with a match (and so on) until one of the dialect's reads the form, otherwise it gets read by the closest "__default" handler.
[ "Read", "the", "form", "under", "the", "current", "position", "using", "the", "closest", "scoped", "dialect", "that", "contains", "a", "matching", "entry", "in", "it", "s", "readtab", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L479-L546
55,001
darrencruse/sugarlisp-core
reader.js
pop_local_dialects
function pop_local_dialects(lexer, list) { if(list && list.length > 0) { // we go in reverse order since the most recently // used (pushed) dialects will be at the end for(var i = list.length-1; i >= 0; i--) { if(list[i].dialect) { unuse_dialect(list[i].dialect, lexer); } } } }
javascript
function pop_local_dialects(lexer, list) { if(list && list.length > 0) { // we go in reverse order since the most recently // used (pushed) dialects will be at the end for(var i = list.length-1; i >= 0; i--) { if(list[i].dialect) { unuse_dialect(list[i].dialect, lexer); } } } }
[ "function", "pop_local_dialects", "(", "lexer", ",", "list", ")", "{", "if", "(", "list", "&&", "list", ".", "length", ">", "0", ")", "{", "// we go in reverse order since the most recently", "// used (pushed) dialects will be at the end", "for", "(", "var", "i", "=", "list", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "if", "(", "list", "[", "i", "]", ".", "dialect", ")", "{", "unuse_dialect", "(", "list", "[", "i", "]", ".", "dialect", ",", "lexer", ")", ";", "}", "}", "}", "}" ]
pop any local dialects enabled within the scope of the provided list. note: here we intentionally look just one level down at the *direct* children of the list, since "grandchildren" have scopes of their own that are "popped" separately.
[ "pop", "any", "local", "dialects", "enabled", "within", "the", "scope", "of", "the", "provided", "list", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L809-L819
55,002
darrencruse/sugarlisp-core
reader.js
read_delimited_text
function read_delimited_text(lexer, start, end, options) { options = options || {includeDelimiters: true}; var delimited = lexer.next_delimited_token(start, end, options); return sl.atom(delimited); }
javascript
function read_delimited_text(lexer, start, end, options) { options = options || {includeDelimiters: true}; var delimited = lexer.next_delimited_token(start, end, options); return sl.atom(delimited); }
[ "function", "read_delimited_text", "(", "lexer", ",", "start", ",", "end", ",", "options", ")", "{", "options", "=", "options", "||", "{", "includeDelimiters", ":", "true", "}", ";", "var", "delimited", "=", "lexer", ".", "next_delimited_token", "(", "start", ",", "end", ",", "options", ")", ";", "return", "sl", ".", "atom", "(", "delimited", ")", ";", "}" ]
scan some delimited text and get it as a string atom lexer.options.omitDelimiters = whether to include the include the delimiters or not
[ "scan", "some", "delimited", "text", "and", "get", "it", "as", "a", "string", "atom", "lexer", ".", "options", ".", "omitDelimiters", "=", "whether", "to", "include", "the", "include", "the", "delimiters", "or", "not" ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L849-L853
55,003
darrencruse/sugarlisp-core
reader.js
symbol
function symbol(lexer, text) { var token = lexer.next_token(text); return sl.atom(text, {token: token}); }
javascript
function symbol(lexer, text) { var token = lexer.next_token(text); return sl.atom(text, {token: token}); }
[ "function", "symbol", "(", "lexer", ",", "text", ")", "{", "var", "token", "=", "lexer", ".", "next_token", "(", "text", ")", ";", "return", "sl", ".", "atom", "(", "text", ",", "{", "token", ":", "token", "}", ")", ";", "}" ]
A symbol Use reader.symbol in their readtab to ensure the lexer scans the specified token text correctly as a symbol.
[ "A", "symbol", "Use", "reader", ".", "symbol", "in", "their", "readtab", "to", "ensure", "the", "lexer", "scans", "the", "specified", "token", "text", "correctly", "as", "a", "symbol", "." ]
c6ff983ebc3d60268054d6fe046db4aff6c5f78c
https://github.com/darrencruse/sugarlisp-core/blob/c6ff983ebc3d60268054d6fe046db4aff6c5f78c/reader.js#L1211-L1214
55,004
Knorcedger/mongoose-schema-extender
index.js
callback
function callback(req, res, resolve, reject, error, result, permissions, action) { if (error) { reqlog.error('internal server error', error); if (exports.handleErrors) { responseBuilder.error(req, res, 'INTERNAL_SERVER_ERROR'); } else { reject(error); } } else { // filter the result attributes to send only those that this userType can see // check if the result is an array, to iterate it if (Array.isArray(result)) { for (var i = 0, length = result.length; i < length; i++) { result[i] = filterAttributes(result[i], permissions); } } else { result = filterAttributes(result, permissions); } reqlog.info(action + '.success', result); resolve(result); } /** * Delete the attributes that the activeUser cant see * @method filterAttributes * @param {object} object The result object * @param {object} permissions The permissions object * @return {object} The filtered object */ function filterAttributes(object, permissions) { if (object) { var userType = req.activeUser && req.activeUser.type || 'null'; for (var attribute in object._doc) { if (object._doc.hasOwnProperty(attribute)) { // dont return this attribute when: if (!permissions[attribute] || // if this attribute is not defined in permissions permissions[attribute][0] !== 'null' && // this attribute is not set as public permissions[attribute].indexOf(userType) === -1 && // this attribute is not available to this userType userType !== 'admin' // the user is not admin ) { delete object._doc[attribute]; } } } } return object; } }
javascript
function callback(req, res, resolve, reject, error, result, permissions, action) { if (error) { reqlog.error('internal server error', error); if (exports.handleErrors) { responseBuilder.error(req, res, 'INTERNAL_SERVER_ERROR'); } else { reject(error); } } else { // filter the result attributes to send only those that this userType can see // check if the result is an array, to iterate it if (Array.isArray(result)) { for (var i = 0, length = result.length; i < length; i++) { result[i] = filterAttributes(result[i], permissions); } } else { result = filterAttributes(result, permissions); } reqlog.info(action + '.success', result); resolve(result); } /** * Delete the attributes that the activeUser cant see * @method filterAttributes * @param {object} object The result object * @param {object} permissions The permissions object * @return {object} The filtered object */ function filterAttributes(object, permissions) { if (object) { var userType = req.activeUser && req.activeUser.type || 'null'; for (var attribute in object._doc) { if (object._doc.hasOwnProperty(attribute)) { // dont return this attribute when: if (!permissions[attribute] || // if this attribute is not defined in permissions permissions[attribute][0] !== 'null' && // this attribute is not set as public permissions[attribute].indexOf(userType) === -1 && // this attribute is not available to this userType userType !== 'admin' // the user is not admin ) { delete object._doc[attribute]; } } } } return object; } }
[ "function", "callback", "(", "req", ",", "res", ",", "resolve", ",", "reject", ",", "error", ",", "result", ",", "permissions", ",", "action", ")", "{", "if", "(", "error", ")", "{", "reqlog", ".", "error", "(", "'internal server error'", ",", "error", ")", ";", "if", "(", "exports", ".", "handleErrors", ")", "{", "responseBuilder", ".", "error", "(", "req", ",", "res", ",", "'INTERNAL_SERVER_ERROR'", ")", ";", "}", "else", "{", "reject", "(", "error", ")", ";", "}", "}", "else", "{", "// filter the result attributes to send only those that this userType can see", "// check if the result is an array, to iterate it", "if", "(", "Array", ".", "isArray", "(", "result", ")", ")", "{", "for", "(", "var", "i", "=", "0", ",", "length", "=", "result", ".", "length", ";", "i", "<", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "filterAttributes", "(", "result", "[", "i", "]", ",", "permissions", ")", ";", "}", "}", "else", "{", "result", "=", "filterAttributes", "(", "result", ",", "permissions", ")", ";", "}", "reqlog", ".", "info", "(", "action", "+", "'.success'", ",", "result", ")", ";", "resolve", "(", "result", ")", ";", "}", "/**\n\t * Delete the attributes that the activeUser cant see\n\t * @method filterAttributes\n\t * @param {object} object The result object\n\t * @param {object} permissions The permissions object\n\t * @return {object} The filtered object\n\t */", "function", "filterAttributes", "(", "object", ",", "permissions", ")", "{", "if", "(", "object", ")", "{", "var", "userType", "=", "req", ".", "activeUser", "&&", "req", ".", "activeUser", ".", "type", "||", "'null'", ";", "for", "(", "var", "attribute", "in", "object", ".", "_doc", ")", "{", "if", "(", "object", ".", "_doc", ".", "hasOwnProperty", "(", "attribute", ")", ")", "{", "// dont return this attribute when:", "if", "(", "!", "permissions", "[", "attribute", "]", "||", "// if this attribute is not defined in permissions", "permissions", "[", "attribute", "]", "[", "0", "]", "!==", "'null'", "&&", "// this attribute is not set as public", "permissions", "[", "attribute", "]", ".", "indexOf", "(", "userType", ")", "===", "-", "1", "&&", "// this attribute is not available to this userType", "userType", "!==", "'admin'", "// the user is not admin", ")", "{", "delete", "object", ".", "_doc", "[", "attribute", "]", ";", "}", "}", "}", "}", "return", "object", ";", "}", "}" ]
Query callback. Handles errors, filters attributes @method callback @param {object} req The request object @param {object} res The response object @param {function} resolve The promise resolve @param {function} reject The promise reject @param {object} error The query error @param {object} result The query result @param {object} permissions The attributes views permissions @param {string} action Action used for logging]
[ "Query", "callback", ".", "Handles", "errors", "filters", "attributes" ]
6878d7bee4a1a4befb8698dd9d1787242c6be395
https://github.com/Knorcedger/mongoose-schema-extender/blob/6878d7bee4a1a4befb8698dd9d1787242c6be395/index.js#L183-L232
55,005
Knorcedger/mongoose-schema-extender
index.js
filterAttributes
function filterAttributes(object, permissions) { if (object) { var userType = req.activeUser && req.activeUser.type || 'null'; for (var attribute in object._doc) { if (object._doc.hasOwnProperty(attribute)) { // dont return this attribute when: if (!permissions[attribute] || // if this attribute is not defined in permissions permissions[attribute][0] !== 'null' && // this attribute is not set as public permissions[attribute].indexOf(userType) === -1 && // this attribute is not available to this userType userType !== 'admin' // the user is not admin ) { delete object._doc[attribute]; } } } } return object; }
javascript
function filterAttributes(object, permissions) { if (object) { var userType = req.activeUser && req.activeUser.type || 'null'; for (var attribute in object._doc) { if (object._doc.hasOwnProperty(attribute)) { // dont return this attribute when: if (!permissions[attribute] || // if this attribute is not defined in permissions permissions[attribute][0] !== 'null' && // this attribute is not set as public permissions[attribute].indexOf(userType) === -1 && // this attribute is not available to this userType userType !== 'admin' // the user is not admin ) { delete object._doc[attribute]; } } } } return object; }
[ "function", "filterAttributes", "(", "object", ",", "permissions", ")", "{", "if", "(", "object", ")", "{", "var", "userType", "=", "req", ".", "activeUser", "&&", "req", ".", "activeUser", ".", "type", "||", "'null'", ";", "for", "(", "var", "attribute", "in", "object", ".", "_doc", ")", "{", "if", "(", "object", ".", "_doc", ".", "hasOwnProperty", "(", "attribute", ")", ")", "{", "// dont return this attribute when:", "if", "(", "!", "permissions", "[", "attribute", "]", "||", "// if this attribute is not defined in permissions", "permissions", "[", "attribute", "]", "[", "0", "]", "!==", "'null'", "&&", "// this attribute is not set as public", "permissions", "[", "attribute", "]", ".", "indexOf", "(", "userType", ")", "===", "-", "1", "&&", "// this attribute is not available to this userType", "userType", "!==", "'admin'", "// the user is not admin", ")", "{", "delete", "object", ".", "_doc", "[", "attribute", "]", ";", "}", "}", "}", "}", "return", "object", ";", "}" ]
Delete the attributes that the activeUser cant see @method filterAttributes @param {object} object The result object @param {object} permissions The permissions object @return {object} The filtered object
[ "Delete", "the", "attributes", "that", "the", "activeUser", "cant", "see" ]
6878d7bee4a1a4befb8698dd9d1787242c6be395
https://github.com/Knorcedger/mongoose-schema-extender/blob/6878d7bee4a1a4befb8698dd9d1787242c6be395/index.js#L213-L231
55,006
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/operations/cursor_ops.js
hasNext
function hasNext(cursor, callback) { const Cursor = require('../cursor'); if (cursor.s.currentDoc) { return callback(null, true); } if (cursor.isNotified()) { return callback(null, false); } nextObject(cursor, (err, doc) => { if (err) return callback(err, null); if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); if (!doc) return callback(null, false); cursor.s.currentDoc = doc; callback(null, true); }); }
javascript
function hasNext(cursor, callback) { const Cursor = require('../cursor'); if (cursor.s.currentDoc) { return callback(null, true); } if (cursor.isNotified()) { return callback(null, false); } nextObject(cursor, (err, doc) => { if (err) return callback(err, null); if (cursor.s.state === Cursor.CLOSED || cursor.isDead()) return callback(null, false); if (!doc) return callback(null, false); cursor.s.currentDoc = doc; callback(null, true); }); }
[ "function", "hasNext", "(", "cursor", ",", "callback", ")", "{", "const", "Cursor", "=", "require", "(", "'../cursor'", ")", ";", "if", "(", "cursor", ".", "s", ".", "currentDoc", ")", "{", "return", "callback", "(", "null", ",", "true", ")", ";", "}", "if", "(", "cursor", ".", "isNotified", "(", ")", ")", "{", "return", "callback", "(", "null", ",", "false", ")", ";", "}", "nextObject", "(", "cursor", ",", "(", "err", ",", "doc", ")", "=>", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ",", "null", ")", ";", "if", "(", "cursor", ".", "s", ".", "state", "===", "Cursor", ".", "CLOSED", "||", "cursor", ".", "isDead", "(", ")", ")", "return", "callback", "(", "null", ",", "false", ")", ";", "if", "(", "!", "doc", ")", "return", "callback", "(", "null", ",", "false", ")", ";", "cursor", ".", "s", ".", "currentDoc", "=", "doc", ";", "callback", "(", "null", ",", "true", ")", ";", "}", ")", ";", "}" ]
Check if there is any document still available in the cursor. @method @param {Cursor} cursor The Cursor instance on which to run. @param {Cursor~resultCallback} [callback] The result callback.
[ "Check", "if", "there", "is", "any", "document", "still", "available", "in", "the", "cursor", "." ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/operations/cursor_ops.js#L116-L134
55,007
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/operations/cursor_ops.js
nextObject
function nextObject(cursor, callback) { const Cursor = require('../cursor'); if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead())) return handleCallback( callback, MongoError.create({ message: 'Cursor is closed', driver: true }) ); if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) { try { cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort); } catch (err) { return handleCallback(callback, err); } } // Get the next object cursor._next((err, doc) => { cursor.s.state = Cursor.OPEN; if (err) return handleCallback(callback, err); handleCallback(callback, null, doc); }); }
javascript
function nextObject(cursor, callback) { const Cursor = require('../cursor'); if (cursor.s.state === Cursor.CLOSED || (cursor.isDead && cursor.isDead())) return handleCallback( callback, MongoError.create({ message: 'Cursor is closed', driver: true }) ); if (cursor.s.state === Cursor.INIT && cursor.s.cmd.sort) { try { cursor.s.cmd.sort = formattedOrderClause(cursor.s.cmd.sort); } catch (err) { return handleCallback(callback, err); } } // Get the next object cursor._next((err, doc) => { cursor.s.state = Cursor.OPEN; if (err) return handleCallback(callback, err); handleCallback(callback, null, doc); }); }
[ "function", "nextObject", "(", "cursor", ",", "callback", ")", "{", "const", "Cursor", "=", "require", "(", "'../cursor'", ")", ";", "if", "(", "cursor", ".", "s", ".", "state", "===", "Cursor", ".", "CLOSED", "||", "(", "cursor", ".", "isDead", "&&", "cursor", ".", "isDead", "(", ")", ")", ")", "return", "handleCallback", "(", "callback", ",", "MongoError", ".", "create", "(", "{", "message", ":", "'Cursor is closed'", ",", "driver", ":", "true", "}", ")", ")", ";", "if", "(", "cursor", ".", "s", ".", "state", "===", "Cursor", ".", "INIT", "&&", "cursor", ".", "s", ".", "cmd", ".", "sort", ")", "{", "try", "{", "cursor", ".", "s", ".", "cmd", ".", "sort", "=", "formattedOrderClause", "(", "cursor", ".", "s", ".", "cmd", ".", "sort", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "}", "}", "// Get the next object", "cursor", ".", "_next", "(", "(", "err", ",", "doc", ")", "=>", "{", "cursor", ".", "s", ".", "state", "=", "Cursor", ".", "OPEN", ";", "if", "(", "err", ")", "return", "handleCallback", "(", "callback", ",", "err", ")", ";", "handleCallback", "(", "callback", ",", "null", ",", "doc", ")", ";", "}", ")", ";", "}" ]
Get the next available document from the cursor, returns null if no more documents are available.
[ "Get", "the", "next", "available", "document", "from", "the", "cursor", "returns", "null", "if", "no", "more", "documents", "are", "available", "." ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/operations/cursor_ops.js#L167-L189
55,008
Industryswarm/isnode-mod-data
lib/mongodb/mongodb/lib/operations/cursor_ops.js
toArray
function toArray(cursor, callback) { const Cursor = require('../cursor'); const items = []; // Reset cursor cursor.rewind(); cursor.s.state = Cursor.INIT; // Fetch all the documents const fetchDocs = () => { cursor._next((err, doc) => { if (err) { return cursor._endSession ? cursor._endSession(() => handleCallback(callback, err)) : handleCallback(callback, err); } if (doc == null) { return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); } // Add doc to items items.push(doc); // Get all buffered objects if (cursor.bufferedCount() > 0) { let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); // Transform the doc if transform method added if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { docs = docs.map(cursor.s.transforms.doc); } push.apply(items, docs); } // Attempt a fetch fetchDocs(); }); }; fetchDocs(); }
javascript
function toArray(cursor, callback) { const Cursor = require('../cursor'); const items = []; // Reset cursor cursor.rewind(); cursor.s.state = Cursor.INIT; // Fetch all the documents const fetchDocs = () => { cursor._next((err, doc) => { if (err) { return cursor._endSession ? cursor._endSession(() => handleCallback(callback, err)) : handleCallback(callback, err); } if (doc == null) { return cursor.close({ skipKillCursors: true }, () => handleCallback(callback, null, items)); } // Add doc to items items.push(doc); // Get all buffered objects if (cursor.bufferedCount() > 0) { let docs = cursor.readBufferedDocuments(cursor.bufferedCount()); // Transform the doc if transform method added if (cursor.s.transforms && typeof cursor.s.transforms.doc === 'function') { docs = docs.map(cursor.s.transforms.doc); } push.apply(items, docs); } // Attempt a fetch fetchDocs(); }); }; fetchDocs(); }
[ "function", "toArray", "(", "cursor", ",", "callback", ")", "{", "const", "Cursor", "=", "require", "(", "'../cursor'", ")", ";", "const", "items", "=", "[", "]", ";", "// Reset cursor", "cursor", ".", "rewind", "(", ")", ";", "cursor", ".", "s", ".", "state", "=", "Cursor", ".", "INIT", ";", "// Fetch all the documents", "const", "fetchDocs", "=", "(", ")", "=>", "{", "cursor", ".", "_next", "(", "(", "err", ",", "doc", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "cursor", ".", "_endSession", "?", "cursor", ".", "_endSession", "(", "(", ")", "=>", "handleCallback", "(", "callback", ",", "err", ")", ")", ":", "handleCallback", "(", "callback", ",", "err", ")", ";", "}", "if", "(", "doc", "==", "null", ")", "{", "return", "cursor", ".", "close", "(", "{", "skipKillCursors", ":", "true", "}", ",", "(", ")", "=>", "handleCallback", "(", "callback", ",", "null", ",", "items", ")", ")", ";", "}", "// Add doc to items", "items", ".", "push", "(", "doc", ")", ";", "// Get all buffered objects", "if", "(", "cursor", ".", "bufferedCount", "(", ")", ">", "0", ")", "{", "let", "docs", "=", "cursor", ".", "readBufferedDocuments", "(", "cursor", ".", "bufferedCount", "(", ")", ")", ";", "// Transform the doc if transform method added", "if", "(", "cursor", ".", "s", ".", "transforms", "&&", "typeof", "cursor", ".", "s", ".", "transforms", ".", "doc", "===", "'function'", ")", "{", "docs", "=", "docs", ".", "map", "(", "cursor", ".", "s", ".", "transforms", ".", "doc", ")", ";", "}", "push", ".", "apply", "(", "items", ",", "docs", ")", ";", "}", "// Attempt a fetch", "fetchDocs", "(", ")", ";", "}", ")", ";", "}", ";", "fetchDocs", "(", ")", ";", "}" ]
Returns an array of documents. See Cursor.prototype.toArray for more information. @method @param {Cursor} cursor The Cursor instance from which to get the next document. @param {Cursor~toArrayResultCallback} [callback] The result callback.
[ "Returns", "an", "array", "of", "documents", ".", "See", "Cursor", ".", "prototype", ".", "toArray", "for", "more", "information", "." ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/mongodb/lib/operations/cursor_ops.js#L198-L240
55,009
composi/idb
src/index.js
get
function get(key, store = getDefaultStore()) { let req return store[IDBStore]('readonly', store => { req = store.get(key) }).then(() => req.result) }
javascript
function get(key, store = getDefaultStore()) { let req return store[IDBStore]('readonly', store => { req = store.get(key) }).then(() => req.result) }
[ "function", "get", "(", "key", ",", "store", "=", "getDefaultStore", "(", ")", ")", "{", "let", "req", "return", "store", "[", "IDBStore", "]", "(", "'readonly'", ",", "store", "=>", "{", "req", "=", "store", ".", "get", "(", "key", ")", "}", ")", ".", "then", "(", "(", ")", "=>", "req", ".", "result", ")", "}" ]
Get a value based on the provided key. @param {string} key The key to use. @param {any} store A default value provided by IDB. @return {Promise} Promise
[ "Get", "a", "value", "based", "on", "the", "provided", "key", "." ]
f64c25ec2b90d23b04820722bac758bc869f0871
https://github.com/composi/idb/blob/f64c25ec2b90d23b04820722bac758bc869f0871/src/index.js#L53-L58
55,010
constantology/id8
src/Source.js
function( config ) { !is_obj( config ) || Object.keys( config ).forEach( function( key ) { if ( typeof config[key] == 'function' && typeof this[key] == 'function' ) // this allows you to override a method for a this[__override__]( key, config[key] ); // specific instance of a Class, rather than require else // you extend the Class for a few minor changes this[key] = config[key]; // NB: can also be achieved by creating a `singleton` }, this ); util.def( this, __config__, { value : config }, 'r', true ); }
javascript
function( config ) { !is_obj( config ) || Object.keys( config ).forEach( function( key ) { if ( typeof config[key] == 'function' && typeof this[key] == 'function' ) // this allows you to override a method for a this[__override__]( key, config[key] ); // specific instance of a Class, rather than require else // you extend the Class for a few minor changes this[key] = config[key]; // NB: can also be achieved by creating a `singleton` }, this ); util.def( this, __config__, { value : config }, 'r', true ); }
[ "function", "(", "config", ")", "{", "!", "is_obj", "(", "config", ")", "||", "Object", ".", "keys", "(", "config", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "typeof", "config", "[", "key", "]", "==", "'function'", "&&", "typeof", "this", "[", "key", "]", "==", "'function'", ")", "// this allows you to override a method for a", "this", "[", "__override__", "]", "(", "key", ",", "config", "[", "key", "]", ")", ";", "// specific instance of a Class, rather than require", "else", "// you extend the Class for a few minor changes", "this", "[", "key", "]", "=", "config", "[", "key", "]", ";", "// NB: can also be achieved by creating a `singleton`", "}", ",", "this", ")", ";", "util", ".", "def", "(", "this", ",", "__config__", ",", "{", "value", ":", "config", "}", ",", "'r'", ",", "true", ")", ";", "}" ]
this is set by `beforeinstance` to avoid weird behaviour constructor methods
[ "this", "is", "set", "by", "beforeinstance", "to", "avoid", "weird", "behaviour", "constructor", "methods" ]
8e97cbf56406da2cd53f825fa4f24ae2263971ce
https://github.com/constantology/id8/blob/8e97cbf56406da2cd53f825fa4f24ae2263971ce/src/Source.js#L115-L124
55,011
antonycourtney/tabli-core
lib/js/tabWindow.js
makeBookmarkedTabItem
function makeBookmarkedTabItem(bm) { var urlStr = bm.url; if (!urlStr) { console.error('makeBookmarkedTabItem: Malformed bookmark: missing URL!: ', bm); urlStr = ''; // better than null or undefined! } if (bm.title === undefined) { console.warn('makeBookmarkedTabItem: Bookmark title undefined (ignoring...): ', bm); } var tabItem = new TabItem({ url: urlStr, saved: true, savedTitle: _.get(bm, 'title', urlStr), savedBookmarkId: bm.id, savedBookmarkIndex: bm.index }); return tabItem; }
javascript
function makeBookmarkedTabItem(bm) { var urlStr = bm.url; if (!urlStr) { console.error('makeBookmarkedTabItem: Malformed bookmark: missing URL!: ', bm); urlStr = ''; // better than null or undefined! } if (bm.title === undefined) { console.warn('makeBookmarkedTabItem: Bookmark title undefined (ignoring...): ', bm); } var tabItem = new TabItem({ url: urlStr, saved: true, savedTitle: _.get(bm, 'title', urlStr), savedBookmarkId: bm.id, savedBookmarkIndex: bm.index }); return tabItem; }
[ "function", "makeBookmarkedTabItem", "(", "bm", ")", "{", "var", "urlStr", "=", "bm", ".", "url", ";", "if", "(", "!", "urlStr", ")", "{", "console", ".", "error", "(", "'makeBookmarkedTabItem: Malformed bookmark: missing URL!: '", ",", "bm", ")", ";", "urlStr", "=", "''", ";", "// better than null or undefined!", "}", "if", "(", "bm", ".", "title", "===", "undefined", ")", "{", "console", ".", "warn", "(", "'makeBookmarkedTabItem: Bookmark title undefined (ignoring...): '", ",", "bm", ")", ";", "}", "var", "tabItem", "=", "new", "TabItem", "(", "{", "url", ":", "urlStr", ",", "saved", ":", "true", ",", "savedTitle", ":", "_", ".", "get", "(", "bm", ",", "'title'", ",", "urlStr", ")", ",", "savedBookmarkId", ":", "bm", ".", "id", ",", "savedBookmarkIndex", ":", "bm", ".", "index", "}", ")", ";", "return", "tabItem", ";", "}" ]
Initialize a TabItem from a bookmark Returned TabItem is closed (not associated with an open tab)
[ "Initialize", "a", "TabItem", "from", "a", "bookmark" ]
76cc540891421bc6c8bdcf00f277ebb6e716fdd9
https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/tabWindow.js#L97-L119
55,012
antonycourtney/tabli-core
lib/js/tabWindow.js
makeOpenTabItem
function makeOpenTabItem(tab) { var urlStr = tab.url; if (!urlStr) { console.error('malformed tab -- no URL: ', tab); urlStr = ''; } /* if (!tab.title) { console.warn("tab missing title (ignoring...): ", tab); } */ var tabItem = new TabItem({ url: urlStr, audible: tab.audible, favIconUrl: tab.favIconUrl, open: true, tabTitle: _.get(tab, 'title', urlStr), openTabId: tab.id, active: tab.active, openTabIndex: tab.index }); return tabItem; }
javascript
function makeOpenTabItem(tab) { var urlStr = tab.url; if (!urlStr) { console.error('malformed tab -- no URL: ', tab); urlStr = ''; } /* if (!tab.title) { console.warn("tab missing title (ignoring...): ", tab); } */ var tabItem = new TabItem({ url: urlStr, audible: tab.audible, favIconUrl: tab.favIconUrl, open: true, tabTitle: _.get(tab, 'title', urlStr), openTabId: tab.id, active: tab.active, openTabIndex: tab.index }); return tabItem; }
[ "function", "makeOpenTabItem", "(", "tab", ")", "{", "var", "urlStr", "=", "tab", ".", "url", ";", "if", "(", "!", "urlStr", ")", "{", "console", ".", "error", "(", "'malformed tab -- no URL: '", ",", "tab", ")", ";", "urlStr", "=", "''", ";", "}", "/*\n if (!tab.title) {\n console.warn(\"tab missing title (ignoring...): \", tab);\n }\n */", "var", "tabItem", "=", "new", "TabItem", "(", "{", "url", ":", "urlStr", ",", "audible", ":", "tab", ".", "audible", ",", "favIconUrl", ":", "tab", ".", "favIconUrl", ",", "open", ":", "true", ",", "tabTitle", ":", "_", ".", "get", "(", "tab", ",", "'title'", ",", "urlStr", ")", ",", "openTabId", ":", "tab", ".", "id", ",", "active", ":", "tab", ".", "active", ",", "openTabIndex", ":", "tab", ".", "index", "}", ")", ";", "return", "tabItem", ";", "}" ]
Initialize a TabItem from an open Chrome tab
[ "Initialize", "a", "TabItem", "from", "an", "open", "Chrome", "tab" ]
76cc540891421bc6c8bdcf00f277ebb6e716fdd9
https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/tabWindow.js#L124-L146
55,013
antonycourtney/tabli-core
lib/js/tabWindow.js
mergeOpenTabs
function mergeOpenTabs(tabItems, openTabs) { var tabInfo = getOpenTabInfo(tabItems, openTabs); /* TODO: Use algorithm from OLDtabWindow.js to determine tab order. * For now, let's just concat open and closed tabs, in their sorted order. */ var openTabItems = tabInfo.get(true, Immutable.Seq()).sortBy(function (ti) { return ti.openTabIndex; }); var closedTabItems = tabInfo.get(false, Immutable.Seq()).sortBy(function (ti) { return ti.savedBookmarkIndex; }); var mergedTabItems = openTabItems.concat(closedTabItems); return mergedTabItems; }
javascript
function mergeOpenTabs(tabItems, openTabs) { var tabInfo = getOpenTabInfo(tabItems, openTabs); /* TODO: Use algorithm from OLDtabWindow.js to determine tab order. * For now, let's just concat open and closed tabs, in their sorted order. */ var openTabItems = tabInfo.get(true, Immutable.Seq()).sortBy(function (ti) { return ti.openTabIndex; }); var closedTabItems = tabInfo.get(false, Immutable.Seq()).sortBy(function (ti) { return ti.savedBookmarkIndex; }); var mergedTabItems = openTabItems.concat(closedTabItems); return mergedTabItems; }
[ "function", "mergeOpenTabs", "(", "tabItems", ",", "openTabs", ")", "{", "var", "tabInfo", "=", "getOpenTabInfo", "(", "tabItems", ",", "openTabs", ")", ";", "/* TODO: Use algorithm from OLDtabWindow.js to determine tab order.\n * For now, let's just concat open and closed tabs, in their sorted order.\n */", "var", "openTabItems", "=", "tabInfo", ".", "get", "(", "true", ",", "Immutable", ".", "Seq", "(", ")", ")", ".", "sortBy", "(", "function", "(", "ti", ")", "{", "return", "ti", ".", "openTabIndex", ";", "}", ")", ";", "var", "closedTabItems", "=", "tabInfo", ".", "get", "(", "false", ",", "Immutable", ".", "Seq", "(", ")", ")", ".", "sortBy", "(", "function", "(", "ti", ")", "{", "return", "ti", ".", "savedBookmarkIndex", ";", "}", ")", ";", "var", "mergedTabItems", "=", "openTabItems", ".", "concat", "(", "closedTabItems", ")", ";", "return", "mergedTabItems", ";", "}" ]
Merge currently open tabs from an open Chrome window with tabItem state of a saved tabWindow @param {Seq<TabItem>} tabItems -- previous TabItem state @param {[Tab]} openTabs -- currently open tabs from Chrome window @returns {Seq<TabItem>} TabItems reflecting current window state
[ "Merge", "currently", "open", "tabs", "from", "an", "open", "Chrome", "window", "with", "tabItem", "state", "of", "a", "saved", "tabWindow" ]
76cc540891421bc6c8bdcf00f277ebb6e716fdd9
https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/tabWindow.js#L370-L386
55,014
antonycourtney/tabli-core
lib/js/tabWindow.js
updateWindow
function updateWindow(tabWindow, chromeWindow) { // console.log("updateWindow: ", tabWindow.toJS(), chromeWindow); var mergedTabItems = mergeOpenTabs(tabWindow.tabItems, chromeWindow.tabs); var updWindow = tabWindow.set('tabItems', mergedTabItems).set('focused', chromeWindow.focused).set('open', true).set('openWindowId', chromeWindow.id); return updWindow; }
javascript
function updateWindow(tabWindow, chromeWindow) { // console.log("updateWindow: ", tabWindow.toJS(), chromeWindow); var mergedTabItems = mergeOpenTabs(tabWindow.tabItems, chromeWindow.tabs); var updWindow = tabWindow.set('tabItems', mergedTabItems).set('focused', chromeWindow.focused).set('open', true).set('openWindowId', chromeWindow.id); return updWindow; }
[ "function", "updateWindow", "(", "tabWindow", ",", "chromeWindow", ")", "{", "// console.log(\"updateWindow: \", tabWindow.toJS(), chromeWindow);", "var", "mergedTabItems", "=", "mergeOpenTabs", "(", "tabWindow", ".", "tabItems", ",", "chromeWindow", ".", "tabs", ")", ";", "var", "updWindow", "=", "tabWindow", ".", "set", "(", "'tabItems'", ",", "mergedTabItems", ")", ".", "set", "(", "'focused'", ",", "chromeWindow", ".", "focused", ")", ".", "set", "(", "'open'", ",", "true", ")", ".", "set", "(", "'openWindowId'", ",", "chromeWindow", ".", "id", ")", ";", "return", "updWindow", ";", "}" ]
update a TabWindow from a current snapshot of the Chrome Window @param {TabWindow} tabWindow - TabWindow to be updated @param {ChromeWindow} chromeWindow - current snapshot of Chrome window state @return {TabWindow} Updated TabWindow
[ "update", "a", "TabWindow", "from", "a", "current", "snapshot", "of", "the", "Chrome", "Window" ]
76cc540891421bc6c8bdcf00f277ebb6e716fdd9
https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/tabWindow.js#L396-L401
55,015
antonycourtney/tabli-core
lib/js/tabWindow.js
saveTab
function saveTab(tabWindow, tabItem, tabNode) { var _tabWindow$tabItems$f3 = tabWindow.tabItems.findEntry(function (ti) { return ti.open && ti.openTabId === tabItem.openTabId; }); var _tabWindow$tabItems$f4 = _slicedToArray(_tabWindow$tabItems$f3, 1); var index = _tabWindow$tabItems$f4[0]; var updTabItem = tabItem.set('saved', true).set('savedTitle', tabNode.title).set('savedBookmarkId', tabNode.id).set('savedBookmarkIndex', tabNode.index); var updItems = tabWindow.tabItems.splice(index, 1, updTabItem); return tabWindow.set('tabItems', updItems); }
javascript
function saveTab(tabWindow, tabItem, tabNode) { var _tabWindow$tabItems$f3 = tabWindow.tabItems.findEntry(function (ti) { return ti.open && ti.openTabId === tabItem.openTabId; }); var _tabWindow$tabItems$f4 = _slicedToArray(_tabWindow$tabItems$f3, 1); var index = _tabWindow$tabItems$f4[0]; var updTabItem = tabItem.set('saved', true).set('savedTitle', tabNode.title).set('savedBookmarkId', tabNode.id).set('savedBookmarkIndex', tabNode.index); var updItems = tabWindow.tabItems.splice(index, 1, updTabItem); return tabWindow.set('tabItems', updItems); }
[ "function", "saveTab", "(", "tabWindow", ",", "tabItem", ",", "tabNode", ")", "{", "var", "_tabWindow$tabItems$f3", "=", "tabWindow", ".", "tabItems", ".", "findEntry", "(", "function", "(", "ti", ")", "{", "return", "ti", ".", "open", "&&", "ti", ".", "openTabId", "===", "tabItem", ".", "openTabId", ";", "}", ")", ";", "var", "_tabWindow$tabItems$f4", "=", "_slicedToArray", "(", "_tabWindow$tabItems$f3", ",", "1", ")", ";", "var", "index", "=", "_tabWindow$tabItems$f4", "[", "0", "]", ";", "var", "updTabItem", "=", "tabItem", ".", "set", "(", "'saved'", ",", "true", ")", ".", "set", "(", "'savedTitle'", ",", "tabNode", ".", "title", ")", ".", "set", "(", "'savedBookmarkId'", ",", "tabNode", ".", "id", ")", ".", "set", "(", "'savedBookmarkIndex'", ",", "tabNode", ".", "index", ")", ";", "var", "updItems", "=", "tabWindow", ".", "tabItems", ".", "splice", "(", "index", ",", "1", ",", "updTabItem", ")", ";", "return", "tabWindow", ".", "set", "(", "'tabItems'", ",", "updItems", ")", ";", "}" ]
Update a tab's saved state @param {TabWindow} tabWindow - tab window with tab that's been closed @param {TabItem} tabItem -- open tab that has been saved @param {BookmarkTreeNode} tabNode -- bookmark node for saved bookmark @return {TabWindow} tabWindow with tabItems updated to reflect saved state
[ "Update", "a", "tab", "s", "saved", "state" ]
76cc540891421bc6c8bdcf00f277ebb6e716fdd9
https://github.com/antonycourtney/tabli-core/blob/76cc540891421bc6c8bdcf00f277ebb6e716fdd9/lib/js/tabWindow.js#L445-L460
55,016
terryweiss/papyrus-core
document/probe.js
pushin
function pushin( path, record, setter, newValue ) { var context = record; var parent = record; var lastPart = null; var _i; var _len; var part; var keys; for ( _i = 0, _len = path.length; _i < _len; _i++ ) { part = path[_i]; lastPart = part; parent = context; context = context[part]; if ( sys.isNull( context ) || sys.isUndefined( context ) ) { parent[part] = {}; context = parent[part]; } } if ( sys.isEmpty( setter ) || setter === '$set' ) { parent[lastPart] = newValue; return parent[lastPart]; } else { switch ( setter ) { case '$inc': /** * Increments a field by the amount you specify. It takes the form * `{ $inc: { field1: amount } }` * @name $inc * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'}, * {$inc : {'password.changes' : 2}} ); */ if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( sys.isNumber( parent[lastPart] ) ) { parent[lastPart] = parent[lastPart] + newValue; return parent[lastPart]; } break; case '$dec': /** * Decrements a field by the amount you specify. It takes the form * `{ $dec: { field1: amount }` * @name $dec * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'}, * {$dec : {'password.changes' : 2}} ); */ if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( sys.isNumber( parent[lastPart] ) ) { parent[lastPart] = parent[lastPart] - newValue; return parent[lastPart]; } break; case '$unset': /** * Removes the field from the object. It takes the form * `{ $unset: { field1: "" } }` * @name $unset * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( data, {'name.first' : 'Yogi'}, {$unset : {'name.first' : ''}} ); */ return delete parent[lastPart]; case '$pop': /** * The $pop operator removes the first or last element of an array. Pass $pop a value of 1 to remove the last element * in an array and a value of -1 to remove the first element of an array. This will only work on arrays. Syntax: * `{ $pop: { field: 1 } }` or `{ $pop: { field: -1 } }` * @name $pop * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {_id : '511d18827da2b88b09000133'}, {$pop : {attr : 1}} ); */ if ( sys.isArray( parent[lastPart] ) ) { if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( newValue === 1 ) { return parent[lastPart].pop(); } else { return parent[lastPart].shift(); } } break; case '$push': /** * The $push operator appends a specified value to an array. It looks like this: * `{ $push: { <field>: <value> } }` * @name $push * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {_id : '511d18827da2b88b09000133'}, * {$push : {attr : {"hand" : "new", "color" : "new"}}} ); */ if ( sys.isArray( parent[lastPart] ) ) { return parent[lastPart].push( newValue ); } break; case '$pull': /** * The $pull operator removes all instances of a value from an existing array. It looks like this: * `{ $pull: { field: <query> } }` * @name $pull * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {'email' : '[email protected]'}, * {$pull : {attr : {"color" : "green"}}} ); */ if ( sys.isArray( parent[lastPart] ) ) { keys = exports.findKeys( parent[lastPart], newValue ); sys.each( keys, function ( val, index ) { return delete parent[lastPart][index]; } ); parent[lastPart] = sys.compact( parent[lastPart] ); return parent[lastPart]; } } } }
javascript
function pushin( path, record, setter, newValue ) { var context = record; var parent = record; var lastPart = null; var _i; var _len; var part; var keys; for ( _i = 0, _len = path.length; _i < _len; _i++ ) { part = path[_i]; lastPart = part; parent = context; context = context[part]; if ( sys.isNull( context ) || sys.isUndefined( context ) ) { parent[part] = {}; context = parent[part]; } } if ( sys.isEmpty( setter ) || setter === '$set' ) { parent[lastPart] = newValue; return parent[lastPart]; } else { switch ( setter ) { case '$inc': /** * Increments a field by the amount you specify. It takes the form * `{ $inc: { field1: amount } }` * @name $inc * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'}, * {$inc : {'password.changes' : 2}} ); */ if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( sys.isNumber( parent[lastPart] ) ) { parent[lastPart] = parent[lastPart] + newValue; return parent[lastPart]; } break; case '$dec': /** * Decrements a field by the amount you specify. It takes the form * `{ $dec: { field1: amount }` * @name $dec * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'}, * {$dec : {'password.changes' : 2}} ); */ if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( sys.isNumber( parent[lastPart] ) ) { parent[lastPart] = parent[lastPart] - newValue; return parent[lastPart]; } break; case '$unset': /** * Removes the field from the object. It takes the form * `{ $unset: { field1: "" } }` * @name $unset * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * probe.update( data, {'name.first' : 'Yogi'}, {$unset : {'name.first' : ''}} ); */ return delete parent[lastPart]; case '$pop': /** * The $pop operator removes the first or last element of an array. Pass $pop a value of 1 to remove the last element * in an array and a value of -1 to remove the first element of an array. This will only work on arrays. Syntax: * `{ $pop: { field: 1 } }` or `{ $pop: { field: -1 } }` * @name $pop * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {_id : '511d18827da2b88b09000133'}, {$pop : {attr : 1}} ); */ if ( sys.isArray( parent[lastPart] ) ) { if ( !sys.isNumber( newValue ) ) { newValue = 1; } if ( newValue === 1 ) { return parent[lastPart].pop(); } else { return parent[lastPart].shift(); } } break; case '$push': /** * The $push operator appends a specified value to an array. It looks like this: * `{ $push: { <field>: <value> } }` * @name $push * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {_id : '511d18827da2b88b09000133'}, * {$push : {attr : {"hand" : "new", "color" : "new"}}} ); */ if ( sys.isArray( parent[lastPart] ) ) { return parent[lastPart].push( newValue ); } break; case '$pull': /** * The $pull operator removes all instances of a value from an existing array. It looks like this: * `{ $pull: { field: <query> } }` * @name $pull * @memberOf module:document/probe.updateOperators * @example * var probe = require("document/probe"); * // attr is the name of the array field * probe.update( data, {'email' : '[email protected]'}, * {$pull : {attr : {"color" : "green"}}} ); */ if ( sys.isArray( parent[lastPart] ) ) { keys = exports.findKeys( parent[lastPart], newValue ); sys.each( keys, function ( val, index ) { return delete parent[lastPart][index]; } ); parent[lastPart] = sys.compact( parent[lastPart] ); return parent[lastPart]; } } } }
[ "function", "pushin", "(", "path", ",", "record", ",", "setter", ",", "newValue", ")", "{", "var", "context", "=", "record", ";", "var", "parent", "=", "record", ";", "var", "lastPart", "=", "null", ";", "var", "_i", ";", "var", "_len", ";", "var", "part", ";", "var", "keys", ";", "for", "(", "_i", "=", "0", ",", "_len", "=", "path", ".", "length", ";", "_i", "<", "_len", ";", "_i", "++", ")", "{", "part", "=", "path", "[", "_i", "]", ";", "lastPart", "=", "part", ";", "parent", "=", "context", ";", "context", "=", "context", "[", "part", "]", ";", "if", "(", "sys", ".", "isNull", "(", "context", ")", "||", "sys", ".", "isUndefined", "(", "context", ")", ")", "{", "parent", "[", "part", "]", "=", "{", "}", ";", "context", "=", "parent", "[", "part", "]", ";", "}", "}", "if", "(", "sys", ".", "isEmpty", "(", "setter", ")", "||", "setter", "===", "'$set'", ")", "{", "parent", "[", "lastPart", "]", "=", "newValue", ";", "return", "parent", "[", "lastPart", "]", ";", "}", "else", "{", "switch", "(", "setter", ")", "{", "case", "'$inc'", ":", "/**\n\t\t\t\t * Increments a field by the amount you specify. It takes the form\n\t\t\t\t * `{ $inc: { field1: amount } }`\n\t\t\t\t * @name $inc\n\t\t\t\t * @memberOf module:document/probe.updateOperators\n\t\t\t\t * @example\n\t\t\t\t * var probe = require(\"document/probe\");\n\t\t\t\t * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'},\n\t\t\t\t * {$inc : {'password.changes' : 2}} );\n\t\t\t\t */", "if", "(", "!", "sys", ".", "isNumber", "(", "newValue", ")", ")", "{", "newValue", "=", "1", ";", "}", "if", "(", "sys", ".", "isNumber", "(", "parent", "[", "lastPart", "]", ")", ")", "{", "parent", "[", "lastPart", "]", "=", "parent", "[", "lastPart", "]", "+", "newValue", ";", "return", "parent", "[", "lastPart", "]", ";", "}", "break", ";", "case", "'$dec'", ":", "/**\n\t\t\t\t * Decrements a field by the amount you specify. It takes the form\n\t\t\t\t * `{ $dec: { field1: amount }`\n * @name $dec\n\t\t\t\t * @memberOf module:document/probe.updateOperators\n\t\t\t\t * @example\n\t\t\t\t * var probe = require(\"document/probe\");\n\t\t\t\t * probe.update( obj, {'name.last' : 'Owen', 'name.first' : 'LeRoy'},\n\t\t\t\t * {$dec : {'password.changes' : 2}} );\n\t\t\t\t */", "if", "(", "!", "sys", ".", "isNumber", "(", "newValue", ")", ")", "{", "newValue", "=", "1", ";", "}", "if", "(", "sys", ".", "isNumber", "(", "parent", "[", "lastPart", "]", ")", ")", "{", "parent", "[", "lastPart", "]", "=", "parent", "[", "lastPart", "]", "-", "newValue", ";", "return", "parent", "[", "lastPart", "]", ";", "}", "break", ";", "case", "'$unset'", ":", "/**\n\t\t\t\t * Removes the field from the object. It takes the form\n\t\t\t\t * `{ $unset: { field1: \"\" } }`\n\t\t\t\t * @name $unset\n\t\t\t\t * @memberOf module:document/probe.updateOperators\n\t\t\t\t * @example\n\t\t\t\t * var probe = require(\"document/probe\");\n\t\t\t\t * probe.update( data, {'name.first' : 'Yogi'}, {$unset : {'name.first' : ''}} );\n\t\t\t\t */", "return", "delete", "parent", "[", "lastPart", "]", ";", "case", "'$pop'", ":", "/**\n\t\t\t\t * The $pop operator removes the first or last element of an array. Pass $pop a value of 1 to remove the last element\n\t\t\t\t * in an array and a value of -1 to remove the first element of an array. This will only work on arrays. Syntax:\n\t\t\t\t * `{ $pop: { field: 1 } }` or `{ $pop: { field: -1 } }`\n\t\t\t\t * @name $pop\n\t\t\t\t * @memberOf module:document/probe.updateOperators\n\t\t\t\t * @example\n\t\t\t\t * var probe = require(\"document/probe\");\n\t\t\t\t * // attr is the name of the array field\n\t\t\t\t * probe.update( data, {_id : '511d18827da2b88b09000133'}, {$pop : {attr : 1}} );\n\t\t\t\t */", "if", "(", "sys", ".", "isArray", "(", "parent", "[", "lastPart", "]", ")", ")", "{", "if", "(", "!", "sys", ".", "isNumber", "(", "newValue", ")", ")", "{", "newValue", "=", "1", ";", "}", "if", "(", "newValue", "===", "1", ")", "{", "return", "parent", "[", "lastPart", "]", ".", "pop", "(", ")", ";", "}", "else", "{", "return", "parent", "[", "lastPart", "]", ".", "shift", "(", ")", ";", "}", "}", "break", ";", "case", "'$push'", ":", "/**\n\t\t\t\t * The $push operator appends a specified value to an array. It looks like this:\n\t\t\t\t * `{ $push: { <field>: <value> } }`\n\t\t\t\t * @name $push\n\t\t\t\t * @memberOf module:document/probe.updateOperators\n\t\t\t\t * @example\n\t\t\t\t * var probe = require(\"document/probe\");\n\t\t\t\t * // attr is the name of the array field\n\t\t\t\t * probe.update( data, {_id : '511d18827da2b88b09000133'},\n\t\t\t\t * {$push : {attr : {\"hand\" : \"new\", \"color\" : \"new\"}}} );\n\t\t\t\t */", "if", "(", "sys", ".", "isArray", "(", "parent", "[", "lastPart", "]", ")", ")", "{", "return", "parent", "[", "lastPart", "]", ".", "push", "(", "newValue", ")", ";", "}", "break", ";", "case", "'$pull'", ":", "/**\n\t\t\t\t * The $pull operator removes all instances of a value from an existing array. It looks like this:\n\t\t\t\t * `{ $pull: { field: <query> } }`\n\t\t\t\t * @name $pull\n\t\t\t\t * @memberOf module:document/probe.updateOperators\n\t\t\t\t * @example\n\t\t\t\t * var probe = require(\"document/probe\");\n\t\t\t\t * // attr is the name of the array field\n\t\t\t\t * probe.update( data, {'email' : '[email protected]'},\n\t\t\t\t * {$pull : {attr : {\"color\" : \"green\"}}} );\n\t\t\t\t */", "if", "(", "sys", ".", "isArray", "(", "parent", "[", "lastPart", "]", ")", ")", "{", "keys", "=", "exports", ".", "findKeys", "(", "parent", "[", "lastPart", "]", ",", "newValue", ")", ";", "sys", ".", "each", "(", "keys", ",", "function", "(", "val", ",", "index", ")", "{", "return", "delete", "parent", "[", "lastPart", "]", "[", "index", "]", ";", "}", ")", ";", "parent", "[", "lastPart", "]", "=", "sys", ".", "compact", "(", "parent", "[", "lastPart", "]", ")", ";", "return", "parent", "[", "lastPart", "]", ";", "}", "}", "}", "}" ]
This will write the value into a record at the path, creating intervening objects if they don't exist @private @param {array} path The split path of the element to work with @param {object} record The record to reach into @param {string} setter The set command, defaults to $set @param {object} newValue The value to write to the, or if the operator is $pull, the query of items to look for
[ "This", "will", "write", "the", "value", "into", "a", "record", "at", "the", "path", "creating", "intervening", "objects", "if", "they", "don", "t", "exist" ]
d80fbcc2a8d07492477bab49df41c536e9a9230b
https://github.com/terryweiss/papyrus-core/blob/d80fbcc2a8d07492477bab49df41c536e9a9230b/document/probe.js#L199-L340
55,017
forfuturellc/svc-fbr
src/lib/fs.js
handle
function handle(options, callback) { if (_.isString(options)) { options = { path: options }; } if (_.isObject(options)) { const opts = { }; _.merge(opts, config, options); options = opts; } else { options = _.cloneDeep(config); } options.path = options.path || config.get("home"); return stat(options.path, function(err, stats) { if (err) { return callback(err); } const done = wrap(stats, callback); if (stats.isDirectory()) { options.dirStats = stats; return processDir(options, done); } else if (stats.isFile()) { return processFile(options, done); } return callback(null, null); }); }
javascript
function handle(options, callback) { if (_.isString(options)) { options = { path: options }; } if (_.isObject(options)) { const opts = { }; _.merge(opts, config, options); options = opts; } else { options = _.cloneDeep(config); } options.path = options.path || config.get("home"); return stat(options.path, function(err, stats) { if (err) { return callback(err); } const done = wrap(stats, callback); if (stats.isDirectory()) { options.dirStats = stats; return processDir(options, done); } else if (stats.isFile()) { return processFile(options, done); } return callback(null, null); }); }
[ "function", "handle", "(", "options", ",", "callback", ")", "{", "if", "(", "_", ".", "isString", "(", "options", ")", ")", "{", "options", "=", "{", "path", ":", "options", "}", ";", "}", "if", "(", "_", ".", "isObject", "(", "options", ")", ")", "{", "const", "opts", "=", "{", "}", ";", "_", ".", "merge", "(", "opts", ",", "config", ",", "options", ")", ";", "options", "=", "opts", ";", "}", "else", "{", "options", "=", "_", ".", "cloneDeep", "(", "config", ")", ";", "}", "options", ".", "path", "=", "options", ".", "path", "||", "config", ".", "get", "(", "\"home\"", ")", ";", "return", "stat", "(", "options", ".", "path", ",", "function", "(", "err", ",", "stats", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "const", "done", "=", "wrap", "(", "stats", ",", "callback", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "options", ".", "dirStats", "=", "stats", ";", "return", "processDir", "(", "options", ",", "done", ")", ";", "}", "else", "if", "(", "stats", ".", "isFile", "(", ")", ")", "{", "return", "processFile", "(", "options", ",", "done", ")", ";", "}", "return", "callback", "(", "null", ",", "null", ")", ";", "}", ")", ";", "}" ]
Handling requests for browsing file-system @param {Object|String} options @param {Function} callback
[ "Handling", "requests", "for", "browsing", "file", "-", "system" ]
8c07c71d6423d1dbd4f903a032dea0bfec63894e
https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/fs.js#L29-L59
55,018
fd/fd-angular-core
lib/Component.js
Component
function Component(opts) { if (typeof opts === "function") { var _constructor = opts;opts = null; return register(_constructor); } opts = opts || {}; var _opts = opts; var _opts$restrict = _opts.restrict; var restrict = _opts$restrict === undefined ? "EA" : _opts$restrict; var _opts$replace = _opts.replace; var replace = _opts$replace === undefined ? false : _opts$replace; var _opts$transclude = _opts.transclude; var transclude = _opts$transclude === undefined ? false : _opts$transclude; var _opts$scope = _opts.scope; var scope = _opts$scope === undefined ? {} : _opts$scope; var template = _opts.template; var templateUrl = _opts.templateUrl; return register; function register(constructor) { (0, _Controller.Controller)(constructor); var meta = (0, _utils.funcMeta)(constructor); var name = meta.name; name = name[0].toLowerCase() + name.substr(1, name.length - DEFAULT_SUFFIX.length - 1); if (!template && !templateUrl && template !== false) { var tmplName = (0, _utils.dashCase)(name); templateUrl = "./components/" + tmplName + "/" + tmplName + ".html"; } if (template === false) { template = undefined; templateUrl = undefined; } _app.app.directive(name, function () { return { restrict: restrict, scope: scope, bindToController: true, controller: meta.controller.name, controllerAs: name, template: template, templateUrl: templateUrl, replace: replace, transclude: transclude }; }); } }
javascript
function Component(opts) { if (typeof opts === "function") { var _constructor = opts;opts = null; return register(_constructor); } opts = opts || {}; var _opts = opts; var _opts$restrict = _opts.restrict; var restrict = _opts$restrict === undefined ? "EA" : _opts$restrict; var _opts$replace = _opts.replace; var replace = _opts$replace === undefined ? false : _opts$replace; var _opts$transclude = _opts.transclude; var transclude = _opts$transclude === undefined ? false : _opts$transclude; var _opts$scope = _opts.scope; var scope = _opts$scope === undefined ? {} : _opts$scope; var template = _opts.template; var templateUrl = _opts.templateUrl; return register; function register(constructor) { (0, _Controller.Controller)(constructor); var meta = (0, _utils.funcMeta)(constructor); var name = meta.name; name = name[0].toLowerCase() + name.substr(1, name.length - DEFAULT_SUFFIX.length - 1); if (!template && !templateUrl && template !== false) { var tmplName = (0, _utils.dashCase)(name); templateUrl = "./components/" + tmplName + "/" + tmplName + ".html"; } if (template === false) { template = undefined; templateUrl = undefined; } _app.app.directive(name, function () { return { restrict: restrict, scope: scope, bindToController: true, controller: meta.controller.name, controllerAs: name, template: template, templateUrl: templateUrl, replace: replace, transclude: transclude }; }); } }
[ "function", "Component", "(", "opts", ")", "{", "if", "(", "typeof", "opts", "===", "\"function\"", ")", "{", "var", "_constructor", "=", "opts", ";", "opts", "=", "null", ";", "return", "register", "(", "_constructor", ")", ";", "}", "opts", "=", "opts", "||", "{", "}", ";", "var", "_opts", "=", "opts", ";", "var", "_opts$restrict", "=", "_opts", ".", "restrict", ";", "var", "restrict", "=", "_opts$restrict", "===", "undefined", "?", "\"EA\"", ":", "_opts$restrict", ";", "var", "_opts$replace", "=", "_opts", ".", "replace", ";", "var", "replace", "=", "_opts$replace", "===", "undefined", "?", "false", ":", "_opts$replace", ";", "var", "_opts$transclude", "=", "_opts", ".", "transclude", ";", "var", "transclude", "=", "_opts$transclude", "===", "undefined", "?", "false", ":", "_opts$transclude", ";", "var", "_opts$scope", "=", "_opts", ".", "scope", ";", "var", "scope", "=", "_opts$scope", "===", "undefined", "?", "{", "}", ":", "_opts$scope", ";", "var", "template", "=", "_opts", ".", "template", ";", "var", "templateUrl", "=", "_opts", ".", "templateUrl", ";", "return", "register", ";", "function", "register", "(", "constructor", ")", "{", "(", "0", ",", "_Controller", ".", "Controller", ")", "(", "constructor", ")", ";", "var", "meta", "=", "(", "0", ",", "_utils", ".", "funcMeta", ")", "(", "constructor", ")", ";", "var", "name", "=", "meta", ".", "name", ";", "name", "=", "name", "[", "0", "]", ".", "toLowerCase", "(", ")", "+", "name", ".", "substr", "(", "1", ",", "name", ".", "length", "-", "DEFAULT_SUFFIX", ".", "length", "-", "1", ")", ";", "if", "(", "!", "template", "&&", "!", "templateUrl", "&&", "template", "!==", "false", ")", "{", "var", "tmplName", "=", "(", "0", ",", "_utils", ".", "dashCase", ")", "(", "name", ")", ";", "templateUrl", "=", "\"./components/\"", "+", "tmplName", "+", "\"/\"", "+", "tmplName", "+", "\".html\"", ";", "}", "if", "(", "template", "===", "false", ")", "{", "template", "=", "undefined", ";", "templateUrl", "=", "undefined", ";", "}", "_app", ".", "app", ".", "directive", "(", "name", ",", "function", "(", ")", "{", "return", "{", "restrict", ":", "restrict", ",", "scope", ":", "scope", ",", "bindToController", ":", "true", ",", "controller", ":", "meta", ".", "controller", ".", "name", ",", "controllerAs", ":", "name", ",", "template", ":", "template", ",", "templateUrl", ":", "templateUrl", ",", "replace", ":", "replace", ",", "transclude", ":", "transclude", "}", ";", "}", ")", ";", "}", "}" ]
Declare an angular Component directive. @function Component @param {Object} [opts] @param {String} [opts.name] @param {String} [opts.restrict="EA"] @param {Boolean} [opts.restrict="false"] @param {Boolean} [opts.transclude="EA"] @param {Object} [opts.scope={}] @param {String} [opts.template] @param {String} [opts.templateUrl] @example [@]Component({ scope: { "attr": "=" } }) class MyComponentController {}
[ "Declare", "an", "angular", "Component", "directive", "." ]
e4206c90310e9fcf440abbd5aa9b12d97ed6c9a6
https://github.com/fd/fd-angular-core/blob/e4206c90310e9fcf440abbd5aa9b12d97ed6c9a6/lib/Component.js#L38-L90
55,019
Majiir/safesocket
safesocket.js
safesocket
function safesocket (expected, fn) { return function () { var _args = []; for (var idx in arguments) { _args.push(arguments[idx]); } var args = _args.filter(notFunction).slice(0, expected); for (var i = args.length; i < expected; i++) { args.push(undefined); } var arg = _args.pop(); args.push((arg instanceof Function) ? arg : noop); fn.apply(this, args); }; }
javascript
function safesocket (expected, fn) { return function () { var _args = []; for (var idx in arguments) { _args.push(arguments[idx]); } var args = _args.filter(notFunction).slice(0, expected); for (var i = args.length; i < expected; i++) { args.push(undefined); } var arg = _args.pop(); args.push((arg instanceof Function) ? arg : noop); fn.apply(this, args); }; }
[ "function", "safesocket", "(", "expected", ",", "fn", ")", "{", "return", "function", "(", ")", "{", "var", "_args", "=", "[", "]", ";", "for", "(", "var", "idx", "in", "arguments", ")", "{", "_args", ".", "push", "(", "arguments", "[", "idx", "]", ")", ";", "}", "var", "args", "=", "_args", ".", "filter", "(", "notFunction", ")", ".", "slice", "(", "0", ",", "expected", ")", ";", "for", "(", "var", "i", "=", "args", ".", "length", ";", "i", "<", "expected", ";", "i", "++", ")", "{", "args", ".", "push", "(", "undefined", ")", ";", "}", "var", "arg", "=", "_args", ".", "pop", "(", ")", ";", "args", ".", "push", "(", "(", "arg", "instanceof", "Function", ")", "?", "arg", ":", "noop", ")", ";", "fn", ".", "apply", "(", "this", ",", "args", ")", ";", "}", ";", "}" ]
Wraps socket.io event handlers to prevent crashes from certain malicious inputs.
[ "Wraps", "socket", ".", "io", "event", "handlers", "to", "prevent", "crashes", "from", "certain", "malicious", "inputs", "." ]
afcb81cc8d861f0f6099c6731c1333265443aa33
https://github.com/Majiir/safesocket/blob/afcb81cc8d861f0f6099c6731c1333265443aa33/safesocket.js#L11-L28
55,020
Acconut/scrib
lib/scrib.js
Scrib
function Scrib(adapters, callback) { EventEmitter.call(this); // Convert array to object if(Array.isArray(adapters)) { var am = adapters; adapters = {}; am.forEach(function(m) { adapters[m] = {}; }); } var all = [], self = this; for(var m in adapters) { try { var adapter; try { adapter = require("scrib-" + m); } catch(e) { adapter = require(path.join(path.dirname(module.parent.filename), m)); } all.push(async.apply(adapter, self, adapters[m])); } catch(e) { return callback(e); } } async.parallel(all, function done(err) { callback(err); }); }
javascript
function Scrib(adapters, callback) { EventEmitter.call(this); // Convert array to object if(Array.isArray(adapters)) { var am = adapters; adapters = {}; am.forEach(function(m) { adapters[m] = {}; }); } var all = [], self = this; for(var m in adapters) { try { var adapter; try { adapter = require("scrib-" + m); } catch(e) { adapter = require(path.join(path.dirname(module.parent.filename), m)); } all.push(async.apply(adapter, self, adapters[m])); } catch(e) { return callback(e); } } async.parallel(all, function done(err) { callback(err); }); }
[ "function", "Scrib", "(", "adapters", ",", "callback", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "// Convert array to object", "if", "(", "Array", ".", "isArray", "(", "adapters", ")", ")", "{", "var", "am", "=", "adapters", ";", "adapters", "=", "{", "}", ";", "am", ".", "forEach", "(", "function", "(", "m", ")", "{", "adapters", "[", "m", "]", "=", "{", "}", ";", "}", ")", ";", "}", "var", "all", "=", "[", "]", ",", "self", "=", "this", ";", "for", "(", "var", "m", "in", "adapters", ")", "{", "try", "{", "var", "adapter", ";", "try", "{", "adapter", "=", "require", "(", "\"scrib-\"", "+", "m", ")", ";", "}", "catch", "(", "e", ")", "{", "adapter", "=", "require", "(", "path", ".", "join", "(", "path", ".", "dirname", "(", "module", ".", "parent", ".", "filename", ")", ",", "m", ")", ")", ";", "}", "all", ".", "push", "(", "async", ".", "apply", "(", "adapter", ",", "self", ",", "adapters", "[", "m", "]", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "callback", "(", "e", ")", ";", "}", "}", "async", ".", "parallel", "(", "all", ",", "function", "done", "(", "err", ")", "{", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
Initalizes a new logger @param {Array|Object} adapters Array containing adapters to load or object with adapters as keys and options as values @param {Function} callback Callback function
[ "Initalizes", "a", "new", "logger" ]
9a1dae602c0badcd00fe2dad88c07e89029dd402
https://github.com/Acconut/scrib/blob/9a1dae602c0badcd00fe2dad88c07e89029dd402/lib/scrib.js#L12-L44
55,021
mgesmundo/authorify-client
lib/class/Header.js
function(header, key, cert) { var parsedHeader; if (header) { if (!header.isBase64()) { throw new CError('missing header or wrong format').log(); } else { parsedHeader = JSON.parse(forge.util.decode64(header)); this.isModeAllowed.call(this, parsedHeader.payload.mode); } var Handshake = app.class.Handshake, Authentication = app.class.Authentication, Authorization = app.class.Authorization, mode = parsedHeader.payload.mode, sid = parsedHeader.payload.sid, result = {}; var options = { sid: sid, key: key || config.key, cert: cert || config.cert }; switch (mode) { case 'handshake': result.header = new Handshake(options); break; case 'auth-init': result.header = new Authentication(options); break; default : result.header = new Authorization(options); break; } try { var ecryptedSecret = parsedHeader.payload.secret; if (ecryptedSecret) { var secret = result.header.keychain.decryptRsa(ecryptedSecret); result.header.setSecret(secret); } parsedHeader.content = result.header.decryptContent(parsedHeader.content); } catch (e) { throw new CError({ body: { code: 'ImATeapot', message: 'unable to decrypt content', cause: e } }).log('body'); } delete result.header; if (debug) { log.debug('%s parsed header', app.name); log.debug(parsedHeader); } } return parsedHeader; }
javascript
function(header, key, cert) { var parsedHeader; if (header) { if (!header.isBase64()) { throw new CError('missing header or wrong format').log(); } else { parsedHeader = JSON.parse(forge.util.decode64(header)); this.isModeAllowed.call(this, parsedHeader.payload.mode); } var Handshake = app.class.Handshake, Authentication = app.class.Authentication, Authorization = app.class.Authorization, mode = parsedHeader.payload.mode, sid = parsedHeader.payload.sid, result = {}; var options = { sid: sid, key: key || config.key, cert: cert || config.cert }; switch (mode) { case 'handshake': result.header = new Handshake(options); break; case 'auth-init': result.header = new Authentication(options); break; default : result.header = new Authorization(options); break; } try { var ecryptedSecret = parsedHeader.payload.secret; if (ecryptedSecret) { var secret = result.header.keychain.decryptRsa(ecryptedSecret); result.header.setSecret(secret); } parsedHeader.content = result.header.decryptContent(parsedHeader.content); } catch (e) { throw new CError({ body: { code: 'ImATeapot', message: 'unable to decrypt content', cause: e } }).log('body'); } delete result.header; if (debug) { log.debug('%s parsed header', app.name); log.debug(parsedHeader); } } return parsedHeader; }
[ "function", "(", "header", ",", "key", ",", "cert", ")", "{", "var", "parsedHeader", ";", "if", "(", "header", ")", "{", "if", "(", "!", "header", ".", "isBase64", "(", ")", ")", "{", "throw", "new", "CError", "(", "'missing header or wrong format'", ")", ".", "log", "(", ")", ";", "}", "else", "{", "parsedHeader", "=", "JSON", ".", "parse", "(", "forge", ".", "util", ".", "decode64", "(", "header", ")", ")", ";", "this", ".", "isModeAllowed", ".", "call", "(", "this", ",", "parsedHeader", ".", "payload", ".", "mode", ")", ";", "}", "var", "Handshake", "=", "app", ".", "class", ".", "Handshake", ",", "Authentication", "=", "app", ".", "class", ".", "Authentication", ",", "Authorization", "=", "app", ".", "class", ".", "Authorization", ",", "mode", "=", "parsedHeader", ".", "payload", ".", "mode", ",", "sid", "=", "parsedHeader", ".", "payload", ".", "sid", ",", "result", "=", "{", "}", ";", "var", "options", "=", "{", "sid", ":", "sid", ",", "key", ":", "key", "||", "config", ".", "key", ",", "cert", ":", "cert", "||", "config", ".", "cert", "}", ";", "switch", "(", "mode", ")", "{", "case", "'handshake'", ":", "result", ".", "header", "=", "new", "Handshake", "(", "options", ")", ";", "break", ";", "case", "'auth-init'", ":", "result", ".", "header", "=", "new", "Authentication", "(", "options", ")", ";", "break", ";", "default", ":", "result", ".", "header", "=", "new", "Authorization", "(", "options", ")", ";", "break", ";", "}", "try", "{", "var", "ecryptedSecret", "=", "parsedHeader", ".", "payload", ".", "secret", ";", "if", "(", "ecryptedSecret", ")", "{", "var", "secret", "=", "result", ".", "header", ".", "keychain", ".", "decryptRsa", "(", "ecryptedSecret", ")", ";", "result", ".", "header", ".", "setSecret", "(", "secret", ")", ";", "}", "parsedHeader", ".", "content", "=", "result", ".", "header", ".", "decryptContent", "(", "parsedHeader", ".", "content", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "CError", "(", "{", "body", ":", "{", "code", ":", "'ImATeapot'", ",", "message", ":", "'unable to decrypt content'", ",", "cause", ":", "e", "}", "}", ")", ".", "log", "(", "'body'", ")", ";", "}", "delete", "result", ".", "header", ";", "if", "(", "debug", ")", "{", "log", ".", "debug", "(", "'%s parsed header'", ",", "app", ".", "name", ")", ";", "log", ".", "debug", "(", "parsedHeader", ")", ";", "}", "}", "return", "parsedHeader", ";", "}" ]
Parse the Authorization header @param {String} header The Authorization header in Base64 format @param {String} key The private RSA key @param {String} cert The public X.509 certificate @return {Object} The parsed header @static
[ "Parse", "the", "Authorization", "header" ]
39fb57db897eaa49b76444ff62bbc0ccedc7ee16
https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/lib/class/Header.js#L57-L114
55,022
mgesmundo/authorify-client
lib/class/Header.js
function(data) { try { data = data || this.getContent(); return this.keychain.sign(JSON.stringify(data)); } catch(e) { throw new CError({ body: { code: 'ImATeapot', message: 'unable to sign content', cause: e } }).log('body'); } }
javascript
function(data) { try { data = data || this.getContent(); return this.keychain.sign(JSON.stringify(data)); } catch(e) { throw new CError({ body: { code: 'ImATeapot', message: 'unable to sign content', cause: e } }).log('body'); } }
[ "function", "(", "data", ")", "{", "try", "{", "data", "=", "data", "||", "this", ".", "getContent", "(", ")", ";", "return", "this", ".", "keychain", ".", "sign", "(", "JSON", ".", "stringify", "(", "data", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "throw", "new", "CError", "(", "{", "body", ":", "{", "code", ":", "'ImATeapot'", ",", "message", ":", "'unable to sign content'", ",", "cause", ":", "e", "}", "}", ")", ".", "log", "(", "'body'", ")", ";", "}", "}" ]
Generate a signature for for data or content property @param {String/Object} data The data to sign or content if missing @return {String} The signature in Base64 format
[ "Generate", "a", "signature", "for", "for", "data", "or", "content", "property" ]
39fb57db897eaa49b76444ff62bbc0ccedc7ee16
https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/lib/class/Header.js#L183-L196
55,023
mgesmundo/authorify-client
lib/class/Header.js
function() { var content = this.getContent(); var out = { payload: this.getPayload(), content: this.cryptContent(content), signature: this.generateSignature() }; if (debug) { log.debug('%s encode with sid %s', app.name, out.payload.sid); log.debug('%s encode with token %s', app.name, content.token); } return forge.util.encode64(JSON.stringify(out)); }
javascript
function() { var content = this.getContent(); var out = { payload: this.getPayload(), content: this.cryptContent(content), signature: this.generateSignature() }; if (debug) { log.debug('%s encode with sid %s', app.name, out.payload.sid); log.debug('%s encode with token %s', app.name, content.token); } return forge.util.encode64(JSON.stringify(out)); }
[ "function", "(", ")", "{", "var", "content", "=", "this", ".", "getContent", "(", ")", ";", "var", "out", "=", "{", "payload", ":", "this", ".", "getPayload", "(", ")", ",", "content", ":", "this", ".", "cryptContent", "(", "content", ")", ",", "signature", ":", "this", ".", "generateSignature", "(", ")", "}", ";", "if", "(", "debug", ")", "{", "log", ".", "debug", "(", "'%s encode with sid %s'", ",", "app", ".", "name", ",", "out", ".", "payload", ".", "sid", ")", ";", "log", ".", "debug", "(", "'%s encode with token %s'", ",", "app", ".", "name", ",", "content", ".", "token", ")", ";", "}", "return", "forge", ".", "util", ".", "encode64", "(", "JSON", ".", "stringify", "(", "out", ")", ")", ";", "}" ]
Encode the header including payload, content and signature @return {String} The encoded header in Base64 format
[ "Encode", "the", "header", "including", "payload", "content", "and", "signature" ]
39fb57db897eaa49b76444ff62bbc0ccedc7ee16
https://github.com/mgesmundo/authorify-client/blob/39fb57db897eaa49b76444ff62bbc0ccedc7ee16/lib/class/Header.js#L220-L233
55,024
Barandis/xduce
src/modules/iteration.js
stringIterator
function stringIterator(str) { let index = 0; return { next() { return index < bmpLength(str) ? { value: bmpCharAt(str, index++), done: false } : { done: true }; } }; }
javascript
function stringIterator(str) { let index = 0; return { next() { return index < bmpLength(str) ? { value: bmpCharAt(str, index++), done: false } : { done: true }; } }; }
[ "function", "stringIterator", "(", "str", ")", "{", "let", "index", "=", "0", ";", "return", "{", "next", "(", ")", "{", "return", "index", "<", "bmpLength", "(", "str", ")", "?", "{", "value", ":", "bmpCharAt", "(", "str", ",", "index", "++", ")", ",", "done", ":", "false", "}", ":", "{", "done", ":", "true", "}", ";", "}", "}", ";", "}" ]
Creates an iterator over strings. ES2015 strings already satisfy the iterator protocol, so this function will not be used for them. This is for ES5 strings where the iterator protocol doesn't exist. As with ES2015 iterators, it takes into account double-width BMP characters and will return the entire character as a two-character string. @private @param {string} str The string to be iterated over.@author [author] @return {module:xduce~iterator} An iterator that returns one character per call to `next`.
[ "Creates", "an", "iterator", "over", "strings", ".", "ES2015", "strings", "already", "satisfy", "the", "iterator", "protocol", "so", "this", "function", "will", "not", "be", "used", "for", "them", ".", "This", "is", "for", "ES5", "strings", "where", "the", "iterator", "protocol", "doesn", "t", "exist", ".", "As", "with", "ES2015", "iterators", "it", "takes", "into", "account", "double", "-", "width", "BMP", "characters", "and", "will", "return", "the", "entire", "character", "as", "a", "two", "-", "character", "string", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/iteration.js#L48-L62
55,025
Barandis/xduce
src/modules/iteration.js
objectIterator
function objectIterator(obj, sort, kv = false) { let keys = Object.keys(obj); keys = typeof sort === 'function' ? keys.sort(sort) : keys.sort(); let index = 0; return { next() { if (index < keys.length) { const k = keys[index++]; const value = {}; if (kv) { value.k = k; value.v = obj[k]; } else { value[k] = obj[k]; } return { value, done: false }; } return { done: true }; } }; }
javascript
function objectIterator(obj, sort, kv = false) { let keys = Object.keys(obj); keys = typeof sort === 'function' ? keys.sort(sort) : keys.sort(); let index = 0; return { next() { if (index < keys.length) { const k = keys[index++]; const value = {}; if (kv) { value.k = k; value.v = obj[k]; } else { value[k] = obj[k]; } return { value, done: false }; } return { done: true }; } }; }
[ "function", "objectIterator", "(", "obj", ",", "sort", ",", "kv", "=", "false", ")", "{", "let", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "keys", "=", "typeof", "sort", "===", "'function'", "?", "keys", ".", "sort", "(", "sort", ")", ":", "keys", ".", "sort", "(", ")", ";", "let", "index", "=", "0", ";", "return", "{", "next", "(", ")", "{", "if", "(", "index", "<", "keys", ".", "length", ")", "{", "const", "k", "=", "keys", "[", "index", "++", "]", ";", "const", "value", "=", "{", "}", ";", "if", "(", "kv", ")", "{", "value", ".", "k", "=", "k", ";", "value", ".", "v", "=", "obj", "[", "k", "]", ";", "}", "else", "{", "value", "[", "k", "]", "=", "obj", "[", "k", "]", ";", "}", "return", "{", "value", ",", "done", ":", "false", "}", ";", "}", "return", "{", "done", ":", "true", "}", ";", "}", "}", ";", "}" ]
Creates an iterator over objcts. Objects are not generally iterable, as there is no defined order for an object, and each "element" of an object actually has two values, unlike any other collection (a key and a property). However, it's tremendously useful to be able to use at least some transformers with objects as well. This iterator adds support in two different ways to make that possible. The first is that a sort order is defined. Quite simply, it's done alphabetically by key. There is also an option - through the second parameter `sort` - to provide a different sort function. This should be a function in the style of `Array.prototype.sort`, where two parameters are compared and -1 is returned if the first is larger, 1 is returned if the second is larger, and 0 is returned if they're equal. This is applied ONLY TO THE KEYS of the object. If you wish to sort on values, consider iterating into an array and then sorting the elements by value. In the public API, this sort function can only be passed through the `{@link module:xduce.iterator|iterator}` function. If you wish to use an object sorted in a non-default order, you should create an iterator out of it and transform that iterator. For example: | DEFAULT ORDER | CUSTOM ORDER | | ------------------------------------ | ---------------------------------------------------- | | `var result = sequence(obj, xform);` | `var result = asObject(iterator(obj, sort), xform);` | The second support feature is the alternative "kv-form" objects. A reasonable way to iterate over objects would be to produce single-property objects, one per property on the original object (i.e., `{a: 1, b: 2}` would become two elements: `{a: 1}` and `{b: 2}`). This is fine for straight iteration and reduction, but it can present a challenge to use a transformer with. Consider this example code, which uppercases the key and adds one to the value. ``` function doObjectSingle(obj) { var key = Object.keys(obj)[0]; var result = {}; result[key.toUpperCase()] = obj[key] + 1; return result; } ``` This is a little unwieldy, so the iterator provides for another kind of iteration. Setting the third parameter, `kv`, to `true` (which is the default), objects will be iterated into two-property objects with `k` and `v` as the property names. For example, `{a: 1, b: 2}` will become two elements: `{k: 'a', v: 1}` and `{k: 'b', v: 2}`. This turns the mapping function shown above into something simpler. ``` function doObjectKv(obj) { var result = {}; result[obj.k.toUpperCase()]: obj.v + 1; return result; } ``` This is the default iteration form for objects internally. If you want to iterate an object into the `{key: value}` form, for which you would have to use the `doObjectSingle` style transformer, you must call `{@link module:xduce.iterator|iterator}` with the third parameter explicitly set to `false` and then pass that iterator to the transducing function. This is availabe in particular for those writing their own transducers. Still, while this is nice, we can do better. The built-in reducers for arrays, objects, strings, and iterators recognize the kv-form and know how to reduce it back into a regular key-value form for output. So instead of that first `doObjectKv`, we could write it this way. ``` function doObjectKvImproved(obj) { return {k: obj.k.toUpperCase(), v: obj.v + 1}; } ``` The reducer will recognize the form and reduce it correctly. The upshot is that in this library, `doObjectKv` and `doObjectKvImproved` will produce the SAME RESULT. Which function to use is purely a matter of preference. IMPORTANT NOTE: If you're adding transducer support to non-supported types, remember that you must decide whether to have your `step` function recognize kv-form objects and reduce them into key-value. If you don't, then the style of `doObjectKvImproved` will not be available. ANOTHER IMPORTANT NOTE: The internal reducers recognize kv-form very explicitly. The object must have exactly two enumerable properties, and those properties must be named 'k' and 'v'. This is to reduce the chance as much as possible of having errors because an object that was meant to be two properties was turned into one. (It is possible to have a transformation function return an object of more than one property; if that happens, and if that object is not a kv-form object, then all of the properties will be merged into the final object.) One final consideration: you have your choice of mapping function styles, but the better choice may depend on language. The above examples are in ES5. If you're using ES2015, however, you have access to destructuring and dynamic object keys. That may make `doObjectKv` look better, because with those features it can be written like this: ``` doObjectKv = ({k, v}) => {[k.toUpperCase()]: v + 1}; ``` And that's about as concise as it gets. Note that some languages that compile into JavaScript, like CoffeeScript and LiveScript, also support these features. @private TL;DR: 1. Iteration order of objects is alphabetical by key, though that can be changed by passing a sort function to `{@link module:xduce.iterator|iterator}`. 2. Iteration is done internally in kv-form. 3. Transformation functions can output objects in key-value, which is easier in ES2015. 4. Transformation functions can output objects in kv-form, which is easier in ES5. @param {object} obj The object to iterate over. @param {module:xduce~sort} [sort] An optional sort function. This is applied to the keys of the object to determine the order of iteration. @param {boolean} [kv=false] Whether or not this object should be iterated into kv-form (if false, it remains in the normal key-value form). @return {module:xduce~iterator} An iterator that returns one key-value pair per call to `next`.
[ "Creates", "an", "iterator", "over", "objcts", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/iteration.js#L191-L217
55,026
Barandis/xduce
src/modules/iteration.js
functionIterator
function functionIterator(fn) { return function* () { let current; let index = 0; for (;;) { current = fn(index++, current); if (current === undefined) { break; } yield current; } }(); }
javascript
function functionIterator(fn) { return function* () { let current; let index = 0; for (;;) { current = fn(index++, current); if (current === undefined) { break; } yield current; } }(); }
[ "function", "functionIterator", "(", "fn", ")", "{", "return", "function", "*", "(", ")", "{", "let", "current", ";", "let", "index", "=", "0", ";", "for", "(", ";", ";", ")", "{", "current", "=", "fn", "(", "index", "++", ",", "current", ")", ";", "if", "(", "current", "===", "undefined", ")", "{", "break", ";", "}", "yield", "current", ";", "}", "}", "(", ")", ";", "}" ]
Creates an iterator that runs a function for each `next` value. The function in question is provided two arguments: the current 0-based index (which starts at `0` and increases by one for each run) and the return value for the prior calling of the function (which is `undefined` if the function has not yet been run). The return value of the function is used as the value that comes from `next` the next time it's called. If the function returns `undefined` at any point, the iteration terminates there and the `done` property of the object returned with the next call to `next` becomes `true`. @private @param {function} fn A function that is run once for each step of the iteration. It is provided two arguments: the `0`-based index of that run (starts at `0` and increments each run) and the return value of the last call to the function (`undefined` if it hasn't been called yet). If the function returns `undefined` at any point, the iteration terminates. @return {function} A generator wrapping `fn`, which is suitable for use as an iterator.
[ "Creates", "an", "iterator", "that", "runs", "a", "function", "for", "each", "next", "value", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/iteration.js#L238-L251
55,027
Barandis/xduce
src/modules/iteration.js
isKvFormObject
function isKvFormObject(obj) { const keys = Object.keys(obj); if (keys.length !== 2) { return false; } return !!~keys.indexOf('k') && !!~keys.indexOf('v'); }
javascript
function isKvFormObject(obj) { const keys = Object.keys(obj); if (keys.length !== 2) { return false; } return !!~keys.indexOf('k') && !!~keys.indexOf('v'); }
[ "function", "isKvFormObject", "(", "obj", ")", "{", "const", "keys", "=", "Object", ".", "keys", "(", "obj", ")", ";", "if", "(", "keys", ".", "length", "!==", "2", ")", "{", "return", "false", ";", "}", "return", "!", "!", "~", "keys", ".", "indexOf", "(", "'k'", ")", "&&", "!", "!", "~", "keys", ".", "indexOf", "(", "'v'", ")", ";", "}" ]
Determines whether an object is in kv-form. This used by the reducers that must recognize this form and reduce those elements back into key-value form. This determination is made by simply checking that the object has exactly two properties and that they are named `k` and `v`. @private @param {object} obj The object to be tested. @return {boolean} Either `true` if the object is in kv-form or `false` if it isn't.
[ "Determines", "whether", "an", "object", "is", "in", "kv", "-", "form", ".", "This", "used", "by", "the", "reducers", "that", "must", "recognize", "this", "form", "and", "reduce", "those", "elements", "back", "into", "key", "-", "value", "form", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/iteration.js#L265-L271
55,028
Barandis/xduce
src/modules/iteration.js
isIterable
function isIterable(obj) { return isImplemented(obj, 'iterator') || isString(obj) || isArray(obj) || isObject(obj); }
javascript
function isIterable(obj) { return isImplemented(obj, 'iterator') || isString(obj) || isArray(obj) || isObject(obj); }
[ "function", "isIterable", "(", "obj", ")", "{", "return", "isImplemented", "(", "obj", ",", "'iterator'", ")", "||", "isString", "(", "obj", ")", "||", "isArray", "(", "obj", ")", "||", "isObject", "(", "obj", ")", ";", "}" ]
Determines whether the passed object is iterable, in terms of what 'iterable' means to this library. In other words, objects and ES5 arrays and strings will return `true`, as will objects with a `next` function. For that reason this function is only really useful within the library and therefore isn't exported. @private @param {*} obj The value to test for iterability. @return {boolean} Either `true` if the value is iterable (`{@link module:xduce.iterator}` will return an iterator for it) or `false` if it is not.
[ "Determines", "whether", "the", "passed", "object", "is", "iterable", "in", "terms", "of", "what", "iterable", "means", "to", "this", "library", ".", "In", "other", "words", "objects", "and", "ES5", "arrays", "and", "strings", "will", "return", "true", "as", "will", "objects", "with", "a", "next", "function", ".", "For", "that", "reason", "this", "function", "is", "only", "really", "useful", "within", "the", "library", "and", "therefore", "isn", "t", "exported", "." ]
b454f154f7663475670d4802e28e98ade8c468e7
https://github.com/Barandis/xduce/blob/b454f154f7663475670d4802e28e98ade8c468e7/src/modules/iteration.js#L392-L394
55,029
hillscottc/nostra
dist/sentence_mgr.js
relationship
function relationship(mood) { var verb = void 0, talk = void 0; if (mood === "good") { verb = "strengthened"; talk = "discussion"; } else { verb = "strained"; talk = "argument"; } var familiar_people = _word_library2.default.getWords("familiar_people"); var conversation_topics = _word_library2.default.getWords("conversation_topics"); var person = nu.chooseFrom(familiar_people); var topic = nu.chooseFrom(conversation_topics); var sentence = 'Your relationship with ' + person + ' may be ' + verb + ' '; sentence += 'as the result of ' + nu.an(talk) + ' about ' + topic; return nu.sentenceCase(sentence); }
javascript
function relationship(mood) { var verb = void 0, talk = void 0; if (mood === "good") { verb = "strengthened"; talk = "discussion"; } else { verb = "strained"; talk = "argument"; } var familiar_people = _word_library2.default.getWords("familiar_people"); var conversation_topics = _word_library2.default.getWords("conversation_topics"); var person = nu.chooseFrom(familiar_people); var topic = nu.chooseFrom(conversation_topics); var sentence = 'Your relationship with ' + person + ' may be ' + verb + ' '; sentence += 'as the result of ' + nu.an(talk) + ' about ' + topic; return nu.sentenceCase(sentence); }
[ "function", "relationship", "(", "mood", ")", "{", "var", "verb", "=", "void", "0", ",", "talk", "=", "void", "0", ";", "if", "(", "mood", "===", "\"good\"", ")", "{", "verb", "=", "\"strengthened\"", ";", "talk", "=", "\"discussion\"", ";", "}", "else", "{", "verb", "=", "\"strained\"", ";", "talk", "=", "\"argument\"", ";", "}", "var", "familiar_people", "=", "_word_library2", ".", "default", ".", "getWords", "(", "\"familiar_people\"", ")", ";", "var", "conversation_topics", "=", "_word_library2", ".", "default", ".", "getWords", "(", "\"conversation_topics\"", ")", ";", "var", "person", "=", "nu", ".", "chooseFrom", "(", "familiar_people", ")", ";", "var", "topic", "=", "nu", ".", "chooseFrom", "(", "conversation_topics", ")", ";", "var", "sentence", "=", "'Your relationship with '", "+", "person", "+", "' may be '", "+", "verb", "+", "' '", ";", "sentence", "+=", "'as the result of '", "+", "nu", ".", "an", "(", "talk", ")", "+", "' about '", "+", "topic", ";", "return", "nu", ".", "sentenceCase", "(", "sentence", ")", ";", "}" ]
Generate a mood-based sentence about a relationship @param mood @returns {*}
[ "Generate", "a", "mood", "-", "based", "sentence", "about", "a", "relationship" ]
1801c8e19f7fab91dd29fea07195789d41624915
https://github.com/hillscottc/nostra/blob/1801c8e19f7fab91dd29fea07195789d41624915/dist/sentence_mgr.js#L24-L46
55,030
hillscottc/nostra
dist/sentence_mgr.js
datePredict
function datePredict() { var daysAhead = Math.floor(Math.random() * 5) + 2; var day = new Date(); day.setDate(day.getDate() + daysAhead); var monthStr = (0, _dateformat2.default)(day, "mmmm"); var dayStr = (0, _dateformat2.default)(day, "d"); var rnum = Math.floor(Math.random() * 10); var str = void 0; if (rnum <= 4) { str = monthStr + ' ' + dayStr + ' will be an important day for you'; } else if (rnum <= 7) { str = 'Interesting things await you on ' + monthStr + ' ' + dayStr; } else { str = 'The events of ' + monthStr + ' ' + dayStr + ' have the potential to change your life.'; } return nu.sentenceCase(str); }
javascript
function datePredict() { var daysAhead = Math.floor(Math.random() * 5) + 2; var day = new Date(); day.setDate(day.getDate() + daysAhead); var monthStr = (0, _dateformat2.default)(day, "mmmm"); var dayStr = (0, _dateformat2.default)(day, "d"); var rnum = Math.floor(Math.random() * 10); var str = void 0; if (rnum <= 4) { str = monthStr + ' ' + dayStr + ' will be an important day for you'; } else if (rnum <= 7) { str = 'Interesting things await you on ' + monthStr + ' ' + dayStr; } else { str = 'The events of ' + monthStr + ' ' + dayStr + ' have the potential to change your life.'; } return nu.sentenceCase(str); }
[ "function", "datePredict", "(", ")", "{", "var", "daysAhead", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "5", ")", "+", "2", ";", "var", "day", "=", "new", "Date", "(", ")", ";", "day", ".", "setDate", "(", "day", ".", "getDate", "(", ")", "+", "daysAhead", ")", ";", "var", "monthStr", "=", "(", "0", ",", "_dateformat2", ".", "default", ")", "(", "day", ",", "\"mmmm\"", ")", ";", "var", "dayStr", "=", "(", "0", ",", "_dateformat2", ".", "default", ")", "(", "day", ",", "\"d\"", ")", ";", "var", "rnum", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "10", ")", ";", "var", "str", "=", "void", "0", ";", "if", "(", "rnum", "<=", "4", ")", "{", "str", "=", "monthStr", "+", "' '", "+", "dayStr", "+", "' will be an important day for you'", ";", "}", "else", "if", "(", "rnum", "<=", "7", ")", "{", "str", "=", "'Interesting things await you on '", "+", "monthStr", "+", "' '", "+", "dayStr", ";", "}", "else", "{", "str", "=", "'The events of '", "+", "monthStr", "+", "' '", "+", "dayStr", "+", "' have the potential to change your life.'", ";", "}", "return", "nu", ".", "sentenceCase", "(", "str", ")", ";", "}" ]
Generate a random prediction sentence containing a date. @returns {*}
[ "Generate", "a", "random", "prediction", "sentence", "containing", "a", "date", "." ]
1801c8e19f7fab91dd29fea07195789d41624915
https://github.com/hillscottc/nostra/blob/1801c8e19f7fab91dd29fea07195789d41624915/dist/sentence_mgr.js#L121-L139
55,031
futagoza/efe
index.js
modifyStatsObject
function modifyStatsObject ( stats, path ) { stats.path = path; stats.basename = fs.basename(path); stats.dirname = fs.dirname(path); stats.extname = fs.extname(path); return stats; }
javascript
function modifyStatsObject ( stats, path ) { stats.path = path; stats.basename = fs.basename(path); stats.dirname = fs.dirname(path); stats.extname = fs.extname(path); return stats; }
[ "function", "modifyStatsObject", "(", "stats", ",", "path", ")", "{", "stats", ".", "path", "=", "path", ";", "stats", ".", "basename", "=", "fs", ".", "basename", "(", "path", ")", ";", "stats", ".", "dirname", "=", "fs", ".", "dirname", "(", "path", ")", ";", "stats", ".", "extname", "=", "fs", ".", "extname", "(", "path", ")", ";", "return", "stats", ";", "}" ]
Update the `stats` object returned by methods using `fs.Stats`.
[ "Update", "the", "stats", "object", "returned", "by", "methods", "using", "fs", ".", "Stats", "." ]
bd7b0e73006672a8d7620f32f731d87d793eb57c
https://github.com/futagoza/efe/blob/bd7b0e73006672a8d7620f32f731d87d793eb57c/index.js#L110-L116
55,032
andrepolischuk/ies
index.js
parse
function parse() { var msie = /MSIE.(\d+)/i.exec(ua); var rv = /Trident.+rv:(\d+)/i.exec(ua); var version = msie || rv || undefined; return version ? +version[1] : version; }
javascript
function parse() { var msie = /MSIE.(\d+)/i.exec(ua); var rv = /Trident.+rv:(\d+)/i.exec(ua); var version = msie || rv || undefined; return version ? +version[1] : version; }
[ "function", "parse", "(", ")", "{", "var", "msie", "=", "/", "MSIE.(\\d+)", "/", "i", ".", "exec", "(", "ua", ")", ";", "var", "rv", "=", "/", "Trident.+rv:(\\d+)", "/", "i", ".", "exec", "(", "ua", ")", ";", "var", "version", "=", "msie", "||", "rv", "||", "undefined", ";", "return", "version", "?", "+", "version", "[", "1", "]", ":", "version", ";", "}" ]
Get IE major version number @return {Number} @api private
[ "Get", "IE", "major", "version", "number" ]
2641e787897fd1602e5a0bd8bd4bd8e56418f1bf
https://github.com/andrepolischuk/ies/blob/2641e787897fd1602e5a0bd8bd4bd8e56418f1bf/index.js#L23-L28
55,033
creationix/git-node-platform
fs.js
stat
function stat(path, callback) { if (!callback) return stat.bind(this, path); fs.lstat(path, function (err, stat) { if (err) return callback(err); var ctime = stat.ctime / 1000; var cseconds = Math.floor(ctime); var mtime = stat.mtime / 1000; var mseconds = Math.floor(mtime); var mode; if (stat.isSymbolicLink()) { mode = 0120000; } else if (stat.mode & 0111) { mode = 0100755; } else { mode = 0100644; } callback(null, { ctime: [cseconds, Math.floor((ctime - cseconds) * 1000000000)], mtime: [mseconds, Math.floor((mtime - mseconds) * 1000000000)], dev: stat.dev, ino: stat.ino, mode: mode, uid: stat.uid, gid: stat.gid, size: stat.size }); }); }
javascript
function stat(path, callback) { if (!callback) return stat.bind(this, path); fs.lstat(path, function (err, stat) { if (err) return callback(err); var ctime = stat.ctime / 1000; var cseconds = Math.floor(ctime); var mtime = stat.mtime / 1000; var mseconds = Math.floor(mtime); var mode; if (stat.isSymbolicLink()) { mode = 0120000; } else if (stat.mode & 0111) { mode = 0100755; } else { mode = 0100644; } callback(null, { ctime: [cseconds, Math.floor((ctime - cseconds) * 1000000000)], mtime: [mseconds, Math.floor((mtime - mseconds) * 1000000000)], dev: stat.dev, ino: stat.ino, mode: mode, uid: stat.uid, gid: stat.gid, size: stat.size }); }); }
[ "function", "stat", "(", "path", ",", "callback", ")", "{", "if", "(", "!", "callback", ")", "return", "stat", ".", "bind", "(", "this", ",", "path", ")", ";", "fs", ".", "lstat", "(", "path", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "var", "ctime", "=", "stat", ".", "ctime", "/", "1000", ";", "var", "cseconds", "=", "Math", ".", "floor", "(", "ctime", ")", ";", "var", "mtime", "=", "stat", ".", "mtime", "/", "1000", ";", "var", "mseconds", "=", "Math", ".", "floor", "(", "mtime", ")", ";", "var", "mode", ";", "if", "(", "stat", ".", "isSymbolicLink", "(", ")", ")", "{", "mode", "=", "0120000", ";", "}", "else", "if", "(", "stat", ".", "mode", "&", "0111", ")", "{", "mode", "=", "0100755", ";", "}", "else", "{", "mode", "=", "0100644", ";", "}", "callback", "(", "null", ",", "{", "ctime", ":", "[", "cseconds", ",", "Math", ".", "floor", "(", "(", "ctime", "-", "cseconds", ")", "*", "1000000000", ")", "]", ",", "mtime", ":", "[", "mseconds", ",", "Math", ".", "floor", "(", "(", "mtime", "-", "mseconds", ")", "*", "1000000000", ")", "]", ",", "dev", ":", "stat", ".", "dev", ",", "ino", ":", "stat", ".", "ino", ",", "mode", ":", "mode", ",", "uid", ":", "stat", ".", "uid", ",", "gid", ":", "stat", ".", "gid", ",", "size", ":", "stat", ".", "size", "}", ")", ";", "}", ")", ";", "}" ]
Given a path, return a continuable for the stat object.
[ "Given", "a", "path", "return", "a", "continuable", "for", "the", "stat", "object", "." ]
fa9b0367e3b92b6f4f50d93b0d2d7ba93cb27fb9
https://github.com/creationix/git-node-platform/blob/fa9b0367e3b92b6f4f50d93b0d2d7ba93cb27fb9/fs.js#L44-L73
55,034
shinuza/captain-core
lib/models/posts.js
find
function find(param) { var fn , asInt = Number(param); fn = isNaN(asInt) ? findBySlug : findById; fn.apply(null, arguments); }
javascript
function find(param) { var fn , asInt = Number(param); fn = isNaN(asInt) ? findBySlug : findById; fn.apply(null, arguments); }
[ "function", "find", "(", "param", ")", "{", "var", "fn", ",", "asInt", "=", "Number", "(", "param", ")", ";", "fn", "=", "isNaN", "(", "asInt", ")", "?", "findBySlug", ":", "findById", ";", "fn", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}" ]
Smart find, uses findBySlug or findById @param {*} param
[ "Smart", "find", "uses", "findBySlug", "or", "findById" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/posts.js#L53-L59
55,035
shinuza/captain-core
lib/models/posts.js
update
function update(id, body, cb) { body.updated_at = new Date(); var q = qb.update(id, body); db.getClient(function(err, client, done) { client.query(q[0], q[1], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.NotFound(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
javascript
function update(id, body, cb) { body.updated_at = new Date(); var q = qb.update(id, body); db.getClient(function(err, client, done) { client.query(q[0], q[1], function(err, r) { var result = r && r.rows[0]; if(!err && !result) { err = new exceptions.NotFound(); } if(err) { cb(err); done(err); } else { cb(null, result); done(); } }); }); }
[ "function", "update", "(", "id", ",", "body", ",", "cb", ")", "{", "body", ".", "updated_at", "=", "new", "Date", "(", ")", ";", "var", "q", "=", "qb", ".", "update", "(", "id", ",", "body", ")", ";", "db", ".", "getClient", "(", "function", "(", "err", ",", "client", ",", "done", ")", "{", "client", ".", "query", "(", "q", "[", "0", "]", ",", "q", "[", "1", "]", ",", "function", "(", "err", ",", "r", ")", "{", "var", "result", "=", "r", "&&", "r", ".", "rows", "[", "0", "]", ";", "if", "(", "!", "err", "&&", "!", "result", ")", "{", "err", "=", "new", "exceptions", ".", "NotFound", "(", ")", ";", "}", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "done", "(", "err", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "result", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Updates post with `id` `cb` is passed the updated post or exceptions.NotFound @param {Number} id @param {Object} body @param {Function} cb
[ "Updates", "post", "with", "id" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/posts.js#L165-L182
55,036
shinuza/captain-core
lib/models/posts.js
archive
function archive(cb) { db.getClient(function(err, client, done) { client.query(qb.select() + ' WHERE published = true', function(err, r) { if(err) { cb(err); done(err); } else { cb(null, r.rows); done(); } }); }); }
javascript
function archive(cb) { db.getClient(function(err, client, done) { client.query(qb.select() + ' WHERE published = true', function(err, r) { if(err) { cb(err); done(err); } else { cb(null, r.rows); done(); } }); }); }
[ "function", "archive", "(", "cb", ")", "{", "db", ".", "getClient", "(", "function", "(", "err", ",", "client", ",", "done", ")", "{", "client", ".", "query", "(", "qb", ".", "select", "(", ")", "+", "' WHERE published = true'", ",", "function", "(", "err", ",", "r", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "done", "(", "err", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "r", ".", "rows", ")", ";", "done", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Returns all published posts without pagination support @param {Function} cb
[ "Returns", "all", "published", "posts", "without", "pagination", "support" ]
02f3a404cdfca608e8726bbacc33e32fec484b21
https://github.com/shinuza/captain-core/blob/02f3a404cdfca608e8726bbacc33e32fec484b21/lib/models/posts.js#L341-L353
55,037
ronanyeah/ooft
src/methods.js
getTargetSize
function getTargetSize(size, buffer) { size *= 1000000; // Converting to MB to B. // 10% is default. buffer = 1 + (buffer ? buffer / 100 : 0.1); return Math.round(size * buffer); }
javascript
function getTargetSize(size, buffer) { size *= 1000000; // Converting to MB to B. // 10% is default. buffer = 1 + (buffer ? buffer / 100 : 0.1); return Math.round(size * buffer); }
[ "function", "getTargetSize", "(", "size", ",", "buffer", ")", "{", "size", "*=", "1000000", ";", "// Converting to MB to B.", "// 10% is default.", "buffer", "=", "1", "+", "(", "buffer", "?", "buffer", "/", "100", ":", "0.1", ")", ";", "return", "Math", ".", "round", "(", "size", "*", "buffer", ")", ";", "}" ]
Gets the desired file size for the resize. @param {number} size Desired size in MB. @param {number} buffer Range of tolerance for target size, 0-100. @returns {number} Desired file size in bytes.
[ "Gets", "the", "desired", "file", "size", "for", "the", "resize", "." ]
a86d9db656a7ebd84915ec4e0d5f474a4b87031b
https://github.com/ronanyeah/ooft/blob/a86d9db656a7ebd84915ec4e0d5f474a4b87031b/src/methods.js#L16-L23
55,038
ronanyeah/ooft
src/methods.js
shrinkImage
function shrinkImage(base64Image, targetSize) { return new Promise( (resolve, reject) => { let canvas = document.createElement('canvas'); let image = new Image(); image.onload = _ => { canvas.height = image.naturalHeight; canvas.width = image.naturalWidth; canvas.getContext('2d').drawImage(image, 0, 0); return resolve(shrink(95)); function shrink(quality) { let redrawnImage = canvas.toDataURL('image/jpeg', quality/100); // 1. Stop at zero because quality can't get any worse! // 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob. return quality !== 0 && redrawnImage.length / 1.33 > targetSize ? shrink(quality - 5) : redrawnImage; } }; image.src = base64Image; }); }
javascript
function shrinkImage(base64Image, targetSize) { return new Promise( (resolve, reject) => { let canvas = document.createElement('canvas'); let image = new Image(); image.onload = _ => { canvas.height = image.naturalHeight; canvas.width = image.naturalWidth; canvas.getContext('2d').drawImage(image, 0, 0); return resolve(shrink(95)); function shrink(quality) { let redrawnImage = canvas.toDataURL('image/jpeg', quality/100); // 1. Stop at zero because quality can't get any worse! // 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob. return quality !== 0 && redrawnImage.length / 1.33 > targetSize ? shrink(quality - 5) : redrawnImage; } }; image.src = base64Image; }); }
[ "function", "shrinkImage", "(", "base64Image", ",", "targetSize", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "canvas", "=", "document", ".", "createElement", "(", "'canvas'", ")", ";", "let", "image", "=", "new", "Image", "(", ")", ";", "image", ".", "onload", "=", "_", "=>", "{", "canvas", ".", "height", "=", "image", ".", "naturalHeight", ";", "canvas", ".", "width", "=", "image", ".", "naturalWidth", ";", "canvas", ".", "getContext", "(", "'2d'", ")", ".", "drawImage", "(", "image", ",", "0", ",", "0", ")", ";", "return", "resolve", "(", "shrink", "(", "95", ")", ")", ";", "function", "shrink", "(", "quality", ")", "{", "let", "redrawnImage", "=", "canvas", ".", "toDataURL", "(", "'image/jpeg'", ",", "quality", "/", "100", ")", ";", "// 1. Stop at zero because quality can't get any worse!", "// 2. Base64 encoded images are 1.33 times larger than once they are converted back to a blob.", "return", "quality", "!==", "0", "&&", "redrawnImage", ".", "length", "/", "1.33", ">", "targetSize", "?", "shrink", "(", "quality", "-", "5", ")", ":", "redrawnImage", ";", "}", "}", ";", "image", ".", "src", "=", "base64Image", ";", "}", ")", ";", "}" ]
Rewrites base64 image using canvas until it is down to desired file size. @param {string} base64Image Base64 image string. @param {number} targetSize Desired file size in bytes. @returns {string} Base64 string of resized image.
[ "Rewrites", "base64", "image", "using", "canvas", "until", "it", "is", "down", "to", "desired", "file", "size", "." ]
a86d9db656a7ebd84915ec4e0d5f474a4b87031b
https://github.com/ronanyeah/ooft/blob/a86d9db656a7ebd84915ec4e0d5f474a4b87031b/src/methods.js#L31-L60
55,039
ronanyeah/ooft
src/methods.js
base64ToBlob
function base64ToBlob(base64Image, contentType) { // http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript // Remove leading 'data:image/jpeg;base64,' or 'data:image/png;base64,' base64Image = base64Image.split(',')[1]; let byteCharacters = atob(base64Image); // http://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long let byteArrays = byteCharacters.match(/[\s\S]{1,512}/g).map( slice => { let byteNumbers = slice.split('').map( x => x.charCodeAt(0) ); return new Uint8Array(byteNumbers); }); let blob = new Blob(byteArrays, { type: contentType || 'image/jpg' /* or 'image/png' */ }); return blob; }
javascript
function base64ToBlob(base64Image, contentType) { // http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript // Remove leading 'data:image/jpeg;base64,' or 'data:image/png;base64,' base64Image = base64Image.split(',')[1]; let byteCharacters = atob(base64Image); // http://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long let byteArrays = byteCharacters.match(/[\s\S]{1,512}/g).map( slice => { let byteNumbers = slice.split('').map( x => x.charCodeAt(0) ); return new Uint8Array(byteNumbers); }); let blob = new Blob(byteArrays, { type: contentType || 'image/jpg' /* or 'image/png' */ }); return blob; }
[ "function", "base64ToBlob", "(", "base64Image", ",", "contentType", ")", "{", "// http://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript", "// Remove leading 'data:image/jpeg;base64,' or 'data:image/png;base64,'", "base64Image", "=", "base64Image", ".", "split", "(", "','", ")", "[", "1", "]", ";", "let", "byteCharacters", "=", "atob", "(", "base64Image", ")", ";", "// http://stackoverflow.com/questions/6259515/javascript-elegant-way-to-split-string-into-segments-n-characters-long", "let", "byteArrays", "=", "byteCharacters", ".", "match", "(", "/", "[\\s\\S]{1,512}", "/", "g", ")", ".", "map", "(", "slice", "=>", "{", "let", "byteNumbers", "=", "slice", ".", "split", "(", "''", ")", ".", "map", "(", "x", "=>", "x", ".", "charCodeAt", "(", "0", ")", ")", ";", "return", "new", "Uint8Array", "(", "byteNumbers", ")", ";", "}", ")", ";", "let", "blob", "=", "new", "Blob", "(", "byteArrays", ",", "{", "type", ":", "contentType", "||", "'image/jpg'", "/* or 'image/png' */", "}", ")", ";", "return", "blob", ";", "}" ]
Converts Base64 image into a blob file. @param {string} base64Image Base64 image string. @param {string} contentType 'image/jpg' or 'image/png'. @returns {file} Image file as a blob.
[ "Converts", "Base64", "image", "into", "a", "blob", "file", "." ]
a86d9db656a7ebd84915ec4e0d5f474a4b87031b
https://github.com/ronanyeah/ooft/blob/a86d9db656a7ebd84915ec4e0d5f474a4b87031b/src/methods.js#L68-L87
55,040
ronanyeah/ooft
src/methods.js
convertImageToBase64
function convertImageToBase64(image) { let fileReader = new FileReader(); return new Promise( (resolve, reject) => { fileReader.onload = fileLoadedEvent => resolve(fileLoadedEvent.target.result); fileReader.readAsDataURL(image); }); }
javascript
function convertImageToBase64(image) { let fileReader = new FileReader(); return new Promise( (resolve, reject) => { fileReader.onload = fileLoadedEvent => resolve(fileLoadedEvent.target.result); fileReader.readAsDataURL(image); }); }
[ "function", "convertImageToBase64", "(", "image", ")", "{", "let", "fileReader", "=", "new", "FileReader", "(", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fileReader", ".", "onload", "=", "fileLoadedEvent", "=>", "resolve", "(", "fileLoadedEvent", ".", "target", ".", "result", ")", ";", "fileReader", ".", "readAsDataURL", "(", "image", ")", ";", "}", ")", ";", "}" ]
Gets image height and width in pixels. @param {file} image Image file as a blob. @returns {string} Base64 image string.
[ "Gets", "image", "height", "and", "width", "in", "pixels", "." ]
a86d9db656a7ebd84915ec4e0d5f474a4b87031b
https://github.com/ronanyeah/ooft/blob/a86d9db656a7ebd84915ec4e0d5f474a4b87031b/src/methods.js#L94-L104
55,041
wigy/chronicles_of_grunt
lib/server.js
handler
function handler(req, res) { var path = cog.getConfig('options.api_data'); var urlRegex = cog.getConfig('options.api_url_regex'); var url = req.url.replace(/^\//, '').replace(/\/$/, ''); console.log(req.method + ' ' + req.url); // Find the JSON-data file and serve it, if URL points to the API. if (path && urlRegex && urlRegex.test(url)) { var file = path + '/' + url + '.json'; if (grunt.file.exists(file)) { res.end(grunt.file.read(file)); return; } } if (req.method == 'POST') { // TODO: This needs fixing, since it throws an error. res.end('{"message": "OK"}'); } }
javascript
function handler(req, res) { var path = cog.getConfig('options.api_data'); var urlRegex = cog.getConfig('options.api_url_regex'); var url = req.url.replace(/^\//, '').replace(/\/$/, ''); console.log(req.method + ' ' + req.url); // Find the JSON-data file and serve it, if URL points to the API. if (path && urlRegex && urlRegex.test(url)) { var file = path + '/' + url + '.json'; if (grunt.file.exists(file)) { res.end(grunt.file.read(file)); return; } } if (req.method == 'POST') { // TODO: This needs fixing, since it throws an error. res.end('{"message": "OK"}'); } }
[ "function", "handler", "(", "req", ",", "res", ")", "{", "var", "path", "=", "cog", ".", "getConfig", "(", "'options.api_data'", ")", ";", "var", "urlRegex", "=", "cog", ".", "getConfig", "(", "'options.api_url_regex'", ")", ";", "var", "url", "=", "req", ".", "url", ".", "replace", "(", "/", "^\\/", "/", ",", "''", ")", ".", "replace", "(", "/", "\\/$", "/", ",", "''", ")", ";", "console", ".", "log", "(", "req", ".", "method", "+", "' '", "+", "req", ".", "url", ")", ";", "// Find the JSON-data file and serve it, if URL points to the API.", "if", "(", "path", "&&", "urlRegex", "&&", "urlRegex", ".", "test", "(", "url", ")", ")", "{", "var", "file", "=", "path", "+", "'/'", "+", "url", "+", "'.json'", ";", "if", "(", "grunt", ".", "file", ".", "exists", "(", "file", ")", ")", "{", "res", ".", "end", "(", "grunt", ".", "file", ".", "read", "(", "file", ")", ")", ";", "return", ";", "}", "}", "if", "(", "req", ".", "method", "==", "'POST'", ")", "{", "// TODO: This needs fixing, since it throws an error.", "res", ".", "end", "(", "'{\"message\": \"OK\"}'", ")", ";", "}", "}" ]
This is the development server used by CoG.
[ "This", "is", "the", "development", "server", "used", "by", "CoG", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/server.js#L28-L50
55,042
MCluck90/clairvoyant
src/reporter.js
function(name, type, filename, code) { this.name = name; this.type = type; this.filename = filename; this.code = code; }
javascript
function(name, type, filename, code) { this.name = name; this.type = type; this.filename = filename; this.code = code; }
[ "function", "(", "name", ",", "type", ",", "filename", ",", "code", ")", "{", "this", ".", "name", "=", "name", ";", "this", ".", "type", "=", "type", ";", "this", ".", "filename", "=", "filename", ";", "this", ".", "code", "=", "code", ";", "}" ]
Represents a single System @param {string} name - Name of the System @param {string} type - System, RenderSystem, or BehaviorSystem @param {string} filename - File path @param {string} code - Code generated for the System @constructor
[ "Represents", "a", "single", "System" ]
4c347499c5fe0f561a53e180d141884b1fa8c21b
https://github.com/MCluck90/clairvoyant/blob/4c347499c5fe0f561a53e180d141884b1fa8c21b/src/reporter.js#L107-L112
55,043
lukin0110/vorto
vorto.js
vorto
function vorto() { var length = arguments.length; var format, options, callback; if (typeof arguments[length-1] !== 'function') { throw new Error('The last argument must be a callback function: function(err, version){...}'); } else { callback = arguments[length-1]; } if (length === 1) { format = '%h'; options = DEFAULTS; } else if (length === 2) { if (typeof arguments[0] === 'string') { format = arguments[0]; options = DEFAULTS; } else if (typeof arguments[0] === 'object'){ format = '%h'; options = createOptions(arguments[0], DEFAULTS); } else { throw new Error('First argument must be a \'string\' or an \'object\''); } } else if (length === 3) { if (typeof arguments[0] !== 'string') { throw new Error('First argument must be a string'); } if (typeof arguments[1] !== 'object') { throw new Error('Second argument must be an object'); } format = arguments[0]; options = createOptions(arguments[1], DEFAULTS); } if (format.indexOf('%j')>-1) { var j = packageVersion(options.repo); git(format, options, function(err, version) { if (err) { callback(err, null); } else { callback(null, version.replace('%j', j)); } }); } else { git(format, options, callback); } }
javascript
function vorto() { var length = arguments.length; var format, options, callback; if (typeof arguments[length-1] !== 'function') { throw new Error('The last argument must be a callback function: function(err, version){...}'); } else { callback = arguments[length-1]; } if (length === 1) { format = '%h'; options = DEFAULTS; } else if (length === 2) { if (typeof arguments[0] === 'string') { format = arguments[0]; options = DEFAULTS; } else if (typeof arguments[0] === 'object'){ format = '%h'; options = createOptions(arguments[0], DEFAULTS); } else { throw new Error('First argument must be a \'string\' or an \'object\''); } } else if (length === 3) { if (typeof arguments[0] !== 'string') { throw new Error('First argument must be a string'); } if (typeof arguments[1] !== 'object') { throw new Error('Second argument must be an object'); } format = arguments[0]; options = createOptions(arguments[1], DEFAULTS); } if (format.indexOf('%j')>-1) { var j = packageVersion(options.repo); git(format, options, function(err, version) { if (err) { callback(err, null); } else { callback(null, version.replace('%j', j)); } }); } else { git(format, options, callback); } }
[ "function", "vorto", "(", ")", "{", "var", "length", "=", "arguments", ".", "length", ";", "var", "format", ",", "options", ",", "callback", ";", "if", "(", "typeof", "arguments", "[", "length", "-", "1", "]", "!==", "'function'", ")", "{", "throw", "new", "Error", "(", "'The last argument must be a callback function: function(err, version){...}'", ")", ";", "}", "else", "{", "callback", "=", "arguments", "[", "length", "-", "1", "]", ";", "}", "if", "(", "length", "===", "1", ")", "{", "format", "=", "'%h'", ";", "options", "=", "DEFAULTS", ";", "}", "else", "if", "(", "length", "===", "2", ")", "{", "if", "(", "typeof", "arguments", "[", "0", "]", "===", "'string'", ")", "{", "format", "=", "arguments", "[", "0", "]", ";", "options", "=", "DEFAULTS", ";", "}", "else", "if", "(", "typeof", "arguments", "[", "0", "]", "===", "'object'", ")", "{", "format", "=", "'%h'", ";", "options", "=", "createOptions", "(", "arguments", "[", "0", "]", ",", "DEFAULTS", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'First argument must be a \\'string\\' or an \\'object\\''", ")", ";", "}", "}", "else", "if", "(", "length", "===", "3", ")", "{", "if", "(", "typeof", "arguments", "[", "0", "]", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'First argument must be a string'", ")", ";", "}", "if", "(", "typeof", "arguments", "[", "1", "]", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'Second argument must be an object'", ")", ";", "}", "format", "=", "arguments", "[", "0", "]", ";", "options", "=", "createOptions", "(", "arguments", "[", "1", "]", ",", "DEFAULTS", ")", ";", "}", "if", "(", "format", ".", "indexOf", "(", "'%j'", ")", ">", "-", "1", ")", "{", "var", "j", "=", "packageVersion", "(", "options", ".", "repo", ")", ";", "git", "(", "format", ",", "options", ",", "function", "(", "err", ",", "version", ")", "{", "if", "(", "err", ")", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "version", ".", "replace", "(", "'%j'", ",", "j", ")", ")", ";", "}", "}", ")", ";", "}", "else", "{", "git", "(", "format", ",", "options", ",", "callback", ")", ";", "}", "}" ]
Init function that might take 3 parameters. It checks the input parameters and will throw errors if they're not valid or wrongly ordered. The callback is always required. vorto([format][, options], callback);
[ "Init", "function", "that", "might", "take", "3", "parameters", ".", "It", "checks", "the", "input", "parameters", "and", "will", "throw", "errors", "if", "they", "re", "not", "valid", "or", "wrongly", "ordered", "." ]
a25ab42e38a7e530ece3f9d0b33d8489f0acc1e9
https://github.com/lukin0110/vorto/blob/a25ab42e38a7e530ece3f9d0b33d8489f0acc1e9/vorto.js#L18-L70
55,044
lukin0110/vorto
vorto.js
packageVersion
function packageVersion(repo) { var location = repo ? path.join(repo, 'package.json') : './package.json'; var pack = require(location); return pack['version']; }
javascript
function packageVersion(repo) { var location = repo ? path.join(repo, 'package.json') : './package.json'; var pack = require(location); return pack['version']; }
[ "function", "packageVersion", "(", "repo", ")", "{", "var", "location", "=", "repo", "?", "path", ".", "join", "(", "repo", ",", "'package.json'", ")", ":", "'./package.json'", ";", "var", "pack", "=", "require", "(", "location", ")", ";", "return", "pack", "[", "'version'", "]", ";", "}" ]
Load the version from package.json @param {string} repo
[ "Load", "the", "version", "from", "package", ".", "json" ]
a25ab42e38a7e530ece3f9d0b33d8489f0acc1e9
https://github.com/lukin0110/vorto/blob/a25ab42e38a7e530ece3f9d0b33d8489f0acc1e9/vorto.js#L90-L94
55,045
rranauro/boxspringjs
boxspring.js
function(name, value, iType) { var type = iType , coded , attach = { '_attachments': this.get('_attachments') || {} } , types = { "html": {"content_type":"text\/html"}, "text": {"content_type":"text\/plain"}, "xml": {"content_type":"text\/plain"}, "jpeg": {"content_type":"image\/jpeg"}, "png": {"content_type":"image\/png"} } // base64 chokes on charCodes > 255 , filterCharCodes = function(s) { // replace newlines and carriage returns with a space. then filter the non-ascii return _.reduce(s.replace(/\n/g, ' ').replace(/\r/g, ' '), function(result, x, i) { if (s.charCodeAt(i) < 256) { result += s[i]; } return result; }, ''); };; // as a prelude to a 'read', the second argument is the 'type' if (arguments.length === 2) { this.options.set('Content-Type', (types && types[value] && types[value].content_type) || 'text\/plain'); } else if (arguments.length === 3) { type = (types && types[type]) ? type : 'xml'; types[type].data = _.encode(filterCharCodes(value)); attach._attachments[name] = types[type]; } this.set('_attachments', attach._attachments); return this; }
javascript
function(name, value, iType) { var type = iType , coded , attach = { '_attachments': this.get('_attachments') || {} } , types = { "html": {"content_type":"text\/html"}, "text": {"content_type":"text\/plain"}, "xml": {"content_type":"text\/plain"}, "jpeg": {"content_type":"image\/jpeg"}, "png": {"content_type":"image\/png"} } // base64 chokes on charCodes > 255 , filterCharCodes = function(s) { // replace newlines and carriage returns with a space. then filter the non-ascii return _.reduce(s.replace(/\n/g, ' ').replace(/\r/g, ' '), function(result, x, i) { if (s.charCodeAt(i) < 256) { result += s[i]; } return result; }, ''); };; // as a prelude to a 'read', the second argument is the 'type' if (arguments.length === 2) { this.options.set('Content-Type', (types && types[value] && types[value].content_type) || 'text\/plain'); } else if (arguments.length === 3) { type = (types && types[type]) ? type : 'xml'; types[type].data = _.encode(filterCharCodes(value)); attach._attachments[name] = types[type]; } this.set('_attachments', attach._attachments); return this; }
[ "function", "(", "name", ",", "value", ",", "iType", ")", "{", "var", "type", "=", "iType", ",", "coded", ",", "attach", "=", "{", "'_attachments'", ":", "this", ".", "get", "(", "'_attachments'", ")", "||", "{", "}", "}", ",", "types", "=", "{", "\"html\"", ":", "{", "\"content_type\"", ":", "\"text\\/html\"", "}", ",", "\"text\"", ":", "{", "\"content_type\"", ":", "\"text\\/plain\"", "}", ",", "\"xml\"", ":", "{", "\"content_type\"", ":", "\"text\\/plain\"", "}", ",", "\"jpeg\"", ":", "{", "\"content_type\"", ":", "\"image\\/jpeg\"", "}", ",", "\"png\"", ":", "{", "\"content_type\"", ":", "\"image\\/png\"", "}", "}", "// base64 chokes on charCodes > 255", ",", "filterCharCodes", "=", "function", "(", "s", ")", "{", "// replace newlines and carriage returns with a space. then filter the non-ascii", "return", "_", ".", "reduce", "(", "s", ".", "replace", "(", "/", "\\n", "/", "g", ",", "' '", ")", ".", "replace", "(", "/", "\\r", "/", "g", ",", "' '", ")", ",", "function", "(", "result", ",", "x", ",", "i", ")", "{", "if", "(", "s", ".", "charCodeAt", "(", "i", ")", "<", "256", ")", "{", "result", "+=", "s", "[", "i", "]", ";", "}", "return", "result", ";", "}", ",", "''", ")", ";", "}", ";", ";", "// as a prelude to a 'read', the second argument is the 'type'", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "this", ".", "options", ".", "set", "(", "'Content-Type'", ",", "(", "types", "&&", "types", "[", "value", "]", "&&", "types", "[", "value", "]", ".", "content_type", ")", "||", "'text\\/plain'", ")", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "type", "=", "(", "types", "&&", "types", "[", "type", "]", ")", "?", "type", ":", "'xml'", ";", "types", "[", "type", "]", ".", "data", "=", "_", ".", "encode", "(", "filterCharCodes", "(", "value", ")", ")", ";", "attach", ".", "_attachments", "[", "name", "]", "=", "types", "[", "type", "]", ";", "}", "this", ".", "set", "(", "'_attachments'", ",", "attach", ".", "_attachments", ")", ";", "return", "this", ";", "}" ]
configure the URL for an attachment
[ "configure", "the", "URL", "for", "an", "attachment" ]
43fd13ae45ba5b16ba9144084b96748a1cd8c0ea
https://github.com/rranauro/boxspringjs/blob/43fd13ae45ba5b16ba9144084b96748a1cd8c0ea/boxspring.js#L649-L685
55,046
observing/eventreactor
lib/index.js
EventReactor
function EventReactor(options, proto) { // allow initialization without a new prefix if (!(this instanceof EventReactor)) return new EventReactor(options, proto); options = options || {}; this.restore = {}; // don't attach the extra event reactor methods, we are going to apply them // manually to the prototypes if (options.manual) return this; var methods = EventReactor.generation , method; for (method in methods) { if (methods.hasOwnProperty(method)) { this[method](proto); } } // such as aliases and emit overrides this.aliases(proto); this.emit(proto); }
javascript
function EventReactor(options, proto) { // allow initialization without a new prefix if (!(this instanceof EventReactor)) return new EventReactor(options, proto); options = options || {}; this.restore = {}; // don't attach the extra event reactor methods, we are going to apply them // manually to the prototypes if (options.manual) return this; var methods = EventReactor.generation , method; for (method in methods) { if (methods.hasOwnProperty(method)) { this[method](proto); } } // such as aliases and emit overrides this.aliases(proto); this.emit(proto); }
[ "function", "EventReactor", "(", "options", ",", "proto", ")", "{", "// allow initialization without a new prefix", "if", "(", "!", "(", "this", "instanceof", "EventReactor", ")", ")", "return", "new", "EventReactor", "(", "options", ",", "proto", ")", ";", "options", "=", "options", "||", "{", "}", ";", "this", ".", "restore", "=", "{", "}", ";", "// don't attach the extra event reactor methods, we are going to apply them", "// manually to the prototypes", "if", "(", "options", ".", "manual", ")", "return", "this", ";", "var", "methods", "=", "EventReactor", ".", "generation", ",", "method", ";", "for", "(", "method", "in", "methods", ")", "{", "if", "(", "methods", ".", "hasOwnProperty", "(", "method", ")", ")", "{", "this", "[", "method", "]", "(", "proto", ")", ";", "}", "}", "// such as aliases and emit overrides", "this", ".", "aliases", "(", "proto", ")", ";", "this", ".", "emit", "(", "proto", ")", ";", "}" ]
The EventReactor plugin that allows you to extend update the EventEmitter prototype. @constructor @param {Object} options @param {Prototype} proto prototype that needs to be extended @api public
[ "The", "EventReactor", "plugin", "that", "allows", "you", "to", "extend", "update", "the", "EventEmitter", "prototype", "." ]
1609083bf56c5ac77809997cd29882910dc2aedf
https://github.com/observing/eventreactor/blob/1609083bf56c5ac77809997cd29882910dc2aedf/lib/index.js#L49-L72
55,047
observing/eventreactor
lib/index.js
every
function every() { for ( var args = slice.call(arguments, 0) , callback = args.pop() , length = args.length , i = 0; i < length; this.on(args[i++], callback) ){} return this; }
javascript
function every() { for ( var args = slice.call(arguments, 0) , callback = args.pop() , length = args.length , i = 0; i < length; this.on(args[i++], callback) ){} return this; }
[ "function", "every", "(", ")", "{", "for", "(", "var", "args", "=", "slice", ".", "call", "(", "arguments", ",", "0", ")", ",", "callback", "=", "args", ".", "pop", "(", ")", ",", "length", "=", "args", ".", "length", ",", "i", "=", "0", ";", "i", "<", "length", ";", "this", ".", "on", "(", "args", "[", "i", "++", "]", ",", "callback", ")", ")", "{", "}", "return", "this", ";", "}" ]
Apply the same callback to every given event. @param {String} .. events @param {Function} callback last argument is always the callback @api private
[ "Apply", "the", "same", "callback", "to", "every", "given", "event", "." ]
1609083bf56c5ac77809997cd29882910dc2aedf
https://github.com/observing/eventreactor/blob/1609083bf56c5ac77809997cd29882910dc2aedf/lib/index.js#L172-L184
55,048
observing/eventreactor
lib/index.js
handle
function handle() { for ( var i = 0 , length = args.length; i < length; self.removeListener(args[i++], handle) ){} // call the function as last as the function might be calling on of // events that where in our either queue, so we need to make sure that // everything is removed callback.apply(self, arguments); }
javascript
function handle() { for ( var i = 0 , length = args.length; i < length; self.removeListener(args[i++], handle) ){} // call the function as last as the function might be calling on of // events that where in our either queue, so we need to make sure that // everything is removed callback.apply(self, arguments); }
[ "function", "handle", "(", ")", "{", "for", "(", "var", "i", "=", "0", ",", "length", "=", "args", ".", "length", ";", "i", "<", "length", ";", "self", ".", "removeListener", "(", "args", "[", "i", "++", "]", ",", "handle", ")", ")", "{", "}", "// call the function as last as the function might be calling on of", "// events that where in our either queue, so we need to make sure that", "// everything is removed", "callback", ".", "apply", "(", "self", ",", "arguments", ")", ";", "}" ]
Handler for all the calls so every remaining event listener is removed removed properly before we call the callback. @api private
[ "Handler", "for", "all", "the", "calls", "so", "every", "remaining", "event", "listener", "is", "removed", "removed", "properly", "before", "we", "call", "the", "callback", "." ]
1609083bf56c5ac77809997cd29882910dc2aedf
https://github.com/observing/eventreactor/blob/1609083bf56c5ac77809997cd29882910dc2aedf/lib/index.js#L201-L214
55,049
observing/eventreactor
lib/index.js
handle
function handle() { self.removeListener(event, reset); callback.apply(self, [event].concat(args)); }
javascript
function handle() { self.removeListener(event, reset); callback.apply(self, [event].concat(args)); }
[ "function", "handle", "(", ")", "{", "self", ".", "removeListener", "(", "event", ",", "reset", ")", ";", "callback", ".", "apply", "(", "self", ",", "[", "event", "]", ".", "concat", "(", "args", ")", ")", ";", "}" ]
Handle the idle callback as the setTimeout got triggerd. @api private
[ "Handle", "the", "idle", "callback", "as", "the", "setTimeout", "got", "triggerd", "." ]
1609083bf56c5ac77809997cd29882910dc2aedf
https://github.com/observing/eventreactor/blob/1609083bf56c5ac77809997cd29882910dc2aedf/lib/index.js#L317-L320
55,050
observing/eventreactor
lib/index.js
reset
function reset() { clearTimeout(timer); self.idle.apply(self, [event, callback, timeout].concat(args)); }
javascript
function reset() { clearTimeout(timer); self.idle.apply(self, [event, callback, timeout].concat(args)); }
[ "function", "reset", "(", ")", "{", "clearTimeout", "(", "timer", ")", ";", "self", ".", "idle", ".", "apply", "(", "self", ",", "[", "event", ",", "callback", ",", "timeout", "]", ".", "concat", "(", "args", ")", ")", ";", "}" ]
Reset the timeout timer again as the event was triggerd. @api private
[ "Reset", "the", "timeout", "timer", "again", "as", "the", "event", "was", "triggerd", "." ]
1609083bf56c5ac77809997cd29882910dc2aedf
https://github.com/observing/eventreactor/blob/1609083bf56c5ac77809997cd29882910dc2aedf/lib/index.js#L327-L331
55,051
ugate/pulses
index.js
listen
function listen(pw, type, listener, fnm, rf, cbtype, passes) { var fn = function pulseListener(flow, artery, pulse) { if (!rf || !(artery instanceof cat.Artery) || !(pulse instanceof cat.Pulse) || flow instanceof Error) return arguments.length ? fn._callback.apply(pw, Array.prototype.slice.call(arguments)) : fn._callback.call(pw); var isRfCb = rf === 'callback', emitErrs = pulse.emitErrors || (pulse.emitErrors !== false && artery.emitErrors) || (pulse.emitErrors !== false && artery.emitErrors !== false && pw.options && pw.options.emitErrors); var args = arguments.length > fn.length ? Array.prototype.slice.call(arguments, isRfCb ? fn.length : 1) : null; if (isRfCb) { (args = args || []).push(function retrofitCb(err) { // last argument should be the callback function if (err instanceof Error) emitError(pw, err, pulse.type, [artery, pulse]); // emit any callback errors var pi = 0, al; if (passes) for (var pl = passes.length; pi < pl; ++pi) { artery.passes[passes[pi]] = arguments[pi]; // pass by name before any other arguments are passed } if ((al = arguments.length - (pi += pi > 0)) === 1) artery.pass.push(arguments[pi]); else if (al) artery.pass.push.apply(artery.pass, Array.prototype.slice.call(arguments, pi)); }); } if (emitErrs) { try { args && args.length ? fn._callback.apply(pw, args) : fn._callback.call(pw, artery, pulse); } catch (e) { emitError(pw, e, pulse.type, [artery, pulse]); } } else args && args.length ? fn._callback.apply(pw, args) : fn._callback.call(pw, artery, pulse); }; fn._callback = listener; if (cbtype) fn._cbtype = cbtype; return PulseEmitter.super_.prototype[fnm || 'addListener'].call(pw, type, fn); }
javascript
function listen(pw, type, listener, fnm, rf, cbtype, passes) { var fn = function pulseListener(flow, artery, pulse) { if (!rf || !(artery instanceof cat.Artery) || !(pulse instanceof cat.Pulse) || flow instanceof Error) return arguments.length ? fn._callback.apply(pw, Array.prototype.slice.call(arguments)) : fn._callback.call(pw); var isRfCb = rf === 'callback', emitErrs = pulse.emitErrors || (pulse.emitErrors !== false && artery.emitErrors) || (pulse.emitErrors !== false && artery.emitErrors !== false && pw.options && pw.options.emitErrors); var args = arguments.length > fn.length ? Array.prototype.slice.call(arguments, isRfCb ? fn.length : 1) : null; if (isRfCb) { (args = args || []).push(function retrofitCb(err) { // last argument should be the callback function if (err instanceof Error) emitError(pw, err, pulse.type, [artery, pulse]); // emit any callback errors var pi = 0, al; if (passes) for (var pl = passes.length; pi < pl; ++pi) { artery.passes[passes[pi]] = arguments[pi]; // pass by name before any other arguments are passed } if ((al = arguments.length - (pi += pi > 0)) === 1) artery.pass.push(arguments[pi]); else if (al) artery.pass.push.apply(artery.pass, Array.prototype.slice.call(arguments, pi)); }); } if (emitErrs) { try { args && args.length ? fn._callback.apply(pw, args) : fn._callback.call(pw, artery, pulse); } catch (e) { emitError(pw, e, pulse.type, [artery, pulse]); } } else args && args.length ? fn._callback.apply(pw, args) : fn._callback.call(pw, artery, pulse); }; fn._callback = listener; if (cbtype) fn._cbtype = cbtype; return PulseEmitter.super_.prototype[fnm || 'addListener'].call(pw, type, fn); }
[ "function", "listen", "(", "pw", ",", "type", ",", "listener", ",", "fnm", ",", "rf", ",", "cbtype", ",", "passes", ")", "{", "var", "fn", "=", "function", "pulseListener", "(", "flow", ",", "artery", ",", "pulse", ")", "{", "if", "(", "!", "rf", "||", "!", "(", "artery", "instanceof", "cat", ".", "Artery", ")", "||", "!", "(", "pulse", "instanceof", "cat", ".", "Pulse", ")", "||", "flow", "instanceof", "Error", ")", "return", "arguments", ".", "length", "?", "fn", ".", "_callback", ".", "apply", "(", "pw", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ":", "fn", ".", "_callback", ".", "call", "(", "pw", ")", ";", "var", "isRfCb", "=", "rf", "===", "'callback'", ",", "emitErrs", "=", "pulse", ".", "emitErrors", "||", "(", "pulse", ".", "emitErrors", "!==", "false", "&&", "artery", ".", "emitErrors", ")", "||", "(", "pulse", ".", "emitErrors", "!==", "false", "&&", "artery", ".", "emitErrors", "!==", "false", "&&", "pw", ".", "options", "&&", "pw", ".", "options", ".", "emitErrors", ")", ";", "var", "args", "=", "arguments", ".", "length", ">", "fn", ".", "length", "?", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "isRfCb", "?", "fn", ".", "length", ":", "1", ")", ":", "null", ";", "if", "(", "isRfCb", ")", "{", "(", "args", "=", "args", "||", "[", "]", ")", ".", "push", "(", "function", "retrofitCb", "(", "err", ")", "{", "// last argument should be the callback function", "if", "(", "err", "instanceof", "Error", ")", "emitError", "(", "pw", ",", "err", ",", "pulse", ".", "type", ",", "[", "artery", ",", "pulse", "]", ")", ";", "// emit any callback errors", "var", "pi", "=", "0", ",", "al", ";", "if", "(", "passes", ")", "for", "(", "var", "pl", "=", "passes", ".", "length", ";", "pi", "<", "pl", ";", "++", "pi", ")", "{", "artery", ".", "passes", "[", "passes", "[", "pi", "]", "]", "=", "arguments", "[", "pi", "]", ";", "// pass by name before any other arguments are passed", "}", "if", "(", "(", "al", "=", "arguments", ".", "length", "-", "(", "pi", "+=", "pi", ">", "0", ")", ")", "===", "1", ")", "artery", ".", "pass", ".", "push", "(", "arguments", "[", "pi", "]", ")", ";", "else", "if", "(", "al", ")", "artery", ".", "pass", ".", "push", ".", "apply", "(", "artery", ".", "pass", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "pi", ")", ")", ";", "}", ")", ";", "}", "if", "(", "emitErrs", ")", "{", "try", "{", "args", "&&", "args", ".", "length", "?", "fn", ".", "_callback", ".", "apply", "(", "pw", ",", "args", ")", ":", "fn", ".", "_callback", ".", "call", "(", "pw", ",", "artery", ",", "pulse", ")", ";", "}", "catch", "(", "e", ")", "{", "emitError", "(", "pw", ",", "e", ",", "pulse", ".", "type", ",", "[", "artery", ",", "pulse", "]", ")", ";", "}", "}", "else", "args", "&&", "args", ".", "length", "?", "fn", ".", "_callback", ".", "apply", "(", "pw", ",", "args", ")", ":", "fn", ".", "_callback", ".", "call", "(", "pw", ",", "artery", ",", "pulse", ")", ";", "}", ";", "fn", ".", "_callback", "=", "listener", ";", "if", "(", "cbtype", ")", "fn", ".", "_cbtype", "=", "cbtype", ";", "return", "PulseEmitter", ".", "super_", ".", "prototype", "[", "fnm", "||", "'addListener'", "]", ".", "call", "(", "pw", ",", "type", ",", "fn", ")", ";", "}" ]
Listens for incoming events using event emitter's add listener function, but with optional error handling and pulse event only capabilities @private @arg {PulseEmitter} pw the pulse emitter @arg {String} type the event type @arg {function} listener the function to execute when the event type is emitted @arg {String} [fnm=addListener] the optional function name that will be called on the pulse emitter @arg {(String | Boolean)} [rf] a flag that indicates a pattern to mimic (e.g. "callback" would pass in pending arguments to the listener with an auto-generated callback function as the last argument and would pass the callback results into the next waiting listeners in the chain; if the first argument is an Error it will emit/throw accordingly) @arg {Array} [passes] an array of names that will automatically be set on the auto-generated callback's artery.passes by name in order and preceeding any arguments in artery.pass @returns {PulseEmitter} the pulse emitter
[ "Listens", "for", "incoming", "events", "using", "event", "emitter", "s", "add", "listener", "function", "but", "with", "optional", "error", "handling", "and", "pulse", "event", "only", "capabilities" ]
214b186e1b72bed9c99c0a7903c70de4eca3c259
https://github.com/ugate/pulses/blob/214b186e1b72bed9c99c0a7903c70de4eca3c259/index.js#L196-L225
55,052
mhelgeson/b9
src/connect/index.js
complete
function complete ( err, msg ){ b9.off('hello', success ); // cleanup // optional callback, error-first... if ( typeof callback == 'function' ){ callback( err, msg ); } }
javascript
function complete ( err, msg ){ b9.off('hello', success ); // cleanup // optional callback, error-first... if ( typeof callback == 'function' ){ callback( err, msg ); } }
[ "function", "complete", "(", "err", ",", "msg", ")", "{", "b9", ".", "off", "(", "'hello'", ",", "success", ")", ";", "// cleanup", "// optional callback, error-first...", "if", "(", "typeof", "callback", "==", "'function'", ")", "{", "callback", "(", "err", ",", "msg", ")", ";", "}", "}" ]
handle complete callback...
[ "handle", "complete", "callback", "..." ]
5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1
https://github.com/mhelgeson/b9/blob/5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1/src/connect/index.js#L43-L49
55,053
mhelgeson/b9
src/connect/index.js
receive
function receive ( str ){ ping(); // clear/schedule next ping var msg = typeof str === 'string' ? JSON.parse( str ) : str; b9.emit('rtm.read', msg, replyTo( null ) ); // acknowledge that a pending message was sent successfully if ( msg.reply_to ){ delete pending[ msg.reply_to ]; } else if ( msg.type != null ){ b9.emit( msg.type, msg, replyTo( msg.channel ) ); } }
javascript
function receive ( str ){ ping(); // clear/schedule next ping var msg = typeof str === 'string' ? JSON.parse( str ) : str; b9.emit('rtm.read', msg, replyTo( null ) ); // acknowledge that a pending message was sent successfully if ( msg.reply_to ){ delete pending[ msg.reply_to ]; } else if ( msg.type != null ){ b9.emit( msg.type, msg, replyTo( msg.channel ) ); } }
[ "function", "receive", "(", "str", ")", "{", "ping", "(", ")", ";", "// clear/schedule next ping", "var", "msg", "=", "typeof", "str", "===", "'string'", "?", "JSON", ".", "parse", "(", "str", ")", ":", "str", ";", "b9", ".", "emit", "(", "'rtm.read'", ",", "msg", ",", "replyTo", "(", "null", ")", ")", ";", "// acknowledge that a pending message was sent successfully", "if", "(", "msg", ".", "reply_to", ")", "{", "delete", "pending", "[", "msg", ".", "reply_to", "]", ";", "}", "else", "if", "(", "msg", ".", "type", "!=", "null", ")", "{", "b9", ".", "emit", "(", "msg", ".", "type", ",", "msg", ",", "replyTo", "(", "msg", ".", "channel", ")", ")", ";", "}", "}" ]
handle a websocket message @private method
[ "handle", "a", "websocket", "message" ]
5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1
https://github.com/mhelgeson/b9/blob/5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1/src/connect/index.js#L115-L126
55,054
mhelgeson/b9
src/connect/index.js
ping
function ping (){ clearTimeout( ping.timer ); ping.timer = setTimeout(function(){ b9.send({ type: 'ping', time: Date.now() }); }, b9._interval ); }
javascript
function ping (){ clearTimeout( ping.timer ); ping.timer = setTimeout(function(){ b9.send({ type: 'ping', time: Date.now() }); }, b9._interval ); }
[ "function", "ping", "(", ")", "{", "clearTimeout", "(", "ping", ".", "timer", ")", ";", "ping", ".", "timer", "=", "setTimeout", "(", "function", "(", ")", "{", "b9", ".", "send", "(", "{", "type", ":", "'ping'", ",", "time", ":", "Date", ".", "now", "(", ")", "}", ")", ";", "}", ",", "b9", ".", "_interval", ")", ";", "}" ]
keep the connection alive @private method
[ "keep", "the", "connection", "alive" ]
5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1
https://github.com/mhelgeson/b9/blob/5f7ad9ac7c3fa586b06f6460b70a42c50b34e6f1/src/connect/index.js#L142-L147
55,055
BladeRunnerJS/jstd-mocha
src/asserts.js
assertEqualsDelta
function assertEqualsDelta(msg, expected, actual, epsilon) { var args = this.argsWithOptionalMsg_(arguments, 4); jstestdriver.assertCount++; msg = args[0]; expected = args[1]; actual = args[2]; epsilon = args[3]; if (!compareDelta_(expected, actual, epsilon)) { this.fail(msg + 'expected ' + epsilon + ' within ' + this.prettyPrintEntity_(expected) + ' but was ' + this.prettyPrintEntity_(actual) + ''); } return true; }
javascript
function assertEqualsDelta(msg, expected, actual, epsilon) { var args = this.argsWithOptionalMsg_(arguments, 4); jstestdriver.assertCount++; msg = args[0]; expected = args[1]; actual = args[2]; epsilon = args[3]; if (!compareDelta_(expected, actual, epsilon)) { this.fail(msg + 'expected ' + epsilon + ' within ' + this.prettyPrintEntity_(expected) + ' but was ' + this.prettyPrintEntity_(actual) + ''); } return true; }
[ "function", "assertEqualsDelta", "(", "msg", ",", "expected", ",", "actual", ",", "epsilon", ")", "{", "var", "args", "=", "this", ".", "argsWithOptionalMsg_", "(", "arguments", ",", "4", ")", ";", "jstestdriver", ".", "assertCount", "++", ";", "msg", "=", "args", "[", "0", "]", ";", "expected", "=", "args", "[", "1", "]", ";", "actual", "=", "args", "[", "2", "]", ";", "epsilon", "=", "args", "[", "3", "]", ";", "if", "(", "!", "compareDelta_", "(", "expected", ",", "actual", ",", "epsilon", ")", ")", "{", "this", ".", "fail", "(", "msg", "+", "'expected '", "+", "epsilon", "+", "' within '", "+", "this", ".", "prettyPrintEntity_", "(", "expected", ")", "+", "' but was '", "+", "this", ".", "prettyPrintEntity_", "(", "actual", ")", "+", "''", ")", ";", "}", "return", "true", ";", "}" ]
Asserts that two doubles, or the elements of two arrays of doubles, are equal to within a positive delta.
[ "Asserts", "that", "two", "doubles", "or", "the", "elements", "of", "two", "arrays", "of", "doubles", "are", "equal", "to", "within", "a", "positive", "delta", "." ]
ac5f524763f644873dfa22d920e9780e3d73c737
https://github.com/BladeRunnerJS/jstd-mocha/blob/ac5f524763f644873dfa22d920e9780e3d73c737/src/asserts.js#L568-L582
55,056
waitingsong/node-rxwalker
rollup.config.js
parseName
function parseName(name) { if (name) { const arr = name.split('.') const len = arr.length if (len > 2) { return arr.slice(0, -1).join('.') } else if (len === 2 || len === 1) { return arr[0] } } return name }
javascript
function parseName(name) { if (name) { const arr = name.split('.') const len = arr.length if (len > 2) { return arr.slice(0, -1).join('.') } else if (len === 2 || len === 1) { return arr[0] } } return name }
[ "function", "parseName", "(", "name", ")", "{", "if", "(", "name", ")", "{", "const", "arr", "=", "name", ".", "split", "(", "'.'", ")", "const", "len", "=", "arr", ".", "length", "if", "(", "len", ">", "2", ")", "{", "return", "arr", ".", "slice", "(", "0", ",", "-", "1", ")", ".", "join", "(", "'.'", ")", "}", "else", "if", "(", "len", "===", "2", "||", "len", "===", "1", ")", "{", "return", "arr", "[", "0", "]", "}", "}", "return", "name", "}" ]
remove pkg.name extension if exists
[ "remove", "pkg", ".", "name", "extension", "if", "exists" ]
b08dae4940329f98229dd38e60da54b7426436ab
https://github.com/waitingsong/node-rxwalker/blob/b08dae4940329f98229dd38e60da54b7426436ab/rollup.config.js#L165-L178
55,057
altshift/altshift
lib/altshift/core/class.js
function (object) { var methodName; methodName = this.test(object, true); if (methodName !== true) { throw new exports.NotImplementedError({ code: 'interface', message: 'Object %(object) does not implement %(interface)#%(method)()', //Additional information interface: this.name, object: object, method: methodName }); } return this; }
javascript
function (object) { var methodName; methodName = this.test(object, true); if (methodName !== true) { throw new exports.NotImplementedError({ code: 'interface', message: 'Object %(object) does not implement %(interface)#%(method)()', //Additional information interface: this.name, object: object, method: methodName }); } return this; }
[ "function", "(", "object", ")", "{", "var", "methodName", ";", "methodName", "=", "this", ".", "test", "(", "object", ",", "true", ")", ";", "if", "(", "methodName", "!==", "true", ")", "{", "throw", "new", "exports", ".", "NotImplementedError", "(", "{", "code", ":", "'interface'", ",", "message", ":", "'Object %(object) does not implement %(interface)#%(method)()'", ",", "//Additional information", "interface", ":", "this", ".", "name", ",", "object", ":", "object", ",", "method", ":", "methodName", "}", ")", ";", "}", "return", "this", ";", "}" ]
Throw error if object does not have all methods @param {Object} object @return this
[ "Throw", "error", "if", "object", "does", "not", "have", "all", "methods" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/class.js#L118-L134
55,058
altshift/altshift
lib/altshift/core/class.js
function (object, returnName) { var methodName; for (methodName in this.methods) { if (!(object[methodName] instanceof Function)) { return returnName ? methodName : false; } } return true; }
javascript
function (object, returnName) { var methodName; for (methodName in this.methods) { if (!(object[methodName] instanceof Function)) { return returnName ? methodName : false; } } return true; }
[ "function", "(", "object", ",", "returnName", ")", "{", "var", "methodName", ";", "for", "(", "methodName", "in", "this", ".", "methods", ")", "{", "if", "(", "!", "(", "object", "[", "methodName", "]", "instanceof", "Function", ")", ")", "{", "return", "returnName", "?", "methodName", ":", "false", ";", "}", "}", "return", "true", ";", "}" ]
Return false or the missing method name in object if method is missing in object @param {Object} object @param {boolean} returnName @return {boolean|string}
[ "Return", "false", "or", "the", "missing", "method", "name", "in", "object", "if", "method", "is", "missing", "in", "object" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/class.js#L143-L151
55,059
altshift/altshift
lib/altshift/core/class.js
function (_module) { if (! this.name) { throw new exports.ValueError({message: 'name is empty'}); } var _exports = _module.exports || _module; _exports[this.name] = this; return this; }
javascript
function (_module) { if (! this.name) { throw new exports.ValueError({message: 'name is empty'}); } var _exports = _module.exports || _module; _exports[this.name] = this; return this; }
[ "function", "(", "_module", ")", "{", "if", "(", "!", "this", ".", "name", ")", "{", "throw", "new", "exports", ".", "ValueError", "(", "{", "message", ":", "'name is empty'", "}", ")", ";", "}", "var", "_exports", "=", "_module", ".", "exports", "||", "_module", ";", "_exports", "[", "this", ".", "name", "]", "=", "this", ";", "return", "this", ";", "}" ]
Export this interface into _exports @return this
[ "Export", "this", "interface", "into", "_exports" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/class.js#L158-L165
55,060
altshift/altshift
lib/altshift/core/class.js
function () { var prefix = '%(', suffix = ')', data = this.data, output = '', dataKey; output = this.__message__; for (dataKey in data) { if (data.hasOwnProperty(dataKey)) { output = output.replace(prefix + dataKey + suffix, '' + data[dataKey]); } } output = output.replace(prefix + 'code' + suffix, '' + this.code); output = output.replace(prefix + 'name' + suffix, '' + this.name); return output; }
javascript
function () { var prefix = '%(', suffix = ')', data = this.data, output = '', dataKey; output = this.__message__; for (dataKey in data) { if (data.hasOwnProperty(dataKey)) { output = output.replace(prefix + dataKey + suffix, '' + data[dataKey]); } } output = output.replace(prefix + 'code' + suffix, '' + this.code); output = output.replace(prefix + 'name' + suffix, '' + this.name); return output; }
[ "function", "(", ")", "{", "var", "prefix", "=", "'%('", ",", "suffix", "=", "')'", ",", "data", "=", "this", ".", "data", ",", "output", "=", "''", ",", "dataKey", ";", "output", "=", "this", ".", "__message__", ";", "for", "(", "dataKey", "in", "data", ")", "{", "if", "(", "data", ".", "hasOwnProperty", "(", "dataKey", ")", ")", "{", "output", "=", "output", ".", "replace", "(", "prefix", "+", "dataKey", "+", "suffix", ",", "''", "+", "data", "[", "dataKey", "]", ")", ";", "}", "}", "output", "=", "output", ".", "replace", "(", "prefix", "+", "'code'", "+", "suffix", ",", "''", "+", "this", ".", "code", ")", ";", "output", "=", "output", ".", "replace", "(", "prefix", "+", "'name'", "+", "suffix", ",", "''", "+", "this", ".", "name", ")", ";", "return", "output", ";", "}" ]
Return formatted message @return {string}
[ "Return", "formatted", "message" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/class.js#L301-L319
55,061
altshift/altshift
lib/altshift/core/class.js
function (full) { var output, data; output = this.name + '[' + this.code + ']: '; output += this.message; if (full) { output += '\n'; output += this.stack.toString(); } return output; }
javascript
function (full) { var output, data; output = this.name + '[' + this.code + ']: '; output += this.message; if (full) { output += '\n'; output += this.stack.toString(); } return output; }
[ "function", "(", "full", ")", "{", "var", "output", ",", "data", ";", "output", "=", "this", ".", "name", "+", "'['", "+", "this", ".", "code", "+", "']: '", ";", "output", "+=", "this", ".", "message", ";", "if", "(", "full", ")", "{", "output", "+=", "'\\n'", ";", "output", "+=", "this", ".", "stack", ".", "toString", "(", ")", ";", "}", "return", "output", ";", "}" ]
Return string formatted representation @param {boolean} full @return {string}
[ "Return", "string", "formatted", "representation" ]
5c051157e6f558636c8e12081b6707caa66249de
https://github.com/altshift/altshift/blob/5c051157e6f558636c8e12081b6707caa66249de/lib/altshift/core/class.js#L327-L337
55,062
ArtOfCode-/nails
src/handlers.js
setView
function setView({ action, config, route, routes, method }) { const ws = route.ws; return exports.getView(action, config).then(view => { routes[ws ? 'ws' : route.type].push({ action, method, view, match: new Route(route.url), }); }); }
javascript
function setView({ action, config, route, routes, method }) { const ws = route.ws; return exports.getView(action, config).then(view => { routes[ws ? 'ws' : route.type].push({ action, method, view, match: new Route(route.url), }); }); }
[ "function", "setView", "(", "{", "action", ",", "config", ",", "route", ",", "routes", ",", "method", "}", ")", "{", "const", "ws", "=", "route", ".", "ws", ";", "return", "exports", ".", "getView", "(", "action", ",", "config", ")", ".", "then", "(", "view", "=>", "{", "routes", "[", "ws", "?", "'ws'", ":", "route", ".", "type", "]", ".", "push", "(", "{", "action", ",", "method", ",", "view", ",", "match", ":", "new", "Route", "(", "route", ".", "url", ")", ",", "}", ")", ";", "}", ")", ";", "}" ]
Set the view for a specific route @private @returns {Promise} Could the view be loaded?
[ "Set", "the", "view", "for", "a", "specific", "route" ]
1ba9158742ba72bc727ad5c881035ee9d99b700c
https://github.com/ArtOfCode-/nails/blob/1ba9158742ba72bc727ad5c881035ee9d99b700c/src/handlers.js#L27-L37
55,063
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/rangelist.js
function() { var rangeList = this, bookmark = CKEDITOR.dom.walker.bookmark(), bookmarks = [], current; return { /** * Retrieves the next range in the list. * * @member CKEDITOR.dom.rangeListIterator * @param {Boolean} [mergeConsequent=false] Whether join two adjacent * ranges into single, e.g. consequent table cells. */ getNextRange: function( mergeConsequent ) { current = current === undefined ? 0 : current + 1; var range = rangeList[ current ]; // Multiple ranges might be mangled by each other. if ( range && rangeList.length > 1 ) { // Bookmarking all other ranges on the first iteration, // the range correctness after it doesn't matter since we'll // restore them before the next iteration. if ( !current ) { // Make sure bookmark correctness by reverse processing. for ( var i = rangeList.length - 1; i >= 0; i-- ) bookmarks.unshift( rangeList[ i ].createBookmark( true ) ); } if ( mergeConsequent ) { // Figure out how many ranges should be merged. var mergeCount = 0; while ( rangeList[ current + mergeCount + 1 ] ) { var doc = range.document, found = 0, left = doc.getById( bookmarks[ mergeCount ].endNode ), right = doc.getById( bookmarks[ mergeCount + 1 ].startNode ), next; // Check subsequent range. while ( 1 ) { next = left.getNextSourceNode( false ); if ( !right.equals( next ) ) { // This could be yet another bookmark or // walking across block boundaries. if ( bookmark( next ) || ( next.type == CKEDITOR.NODE_ELEMENT && next.isBlockBoundary() ) ) { left = next; continue; } } else { found = 1; } break; } if ( !found ) break; mergeCount++; } } range.moveToBookmark( bookmarks.shift() ); // Merge ranges finally after moving to bookmarks. while ( mergeCount-- ) { next = rangeList[ ++current ]; next.moveToBookmark( bookmarks.shift() ); range.setEnd( next.endContainer, next.endOffset ); } } return range; } }; }
javascript
function() { var rangeList = this, bookmark = CKEDITOR.dom.walker.bookmark(), bookmarks = [], current; return { /** * Retrieves the next range in the list. * * @member CKEDITOR.dom.rangeListIterator * @param {Boolean} [mergeConsequent=false] Whether join two adjacent * ranges into single, e.g. consequent table cells. */ getNextRange: function( mergeConsequent ) { current = current === undefined ? 0 : current + 1; var range = rangeList[ current ]; // Multiple ranges might be mangled by each other. if ( range && rangeList.length > 1 ) { // Bookmarking all other ranges on the first iteration, // the range correctness after it doesn't matter since we'll // restore them before the next iteration. if ( !current ) { // Make sure bookmark correctness by reverse processing. for ( var i = rangeList.length - 1; i >= 0; i-- ) bookmarks.unshift( rangeList[ i ].createBookmark( true ) ); } if ( mergeConsequent ) { // Figure out how many ranges should be merged. var mergeCount = 0; while ( rangeList[ current + mergeCount + 1 ] ) { var doc = range.document, found = 0, left = doc.getById( bookmarks[ mergeCount ].endNode ), right = doc.getById( bookmarks[ mergeCount + 1 ].startNode ), next; // Check subsequent range. while ( 1 ) { next = left.getNextSourceNode( false ); if ( !right.equals( next ) ) { // This could be yet another bookmark or // walking across block boundaries. if ( bookmark( next ) || ( next.type == CKEDITOR.NODE_ELEMENT && next.isBlockBoundary() ) ) { left = next; continue; } } else { found = 1; } break; } if ( !found ) break; mergeCount++; } } range.moveToBookmark( bookmarks.shift() ); // Merge ranges finally after moving to bookmarks. while ( mergeCount-- ) { next = rangeList[ ++current ]; next.moveToBookmark( bookmarks.shift() ); range.setEnd( next.endContainer, next.endOffset ); } } return range; } }; }
[ "function", "(", ")", "{", "var", "rangeList", "=", "this", ",", "bookmark", "=", "CKEDITOR", ".", "dom", ".", "walker", ".", "bookmark", "(", ")", ",", "bookmarks", "=", "[", "]", ",", "current", ";", "return", "{", "/**\n\t\t\t\t * Retrieves the next range in the list.\n\t\t\t\t *\n\t\t\t\t * @member CKEDITOR.dom.rangeListIterator\n\t\t\t\t * @param {Boolean} [mergeConsequent=false] Whether join two adjacent\n\t\t\t\t * ranges into single, e.g. consequent table cells.\n\t\t\t\t */", "getNextRange", ":", "function", "(", "mergeConsequent", ")", "{", "current", "=", "current", "===", "undefined", "?", "0", ":", "current", "+", "1", ";", "var", "range", "=", "rangeList", "[", "current", "]", ";", "// Multiple ranges might be mangled by each other.", "if", "(", "range", "&&", "rangeList", ".", "length", ">", "1", ")", "{", "// Bookmarking all other ranges on the first iteration,", "// the range correctness after it doesn't matter since we'll", "// restore them before the next iteration.", "if", "(", "!", "current", ")", "{", "// Make sure bookmark correctness by reverse processing.", "for", "(", "var", "i", "=", "rangeList", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "bookmarks", ".", "unshift", "(", "rangeList", "[", "i", "]", ".", "createBookmark", "(", "true", ")", ")", ";", "}", "if", "(", "mergeConsequent", ")", "{", "// Figure out how many ranges should be merged.", "var", "mergeCount", "=", "0", ";", "while", "(", "rangeList", "[", "current", "+", "mergeCount", "+", "1", "]", ")", "{", "var", "doc", "=", "range", ".", "document", ",", "found", "=", "0", ",", "left", "=", "doc", ".", "getById", "(", "bookmarks", "[", "mergeCount", "]", ".", "endNode", ")", ",", "right", "=", "doc", ".", "getById", "(", "bookmarks", "[", "mergeCount", "+", "1", "]", ".", "startNode", ")", ",", "next", ";", "// Check subsequent range.", "while", "(", "1", ")", "{", "next", "=", "left", ".", "getNextSourceNode", "(", "false", ")", ";", "if", "(", "!", "right", ".", "equals", "(", "next", ")", ")", "{", "// This could be yet another bookmark or", "// walking across block boundaries.", "if", "(", "bookmark", "(", "next", ")", "||", "(", "next", ".", "type", "==", "CKEDITOR", ".", "NODE_ELEMENT", "&&", "next", ".", "isBlockBoundary", "(", ")", ")", ")", "{", "left", "=", "next", ";", "continue", ";", "}", "}", "else", "{", "found", "=", "1", ";", "}", "break", ";", "}", "if", "(", "!", "found", ")", "break", ";", "mergeCount", "++", ";", "}", "}", "range", ".", "moveToBookmark", "(", "bookmarks", ".", "shift", "(", ")", ")", ";", "// Merge ranges finally after moving to bookmarks.", "while", "(", "mergeCount", "--", ")", "{", "next", "=", "rangeList", "[", "++", "current", "]", ";", "next", ".", "moveToBookmark", "(", "bookmarks", ".", "shift", "(", ")", ")", ";", "range", ".", "setEnd", "(", "next", ".", "endContainer", ",", "next", ".", "endOffset", ")", ";", "}", "}", "return", "range", ";", "}", "}", ";", "}" ]
Creates an instance of the rangeList iterator, it should be used only when the ranges processing could be DOM intrusive, which means it may pollute and break other ranges in this list. Otherwise, it's enough to just iterate over this array in a for loop. @returns {CKEDITOR.dom.rangeListIterator}
[ "Creates", "an", "instance", "of", "the", "rangeList", "iterator", "it", "should", "be", "used", "only", "when", "the", "ranges", "processing", "could", "be", "DOM", "intrusive", "which", "means", "it", "may", "pollute", "and", "break", "other", "ranges", "in", "this", "list", ".", "Otherwise", "it", "s", "enough", "to", "just", "iterate", "over", "this", "array", "in", "a", "for", "loop", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/rangelist.js#L39-L116
55,064
frisb/fdboost
lib/enhance/encoding/adapters/index.js
function(typeCode) { switch (typeCode) { case this.types.undefined: return this.Undefined; case this.types.string: return this.String; case this.types.integer: return this.Integer; case this.types.double: return this.Double; case this.types.boolean: return this.Boolean; case this.types["null"]: return this.Null; case this.types.datetime: return this.DateTime; case this.types.array: return this.Array; case this.types.object: return this.Object; case this.types["function"]: return this.Function; default: throw new Error("Unknown typeCode \"" + typeCode + "\"."); } }
javascript
function(typeCode) { switch (typeCode) { case this.types.undefined: return this.Undefined; case this.types.string: return this.String; case this.types.integer: return this.Integer; case this.types.double: return this.Double; case this.types.boolean: return this.Boolean; case this.types["null"]: return this.Null; case this.types.datetime: return this.DateTime; case this.types.array: return this.Array; case this.types.object: return this.Object; case this.types["function"]: return this.Function; default: throw new Error("Unknown typeCode \"" + typeCode + "\"."); } }
[ "function", "(", "typeCode", ")", "{", "switch", "(", "typeCode", ")", "{", "case", "this", ".", "types", ".", "undefined", ":", "return", "this", ".", "Undefined", ";", "case", "this", ".", "types", ".", "string", ":", "return", "this", ".", "String", ";", "case", "this", ".", "types", ".", "integer", ":", "return", "this", ".", "Integer", ";", "case", "this", ".", "types", ".", "double", ":", "return", "this", ".", "Double", ";", "case", "this", ".", "types", ".", "boolean", ":", "return", "this", ".", "Boolean", ";", "case", "this", ".", "types", "[", "\"null\"", "]", ":", "return", "this", ".", "Null", ";", "case", "this", ".", "types", ".", "datetime", ":", "return", "this", ".", "DateTime", ";", "case", "this", ".", "types", ".", "array", ":", "return", "this", ".", "Array", ";", "case", "this", ".", "types", ".", "object", ":", "return", "this", ".", "Object", ";", "case", "this", ".", "types", "[", "\"function\"", "]", ":", "return", "this", ".", "Function", ";", "default", ":", "throw", "new", "Error", "(", "\"Unknown typeCode \\\"\"", "+", "typeCode", "+", "\"\\\".\"", ")", ";", "}", "}" ]
Get an Adapter for typeCode @method @param {integer} typeCode Type code. @return {AbstractAdapter} AbstractAdapter extension
[ "Get", "an", "Adapter", "for", "typeCode" ]
66cfb6552940aa92f35dbb1cf4d0695d842205c2
https://github.com/frisb/fdboost/blob/66cfb6552940aa92f35dbb1cf4d0695d842205c2/lib/enhance/encoding/adapters/index.js#L30-L55
55,065
forfuturellc/svc-fbr
src/lib/utils.js
addType
function addType(descriptor) { if (!(descriptor instanceof fs.Stats)) { return descriptor; } [ "isFile", "isDirectory", "isBlockDevice", "isCharacterDevice", "isSymbolicLink", "isFIFO", "isSocket", ].forEach(function(funcName) { if (descriptor[funcName]()) { descriptor[funcName] = true; } else { descriptor[funcName] = undefined; } }); if (_.isArray(descriptor.content)) { descriptor.content.forEach(function(obj) { addType(obj); }); } return descriptor; }
javascript
function addType(descriptor) { if (!(descriptor instanceof fs.Stats)) { return descriptor; } [ "isFile", "isDirectory", "isBlockDevice", "isCharacterDevice", "isSymbolicLink", "isFIFO", "isSocket", ].forEach(function(funcName) { if (descriptor[funcName]()) { descriptor[funcName] = true; } else { descriptor[funcName] = undefined; } }); if (_.isArray(descriptor.content)) { descriptor.content.forEach(function(obj) { addType(obj); }); } return descriptor; }
[ "function", "addType", "(", "descriptor", ")", "{", "if", "(", "!", "(", "descriptor", "instanceof", "fs", ".", "Stats", ")", ")", "{", "return", "descriptor", ";", "}", "[", "\"isFile\"", ",", "\"isDirectory\"", ",", "\"isBlockDevice\"", ",", "\"isCharacterDevice\"", ",", "\"isSymbolicLink\"", ",", "\"isFIFO\"", ",", "\"isSocket\"", ",", "]", ".", "forEach", "(", "function", "(", "funcName", ")", "{", "if", "(", "descriptor", "[", "funcName", "]", "(", ")", ")", "{", "descriptor", "[", "funcName", "]", "=", "true", ";", "}", "else", "{", "descriptor", "[", "funcName", "]", "=", "undefined", ";", "}", "}", ")", ";", "if", "(", "_", ".", "isArray", "(", "descriptor", ".", "content", ")", ")", "{", "descriptor", ".", "content", ".", "forEach", "(", "function", "(", "obj", ")", "{", "addType", "(", "obj", ")", ";", "}", ")", ";", "}", "return", "descriptor", ";", "}" ]
Add type to all stat objects in a descriptor @param {fs.Stats} stats @return {fs.Stats}
[ "Add", "type", "to", "all", "stat", "objects", "in", "a", "descriptor" ]
8c07c71d6423d1dbd4f903a032dea0bfec63894e
https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/utils.js#L26-L46
55,066
forfuturellc/svc-fbr
src/lib/utils.js
getArgs
function getArgs(userArgs, defaultArgs, userCallback) { let args = { }; let callback = userCallback || function() { }; defaultArgs.unshift(args); _.assign.apply(null, defaultArgs); if (_.isPlainObject(userArgs)) { _.merge(args, userArgs); } else { callback = userArgs; } return { options: args, callback, }; }
javascript
function getArgs(userArgs, defaultArgs, userCallback) { let args = { }; let callback = userCallback || function() { }; defaultArgs.unshift(args); _.assign.apply(null, defaultArgs); if (_.isPlainObject(userArgs)) { _.merge(args, userArgs); } else { callback = userArgs; } return { options: args, callback, }; }
[ "function", "getArgs", "(", "userArgs", ",", "defaultArgs", ",", "userCallback", ")", "{", "let", "args", "=", "{", "}", ";", "let", "callback", "=", "userCallback", "||", "function", "(", ")", "{", "}", ";", "defaultArgs", ".", "unshift", "(", "args", ")", ";", "_", ".", "assign", ".", "apply", "(", "null", ",", "defaultArgs", ")", ";", "if", "(", "_", ".", "isPlainObject", "(", "userArgs", ")", ")", "{", "_", ".", "merge", "(", "args", ",", "userArgs", ")", ";", "}", "else", "{", "callback", "=", "userArgs", ";", "}", "return", "{", "options", ":", "args", ",", "callback", ",", "}", ";", "}" ]
Get arguments passed by user curated with configurations @param {Object} userArgs - arguments from user @param {Object[]} defaultArgs - default arguments to use @param {Function} userCallback - callback passed by user
[ "Get", "arguments", "passed", "by", "user", "curated", "with", "configurations" ]
8c07c71d6423d1dbd4f903a032dea0bfec63894e
https://github.com/forfuturellc/svc-fbr/blob/8c07c71d6423d1dbd4f903a032dea0bfec63894e/src/lib/utils.js#L56-L72
55,067
wigy/chronicles_of_grunt
lib/file-filter.js
removeDuplicates
function removeDuplicates(files, duplicates) { var i; var ret = []; var found = {}; if (duplicates) { for (i=0; i < duplicates.length; i++) { found[duplicates[i].dst] = true; } } for (i=0; i < files.length; i++) { if (!found[files[i].dst]) { found[files[i].dst] = true; ret.push(files[i]); } } return ret; }
javascript
function removeDuplicates(files, duplicates) { var i; var ret = []; var found = {}; if (duplicates) { for (i=0; i < duplicates.length; i++) { found[duplicates[i].dst] = true; } } for (i=0; i < files.length; i++) { if (!found[files[i].dst]) { found[files[i].dst] = true; ret.push(files[i]); } } return ret; }
[ "function", "removeDuplicates", "(", "files", ",", "duplicates", ")", "{", "var", "i", ";", "var", "ret", "=", "[", "]", ";", "var", "found", "=", "{", "}", ";", "if", "(", "duplicates", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "duplicates", ".", "length", ";", "i", "++", ")", "{", "found", "[", "duplicates", "[", "i", "]", ".", "dst", "]", "=", "true", ";", "}", "}", "for", "(", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "found", "[", "files", "[", "i", "]", ".", "dst", "]", ")", "{", "found", "[", "files", "[", "i", "]", ".", "dst", "]", "=", "true", ";", "ret", ".", "push", "(", "files", "[", "i", "]", ")", ";", "}", "}", "return", "ret", ";", "}" ]
Scan file specs and remove duplicates. @param files {Array} List of resolved file specs. @param duplicates {Array} Optional list of resolved file specs to consider duplicates.
[ "Scan", "file", "specs", "and", "remove", "duplicates", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L164-L182
55,068
wigy/chronicles_of_grunt
lib/file-filter.js
flatten
function flatten(files) { var ret = []; for (var i=0; i < files.length; i++) { ret.push(files[i].dst); } return ret; }
javascript
function flatten(files) { var ret = []; for (var i=0; i < files.length; i++) { ret.push(files[i].dst); } return ret; }
[ "function", "flatten", "(", "files", ")", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "ret", ".", "push", "(", "files", "[", "i", "]", ".", "dst", ")", ";", "}", "return", "ret", ";", "}" ]
Collect destination files from file spec list.
[ "Collect", "destination", "files", "from", "file", "spec", "list", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L187-L193
55,069
wigy/chronicles_of_grunt
lib/file-filter.js
prefixDest
function prefixDest(prefix, files) { for (var i = 0; i < files.length; i++) { files[i].dst = prefix + files[i].dst; } return files; }
javascript
function prefixDest(prefix, files) { for (var i = 0; i < files.length; i++) { files[i].dst = prefix + files[i].dst; } return files; }
[ "function", "prefixDest", "(", "prefix", ",", "files", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "files", "[", "i", "]", ".", "dst", "=", "prefix", "+", "files", "[", "i", "]", ".", "dst", ";", "}", "return", "files", ";", "}" ]
Add a directory prefix to all destinations in the file list.
[ "Add", "a", "directory", "prefix", "to", "all", "destinations", "in", "the", "file", "list", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L198-L203
55,070
wigy/chronicles_of_grunt
lib/file-filter.js
filesInRepository
function filesInRepository(dir) { var ignoreDirs = cog.getOption('ignore_dirs'); // TODO: Allow an array and move to config. var ignoreFiles = /~$/; var files = glob.sync(dir ? dir + '/*' : '*'); var ret = []; for (var i = 0; i < files.length; i++) { if (fs.lstatSync(files[i]).isDirectory()) { // Ignore standard directories of uninterest. if (!dir && ignoreDirs.indexOf(files[i]) >= 0) { continue; } ret = filesInRepository(files[i]).concat(ret); } else { if (!ignoreFiles.test(files[i])) { ret.push(files[i]); } } } return ret; }
javascript
function filesInRepository(dir) { var ignoreDirs = cog.getOption('ignore_dirs'); // TODO: Allow an array and move to config. var ignoreFiles = /~$/; var files = glob.sync(dir ? dir + '/*' : '*'); var ret = []; for (var i = 0; i < files.length; i++) { if (fs.lstatSync(files[i]).isDirectory()) { // Ignore standard directories of uninterest. if (!dir && ignoreDirs.indexOf(files[i]) >= 0) { continue; } ret = filesInRepository(files[i]).concat(ret); } else { if (!ignoreFiles.test(files[i])) { ret.push(files[i]); } } } return ret; }
[ "function", "filesInRepository", "(", "dir", ")", "{", "var", "ignoreDirs", "=", "cog", ".", "getOption", "(", "'ignore_dirs'", ")", ";", "// TODO: Allow an array and move to config.", "var", "ignoreFiles", "=", "/", "~$", "/", ";", "var", "files", "=", "glob", ".", "sync", "(", "dir", "?", "dir", "+", "'/*'", ":", "'*'", ")", ";", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "if", "(", "fs", ".", "lstatSync", "(", "files", "[", "i", "]", ")", ".", "isDirectory", "(", ")", ")", "{", "// Ignore standard directories of uninterest.", "if", "(", "!", "dir", "&&", "ignoreDirs", ".", "indexOf", "(", "files", "[", "i", "]", ")", ">=", "0", ")", "{", "continue", ";", "}", "ret", "=", "filesInRepository", "(", "files", "[", "i", "]", ")", ".", "concat", "(", "ret", ")", ";", "}", "else", "{", "if", "(", "!", "ignoreFiles", ".", "test", "(", "files", "[", "i", "]", ")", ")", "{", "ret", ".", "push", "(", "files", "[", "i", "]", ")", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Perform recursive lookup for files in the repository. @return {Array} A list of files in the repository ignoring files of not interest.
[ "Perform", "recursive", "lookup", "for", "files", "in", "the", "repository", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L210-L230
55,071
wigy/chronicles_of_grunt
lib/file-filter.js
excludeFiles
function excludeFiles(list, regex) { var ret = []; for (var i=0; i < list.length; i++) { if (!regex.test(list[i].dst)) { ret.push(list[i]); } } return ret; }
javascript
function excludeFiles(list, regex) { var ret = []; for (var i=0; i < list.length; i++) { if (!regex.test(list[i].dst)) { ret.push(list[i]); } } return ret; }
[ "function", "excludeFiles", "(", "list", ",", "regex", ")", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "regex", ".", "test", "(", "list", "[", "i", "]", ".", "dst", ")", ")", "{", "ret", ".", "push", "(", "list", "[", "i", "]", ")", ";", "}", "}", "return", "ret", ";", "}" ]
Remove specs whose destination matches to the given regex pattern.
[ "Remove", "specs", "whose", "destination", "matches", "to", "the", "given", "regex", "pattern", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L235-L243
55,072
wigy/chronicles_of_grunt
lib/file-filter.js
srcFiles
function srcFiles() { return removeDuplicates(configFiles().concat(libFiles()).concat(modelFiles()).concat(srcDataFiles()).concat(codeFiles())); }
javascript
function srcFiles() { return removeDuplicates(configFiles().concat(libFiles()).concat(modelFiles()).concat(srcDataFiles()).concat(codeFiles())); }
[ "function", "srcFiles", "(", ")", "{", "return", "removeDuplicates", "(", "configFiles", "(", ")", ".", "concat", "(", "libFiles", "(", ")", ")", ".", "concat", "(", "modelFiles", "(", ")", ")", ".", "concat", "(", "srcDataFiles", "(", ")", ")", ".", "concat", "(", "codeFiles", "(", ")", ")", ")", ";", "}" ]
Find all source code files for the actual application.
[ "Find", "all", "source", "code", "files", "for", "the", "actual", "application", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L359-L361
55,073
wigy/chronicles_of_grunt
lib/file-filter.js
otherNonJsFiles
function otherNonJsFiles() { return removeDuplicates(files(cog.getConfig('src.other'), 'other'), srcFiles().concat(otherJsFiles().concat(appIndexFiles()))); }
javascript
function otherNonJsFiles() { return removeDuplicates(files(cog.getConfig('src.other'), 'other'), srcFiles().concat(otherJsFiles().concat(appIndexFiles()))); }
[ "function", "otherNonJsFiles", "(", ")", "{", "return", "removeDuplicates", "(", "files", "(", "cog", ".", "getConfig", "(", "'src.other'", ")", ",", "'other'", ")", ",", "srcFiles", "(", ")", ".", "concat", "(", "otherJsFiles", "(", ")", ".", "concat", "(", "appIndexFiles", "(", ")", ")", ")", ")", ";", "}" ]
Find other files that are not Javascript.
[ "Find", "other", "files", "that", "are", "not", "Javascript", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L387-L389
55,074
wigy/chronicles_of_grunt
lib/file-filter.js
includeJsFiles
function includeJsFiles() { if (cog.getOption('include_only_external')) { return extLibFiles().concat(generatedJsFiles()); } if (cog.getOption('compile_typescript')) { return extLibFiles().concat(generatedJsFiles()); } return extLibFiles().concat(srcFiles()).concat(generatedJsFiles()); }
javascript
function includeJsFiles() { if (cog.getOption('include_only_external')) { return extLibFiles().concat(generatedJsFiles()); } if (cog.getOption('compile_typescript')) { return extLibFiles().concat(generatedJsFiles()); } return extLibFiles().concat(srcFiles()).concat(generatedJsFiles()); }
[ "function", "includeJsFiles", "(", ")", "{", "if", "(", "cog", ".", "getOption", "(", "'include_only_external'", ")", ")", "{", "return", "extLibFiles", "(", ")", ".", "concat", "(", "generatedJsFiles", "(", ")", ")", ";", "}", "if", "(", "cog", ".", "getOption", "(", "'compile_typescript'", ")", ")", "{", "return", "extLibFiles", "(", ")", ".", "concat", "(", "generatedJsFiles", "(", ")", ")", ";", "}", "return", "extLibFiles", "(", ")", ".", "concat", "(", "srcFiles", "(", ")", ")", ".", "concat", "(", "generatedJsFiles", "(", ")", ")", ";", "}" ]
Find all code files needed to include in HTML index.
[ "Find", "all", "code", "files", "needed", "to", "include", "in", "HTML", "index", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L450-L458
55,075
wigy/chronicles_of_grunt
lib/file-filter.js
allJavascriptFiles
function allJavascriptFiles() { return srcFiles().concat(otherJsFiles()).concat(unitTestFiles()).concat(unitTestHelperFiles()).concat(taskFiles()).concat(commonJsFiles()); }
javascript
function allJavascriptFiles() { return srcFiles().concat(otherJsFiles()).concat(unitTestFiles()).concat(unitTestHelperFiles()).concat(taskFiles()).concat(commonJsFiles()); }
[ "function", "allJavascriptFiles", "(", ")", "{", "return", "srcFiles", "(", ")", ".", "concat", "(", "otherJsFiles", "(", ")", ")", ".", "concat", "(", "unitTestFiles", "(", ")", ")", ".", "concat", "(", "unitTestHelperFiles", "(", ")", ")", ".", "concat", "(", "taskFiles", "(", ")", ")", ".", "concat", "(", "commonJsFiles", "(", ")", ")", ";", "}" ]
Find all Javascript based work files.
[ "Find", "all", "Javascript", "based", "work", "files", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L572-L574
55,076
wigy/chronicles_of_grunt
lib/file-filter.js
workTextFiles
function workTextFiles() { return indexFiles().concat(srcFiles()).concat(allTestFiles()).concat(otherJsFiles()).concat(otherNonJsFiles()).concat(taskFiles()).concat(cssFiles()) .concat(toolsShellFiles()).concat(commonJsFiles()).concat(htmlTemplateFiles()).concat(pythonFiles()).concat(textDataFiles()); }
javascript
function workTextFiles() { return indexFiles().concat(srcFiles()).concat(allTestFiles()).concat(otherJsFiles()).concat(otherNonJsFiles()).concat(taskFiles()).concat(cssFiles()) .concat(toolsShellFiles()).concat(commonJsFiles()).concat(htmlTemplateFiles()).concat(pythonFiles()).concat(textDataFiles()); }
[ "function", "workTextFiles", "(", ")", "{", "return", "indexFiles", "(", ")", ".", "concat", "(", "srcFiles", "(", ")", ")", ".", "concat", "(", "allTestFiles", "(", ")", ")", ".", "concat", "(", "otherJsFiles", "(", ")", ")", ".", "concat", "(", "otherNonJsFiles", "(", ")", ")", ".", "concat", "(", "taskFiles", "(", ")", ")", ".", "concat", "(", "cssFiles", "(", ")", ")", ".", "concat", "(", "toolsShellFiles", "(", ")", ")", ".", "concat", "(", "commonJsFiles", "(", ")", ")", ".", "concat", "(", "htmlTemplateFiles", "(", ")", ")", ".", "concat", "(", "pythonFiles", "(", ")", ")", ".", "concat", "(", "textDataFiles", "(", ")", ")", ";", "}" ]
Find all text based work files.
[ "Find", "all", "text", "based", "work", "files", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L628-L631
55,077
wigy/chronicles_of_grunt
lib/file-filter.js
generatedJsFiles
function generatedJsFiles(what) { var ret = []; if ((!what || what === 'templates') && cog.getOption('template')) { ret.push({src: null, dst: cog.getOption('template')}); } if (cog.getOption('compile_typescript')) { var src = srcTypescriptFiles(); for (var i = 0; i < src.length; i++) { if (src[i].src.substr(-3) === '.ts') { src[i].dst = src[i].src.substr(0, src[i].src.length - 3) + '.js'; ret.push(src[i]); } } } return ret; }
javascript
function generatedJsFiles(what) { var ret = []; if ((!what || what === 'templates') && cog.getOption('template')) { ret.push({src: null, dst: cog.getOption('template')}); } if (cog.getOption('compile_typescript')) { var src = srcTypescriptFiles(); for (var i = 0; i < src.length; i++) { if (src[i].src.substr(-3) === '.ts') { src[i].dst = src[i].src.substr(0, src[i].src.length - 3) + '.js'; ret.push(src[i]); } } } return ret; }
[ "function", "generatedJsFiles", "(", "what", ")", "{", "var", "ret", "=", "[", "]", ";", "if", "(", "(", "!", "what", "||", "what", "===", "'templates'", ")", "&&", "cog", ".", "getOption", "(", "'template'", ")", ")", "{", "ret", ".", "push", "(", "{", "src", ":", "null", ",", "dst", ":", "cog", ".", "getOption", "(", "'template'", ")", "}", ")", ";", "}", "if", "(", "cog", ".", "getOption", "(", "'compile_typescript'", ")", ")", "{", "var", "src", "=", "srcTypescriptFiles", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "src", ".", "length", ";", "i", "++", ")", "{", "if", "(", "src", "[", "i", "]", ".", "src", ".", "substr", "(", "-", "3", ")", "===", "'.ts'", ")", "{", "src", "[", "i", "]", ".", "dst", "=", "src", "[", "i", "]", ".", "src", ".", "substr", "(", "0", ",", "src", "[", "i", "]", ".", "src", ".", "length", "-", "3", ")", "+", "'.js'", ";", "ret", ".", "push", "(", "src", "[", "i", "]", ")", ";", "}", "}", "}", "return", "ret", ";", "}" ]
List of files that are generated Javascript files.
[ "List", "of", "files", "that", "are", "generated", "Javascript", "files", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L650-L665
55,078
wigy/chronicles_of_grunt
lib/file-filter.js
fileCategoryMap
function fileCategoryMap() { // Go over every file lookup function we export. var exports = module.exports(grunt); // This list of categories must contain all non-overlapping file categories. var categories = ['extLibFiles', 'extLibMapFiles', 'extCssFiles', 'extFontFiles', 'fontFiles', 'appIndexFiles', 'testIndexFiles', 'configFiles', 'libFiles', 'modelFiles', 'srcDataFiles', 'codeFiles', 'otherJsFiles', 'otherNonJsFiles', 'taskFiles', 'cssFiles', 'picFiles', 'soundFiles', 'unitTestFiles', 'commonJsFiles', 'commonOtherFiles', 'ignoredFiles', 'distUncompressedFiles', 'distLibFiles', 'distIndexFiles', 'distJsFiles', 'distCssFiles', 'toolsShellFiles', 'unitTestDataFiles', 'picSrcFiles', 'soundSrcFiles', 'htmlTemplateFiles', 'generatedJsFiles', 'otherMediaFiles', 'unitTestHelperFiles', 'pythonFiles', 'compiledPythonFiles', 'localizationDataFiles', 'developmentOtherDataFiles', 'developmentTextDataFiles']; // Construct the map by calling each function defined above. var map = {}; for (var i = 0; i < categories.length; i++) { var files = flatten(exports[categories[i]]()); for (var j = 0; j < files.length; j++) { if (map[files[j]]) { grunt.fail.warn("A file '" + files[j] + "' maps to category '" + categories[i] + "' in addition to '" + map[files[j]] + "' category."); } else { map[files[j]] = categories[i]; } } } return map; }
javascript
function fileCategoryMap() { // Go over every file lookup function we export. var exports = module.exports(grunt); // This list of categories must contain all non-overlapping file categories. var categories = ['extLibFiles', 'extLibMapFiles', 'extCssFiles', 'extFontFiles', 'fontFiles', 'appIndexFiles', 'testIndexFiles', 'configFiles', 'libFiles', 'modelFiles', 'srcDataFiles', 'codeFiles', 'otherJsFiles', 'otherNonJsFiles', 'taskFiles', 'cssFiles', 'picFiles', 'soundFiles', 'unitTestFiles', 'commonJsFiles', 'commonOtherFiles', 'ignoredFiles', 'distUncompressedFiles', 'distLibFiles', 'distIndexFiles', 'distJsFiles', 'distCssFiles', 'toolsShellFiles', 'unitTestDataFiles', 'picSrcFiles', 'soundSrcFiles', 'htmlTemplateFiles', 'generatedJsFiles', 'otherMediaFiles', 'unitTestHelperFiles', 'pythonFiles', 'compiledPythonFiles', 'localizationDataFiles', 'developmentOtherDataFiles', 'developmentTextDataFiles']; // Construct the map by calling each function defined above. var map = {}; for (var i = 0; i < categories.length; i++) { var files = flatten(exports[categories[i]]()); for (var j = 0; j < files.length; j++) { if (map[files[j]]) { grunt.fail.warn("A file '" + files[j] + "' maps to category '" + categories[i] + "' in addition to '" + map[files[j]] + "' category."); } else { map[files[j]] = categories[i]; } } } return map; }
[ "function", "fileCategoryMap", "(", ")", "{", "// Go over every file lookup function we export.", "var", "exports", "=", "module", ".", "exports", "(", "grunt", ")", ";", "// This list of categories must contain all non-overlapping file categories.", "var", "categories", "=", "[", "'extLibFiles'", ",", "'extLibMapFiles'", ",", "'extCssFiles'", ",", "'extFontFiles'", ",", "'fontFiles'", ",", "'appIndexFiles'", ",", "'testIndexFiles'", ",", "'configFiles'", ",", "'libFiles'", ",", "'modelFiles'", ",", "'srcDataFiles'", ",", "'codeFiles'", ",", "'otherJsFiles'", ",", "'otherNonJsFiles'", ",", "'taskFiles'", ",", "'cssFiles'", ",", "'picFiles'", ",", "'soundFiles'", ",", "'unitTestFiles'", ",", "'commonJsFiles'", ",", "'commonOtherFiles'", ",", "'ignoredFiles'", ",", "'distUncompressedFiles'", ",", "'distLibFiles'", ",", "'distIndexFiles'", ",", "'distJsFiles'", ",", "'distCssFiles'", ",", "'toolsShellFiles'", ",", "'unitTestDataFiles'", ",", "'picSrcFiles'", ",", "'soundSrcFiles'", ",", "'htmlTemplateFiles'", ",", "'generatedJsFiles'", ",", "'otherMediaFiles'", ",", "'unitTestHelperFiles'", ",", "'pythonFiles'", ",", "'compiledPythonFiles'", ",", "'localizationDataFiles'", ",", "'developmentOtherDataFiles'", ",", "'developmentTextDataFiles'", "]", ";", "// Construct the map by calling each function defined above.", "var", "map", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "categories", ".", "length", ";", "i", "++", ")", "{", "var", "files", "=", "flatten", "(", "exports", "[", "categories", "[", "i", "]", "]", "(", ")", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "files", ".", "length", ";", "j", "++", ")", "{", "if", "(", "map", "[", "files", "[", "j", "]", "]", ")", "{", "grunt", ".", "fail", ".", "warn", "(", "\"A file '\"", "+", "files", "[", "j", "]", "+", "\"' maps to category '\"", "+", "categories", "[", "i", "]", "+", "\"' in addition to '\"", "+", "map", "[", "files", "[", "j", "]", "]", "+", "\"' category.\"", ")", ";", "}", "else", "{", "map", "[", "files", "[", "j", "]", "]", "=", "categories", "[", "i", "]", ";", "}", "}", "}", "return", "map", ";", "}" ]
Build complete map of known files. Note that when adding new file categories, this function must be updated and all new non-overlapping (i.e. atomic) categories needs to be added here.
[ "Build", "complete", "map", "of", "known", "files", "." ]
c5f089a6f391a0ca625fcb81ef51907713471bb3
https://github.com/wigy/chronicles_of_grunt/blob/c5f089a6f391a0ca625fcb81ef51907713471bb3/lib/file-filter.js#L708-L735
55,079
intervolga/bemjson-loader
lib/validate-bemjson.js
validateBemJson
function validateBemJson(bemJson, fileName) { let errors = []; if (Array.isArray(bemJson)) { bemJson.forEach((childBemJson) => { errors = errors.concat(validateBemJson(childBemJson, fileName)); }); } else if (bemJson instanceof Object) { Object.keys(bemJson).forEach((key) => { const childBemJson = bemJson[key]; errors = errors.concat(validateBemJson(childBemJson, fileName)); }); errors = errors.concat(validateBemJsonNode(bemJson, fileName)); // TODO } // TODO return errors; }
javascript
function validateBemJson(bemJson, fileName) { let errors = []; if (Array.isArray(bemJson)) { bemJson.forEach((childBemJson) => { errors = errors.concat(validateBemJson(childBemJson, fileName)); }); } else if (bemJson instanceof Object) { Object.keys(bemJson).forEach((key) => { const childBemJson = bemJson[key]; errors = errors.concat(validateBemJson(childBemJson, fileName)); }); errors = errors.concat(validateBemJsonNode(bemJson, fileName)); // TODO } // TODO return errors; }
[ "function", "validateBemJson", "(", "bemJson", ",", "fileName", ")", "{", "let", "errors", "=", "[", "]", ";", "if", "(", "Array", ".", "isArray", "(", "bemJson", ")", ")", "{", "bemJson", ".", "forEach", "(", "(", "childBemJson", ")", "=>", "{", "errors", "=", "errors", ".", "concat", "(", "validateBemJson", "(", "childBemJson", ",", "fileName", ")", ")", ";", "}", ")", ";", "}", "else", "if", "(", "bemJson", "instanceof", "Object", ")", "{", "Object", ".", "keys", "(", "bemJson", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "const", "childBemJson", "=", "bemJson", "[", "key", "]", ";", "errors", "=", "errors", ".", "concat", "(", "validateBemJson", "(", "childBemJson", ",", "fileName", ")", ")", ";", "}", ")", ";", "errors", "=", "errors", ".", "concat", "(", "validateBemJsonNode", "(", "bemJson", ",", "fileName", ")", ")", ";", "// TODO", "}", "// TODO", "return", "errors", ";", "}" ]
Validate BEM JSON @param {Object} bemJson @param {String} fileName @return {Array} of validation errors
[ "Validate", "BEM", "JSON" ]
c4ff680ee07ab939d400f241859fe608411fd8de
https://github.com/intervolga/bemjson-loader/blob/c4ff680ee07ab939d400f241859fe608411fd8de/lib/validate-bemjson.js#L8-L25
55,080
intervolga/bemjson-loader
lib/validate-bemjson.js
extractBemJsonNode
function extractBemJsonNode(bemJson) { let result = JSON.parse(JSON.stringify(bemJson)); Object.keys(result).forEach((key) => { result[key] = result[key].toString(); }); return JSON.stringify(result, null, 2); }
javascript
function extractBemJsonNode(bemJson) { let result = JSON.parse(JSON.stringify(bemJson)); Object.keys(result).forEach((key) => { result[key] = result[key].toString(); }); return JSON.stringify(result, null, 2); }
[ "function", "extractBemJsonNode", "(", "bemJson", ")", "{", "let", "result", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "bemJson", ")", ")", ";", "Object", ".", "keys", "(", "result", ")", ".", "forEach", "(", "(", "key", ")", "=>", "{", "result", "[", "key", "]", "=", "result", "[", "key", "]", ".", "toString", "(", ")", ";", "}", ")", ";", "return", "JSON", ".", "stringify", "(", "result", ",", "null", ",", "2", ")", ";", "}" ]
Strips all child nodes from BemJson node for print puproses @param {Object} bemJson @return {Object}
[ "Strips", "all", "child", "nodes", "from", "BemJson", "node", "for", "print", "puproses" ]
c4ff680ee07ab939d400f241859fe608411fd8de
https://github.com/intervolga/bemjson-loader/blob/c4ff680ee07ab939d400f241859fe608411fd8de/lib/validate-bemjson.js#L98-L106
55,081
codenothing/munit
lib/queue.js
function(){ var copy = []; // Handle recursive loops if ( queue.running ) { queue.waiting = true; return; } // Mark queue as running, then search for queue.running = true; munit.each( queue.modules, function( assert, index ) { if ( ! queue.objects.length ) { return false; } else if ( ! munit.render.checkDepency( assert ) ) { return; } // Looking for specific key in queue object if ( munit.isString( assert.options.queue ) ) { munit.each( queue.objects, function( object, i ) { if ( object[ assert.options.queue ] ) { queue.modules[ index ] = null; queue.objects.splice( i, 1 ); assert.queue = object; assert.trigger(); return false; } }); } // Any queue will do else { queue.modules[ index ] = null; assert.queue = queue.objects.shift(); assert.trigger(); } }); // Clean out modules that completed (splicing causes iteration fails) queue.modules.forEach(function( assert ) { if ( assert !== null ) { copy.push( assert ); } }); queue.modules = copy; // Run again if check method was called during loop queue.running = false; if ( queue.waiting ) { queue.waiting = false; queue.check(); } }
javascript
function(){ var copy = []; // Handle recursive loops if ( queue.running ) { queue.waiting = true; return; } // Mark queue as running, then search for queue.running = true; munit.each( queue.modules, function( assert, index ) { if ( ! queue.objects.length ) { return false; } else if ( ! munit.render.checkDepency( assert ) ) { return; } // Looking for specific key in queue object if ( munit.isString( assert.options.queue ) ) { munit.each( queue.objects, function( object, i ) { if ( object[ assert.options.queue ] ) { queue.modules[ index ] = null; queue.objects.splice( i, 1 ); assert.queue = object; assert.trigger(); return false; } }); } // Any queue will do else { queue.modules[ index ] = null; assert.queue = queue.objects.shift(); assert.trigger(); } }); // Clean out modules that completed (splicing causes iteration fails) queue.modules.forEach(function( assert ) { if ( assert !== null ) { copy.push( assert ); } }); queue.modules = copy; // Run again if check method was called during loop queue.running = false; if ( queue.waiting ) { queue.waiting = false; queue.check(); } }
[ "function", "(", ")", "{", "var", "copy", "=", "[", "]", ";", "// Handle recursive loops", "if", "(", "queue", ".", "running", ")", "{", "queue", ".", "waiting", "=", "true", ";", "return", ";", "}", "// Mark queue as running, then search for ", "queue", ".", "running", "=", "true", ";", "munit", ".", "each", "(", "queue", ".", "modules", ",", "function", "(", "assert", ",", "index", ")", "{", "if", "(", "!", "queue", ".", "objects", ".", "length", ")", "{", "return", "false", ";", "}", "else", "if", "(", "!", "munit", ".", "render", ".", "checkDepency", "(", "assert", ")", ")", "{", "return", ";", "}", "// Looking for specific key in queue object", "if", "(", "munit", ".", "isString", "(", "assert", ".", "options", ".", "queue", ")", ")", "{", "munit", ".", "each", "(", "queue", ".", "objects", ",", "function", "(", "object", ",", "i", ")", "{", "if", "(", "object", "[", "assert", ".", "options", ".", "queue", "]", ")", "{", "queue", ".", "modules", "[", "index", "]", "=", "null", ";", "queue", ".", "objects", ".", "splice", "(", "i", ",", "1", ")", ";", "assert", ".", "queue", "=", "object", ";", "assert", ".", "trigger", "(", ")", ";", "return", "false", ";", "}", "}", ")", ";", "}", "// Any queue will do", "else", "{", "queue", ".", "modules", "[", "index", "]", "=", "null", ";", "assert", ".", "queue", "=", "queue", ".", "objects", ".", "shift", "(", ")", ";", "assert", ".", "trigger", "(", ")", ";", "}", "}", ")", ";", "// Clean out modules that completed (splicing causes iteration fails)", "queue", ".", "modules", ".", "forEach", "(", "function", "(", "assert", ")", "{", "if", "(", "assert", "!==", "null", ")", "{", "copy", ".", "push", "(", "assert", ")", ";", "}", "}", ")", ";", "queue", ".", "modules", "=", "copy", ";", "// Run again if check method was called during loop", "queue", ".", "running", "=", "false", ";", "if", "(", "queue", ".", "waiting", ")", "{", "queue", ".", "waiting", "=", "false", ";", "queue", ".", "check", "(", ")", ";", "}", "}" ]
Runs through queued modules and finds objects to run them with
[ "Runs", "through", "queued", "modules", "and", "finds", "objects", "to", "run", "them", "with" ]
aedf3f31aafc05441970eec49eeeb81174c14033
https://github.com/codenothing/munit/blob/aedf3f31aafc05441970eec49eeeb81174c14033/lib/queue.js#L58-L111
55,082
andreypopp/stream-recreate
index.js
recreate
function recreate(makeStream, options) { if (options === undefined && isObject(makeStream)) { options = makeStream; makeStream = options.makeStream; } options = options || {}; if (options.connect === undefined) { options.connect = true; } var connectedEvent = options.connectedEvent || 'open'; var stream = through(); stream.inverse = through(); stream.inverse.pause(); stream.write = function(chunk) { return stream.inverse.write(chunk); }; stream.connect = function() { stream.underlying = makeStream(); stream.inverse.pipe(stream.underlying, {end: false}); stream.underlying.on('data', function(chunk) { return stream.emit('data', chunk); }); stream.underlying.on(connectedEvent, function() { stream.backoff.reset(); stream.inverse.resume(); stream.emit('open'); stream.emit('underlying-open'); }); stream.underlying.on('end', function() { stream.inverse.pause(); if (!stream.preventBackoff) { stream.backoff.backoff(); } stream.emit('underlying-end'); }); stream.underlying.on('error', function(e) { stream.inverse.pause(); if (!stream.preventBackoff) { stream.backoff.backoff(); } stream.emit('underlying-error'); }); }; var origEnd = stream.end.bind(stream); stream.end = function() { stream.preventBackoff = true; stream.underlying.end(); return origEnd(); }; stream.backoff = options.backoff || backoff.exponential(options); stream.backoff.on('backoff', function(num, delay) { stream.emit('backoff-schedule', num, delay); }); stream.backoff.on('ready', function() { stream.connect(); stream.emit('backoff-ready'); }); stream.backoff.on('fail', function() { stream.emit('backoff-fail'); }); if (options.connect) { stream.connect(); } return stream; }
javascript
function recreate(makeStream, options) { if (options === undefined && isObject(makeStream)) { options = makeStream; makeStream = options.makeStream; } options = options || {}; if (options.connect === undefined) { options.connect = true; } var connectedEvent = options.connectedEvent || 'open'; var stream = through(); stream.inverse = through(); stream.inverse.pause(); stream.write = function(chunk) { return stream.inverse.write(chunk); }; stream.connect = function() { stream.underlying = makeStream(); stream.inverse.pipe(stream.underlying, {end: false}); stream.underlying.on('data', function(chunk) { return stream.emit('data', chunk); }); stream.underlying.on(connectedEvent, function() { stream.backoff.reset(); stream.inverse.resume(); stream.emit('open'); stream.emit('underlying-open'); }); stream.underlying.on('end', function() { stream.inverse.pause(); if (!stream.preventBackoff) { stream.backoff.backoff(); } stream.emit('underlying-end'); }); stream.underlying.on('error', function(e) { stream.inverse.pause(); if (!stream.preventBackoff) { stream.backoff.backoff(); } stream.emit('underlying-error'); }); }; var origEnd = stream.end.bind(stream); stream.end = function() { stream.preventBackoff = true; stream.underlying.end(); return origEnd(); }; stream.backoff = options.backoff || backoff.exponential(options); stream.backoff.on('backoff', function(num, delay) { stream.emit('backoff-schedule', num, delay); }); stream.backoff.on('ready', function() { stream.connect(); stream.emit('backoff-ready'); }); stream.backoff.on('fail', function() { stream.emit('backoff-fail'); }); if (options.connect) { stream.connect(); } return stream; }
[ "function", "recreate", "(", "makeStream", ",", "options", ")", "{", "if", "(", "options", "===", "undefined", "&&", "isObject", "(", "makeStream", ")", ")", "{", "options", "=", "makeStream", ";", "makeStream", "=", "options", ".", "makeStream", ";", "}", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "connect", "===", "undefined", ")", "{", "options", ".", "connect", "=", "true", ";", "}", "var", "connectedEvent", "=", "options", ".", "connectedEvent", "||", "'open'", ";", "var", "stream", "=", "through", "(", ")", ";", "stream", ".", "inverse", "=", "through", "(", ")", ";", "stream", ".", "inverse", ".", "pause", "(", ")", ";", "stream", ".", "write", "=", "function", "(", "chunk", ")", "{", "return", "stream", ".", "inverse", ".", "write", "(", "chunk", ")", ";", "}", ";", "stream", ".", "connect", "=", "function", "(", ")", "{", "stream", ".", "underlying", "=", "makeStream", "(", ")", ";", "stream", ".", "inverse", ".", "pipe", "(", "stream", ".", "underlying", ",", "{", "end", ":", "false", "}", ")", ";", "stream", ".", "underlying", ".", "on", "(", "'data'", ",", "function", "(", "chunk", ")", "{", "return", "stream", ".", "emit", "(", "'data'", ",", "chunk", ")", ";", "}", ")", ";", "stream", ".", "underlying", ".", "on", "(", "connectedEvent", ",", "function", "(", ")", "{", "stream", ".", "backoff", ".", "reset", "(", ")", ";", "stream", ".", "inverse", ".", "resume", "(", ")", ";", "stream", ".", "emit", "(", "'open'", ")", ";", "stream", ".", "emit", "(", "'underlying-open'", ")", ";", "}", ")", ";", "stream", ".", "underlying", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "stream", ".", "inverse", ".", "pause", "(", ")", ";", "if", "(", "!", "stream", ".", "preventBackoff", ")", "{", "stream", ".", "backoff", ".", "backoff", "(", ")", ";", "}", "stream", ".", "emit", "(", "'underlying-end'", ")", ";", "}", ")", ";", "stream", ".", "underlying", ".", "on", "(", "'error'", ",", "function", "(", "e", ")", "{", "stream", ".", "inverse", ".", "pause", "(", ")", ";", "if", "(", "!", "stream", ".", "preventBackoff", ")", "{", "stream", ".", "backoff", ".", "backoff", "(", ")", ";", "}", "stream", ".", "emit", "(", "'underlying-error'", ")", ";", "}", ")", ";", "}", ";", "var", "origEnd", "=", "stream", ".", "end", ".", "bind", "(", "stream", ")", ";", "stream", ".", "end", "=", "function", "(", ")", "{", "stream", ".", "preventBackoff", "=", "true", ";", "stream", ".", "underlying", ".", "end", "(", ")", ";", "return", "origEnd", "(", ")", ";", "}", ";", "stream", ".", "backoff", "=", "options", ".", "backoff", "||", "backoff", ".", "exponential", "(", "options", ")", ";", "stream", ".", "backoff", ".", "on", "(", "'backoff'", ",", "function", "(", "num", ",", "delay", ")", "{", "stream", ".", "emit", "(", "'backoff-schedule'", ",", "num", ",", "delay", ")", ";", "}", ")", ";", "stream", ".", "backoff", ".", "on", "(", "'ready'", ",", "function", "(", ")", "{", "stream", ".", "connect", "(", ")", ";", "stream", ".", "emit", "(", "'backoff-ready'", ")", ";", "}", ")", ";", "stream", ".", "backoff", ".", "on", "(", "'fail'", ",", "function", "(", ")", "{", "stream", ".", "emit", "(", "'backoff-fail'", ")", ";", "}", ")", ";", "if", "(", "options", ".", "connect", ")", "{", "stream", ".", "connect", "(", ")", ";", "}", "return", "stream", ";", "}" ]
Create wrapper stream which takes care of recreating logic. @param {Function} makeStream a function which returns a stream @param {Object}
[ "Create", "wrapper", "stream", "which", "takes", "care", "of", "recreating", "logic", "." ]
ed814ceb3e6d8c943f9cff919f64a426a196399a
https://github.com/andreypopp/stream-recreate/blob/ed814ceb3e6d8c943f9cff919f64a426a196399a/index.js#L19-L104
55,083
shama/grunt-net
tasks/net.js
createServer
function createServer() { grunt.log.ok('Registered as a grunt-net server [' + host + ':' + port + '].'); dnode({ spawn: spawn }).listen(host, port); }
javascript
function createServer() { grunt.log.ok('Registered as a grunt-net server [' + host + ':' + port + '].'); dnode({ spawn: spawn }).listen(host, port); }
[ "function", "createServer", "(", ")", "{", "grunt", ".", "log", ".", "ok", "(", "'Registered as a grunt-net server ['", "+", "host", "+", "':'", "+", "port", "+", "'].'", ")", ";", "dnode", "(", "{", "spawn", ":", "spawn", "}", ")", ".", "listen", "(", "host", ",", "port", ")", ";", "}" ]
create a server
[ "create", "a", "server" ]
19fc0969e14e5db3207dd42b2ac1d76464e7da86
https://github.com/shama/grunt-net/blob/19fc0969e14e5db3207dd42b2ac1d76464e7da86/tasks/net.js#L39-L42
55,084
je3f0o/jeefo_preprocessor
src/preprocessor.js
function (token) { var pp = new JavascriptPreprocessor(this.parser, this.compiler, this.actions, this.scope, this.state); if (token) { pp.code = this.get_code(this.code, token); } return pp; }
javascript
function (token) { var pp = new JavascriptPreprocessor(this.parser, this.compiler, this.actions, this.scope, this.state); if (token) { pp.code = this.get_code(this.code, token); } return pp; }
[ "function", "(", "token", ")", "{", "var", "pp", "=", "new", "JavascriptPreprocessor", "(", "this", ".", "parser", ",", "this", ".", "compiler", ",", "this", ".", "actions", ",", "this", ".", "scope", ",", "this", ".", "state", ")", ";", "if", "(", "token", ")", "{", "pp", ".", "code", "=", "this", ".", "get_code", "(", "this", ".", "code", ",", "token", ")", ";", "}", "return", "pp", ";", "}" ]
Utils {{{1
[ "Utils", "{{{", "1" ]
77050d8b2c1856a29a04d6de4fa602d05357175b
https://github.com/je3f0o/jeefo_preprocessor/blob/77050d8b2c1856a29a04d6de4fa602d05357175b/src/preprocessor.js#L26-L32
55,085
je3f0o/jeefo_preprocessor
src/preprocessor.js
function (action) { if (action) { switch (action.type) { case "replace" : this.code = `${ this.code.substr(0, action.start) }${ action.value }${ this.code.substr(action.end) }`; return true; case "remove" : this.code = `${ this.code.substr(0, action.start) }${ this.code.substr(action.end) }`; return true; } } }
javascript
function (action) { if (action) { switch (action.type) { case "replace" : this.code = `${ this.code.substr(0, action.start) }${ action.value }${ this.code.substr(action.end) }`; return true; case "remove" : this.code = `${ this.code.substr(0, action.start) }${ this.code.substr(action.end) }`; return true; } } }
[ "function", "(", "action", ")", "{", "if", "(", "action", ")", "{", "switch", "(", "action", ".", "type", ")", "{", "case", "\"replace\"", ":", "this", ".", "code", "=", "`", "${", "this", ".", "code", ".", "substr", "(", "0", ",", "action", ".", "start", ")", "}", "${", "action", ".", "value", "}", "${", "this", ".", "code", ".", "substr", "(", "action", ".", "end", ")", "}", "`", ";", "return", "true", ";", "case", "\"remove\"", ":", "this", ".", "code", "=", "`", "${", "this", ".", "code", ".", "substr", "(", "0", ",", "action", ".", "start", ")", "}", "${", "this", ".", "code", ".", "substr", "(", "action", ".", "end", ")", "}", "`", ";", "return", "true", ";", "}", "}", "}" ]
Actions {{{1
[ "Actions", "{{{", "1" ]
77050d8b2c1856a29a04d6de4fa602d05357175b
https://github.com/je3f0o/jeefo_preprocessor/blob/77050d8b2c1856a29a04d6de4fa602d05357175b/src/preprocessor.js#L39-L50
55,086
je3f0o/jeefo_preprocessor
src/preprocessor.js
function (name, definition, is_return) { var pp = this.$new(), code = `PP.define("${ name }", ${ definition.toString() }, ${ is_return });`; pp.scope = this.scope; pp.process("[IN MEMORY]", code); }
javascript
function (name, definition, is_return) { var pp = this.$new(), code = `PP.define("${ name }", ${ definition.toString() }, ${ is_return });`; pp.scope = this.scope; pp.process("[IN MEMORY]", code); }
[ "function", "(", "name", ",", "definition", ",", "is_return", ")", "{", "var", "pp", "=", "this", ".", "$new", "(", ")", ",", "code", "=", "`", "${", "name", "}", "${", "definition", ".", "toString", "(", ")", "}", "${", "is_return", "}", "`", ";", "pp", ".", "scope", "=", "this", ".", "scope", ";", "pp", ".", "process", "(", "\"[IN MEMORY]\"", ",", "code", ")", ";", "}" ]
Define {{{1
[ "Define", "{{{", "1" ]
77050d8b2c1856a29a04d6de4fa602d05357175b
https://github.com/je3f0o/jeefo_preprocessor/blob/77050d8b2c1856a29a04d6de4fa602d05357175b/src/preprocessor.js#L70-L76
55,087
je3f0o/jeefo_preprocessor
src/preprocessor.js
function (code, tokens) { var actions = [], i = 0; this.code = code; for (; i < tokens.length; ++i) { actions[i] = this.actions.invoke(this, tokens[i]); } i = actions.length; while (i--) { this.action(actions[i]); } return this.code; }
javascript
function (code, tokens) { var actions = [], i = 0; this.code = code; for (; i < tokens.length; ++i) { actions[i] = this.actions.invoke(this, tokens[i]); } i = actions.length; while (i--) { this.action(actions[i]); } return this.code; }
[ "function", "(", "code", ",", "tokens", ")", "{", "var", "actions", "=", "[", "]", ",", "i", "=", "0", ";", "this", ".", "code", "=", "code", ";", "for", "(", ";", "i", "<", "tokens", ".", "length", ";", "++", "i", ")", "{", "actions", "[", "i", "]", "=", "this", ".", "actions", ".", "invoke", "(", "this", ",", "tokens", "[", "i", "]", ")", ";", "}", "i", "=", "actions", ".", "length", ";", "while", "(", "i", "--", ")", "{", "this", ".", "action", "(", "actions", "[", "i", "]", ")", ";", "}", "return", "this", ".", "code", ";", "}" ]
Processor {{{1
[ "Processor", "{{{", "1" ]
77050d8b2c1856a29a04d6de4fa602d05357175b
https://github.com/je3f0o/jeefo_preprocessor/blob/77050d8b2c1856a29a04d6de4fa602d05357175b/src/preprocessor.js#L138-L153
55,088
je3f0o/jeefo_preprocessor
src/preprocessor.js
function (code) { try { return this.parser.parse(code); } catch(e) { console.log("E", e); console.log(code); process.exit(); } }
javascript
function (code) { try { return this.parser.parse(code); } catch(e) { console.log("E", e); console.log(code); process.exit(); } }
[ "function", "(", "code", ")", "{", "try", "{", "return", "this", ".", "parser", ".", "parse", "(", "code", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "\"E\"", ",", "e", ")", ";", "console", ".", "log", "(", "code", ")", ";", "process", ".", "exit", "(", ")", ";", "}", "}" ]
Parser {{{1
[ "Parser", "{{{", "1" ]
77050d8b2c1856a29a04d6de4fa602d05357175b
https://github.com/je3f0o/jeefo_preprocessor/blob/77050d8b2c1856a29a04d6de4fa602d05357175b/src/preprocessor.js#L160-L168
55,089
bvalosek/sack
lib/Container.js
callNew
function callNew(T, args) { return new (Function.prototype.bind.apply(T, [null].concat(args))); }
javascript
function callNew(T, args) { return new (Function.prototype.bind.apply(T, [null].concat(args))); }
[ "function", "callNew", "(", "T", ",", "args", ")", "{", "return", "new", "(", "Function", ".", "prototype", ".", "bind", ".", "apply", "(", "T", ",", "[", "null", "]", ".", "concat", "(", "args", ")", ")", ")", ";", "}" ]
Give us a way to instantiate a new class with an array of args @private
[ "Give", "us", "a", "way", "to", "instantiate", "a", "new", "class", "with", "an", "array", "of", "args" ]
65e2ab133b6c40400c200c2e071052dea6b23c24
https://github.com/bvalosek/sack/blob/65e2ab133b6c40400c200c2e071052dea6b23c24/lib/Container.js#L222-L225
55,090
patgrasso/parsey
lib/parser.js
earley
function earley(tokens, grammar) { let states = Array.apply(null, Array(tokens.length + 1)).map(() => []); var i, j; let rulePairs = grammar.map((rule) => ({ name : rule.lhs.name, rule : rule, position: 0, origin : 0 })); [].push.apply(states[0], rulePairs); for (i = 0; i <= tokens.length; i += 1) { for (j = 0; j < states[i].length; j += 1) { predict(tokens, states, i, j, grammar); scan(tokens, states, i, j); complete(tokens, states, i, j); } } return swap(removeUnfinishedItems(states)); }
javascript
function earley(tokens, grammar) { let states = Array.apply(null, Array(tokens.length + 1)).map(() => []); var i, j; let rulePairs = grammar.map((rule) => ({ name : rule.lhs.name, rule : rule, position: 0, origin : 0 })); [].push.apply(states[0], rulePairs); for (i = 0; i <= tokens.length; i += 1) { for (j = 0; j < states[i].length; j += 1) { predict(tokens, states, i, j, grammar); scan(tokens, states, i, j); complete(tokens, states, i, j); } } return swap(removeUnfinishedItems(states)); }
[ "function", "earley", "(", "tokens", ",", "grammar", ")", "{", "let", "states", "=", "Array", ".", "apply", "(", "null", ",", "Array", "(", "tokens", ".", "length", "+", "1", ")", ")", ".", "map", "(", "(", ")", "=>", "[", "]", ")", ";", "var", "i", ",", "j", ";", "let", "rulePairs", "=", "grammar", ".", "map", "(", "(", "rule", ")", "=>", "(", "{", "name", ":", "rule", ".", "lhs", ".", "name", ",", "rule", ":", "rule", ",", "position", ":", "0", ",", "origin", ":", "0", "}", ")", ")", ";", "[", "]", ".", "push", ".", "apply", "(", "states", "[", "0", "]", ",", "rulePairs", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<=", "tokens", ".", "length", ";", "i", "+=", "1", ")", "{", "for", "(", "j", "=", "0", ";", "j", "<", "states", "[", "i", "]", ".", "length", ";", "j", "+=", "1", ")", "{", "predict", "(", "tokens", ",", "states", ",", "i", ",", "j", ",", "grammar", ")", ";", "scan", "(", "tokens", ",", "states", ",", "i", ",", "j", ")", ";", "complete", "(", "tokens", ",", "states", ",", "i", ",", "j", ")", ";", "}", "}", "return", "swap", "(", "removeUnfinishedItems", "(", "states", ")", ")", ";", "}" ]
Parses the input tokens using the earley top-down chart parsing algorithm to product a set of states, each containing a list of earley items @function earley @memberof module:lib/parser @param {string[]} tokens - Sequence of symbols to be parsed @param {Rule[]|CFG} grammar - Set of rules that define a language @return {state[]} Set of 'states', each of which contains a list of earley items. Each earley item looks something like this: <pre><code> { name: [string], rule: [Rule], position: [number], origin: [number] } </code></pre> An earley item represents a completed parse of some individual rule. The position should be equivalent to rule.length, and the origin, despite its name, describes the state at which parse finished. This means that an earley item <i>should</i> exist in state 0 with an origin equivalent to the number of tokens passed in to indicate that the entire input was parsed successfully for some rule
[ "Parses", "the", "input", "tokens", "using", "the", "earley", "top", "-", "down", "chart", "parsing", "algorithm", "to", "product", "a", "set", "of", "states", "each", "containing", "a", "list", "of", "earley", "items" ]
d28b3f330ee03b5c273f1ce5871a5b86dac79fb0
https://github.com/patgrasso/parsey/blob/d28b3f330ee03b5c273f1ce5871a5b86dac79fb0/lib/parser.js#L64-L86
55,091
patgrasso/parsey
lib/parser.js
removeUnfinishedItems
function removeUnfinishedItems(states) { return states.map((state) => state.filter((earleyItem) => { return earleyItem.position >= earleyItem.rule.length; })); }
javascript
function removeUnfinishedItems(states) { return states.map((state) => state.filter((earleyItem) => { return earleyItem.position >= earleyItem.rule.length; })); }
[ "function", "removeUnfinishedItems", "(", "states", ")", "{", "return", "states", ".", "map", "(", "(", "state", ")", "=>", "state", ".", "filter", "(", "(", "earleyItem", ")", "=>", "{", "return", "earleyItem", ".", "position", ">=", "earleyItem", ".", "rule", ".", "length", ";", "}", ")", ")", ";", "}" ]
Removes earley items from each state that failed to completely parse through. In other words, removes earley items whose position is less than the length of its rule @function removeUnfinishedItems @param {state[]} states - Set of lists of earley items @return {state[]} Set of lists of completed earley items
[ "Removes", "earley", "items", "from", "each", "state", "that", "failed", "to", "completely", "parse", "through", ".", "In", "other", "words", "removes", "earley", "items", "whose", "position", "is", "less", "than", "the", "length", "of", "its", "rule" ]
d28b3f330ee03b5c273f1ce5871a5b86dac79fb0
https://github.com/patgrasso/parsey/blob/d28b3f330ee03b5c273f1ce5871a5b86dac79fb0/lib/parser.js#L206-L210
55,092
patgrasso/parsey
lib/parser.js
swap
function swap(states) { let newStates = Array.apply(null, Array(states.length)).map(() => []); states.forEach((state, i) => { state.forEach((earleyItem) => { newStates[earleyItem.origin].push(earleyItem); earleyItem.origin = i; }); }); return newStates; }
javascript
function swap(states) { let newStates = Array.apply(null, Array(states.length)).map(() => []); states.forEach((state, i) => { state.forEach((earleyItem) => { newStates[earleyItem.origin].push(earleyItem); earleyItem.origin = i; }); }); return newStates; }
[ "function", "swap", "(", "states", ")", "{", "let", "newStates", "=", "Array", ".", "apply", "(", "null", ",", "Array", "(", "states", ".", "length", ")", ")", ".", "map", "(", "(", ")", "=>", "[", "]", ")", ";", "states", ".", "forEach", "(", "(", "state", ",", "i", ")", "=>", "{", "state", ".", "forEach", "(", "(", "earleyItem", ")", "=>", "{", "newStates", "[", "earleyItem", ".", "origin", "]", ".", "push", "(", "earleyItem", ")", ";", "earleyItem", ".", "origin", "=", "i", ";", "}", ")", ";", "}", ")", ";", "return", "newStates", ";", "}" ]
Places earley items in the states in which they originated, as opposed to the states in which they finished parsing, and set their `origin` properties to the state in which they finished. This allows a depth-first search of the chart to move forwards through the graph, which is more intuitive than having to move backwards @function swap @param {state[]} states - Set of lists of earley items @return {state[]} Set of lists of earley items, but each item now exists in the state at which it originated, and the <code>origin</code> property of each item points to the state at which the parse completed
[ "Places", "earley", "items", "in", "the", "states", "in", "which", "they", "originated", "as", "opposed", "to", "the", "states", "in", "which", "they", "finished", "parsing", "and", "set", "their", "origin", "properties", "to", "the", "state", "in", "which", "they", "finished", "." ]
d28b3f330ee03b5c273f1ce5871a5b86dac79fb0
https://github.com/patgrasso/parsey/blob/d28b3f330ee03b5c273f1ce5871a5b86dac79fb0/lib/parser.js#L227-L237
55,093
patgrasso/parsey
lib/parser.js
dfsHelper
function dfsHelper(states, root, state, depth, tokens) { var edges; // Base case: we finished the root rule if (state === root.origin && depth === root.rule.length) { return []; } // If the current production symbol is a terminal if (root.rule[depth] instanceof RegExp) { if (root.rule[depth].test(tokens[state])) { let subMatch = dfsHelper(states, root, state + 1, depth + 1, tokens); if (subMatch) { return [tokens[state]].concat(subMatch); } } return null; } else if (typeof root.rule[depth] === 'string') { if (root.rule[depth] === tokens[state]) { let subMatch = dfsHelper(states, root, state + 1, depth + 1, tokens); if (subMatch) { return [tokens[state]].concat(subMatch); } } return null; } // Otherwise, it must be a non-terminal edges = states[state] .filter((item) => item.rule.lhs === root.rule[depth]) .map((item) => { let subMatch = dfsHelper(states, root, item.origin, depth + 1, tokens); if (subMatch) { return [{ item : item.rule, children: dfsHelper(states, item, state, 0, tokens) }].concat(subMatch); } return null; }) .filter((list) => list); if (edges.length > 1) { let diffs = edges.filter( (tree) => JSON.stringify(tree) !== JSON.stringify(edges[0]) ); if (diffs.length > 0) { //console.log('Ambiguity\n' + JSON.stringify(edges, null, 2)); console.log('Ambiguous rules'); } } return edges[0]; }
javascript
function dfsHelper(states, root, state, depth, tokens) { var edges; // Base case: we finished the root rule if (state === root.origin && depth === root.rule.length) { return []; } // If the current production symbol is a terminal if (root.rule[depth] instanceof RegExp) { if (root.rule[depth].test(tokens[state])) { let subMatch = dfsHelper(states, root, state + 1, depth + 1, tokens); if (subMatch) { return [tokens[state]].concat(subMatch); } } return null; } else if (typeof root.rule[depth] === 'string') { if (root.rule[depth] === tokens[state]) { let subMatch = dfsHelper(states, root, state + 1, depth + 1, tokens); if (subMatch) { return [tokens[state]].concat(subMatch); } } return null; } // Otherwise, it must be a non-terminal edges = states[state] .filter((item) => item.rule.lhs === root.rule[depth]) .map((item) => { let subMatch = dfsHelper(states, root, item.origin, depth + 1, tokens); if (subMatch) { return [{ item : item.rule, children: dfsHelper(states, item, state, 0, tokens) }].concat(subMatch); } return null; }) .filter((list) => list); if (edges.length > 1) { let diffs = edges.filter( (tree) => JSON.stringify(tree) !== JSON.stringify(edges[0]) ); if (diffs.length > 0) { //console.log('Ambiguity\n' + JSON.stringify(edges, null, 2)); console.log('Ambiguous rules'); } } return edges[0]; }
[ "function", "dfsHelper", "(", "states", ",", "root", ",", "state", ",", "depth", ",", "tokens", ")", "{", "var", "edges", ";", "// Base case: we finished the root rule", "if", "(", "state", "===", "root", ".", "origin", "&&", "depth", "===", "root", ".", "rule", ".", "length", ")", "{", "return", "[", "]", ";", "}", "// If the current production symbol is a terminal", "if", "(", "root", ".", "rule", "[", "depth", "]", "instanceof", "RegExp", ")", "{", "if", "(", "root", ".", "rule", "[", "depth", "]", ".", "test", "(", "tokens", "[", "state", "]", ")", ")", "{", "let", "subMatch", "=", "dfsHelper", "(", "states", ",", "root", ",", "state", "+", "1", ",", "depth", "+", "1", ",", "tokens", ")", ";", "if", "(", "subMatch", ")", "{", "return", "[", "tokens", "[", "state", "]", "]", ".", "concat", "(", "subMatch", ")", ";", "}", "}", "return", "null", ";", "}", "else", "if", "(", "typeof", "root", ".", "rule", "[", "depth", "]", "===", "'string'", ")", "{", "if", "(", "root", ".", "rule", "[", "depth", "]", "===", "tokens", "[", "state", "]", ")", "{", "let", "subMatch", "=", "dfsHelper", "(", "states", ",", "root", ",", "state", "+", "1", ",", "depth", "+", "1", ",", "tokens", ")", ";", "if", "(", "subMatch", ")", "{", "return", "[", "tokens", "[", "state", "]", "]", ".", "concat", "(", "subMatch", ")", ";", "}", "}", "return", "null", ";", "}", "// Otherwise, it must be a non-terminal", "edges", "=", "states", "[", "state", "]", ".", "filter", "(", "(", "item", ")", "=>", "item", ".", "rule", ".", "lhs", "===", "root", ".", "rule", "[", "depth", "]", ")", ".", "map", "(", "(", "item", ")", "=>", "{", "let", "subMatch", "=", "dfsHelper", "(", "states", ",", "root", ",", "item", ".", "origin", ",", "depth", "+", "1", ",", "tokens", ")", ";", "if", "(", "subMatch", ")", "{", "return", "[", "{", "item", ":", "item", ".", "rule", ",", "children", ":", "dfsHelper", "(", "states", ",", "item", ",", "state", ",", "0", ",", "tokens", ")", "}", "]", ".", "concat", "(", "subMatch", ")", ";", "}", "return", "null", ";", "}", ")", ".", "filter", "(", "(", "list", ")", "=>", "list", ")", ";", "if", "(", "edges", ".", "length", ">", "1", ")", "{", "let", "diffs", "=", "edges", ".", "filter", "(", "(", "tree", ")", "=>", "JSON", ".", "stringify", "(", "tree", ")", "!==", "JSON", ".", "stringify", "(", "edges", "[", "0", "]", ")", ")", ";", "if", "(", "diffs", ".", "length", ">", "0", ")", "{", "//console.log('Ambiguity\\n' + JSON.stringify(edges, null, 2));", "console", ".", "log", "(", "'Ambiguous rules'", ")", ";", "}", "}", "return", "edges", "[", "0", "]", ";", "}" ]
Recursive function that explores a specific earley item, constructs the parse tree for it, then sends it up the chimney! @function dfsHelper @param {state[]} states - Set of lists of earley items @param {earleyItem} root - Current earley item being explored, a tree for which is to be constructed @param {number} state - Current state/index of our current position in the list of tokens @param {number} depth - Index/position in the root's rule (RHS). In other words, index of the next symbol to match or explore @param {string[]} tokens - List of input tokens @return {null|object[]} Null if the search provided NO results for the given node, or a list of tree nodes, which are the respective parse trees of each of the root rule's RHS symbols
[ "Recursive", "function", "that", "explores", "a", "specific", "earley", "item", "constructs", "the", "parse", "tree", "for", "it", "then", "sends", "it", "up", "the", "chimney!" ]
d28b3f330ee03b5c273f1ce5871a5b86dac79fb0
https://github.com/patgrasso/parsey/blob/d28b3f330ee03b5c273f1ce5871a5b86dac79fb0/lib/parser.js#L309-L366
55,094
tests-always-included/ddq-backend-mock
lib/ddq-backend-mock.js
remove
function remove(ddqBackendInstance, recordId, callback) { // Note, this is not what we want. // it does not handle the times when the // isProcessing flag is true. ddqBackendInstance.deleteData(recordId); ddqBackendInstance.checkAndEmitData(); callback(); }
javascript
function remove(ddqBackendInstance, recordId, callback) { // Note, this is not what we want. // it does not handle the times when the // isProcessing flag is true. ddqBackendInstance.deleteData(recordId); ddqBackendInstance.checkAndEmitData(); callback(); }
[ "function", "remove", "(", "ddqBackendInstance", ",", "recordId", ",", "callback", ")", "{", "// Note, this is not what we want.", "// it does not handle the times when the", "// isProcessing flag is true.", "ddqBackendInstance", ".", "deleteData", "(", "recordId", ")", ";", "ddqBackendInstance", ".", "checkAndEmitData", "(", ")", ";", "callback", "(", ")", ";", "}" ]
Removes the message from stored data. @param {Object} ddqBackendInstance @param {string} recordId @param {Function} callback
[ "Removes", "the", "message", "from", "stored", "data", "." ]
7d3cbf25a4533db9dac68193ac0af648ee38a435
https://github.com/tests-always-included/ddq-backend-mock/blob/7d3cbf25a4533db9dac68193ac0af648ee38a435/lib/ddq-backend-mock.js#L59-L66
55,095
tests-always-included/ddq-backend-mock
lib/ddq-backend-mock.js
requeue
function requeue(ddqBackendInstance, recordId, callback) { var record; record = ddqBackendInstance.getRecord(recordId); record.isProcessing = false; record.requeued = true; callback(); }
javascript
function requeue(ddqBackendInstance, recordId, callback) { var record; record = ddqBackendInstance.getRecord(recordId); record.isProcessing = false; record.requeued = true; callback(); }
[ "function", "requeue", "(", "ddqBackendInstance", ",", "recordId", ",", "callback", ")", "{", "var", "record", ";", "record", "=", "ddqBackendInstance", ".", "getRecord", "(", "recordId", ")", ";", "record", ".", "isProcessing", "=", "false", ";", "record", ".", "requeued", "=", "true", ";", "callback", "(", ")", ";", "}" ]
Sets the record to be requeued so another listener can pick it up and try to process the message again. @param {Object} ddqBackendInstance @param {string} recordId @param {Function} callback
[ "Sets", "the", "record", "to", "be", "requeued", "so", "another", "listener", "can", "pick", "it", "up", "and", "try", "to", "process", "the", "message", "again", "." ]
7d3cbf25a4533db9dac68193ac0af648ee38a435
https://github.com/tests-always-included/ddq-backend-mock/blob/7d3cbf25a4533db9dac68193ac0af648ee38a435/lib/ddq-backend-mock.js#L77-L84
55,096
binder-project/binder-health-checker
lib/cli.js
Command
function Command (name, cli, action) { if (!(this instanceof Command)) { return new Command(name, cli, action) } this.name = name this.cli = cli this.action = action }
javascript
function Command (name, cli, action) { if (!(this instanceof Command)) { return new Command(name, cli, action) } this.name = name this.cli = cli this.action = action }
[ "function", "Command", "(", "name", ",", "cli", ",", "action", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Command", ")", ")", "{", "return", "new", "Command", "(", "name", ",", "cli", ",", "action", ")", "}", "this", ".", "name", "=", "name", "this", ".", "cli", "=", "cli", "this", ".", "action", "=", "action", "}" ]
The argument-parsing and action components of a CLI command are separated so that the CLI can both be imported from other modules and launched via PM2
[ "The", "argument", "-", "parsing", "and", "action", "components", "of", "a", "CLI", "command", "are", "separated", "so", "that", "the", "CLI", "can", "both", "be", "imported", "from", "other", "modules", "and", "launched", "via", "PM2" ]
7c6c7973464c42a67b7f860ca6cceb40f29c1e5e
https://github.com/binder-project/binder-health-checker/blob/7c6c7973464c42a67b7f860ca6cceb40f29c1e5e/lib/cli.js#L13-L20
55,097
peerigon/alamid-sorted-array
lib/sortedArray.js
sortedArray
function sortedArray(arr, comparator1, comparator2, comparator3) { var _ = {}; arr = arr || []; if (typeof arr._sortedArray === "object") { throw new Error("(sortedArray) Cannot extend array: Special key _sortedArray is already defined. Did you apply it twice?"); } arr._sortedArray = _; _.reversed = false; _.push = arr.push; arr.push = push; _.unshift = arr.unshift; _.splice = arr.splice; arr.splice = splice; arr.unshift = push; _.indexOf = arr.indexOf; arr.indexOf = indexOf; _.sort = arr.sort; arr.sort = sort; _.reverse = arr.reverse; arr.reverse = reverse; arr.sortedIndex = sortedIndex; if (arguments.length === 1) { arr.comparator = arr.comparator || defaultComparator; } else if (arguments.length === 2) { arr.comparator = comparator1; } else { arr.comparator = multipleComparators(slice.call(arguments, 1)); } if (arr.length > 0) { arr.sort(); } return arr; }
javascript
function sortedArray(arr, comparator1, comparator2, comparator3) { var _ = {}; arr = arr || []; if (typeof arr._sortedArray === "object") { throw new Error("(sortedArray) Cannot extend array: Special key _sortedArray is already defined. Did you apply it twice?"); } arr._sortedArray = _; _.reversed = false; _.push = arr.push; arr.push = push; _.unshift = arr.unshift; _.splice = arr.splice; arr.splice = splice; arr.unshift = push; _.indexOf = arr.indexOf; arr.indexOf = indexOf; _.sort = arr.sort; arr.sort = sort; _.reverse = arr.reverse; arr.reverse = reverse; arr.sortedIndex = sortedIndex; if (arguments.length === 1) { arr.comparator = arr.comparator || defaultComparator; } else if (arguments.length === 2) { arr.comparator = comparator1; } else { arr.comparator = multipleComparators(slice.call(arguments, 1)); } if (arr.length > 0) { arr.sort(); } return arr; }
[ "function", "sortedArray", "(", "arr", ",", "comparator1", ",", "comparator2", ",", "comparator3", ")", "{", "var", "_", "=", "{", "}", ";", "arr", "=", "arr", "||", "[", "]", ";", "if", "(", "typeof", "arr", ".", "_sortedArray", "===", "\"object\"", ")", "{", "throw", "new", "Error", "(", "\"(sortedArray) Cannot extend array: Special key _sortedArray is already defined. Did you apply it twice?\"", ")", ";", "}", "arr", ".", "_sortedArray", "=", "_", ";", "_", ".", "reversed", "=", "false", ";", "_", ".", "push", "=", "arr", ".", "push", ";", "arr", ".", "push", "=", "push", ";", "_", ".", "unshift", "=", "arr", ".", "unshift", ";", "_", ".", "splice", "=", "arr", ".", "splice", ";", "arr", ".", "splice", "=", "splice", ";", "arr", ".", "unshift", "=", "push", ";", "_", ".", "indexOf", "=", "arr", ".", "indexOf", ";", "arr", ".", "indexOf", "=", "indexOf", ";", "_", ".", "sort", "=", "arr", ".", "sort", ";", "arr", ".", "sort", "=", "sort", ";", "_", ".", "reverse", "=", "arr", ".", "reverse", ";", "arr", ".", "reverse", "=", "reverse", ";", "arr", ".", "sortedIndex", "=", "sortedIndex", ";", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "arr", ".", "comparator", "=", "arr", ".", "comparator", "||", "defaultComparator", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "arr", ".", "comparator", "=", "comparator1", ";", "}", "else", "{", "arr", ".", "comparator", "=", "multipleComparators", "(", "slice", ".", "call", "(", "arguments", ",", "1", ")", ")", ";", "}", "if", "(", "arr", ".", "length", ">", "0", ")", "{", "arr", ".", "sort", "(", ")", ";", "}", "return", "arr", ";", "}" ]
Turns an array or every object with an array-like interface into a sorted array that maintains the sort order. This is basically achieved by replacing the original mutator methods with versions that respect the order. If the supplied array has a comparator-function, this function will be used for comparison. You may also provide multiple comparators. If comparator1 returns 0, comparator2 is applied, etc. @param {Array|Object} arr @param {Function=} comparator1 @param {Function=} comparator2 @param {Function=} comparator3 @returns {Array|Object}
[ "Turns", "an", "array", "or", "every", "object", "with", "an", "array", "-", "like", "interface", "into", "a", "sorted", "array", "that", "maintains", "the", "sort", "order", ".", "This", "is", "basically", "achieved", "by", "replacing", "the", "original", "mutator", "methods", "with", "versions", "that", "respect", "the", "order", "." ]
59d58fd3b94d26c873c2a4ba2ecd18758309bd0b
https://github.com/peerigon/alamid-sorted-array/blob/59d58fd3b94d26c873c2a4ba2ecd18758309bd0b/lib/sortedArray.js#L21-L60
55,098
peerigon/alamid-sorted-array
lib/sortedArray.js
indexOf
function indexOf(element, fromIndex) { /* jshint validthis:true */ var arr = toArray(this), index; if (fromIndex) { arr = arr.slice(fromIndex); } index = binarySearch(arr, element, this.comparator); if (index < 0) { return -1; } else { return index; } }
javascript
function indexOf(element, fromIndex) { /* jshint validthis:true */ var arr = toArray(this), index; if (fromIndex) { arr = arr.slice(fromIndex); } index = binarySearch(arr, element, this.comparator); if (index < 0) { return -1; } else { return index; } }
[ "function", "indexOf", "(", "element", ",", "fromIndex", ")", "{", "/* jshint validthis:true */", "var", "arr", "=", "toArray", "(", "this", ")", ",", "index", ";", "if", "(", "fromIndex", ")", "{", "arr", "=", "arr", ".", "slice", "(", "fromIndex", ")", ";", "}", "index", "=", "binarySearch", "(", "arr", ",", "element", ",", "this", ".", "comparator", ")", ";", "if", "(", "index", "<", "0", ")", "{", "return", "-", "1", ";", "}", "else", "{", "return", "index", ";", "}", "}" ]
Works like Array.prototype.indexOf but uses a faster binary search. Same signature as Array.prototype.indexOf @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
[ "Works", "like", "Array", ".", "prototype", ".", "indexOf", "but", "uses", "a", "faster", "binary", "search", "." ]
59d58fd3b94d26c873c2a4ba2ecd18758309bd0b
https://github.com/peerigon/alamid-sorted-array/blob/59d58fd3b94d26c873c2a4ba2ecd18758309bd0b/lib/sortedArray.js#L109-L125
55,099
peerigon/alamid-sorted-array
lib/sortedArray.js
reverse
function reverse() { /* jshint validthis:true */ var _ = this._sortedArray, reversed = _.reversed; if (reversed) { this.comparator = this.comparator.original; } else { this.comparator = getInversionOf(this.comparator); } _.reversed = !reversed; _.reverse.call(this); }
javascript
function reverse() { /* jshint validthis:true */ var _ = this._sortedArray, reversed = _.reversed; if (reversed) { this.comparator = this.comparator.original; } else { this.comparator = getInversionOf(this.comparator); } _.reversed = !reversed; _.reverse.call(this); }
[ "function", "reverse", "(", ")", "{", "/* jshint validthis:true */", "var", "_", "=", "this", ".", "_sortedArray", ",", "reversed", "=", "_", ".", "reversed", ";", "if", "(", "reversed", ")", "{", "this", ".", "comparator", "=", "this", ".", "comparator", ".", "original", ";", "}", "else", "{", "this", ".", "comparator", "=", "getInversionOf", "(", "this", ".", "comparator", ")", ";", "}", "_", ".", "reversed", "=", "!", "reversed", ";", "_", ".", "reverse", ".", "call", "(", "this", ")", ";", "}" ]
Works like Array.prototype.reverse. Please note that this function wraps the current arr.comparator in order to invert the result. Reverting it back removes the wrapper. Same signature as Array.prototype.reverse @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
[ "Works", "like", "Array", ".", "prototype", ".", "reverse", "." ]
59d58fd3b94d26c873c2a4ba2ecd18758309bd0b
https://github.com/peerigon/alamid-sorted-array/blob/59d58fd3b94d26c873c2a4ba2ecd18758309bd0b/lib/sortedArray.js#L167-L180