id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
35,400
glennjones/elsewhere-profiles
lib/page.js
function(callback){ var options = this.options, cache = this.options.cache, logger = this.options.logger; if(this.apiInterface){ logger.info('fetch data from api: ' + this.apiInterface.name); var sgn = this.profile.identity.sgn || '', self = this; try { this.apiInterface.getProfile(this.url, sgn, options, function(hCard){ if(hCard){ self.profile.hCards = [hCard]; } self.status = "fetched"; callback(); }); } catch(err) { logger.warn('error getting api data with plugin for: ' + self.domain + ' - ' + err); self.error = err; self.status = "errored"; callback(); } } }
javascript
function(callback){ var options = this.options, cache = this.options.cache, logger = this.options.logger; if(this.apiInterface){ logger.info('fetch data from api: ' + this.apiInterface.name); var sgn = this.profile.identity.sgn || '', self = this; try { this.apiInterface.getProfile(this.url, sgn, options, function(hCard){ if(hCard){ self.profile.hCards = [hCard]; } self.status = "fetched"; callback(); }); } catch(err) { logger.warn('error getting api data with plugin for: ' + self.domain + ' - ' + err); self.error = err; self.status = "errored"; callback(); } } }
[ "function", "(", "callback", ")", "{", "var", "options", "=", "this", ".", "options", ",", "cache", "=", "this", ".", "options", ".", "cache", ",", "logger", "=", "this", ".", "options", ".", "logger", ";", "if", "(", "this", ".", "apiInterface", ")", "{", "logger", ".", "info", "(", "'fetch data from api: '", "+", "this", ".", "apiInterface", ".", "name", ")", ";", "var", "sgn", "=", "this", ".", "profile", ".", "identity", ".", "sgn", "||", "''", ",", "self", "=", "this", ";", "try", "{", "this", ".", "apiInterface", ".", "getProfile", "(", "this", ".", "url", ",", "sgn", ",", "options", ",", "function", "(", "hCard", ")", "{", "if", "(", "hCard", ")", "{", "self", ".", "profile", ".", "hCards", "=", "[", "hCard", "]", ";", "}", "self", ".", "status", "=", "\"fetched\"", ";", "callback", "(", ")", ";", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "warn", "(", "'error getting api data with plugin for: '", "+", "self", ".", "domain", "+", "' - '", "+", "err", ")", ";", "self", ".", "error", "=", "err", ";", "self", ".", "status", "=", "\"errored\"", ";", "callback", "(", ")", ";", "}", "}", "}" ]
uses plug-in interface to get profile from an api
[ "uses", "plug", "-", "in", "interface", "to", "get", "profile", "from", "an", "api" ]
f86a5d040d540d4f8ed4f86518b75a0e6c8855ba
https://github.com/glennjones/elsewhere-profiles/blob/f86a5d040d540d4f8ed4f86518b75a0e6c8855ba/lib/page.js#L188-L219
35,401
claudio-silva/grunt-angular-builder
tasks/middleware/includeRequiredScripts.js
IncludeRequiredScriptsMiddleware
function IncludeRequiredScriptsMiddleware (context) { var path = require ('path'); /** * Paths of the required scripts. * @type {string[]} */ var paths = []; /** * File content of the required scripts. * @type {string[]} */ var sources = []; /** * Map of required script paths, as they are being resolved. * Prevents infinite recursion and redundant scans. * Note: paths will be registered here *before* being added to `paths`. * @type {Object.<string,boolean>} */ var references = {}; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { util.info ("Scanning <cyan>%</cyan> for non-angular script dependencies...", module.name); scan (module.head, module.headPath); module.bodies.forEach (function (path, i) { scan (path, module.bodyPaths[i]); }); }; this.build = function (targetScript) { /* jshint unused: vars */ var scripts = paths.map (function (path, i) { return { path: path, content: sources[i] }; }); util.arrayAppend (context.standaloneScripts, scripts); if (context.standaloneScripts.length) { var list = context.standaloneScripts.map ( function (e, i) { return ' ' + (i + 1) + '. ' + e.path; } ).join (util.NL); util.info ("Required non-angular scripts:%<cyan>%</cyan>", util.NL, list); } }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Extracts file paths from embedded comment references to scripts and appends them to `paths`. * @param {string} sourceCode * @param {string} filePath */ function scan (sourceCode, filePath) { /* jshint -W083 */ var match , r = new RegExp (MATCH_DIRECTIVE); while ((match = r.exec (sourceCode))) { match[1].split (/\s*,\s*/).forEach (function (s) { var m = s.match (/(["'])(.*?)\1/); if (!m) util.warn ('syntax error on #script directive on argument ...<cyan> % </cyan>...%At <cyan>%</cyan>\t', s, util.NL, filePath); else { var url = m[2]; var requiredPath = path.normalize (path.dirname (filePath) + '/' + url); // Check if this script was not already referenced. if (!references[requiredPath]) { references[requiredPath] = true; var source = context.grunt.file.read (requiredPath); // First, see if the required script has its own 'requires'. // If so, they must be required *before* the current script. scan (source, requiredPath); // Let's register the dependency now. paths.push (requiredPath); sources.push (source); } } }); } } }
javascript
function IncludeRequiredScriptsMiddleware (context) { var path = require ('path'); /** * Paths of the required scripts. * @type {string[]} */ var paths = []; /** * File content of the required scripts. * @type {string[]} */ var sources = []; /** * Map of required script paths, as they are being resolved. * Prevents infinite recursion and redundant scans. * Note: paths will be registered here *before* being added to `paths`. * @type {Object.<string,boolean>} */ var references = {}; //-------------------------------------------------------------------------------------------------------------------- // PUBLIC API //-------------------------------------------------------------------------------------------------------------------- this.analyze = function (filesArray) { /* jshint unused: vars */ // Do nothing }; this.trace = function (module) { util.info ("Scanning <cyan>%</cyan> for non-angular script dependencies...", module.name); scan (module.head, module.headPath); module.bodies.forEach (function (path, i) { scan (path, module.bodyPaths[i]); }); }; this.build = function (targetScript) { /* jshint unused: vars */ var scripts = paths.map (function (path, i) { return { path: path, content: sources[i] }; }); util.arrayAppend (context.standaloneScripts, scripts); if (context.standaloneScripts.length) { var list = context.standaloneScripts.map ( function (e, i) { return ' ' + (i + 1) + '. ' + e.path; } ).join (util.NL); util.info ("Required non-angular scripts:%<cyan>%</cyan>", util.NL, list); } }; //-------------------------------------------------------------------------------------------------------------------- // PRIVATE //-------------------------------------------------------------------------------------------------------------------- /** * Extracts file paths from embedded comment references to scripts and appends them to `paths`. * @param {string} sourceCode * @param {string} filePath */ function scan (sourceCode, filePath) { /* jshint -W083 */ var match , r = new RegExp (MATCH_DIRECTIVE); while ((match = r.exec (sourceCode))) { match[1].split (/\s*,\s*/).forEach (function (s) { var m = s.match (/(["'])(.*?)\1/); if (!m) util.warn ('syntax error on #script directive on argument ...<cyan> % </cyan>...%At <cyan>%</cyan>\t', s, util.NL, filePath); else { var url = m[2]; var requiredPath = path.normalize (path.dirname (filePath) + '/' + url); // Check if this script was not already referenced. if (!references[requiredPath]) { references[requiredPath] = true; var source = context.grunt.file.read (requiredPath); // First, see if the required script has its own 'requires'. // If so, they must be required *before* the current script. scan (source, requiredPath); // Let's register the dependency now. paths.push (requiredPath); sources.push (source); } } }); } } }
[ "function", "IncludeRequiredScriptsMiddleware", "(", "context", ")", "{", "var", "path", "=", "require", "(", "'path'", ")", ";", "/**\n * Paths of the required scripts.\n * @type {string[]}\n */", "var", "paths", "=", "[", "]", ";", "/**\n * File content of the required scripts.\n * @type {string[]}\n */", "var", "sources", "=", "[", "]", ";", "/**\n * Map of required script paths, as they are being resolved.\n * Prevents infinite recursion and redundant scans.\n * Note: paths will be registered here *before* being added to `paths`.\n * @type {Object.<string,boolean>}\n */", "var", "references", "=", "{", "}", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PUBLIC API", "//--------------------------------------------------------------------------------------------------------------------", "this", ".", "analyze", "=", "function", "(", "filesArray", ")", "{", "/* jshint unused: vars */", "// Do nothing", "}", ";", "this", ".", "trace", "=", "function", "(", "module", ")", "{", "util", ".", "info", "(", "\"Scanning <cyan>%</cyan> for non-angular script dependencies...\"", ",", "module", ".", "name", ")", ";", "scan", "(", "module", ".", "head", ",", "module", ".", "headPath", ")", ";", "module", ".", "bodies", ".", "forEach", "(", "function", "(", "path", ",", "i", ")", "{", "scan", "(", "path", ",", "module", ".", "bodyPaths", "[", "i", "]", ")", ";", "}", ")", ";", "}", ";", "this", ".", "build", "=", "function", "(", "targetScript", ")", "{", "/* jshint unused: vars */", "var", "scripts", "=", "paths", ".", "map", "(", "function", "(", "path", ",", "i", ")", "{", "return", "{", "path", ":", "path", ",", "content", ":", "sources", "[", "i", "]", "}", ";", "}", ")", ";", "util", ".", "arrayAppend", "(", "context", ".", "standaloneScripts", ",", "scripts", ")", ";", "if", "(", "context", ".", "standaloneScripts", ".", "length", ")", "{", "var", "list", "=", "context", ".", "standaloneScripts", ".", "map", "(", "function", "(", "e", ",", "i", ")", "{", "return", "' '", "+", "(", "i", "+", "1", ")", "+", "'. '", "+", "e", ".", "path", ";", "}", ")", ".", "join", "(", "util", ".", "NL", ")", ";", "util", ".", "info", "(", "\"Required non-angular scripts:%<cyan>%</cyan>\"", ",", "util", ".", "NL", ",", "list", ")", ";", "}", "}", ";", "//--------------------------------------------------------------------------------------------------------------------", "// PRIVATE", "//--------------------------------------------------------------------------------------------------------------------", "/**\n * Extracts file paths from embedded comment references to scripts and appends them to `paths`.\n * @param {string} sourceCode\n * @param {string} filePath\n */", "function", "scan", "(", "sourceCode", ",", "filePath", ")", "{", "/* jshint -W083 */", "var", "match", ",", "r", "=", "new", "RegExp", "(", "MATCH_DIRECTIVE", ")", ";", "while", "(", "(", "match", "=", "r", ".", "exec", "(", "sourceCode", ")", ")", ")", "{", "match", "[", "1", "]", ".", "split", "(", "/", "\\s*,\\s*", "/", ")", ".", "forEach", "(", "function", "(", "s", ")", "{", "var", "m", "=", "s", ".", "match", "(", "/", "([\"'])(.*?)\\1", "/", ")", ";", "if", "(", "!", "m", ")", "util", ".", "warn", "(", "'syntax error on #script directive on argument ...<cyan> % </cyan>...%At <cyan>%</cyan>\\t'", ",", "s", ",", "util", ".", "NL", ",", "filePath", ")", ";", "else", "{", "var", "url", "=", "m", "[", "2", "]", ";", "var", "requiredPath", "=", "path", ".", "normalize", "(", "path", ".", "dirname", "(", "filePath", ")", "+", "'/'", "+", "url", ")", ";", "// Check if this script was not already referenced.", "if", "(", "!", "references", "[", "requiredPath", "]", ")", "{", "references", "[", "requiredPath", "]", "=", "true", ";", "var", "source", "=", "context", ".", "grunt", ".", "file", ".", "read", "(", "requiredPath", ")", ";", "// First, see if the required script has its own 'requires'.", "// If so, they must be required *before* the current script.", "scan", "(", "source", ",", "requiredPath", ")", ";", "// Let's register the dependency now.", "paths", ".", "push", "(", "requiredPath", ")", ";", "sources", ".", "push", "(", "source", ")", ";", "}", "}", "}", ")", ";", "}", "}", "}" ]
Exports to the context the paths of all extra scripts required explicitly by build-directives, in the order defined by the modules' dependency graph. @constructor @implements {MiddlewareInterface} @param {Context} context The execution context for the middleware stack.
[ "Exports", "to", "the", "context", "the", "paths", "of", "all", "extra", "scripts", "required", "explicitly", "by", "build", "-", "directives", "in", "the", "order", "defined", "by", "the", "modules", "dependency", "graph", "." ]
0aa4232257e4ae95d0aa9258ff0a91395383d8b7
https://github.com/claudio-silva/grunt-angular-builder/blob/0aa4232257e4ae95d0aa9258ff0a91395383d8b7/tasks/middleware/includeRequiredScripts.js#L26-L131
35,402
commenthol/markedpp
src/Parser.js
prep
function prep (id) { id = id.replace(/(?:%20|\+)/g, ' ') id = self.headingAutoId({ text: id }) return id }
javascript
function prep (id) { id = id.replace(/(?:%20|\+)/g, ' ') id = self.headingAutoId({ text: id }) return id }
[ "function", "prep", "(", "id", ")", "{", "id", "=", "id", ".", "replace", "(", "/", "(?:%20|\\+)", "/", "g", ",", "' '", ")", "id", "=", "self", ".", "headingAutoId", "(", "{", "text", ":", "id", "}", ")", "return", "id", "}" ]
sanitize the id before lookup
[ "sanitize", "the", "id", "before", "lookup" ]
f72db5aa2c1b858a9d5403c6103f24227d74c611
https://github.com/commenthol/markedpp/blob/f72db5aa2c1b858a9d5403c6103f24227d74c611/src/Parser.js#L167-L171
35,403
strapi/strapi-generate-upload
files/api/upload/controllers/Upload.js
function (fieldname, file, filename) { const acceptedExtensions = strapi.api.upload.config.acceptedExtensions || []; if (acceptedExtensions[0] !== '*' && !_.contains(acceptedExtensions, path.extname(filename))) { this.status = 400; this.body = { message: 'Invalid file format ' + filename ? 'for this file' + filename : '' }; } }
javascript
function (fieldname, file, filename) { const acceptedExtensions = strapi.api.upload.config.acceptedExtensions || []; if (acceptedExtensions[0] !== '*' && !_.contains(acceptedExtensions, path.extname(filename))) { this.status = 400; this.body = { message: 'Invalid file format ' + filename ? 'for this file' + filename : '' }; } }
[ "function", "(", "fieldname", ",", "file", ",", "filename", ")", "{", "const", "acceptedExtensions", "=", "strapi", ".", "api", ".", "upload", ".", "config", ".", "acceptedExtensions", "||", "[", "]", ";", "if", "(", "acceptedExtensions", "[", "0", "]", "!==", "'*'", "&&", "!", "_", ".", "contains", "(", "acceptedExtensions", ",", "path", ".", "extname", "(", "filename", ")", ")", ")", "{", "this", ".", "status", "=", "400", ";", "this", ".", "body", "=", "{", "message", ":", "'Invalid file format '", "+", "filename", "?", "'for this file'", "+", "filename", ":", "''", "}", ";", "}", "}" ]
Validation used by `co-busboy`.
[ "Validation", "used", "by", "co", "-", "busboy", "." ]
52d2202743e3f1b6390b4db5dcb9484f44d2bb85
https://github.com/strapi/strapi-generate-upload/blob/52d2202743e3f1b6390b4db5dcb9484f44d2bb85/files/api/upload/controllers/Upload.js#L32-L40
35,404
koa-modules/methodoverride
index.js
createHeaderGetter
function createHeaderGetter(str) { var header = str.toLowerCase() return headerGetter function headerGetter(req, res) { // set appropriate Vary header res.vary(str) // multiple headers get joined with comma by node.js core return (req.headers[header] || '').split(/ *, */) } }
javascript
function createHeaderGetter(str) { var header = str.toLowerCase() return headerGetter function headerGetter(req, res) { // set appropriate Vary header res.vary(str) // multiple headers get joined with comma by node.js core return (req.headers[header] || '').split(/ *, */) } }
[ "function", "createHeaderGetter", "(", "str", ")", "{", "var", "header", "=", "str", ".", "toLowerCase", "(", ")", "return", "headerGetter", "function", "headerGetter", "(", "req", ",", "res", ")", "{", "// set appropriate Vary header", "res", ".", "vary", "(", "str", ")", "// multiple headers get joined with comma by node.js core", "return", "(", "req", ".", "headers", "[", "header", "]", "||", "''", ")", ".", "split", "(", "/", " *, *", "/", ")", "}", "}" ]
Create a getter for the given header name.
[ "Create", "a", "getter", "for", "the", "given", "header", "name", "." ]
b1ca34955b6243655dd979c106544d15051d3093
https://github.com/koa-modules/methodoverride/blob/b1ca34955b6243655dd979c106544d15051d3093/index.js#L114-L126
35,405
danielstjules/pattern-emitter
lib/patternEmitter.js
PatternEmitter
function PatternEmitter() { EventEmitter.call(this); this.event = ''; this._regexesCount = 0; this._events = this._events || {}; this._patternEvents = this._patternEvents || {}; this._regexes = this._regexes || {}; }
javascript
function PatternEmitter() { EventEmitter.call(this); this.event = ''; this._regexesCount = 0; this._events = this._events || {}; this._patternEvents = this._patternEvents || {}; this._regexes = this._regexes || {}; }
[ "function", "PatternEmitter", "(", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "event", "=", "''", ";", "this", ".", "_regexesCount", "=", "0", ";", "this", ".", "_events", "=", "this", ".", "_events", "||", "{", "}", ";", "this", ".", "_patternEvents", "=", "this", ".", "_patternEvents", "||", "{", "}", ";", "this", ".", "_regexes", "=", "this", ".", "_regexes", "||", "{", "}", ";", "}" ]
Creates a new PatternEmitter, which extends EventEmitter. In addition to EventEmitter's prototype, it allows listeners to register to events matching a RegExp. @constructor @extends EventEmitter @property {*} event The type of the last emitted event
[ "Creates", "a", "new", "PatternEmitter", "which", "extends", "EventEmitter", ".", "In", "addition", "to", "EventEmitter", "s", "prototype", "it", "allows", "listeners", "to", "register", "to", "events", "matching", "a", "RegExp", "." ]
93f76146b414a16864ce340e40ad9f18505ecebf
https://github.com/danielstjules/pattern-emitter/blob/93f76146b414a16864ce340e40ad9f18505ecebf/lib/patternEmitter.js#L16-L25
35,406
bmeck/understudy
index.js
iterate
function iterate(self, interceptors, args, after) { if (!interceptors || !interceptors.length) { after.apply(self, args); return; } var i = 0; var len = interceptors.length; if (!len) { after.apply(self, args); return; } function nextInterceptor() { if (i === len) { i++; after.apply(self, arguments); } else if (i < len) { var used = false; var interceptor = interceptors[i++]; interceptor.apply(self, Array.prototype.slice.call(arguments, 1).concat(function next(err) { // // Do not allow multiple continuations // if (used) { return; } used = true; if (!err || !callback) { nextInterceptor.apply(null, waterfall ? arguments : args); } else { after.call(self, err); } })); } } nextInterceptor.apply(null, args); }
javascript
function iterate(self, interceptors, args, after) { if (!interceptors || !interceptors.length) { after.apply(self, args); return; } var i = 0; var len = interceptors.length; if (!len) { after.apply(self, args); return; } function nextInterceptor() { if (i === len) { i++; after.apply(self, arguments); } else if (i < len) { var used = false; var interceptor = interceptors[i++]; interceptor.apply(self, Array.prototype.slice.call(arguments, 1).concat(function next(err) { // // Do not allow multiple continuations // if (used) { return; } used = true; if (!err || !callback) { nextInterceptor.apply(null, waterfall ? arguments : args); } else { after.call(self, err); } })); } } nextInterceptor.apply(null, args); }
[ "function", "iterate", "(", "self", ",", "interceptors", ",", "args", ",", "after", ")", "{", "if", "(", "!", "interceptors", "||", "!", "interceptors", ".", "length", ")", "{", "after", ".", "apply", "(", "self", ",", "args", ")", ";", "return", ";", "}", "var", "i", "=", "0", ";", "var", "len", "=", "interceptors", ".", "length", ";", "if", "(", "!", "len", ")", "{", "after", ".", "apply", "(", "self", ",", "args", ")", ";", "return", ";", "}", "function", "nextInterceptor", "(", ")", "{", "if", "(", "i", "===", "len", ")", "{", "i", "++", ";", "after", ".", "apply", "(", "self", ",", "arguments", ")", ";", "}", "else", "if", "(", "i", "<", "len", ")", "{", "var", "used", "=", "false", ";", "var", "interceptor", "=", "interceptors", "[", "i", "++", "]", ";", "interceptor", ".", "apply", "(", "self", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ".", "concat", "(", "function", "next", "(", "err", ")", "{", "//", "// Do not allow multiple continuations", "//", "if", "(", "used", ")", "{", "return", ";", "}", "used", "=", "true", ";", "if", "(", "!", "err", "||", "!", "callback", ")", "{", "nextInterceptor", ".", "apply", "(", "null", ",", "waterfall", "?", "arguments", ":", "args", ")", ";", "}", "else", "{", "after", ".", "call", "(", "self", ",", "err", ")", ";", "}", "}", ")", ")", ";", "}", "}", "nextInterceptor", ".", "apply", "(", "null", ",", "args", ")", ";", "}" ]
This is called in multiple temporal localities, put into a function instead of inline minor speed loss for more maintainability
[ "This", "is", "called", "in", "multiple", "temporal", "localities", "put", "into", "a", "function", "instead", "of", "inline", "minor", "speed", "loss", "for", "more", "maintainability" ]
1f77aca180f7ce9736d7c75cad5594df86f921d7
https://github.com/bmeck/understudy/blob/1f77aca180f7ce9736d7c75cad5594df86f921d7/index.js#L71-L108
35,407
flux-capacitor/flux-capacitor
packages/flux-capacitor-sequelize/lib/createTransaction.js
createTransaction
function createTransaction (database, sequelizeTransaction) { const transaction = Object.assign(sequelizeTransaction, { getImplementation () { return sequelizeTransaction }, perform (changeset) { return database.applyChangeset(changeset, { transaction }) } }) return transaction }
javascript
function createTransaction (database, sequelizeTransaction) { const transaction = Object.assign(sequelizeTransaction, { getImplementation () { return sequelizeTransaction }, perform (changeset) { return database.applyChangeset(changeset, { transaction }) } }) return transaction }
[ "function", "createTransaction", "(", "database", ",", "sequelizeTransaction", ")", "{", "const", "transaction", "=", "Object", ".", "assign", "(", "sequelizeTransaction", ",", "{", "getImplementation", "(", ")", "{", "return", "sequelizeTransaction", "}", ",", "perform", "(", "changeset", ")", "{", "return", "database", ".", "applyChangeset", "(", "changeset", ",", "{", "transaction", "}", ")", "}", "}", ")", "return", "transaction", "}" ]
Extends sequelize transaction. @param {Database} database @param {Sequelize.Transaction} sequelizeTransaction @return {Transaction}
[ "Extends", "sequelize", "transaction", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-sequelize/lib/createTransaction.js#L10-L21
35,408
NetEase/pomelo-loader
lib/loader.js
function(fn, suffix) { if(suffix.charAt(0) !== '.') { suffix = '.' + suffix; } if(fn.length <= suffix.length) { return false; } var str = fn.substring(fn.length - suffix.length).toLowerCase(); suffix = suffix.toLowerCase(); return str === suffix; }
javascript
function(fn, suffix) { if(suffix.charAt(0) !== '.') { suffix = '.' + suffix; } if(fn.length <= suffix.length) { return false; } var str = fn.substring(fn.length - suffix.length).toLowerCase(); suffix = suffix.toLowerCase(); return str === suffix; }
[ "function", "(", "fn", ",", "suffix", ")", "{", "if", "(", "suffix", ".", "charAt", "(", "0", ")", "!==", "'.'", ")", "{", "suffix", "=", "'.'", "+", "suffix", ";", "}", "if", "(", "fn", ".", "length", "<=", "suffix", ".", "length", ")", "{", "return", "false", ";", "}", "var", "str", "=", "fn", ".", "substring", "(", "fn", ".", "length", "-", "suffix", ".", "length", ")", ".", "toLowerCase", "(", ")", ";", "suffix", "=", "suffix", ".", "toLowerCase", "(", ")", ";", "return", "str", "===", "suffix", ";", "}" ]
Check file suffix @param fn {String} file name @param suffix {String} suffix string, such as .js, etc.
[ "Check", "file", "suffix" ]
3036711de323f6a5350c2bf634b0a69b110de458
https://github.com/NetEase/pomelo-loader/blob/3036711de323f6a5350c2bf634b0a69b110de458/lib/loader.js#L98-L110
35,409
flux-capacitor/flux-capacitor
packages/flux-capacitor/lib/combineReducers.js
combineReducers
function combineReducers (reducers) { const databaseReducers = Object.keys(reducers) .map((collectionName) => { const reducer = reducers[ collectionName ] return createDatabaseReducer(reducer, collectionName) }) return (database, event) => { const changesets = databaseReducers.map((reducer) => reducer(database, event)) return combineChangesets(changesets) } }
javascript
function combineReducers (reducers) { const databaseReducers = Object.keys(reducers) .map((collectionName) => { const reducer = reducers[ collectionName ] return createDatabaseReducer(reducer, collectionName) }) return (database, event) => { const changesets = databaseReducers.map((reducer) => reducer(database, event)) return combineChangesets(changesets) } }
[ "function", "combineReducers", "(", "reducers", ")", "{", "const", "databaseReducers", "=", "Object", ".", "keys", "(", "reducers", ")", ".", "map", "(", "(", "collectionName", ")", "=>", "{", "const", "reducer", "=", "reducers", "[", "collectionName", "]", "return", "createDatabaseReducer", "(", "reducer", ",", "collectionName", ")", "}", ")", "return", "(", "database", ",", "event", ")", "=>", "{", "const", "changesets", "=", "databaseReducers", ".", "map", "(", "(", "reducer", ")", "=>", "reducer", "(", "database", ",", "event", ")", ")", "return", "combineChangesets", "(", "changesets", ")", "}", "}" ]
Will combine multiple collection reducers to one database reducer. Takes an object whose keys are collection names and whose values are reducer functions. The input reducers have the signature `(Collection, Event) => Changeset`, the resulting combined reducer is `(Database, Event) => Changeset`. @param {object} reducers { [collectionName: string]: Function } @return {Function}
[ "Will", "combine", "multiple", "collection", "reducers", "to", "one", "database", "reducer", ".", "Takes", "an", "object", "whose", "keys", "are", "collection", "names", "and", "whose", "values", "are", "reducer", "functions", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor/lib/combineReducers.js#L18-L29
35,410
flux-capacitor/flux-capacitor
packages/flux-capacitor/lib/combineReducers.js
createDatabaseReducer
function createDatabaseReducer (collectionReducer, collectionName) { return (database, event) => { const collection = database.collections[ collectionName ] if (!collection) { throw new Error(`Collection '${collectionName}' not known by database instance.`) } return collectionReducer(collection, event) } }
javascript
function createDatabaseReducer (collectionReducer, collectionName) { return (database, event) => { const collection = database.collections[ collectionName ] if (!collection) { throw new Error(`Collection '${collectionName}' not known by database instance.`) } return collectionReducer(collection, event) } }
[ "function", "createDatabaseReducer", "(", "collectionReducer", ",", "collectionName", ")", "{", "return", "(", "database", ",", "event", ")", "=>", "{", "const", "collection", "=", "database", ".", "collections", "[", "collectionName", "]", "if", "(", "!", "collection", ")", "{", "throw", "new", "Error", "(", "`", "${", "collectionName", "}", "`", ")", "}", "return", "collectionReducer", "(", "collection", ",", "event", ")", "}", "}" ]
Takes a collection reducer and turns it into a database reducer by binding it to one of the database's collections. @param {Function} collectionReducer (Collection, Event) => Changeset @param {string} collectionName @return {Function} (Database, Event) => Changeset
[ "Takes", "a", "collection", "reducer", "and", "turns", "it", "into", "a", "database", "reducer", "by", "binding", "it", "to", "one", "of", "the", "database", "s", "collections", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor/lib/combineReducers.js#L39-L49
35,411
igorski/zCanvas
dist/es5/Loader.js
isReady
function isReady(aImage) { // first check : load status if (typeof aImage.complete === "boolean" && !aImage.complete) return false; // second check : validity of source (can be 0 until bitmap has been fully parsed by browser) return !(typeof aImage.naturalWidth !== "undefined" && aImage.naturalWidth === 0); }
javascript
function isReady(aImage) { // first check : load status if (typeof aImage.complete === "boolean" && !aImage.complete) return false; // second check : validity of source (can be 0 until bitmap has been fully parsed by browser) return !(typeof aImage.naturalWidth !== "undefined" && aImage.naturalWidth === 0); }
[ "function", "isReady", "(", "aImage", ")", "{", "// first check : load status", "if", "(", "typeof", "aImage", ".", "complete", "===", "\"boolean\"", "&&", "!", "aImage", ".", "complete", ")", "return", "false", ";", "// second check : validity of source (can be 0 until bitmap has been fully parsed by browser)", "return", "!", "(", "typeof", "aImage", ".", "naturalWidth", "!==", "\"undefined\"", "&&", "aImage", ".", "naturalWidth", "===", "0", ")", ";", "}" ]
a quick query to check whether the Image is ready for rendering @public @param {Image} aImage @return {boolean}
[ "a", "quick", "query", "to", "check", "whether", "the", "Image", "is", "ready", "for", "rendering" ]
8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82
https://github.com/igorski/zCanvas/blob/8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82/dist/es5/Loader.js#L123-L130
35,412
igorski/zCanvas
dist/es5/Loader.js
onReady
function onReady(aImage, aCallback, aErrorCallback) { // if this didn't resolve in a full second, we presume the Image is corrupt var MAX_ITERATIONS = 60; var iterations = 0; function readyCheck() { if (Loader.isReady(aImage)) { aCallback(); } else if (++iterations === MAX_ITERATIONS) { if (typeof aErrorCallback === "function") aErrorCallback(); console.warn("Image could not be resolved. This shouldn't occur."); } else { // requestAnimationFrame preferred over a timeout as // browsers will fire this when the DOM is actually ready (e.g. Image is rendered) window.requestAnimationFrame(readyCheck); } } readyCheck(); }
javascript
function onReady(aImage, aCallback, aErrorCallback) { // if this didn't resolve in a full second, we presume the Image is corrupt var MAX_ITERATIONS = 60; var iterations = 0; function readyCheck() { if (Loader.isReady(aImage)) { aCallback(); } else if (++iterations === MAX_ITERATIONS) { if (typeof aErrorCallback === "function") aErrorCallback(); console.warn("Image could not be resolved. This shouldn't occur."); } else { // requestAnimationFrame preferred over a timeout as // browsers will fire this when the DOM is actually ready (e.g. Image is rendered) window.requestAnimationFrame(readyCheck); } } readyCheck(); }
[ "function", "onReady", "(", "aImage", ",", "aCallback", ",", "aErrorCallback", ")", "{", "// if this didn't resolve in a full second, we presume the Image is corrupt", "var", "MAX_ITERATIONS", "=", "60", ";", "var", "iterations", "=", "0", ";", "function", "readyCheck", "(", ")", "{", "if", "(", "Loader", ".", "isReady", "(", "aImage", ")", ")", "{", "aCallback", "(", ")", ";", "}", "else", "if", "(", "++", "iterations", "===", "MAX_ITERATIONS", ")", "{", "if", "(", "typeof", "aErrorCallback", "===", "\"function\"", ")", "aErrorCallback", "(", ")", ";", "console", ".", "warn", "(", "\"Image could not be resolved. This shouldn't occur.\"", ")", ";", "}", "else", "{", "// requestAnimationFrame preferred over a timeout as", "// browsers will fire this when the DOM is actually ready (e.g. Image is rendered)", "window", ".", "requestAnimationFrame", "(", "readyCheck", ")", ";", "}", "}", "readyCheck", "(", ")", ";", "}" ]
Executes given callback when given Image is actually ready for rendering If the image was ready when this function was called, execution is synchronous if not it will be made asynchronous via RAF delegation @public @param {Image} aImage @param {!Function} aCallback @param {!Function=} aErrorCallback optional callback to fire if Image is never ready
[ "Executes", "given", "callback", "when", "given", "Image", "is", "actually", "ready", "for", "rendering", "If", "the", "image", "was", "ready", "when", "this", "function", "was", "called", "execution", "is", "synchronous", "if", "not", "it", "will", "be", "made", "asynchronous", "via", "RAF", "delegation" ]
8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82
https://github.com/igorski/zCanvas/blob/8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82/dist/es5/Loader.js#L143-L166
35,413
scienceai/crossref
source.js
listRequest
function listRequest (path, options = {}, cb) { if (typeof options === 'function') { cb = options; options = {}; } // serialise options let opts = []; for (let k in options) { // The whole URL *minus* the scheme and "://" (for whatever benighted reason) has to be at most // 4096 characters long. Taking the extra bloat that `encodeURIComponent()` adds we truncate the // query to 2000 chars. We could be more precise and regenerate the URL until we reach as close // as possible to 4096, but frankly if you're searching for a string longer than 2000 characters // you're probably doing something wrong. if (k === 'query') { if (options.query.length > 2000) options.query = options.query.substr(0, 2000); opts.push(`query=${encodeURIComponent(options.query)}`); } else if (k === 'filter') { let filts = []; for (let f in options.filter) { if (Array.isArray(options.filter[f])) { options.filter[f].forEach(val => { filts.push(`${f}:${val}`); }); } else { filts.push(`${f}:${options.filter[f]}`); } } opts.push(`filter=${filts.join(',')}`); } else if (k === 'facet' && options.facet) opts.push('facet=t'); else opts.push(`${k}=${options[k]}`); } if (opts.length) path += `?${opts.join('&')}`; return GET(path, (err, msg) => { if (err) return cb(err); let objects = msg.items; delete msg.items; let nextOffset = 0 , isDone = false , nextOptions ; // /types is a list but it does not behave like the other lists // Once again the science.ai League of JStice saves the day papering over inconsistency! if (msg['items-per-page'] && msg.query) { nextOffset = msg.query['start-index'] + msg['items-per-page']; if (nextOffset > msg['total-results']) isDone = true; nextOptions = assign({}, options, { offset: nextOffset }); } else { isDone = true; nextOptions = assign({}, options); } cb(null, objects, nextOptions, isDone, msg); }); }
javascript
function listRequest (path, options = {}, cb) { if (typeof options === 'function') { cb = options; options = {}; } // serialise options let opts = []; for (let k in options) { // The whole URL *minus* the scheme and "://" (for whatever benighted reason) has to be at most // 4096 characters long. Taking the extra bloat that `encodeURIComponent()` adds we truncate the // query to 2000 chars. We could be more precise and regenerate the URL until we reach as close // as possible to 4096, but frankly if you're searching for a string longer than 2000 characters // you're probably doing something wrong. if (k === 'query') { if (options.query.length > 2000) options.query = options.query.substr(0, 2000); opts.push(`query=${encodeURIComponent(options.query)}`); } else if (k === 'filter') { let filts = []; for (let f in options.filter) { if (Array.isArray(options.filter[f])) { options.filter[f].forEach(val => { filts.push(`${f}:${val}`); }); } else { filts.push(`${f}:${options.filter[f]}`); } } opts.push(`filter=${filts.join(',')}`); } else if (k === 'facet' && options.facet) opts.push('facet=t'); else opts.push(`${k}=${options[k]}`); } if (opts.length) path += `?${opts.join('&')}`; return GET(path, (err, msg) => { if (err) return cb(err); let objects = msg.items; delete msg.items; let nextOffset = 0 , isDone = false , nextOptions ; // /types is a list but it does not behave like the other lists // Once again the science.ai League of JStice saves the day papering over inconsistency! if (msg['items-per-page'] && msg.query) { nextOffset = msg.query['start-index'] + msg['items-per-page']; if (nextOffset > msg['total-results']) isDone = true; nextOptions = assign({}, options, { offset: nextOffset }); } else { isDone = true; nextOptions = assign({}, options); } cb(null, objects, nextOptions, isDone, msg); }); }
[ "function", "listRequest", "(", "path", ",", "options", "=", "{", "}", ",", "cb", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "cb", "=", "options", ";", "options", "=", "{", "}", ";", "}", "// serialise options", "let", "opts", "=", "[", "]", ";", "for", "(", "let", "k", "in", "options", ")", "{", "// The whole URL *minus* the scheme and \"://\" (for whatever benighted reason) has to be at most", "// 4096 characters long. Taking the extra bloat that `encodeURIComponent()` adds we truncate the", "// query to 2000 chars. We could be more precise and regenerate the URL until we reach as close", "// as possible to 4096, but frankly if you're searching for a string longer than 2000 characters", "// you're probably doing something wrong.", "if", "(", "k", "===", "'query'", ")", "{", "if", "(", "options", ".", "query", ".", "length", ">", "2000", ")", "options", ".", "query", "=", "options", ".", "query", ".", "substr", "(", "0", ",", "2000", ")", ";", "opts", ".", "push", "(", "`", "${", "encodeURIComponent", "(", "options", ".", "query", ")", "}", "`", ")", ";", "}", "else", "if", "(", "k", "===", "'filter'", ")", "{", "let", "filts", "=", "[", "]", ";", "for", "(", "let", "f", "in", "options", ".", "filter", ")", "{", "if", "(", "Array", ".", "isArray", "(", "options", ".", "filter", "[", "f", "]", ")", ")", "{", "options", ".", "filter", "[", "f", "]", ".", "forEach", "(", "val", "=>", "{", "filts", ".", "push", "(", "`", "${", "f", "}", "${", "val", "}", "`", ")", ";", "}", ")", ";", "}", "else", "{", "filts", ".", "push", "(", "`", "${", "f", "}", "${", "options", ".", "filter", "[", "f", "]", "}", "`", ")", ";", "}", "}", "opts", ".", "push", "(", "`", "${", "filts", ".", "join", "(", "','", ")", "}", "`", ")", ";", "}", "else", "if", "(", "k", "===", "'facet'", "&&", "options", ".", "facet", ")", "opts", ".", "push", "(", "'facet=t'", ")", ";", "else", "opts", ".", "push", "(", "`", "${", "k", "}", "${", "options", "[", "k", "]", "}", "`", ")", ";", "}", "if", "(", "opts", ".", "length", ")", "path", "+=", "`", "${", "opts", ".", "join", "(", "'&'", ")", "}", "`", ";", "return", "GET", "(", "path", ",", "(", "err", ",", "msg", ")", "=>", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "let", "objects", "=", "msg", ".", "items", ";", "delete", "msg", ".", "items", ";", "let", "nextOffset", "=", "0", ",", "isDone", "=", "false", ",", "nextOptions", ";", "// /types is a list but it does not behave like the other lists", "// Once again the science.ai League of JStice saves the day papering over inconsistency!", "if", "(", "msg", "[", "'items-per-page'", "]", "&&", "msg", ".", "query", ")", "{", "nextOffset", "=", "msg", ".", "query", "[", "'start-index'", "]", "+", "msg", "[", "'items-per-page'", "]", ";", "if", "(", "nextOffset", ">", "msg", "[", "'total-results'", "]", ")", "isDone", "=", "true", ";", "nextOptions", "=", "assign", "(", "{", "}", ",", "options", ",", "{", "offset", ":", "nextOffset", "}", ")", ";", "}", "else", "{", "isDone", "=", "true", ";", "nextOptions", "=", "assign", "(", "{", "}", ",", "options", ")", ";", "}", "cb", "(", "null", ",", "objects", ",", "nextOptions", ",", "isDone", ",", "msg", ")", ";", "}", ")", ";", "}" ]
backend for list requests
[ "backend", "for", "list", "requests" ]
cfda7f2a705663e9bc595a6599329e094f3e3725
https://github.com/scienceai/crossref/blob/cfda7f2a705663e9bc595a6599329e094f3e3725/source.js#L41-L97
35,414
crysalead-js/string-placeholder
index.js
template
function template(str, data, options) { var data = data || {}; var options = options || {}; var keys = Array.isArray(data) ? Array.apply(null, { length: data.length }).map(Number.call, Number) : Object.keys(data); var len = keys.length; if (!len) { return str; } var before = options.before !== undefined ? options.before : '${'; var after = options.after !== undefined ? options.after : '}'; var escape = options.escape !== undefined ? options.escape : '\\'; var clean = options.clean !== undefined ? options.clean : false; cache[escape] = cache[escape] || escapeRegExp(escape); cache[before] = cache[before] || escapeRegExp(before); cache[after] = cache[after] || escapeRegExp(after); var begin = escape ? '(' + cache[escape] + ')?' + cache[before] : cache[before]; var end = cache[after]; for (var i = 0; i < len; i++) { str = str.replace(new RegExp(begin + String(keys[i]) + end, 'g'), function(match, behind) { return behind ? match : String(data[keys[i]]) }); } if (escape) { str = str.replace(new RegExp(escapeRegExp(escape) + escapeRegExp(before), 'g'), before); } return clean ? template.clean(str, options) : str; }
javascript
function template(str, data, options) { var data = data || {}; var options = options || {}; var keys = Array.isArray(data) ? Array.apply(null, { length: data.length }).map(Number.call, Number) : Object.keys(data); var len = keys.length; if (!len) { return str; } var before = options.before !== undefined ? options.before : '${'; var after = options.after !== undefined ? options.after : '}'; var escape = options.escape !== undefined ? options.escape : '\\'; var clean = options.clean !== undefined ? options.clean : false; cache[escape] = cache[escape] || escapeRegExp(escape); cache[before] = cache[before] || escapeRegExp(before); cache[after] = cache[after] || escapeRegExp(after); var begin = escape ? '(' + cache[escape] + ')?' + cache[before] : cache[before]; var end = cache[after]; for (var i = 0; i < len; i++) { str = str.replace(new RegExp(begin + String(keys[i]) + end, 'g'), function(match, behind) { return behind ? match : String(data[keys[i]]) }); } if (escape) { str = str.replace(new RegExp(escapeRegExp(escape) + escapeRegExp(before), 'g'), before); } return clean ? template.clean(str, options) : str; }
[ "function", "template", "(", "str", ",", "data", ",", "options", ")", "{", "var", "data", "=", "data", "||", "{", "}", ";", "var", "options", "=", "options", "||", "{", "}", ";", "var", "keys", "=", "Array", ".", "isArray", "(", "data", ")", "?", "Array", ".", "apply", "(", "null", ",", "{", "length", ":", "data", ".", "length", "}", ")", ".", "map", "(", "Number", ".", "call", ",", "Number", ")", ":", "Object", ".", "keys", "(", "data", ")", ";", "var", "len", "=", "keys", ".", "length", ";", "if", "(", "!", "len", ")", "{", "return", "str", ";", "}", "var", "before", "=", "options", ".", "before", "!==", "undefined", "?", "options", ".", "before", ":", "'${'", ";", "var", "after", "=", "options", ".", "after", "!==", "undefined", "?", "options", ".", "after", ":", "'}'", ";", "var", "escape", "=", "options", ".", "escape", "!==", "undefined", "?", "options", ".", "escape", ":", "'\\\\'", ";", "var", "clean", "=", "options", ".", "clean", "!==", "undefined", "?", "options", ".", "clean", ":", "false", ";", "cache", "[", "escape", "]", "=", "cache", "[", "escape", "]", "||", "escapeRegExp", "(", "escape", ")", ";", "cache", "[", "before", "]", "=", "cache", "[", "before", "]", "||", "escapeRegExp", "(", "before", ")", ";", "cache", "[", "after", "]", "=", "cache", "[", "after", "]", "||", "escapeRegExp", "(", "after", ")", ";", "var", "begin", "=", "escape", "?", "'('", "+", "cache", "[", "escape", "]", "+", "')?'", "+", "cache", "[", "before", "]", ":", "cache", "[", "before", "]", ";", "var", "end", "=", "cache", "[", "after", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "str", "=", "str", ".", "replace", "(", "new", "RegExp", "(", "begin", "+", "String", "(", "keys", "[", "i", "]", ")", "+", "end", ",", "'g'", ")", ",", "function", "(", "match", ",", "behind", ")", "{", "return", "behind", "?", "match", ":", "String", "(", "data", "[", "keys", "[", "i", "]", "]", ")", "}", ")", ";", "}", "if", "(", "escape", ")", "{", "str", "=", "str", ".", "replace", "(", "new", "RegExp", "(", "escapeRegExp", "(", "escape", ")", "+", "escapeRegExp", "(", "before", ")", ",", "'g'", ")", ",", "before", ")", ";", "}", "return", "clean", "?", "template", ".", "clean", "(", "str", ",", "options", ")", ":", "str", ";", "}" ]
Replaces variable placeholders inside a string with any given data. Each key in `data` corresponds to a variable placeholder name in `str`. Usage: {{{ template('My name is ${name} and I am ${age} years old.', { name: 'Bob', age: '65' }); }}} @param String str A string containing variable place-holders. @param Object data A key, value array where each key stands for a place-holder variable name to be replaced with value. @param Object options Available options are: - `'before'`: The character or string in front of the name of the variable place-holder (defaults to `'${'`). - `'after'`: The character or string after the name of the variable place-holder (defaults to `}`). - `'escape'`: The character or string used to escape the before character or string (defaults to `'\\'`). - `'clean'`: A boolean or array with instructions for cleaning. @return String
[ "Replaces", "variable", "placeholders", "inside", "a", "string", "with", "any", "given", "data", ".", "Each", "key", "in", "data", "corresponds", "to", "a", "variable", "placeholder", "name", "in", "str", "." ]
73e399bd8ef35ac74118139aa606c00874682e1d
https://github.com/crysalead-js/string-placeholder/blob/73e399bd8ef35ac74118139aa606c00874682e1d/index.js#L28-L61
35,415
flux-capacitor/flux-capacitor
packages/flux-capacitor-boot/src/express/bootstrap.js
bootstrap
function bootstrap (bootstrappers) { const bootstrapPromise = bootstrappers.reduce( (metaPromise, bootstrapper) => metaPromise.then((prevMeta) => Promise.resolve(bootstrapper(prevMeta)).then((newMeta) => Object.assign({}, prevMeta, newMeta)) ), Promise.resolve({}) ).then((meta) => checkIfReadyToBoot(meta)) /** * @param {int} [port] * @param {string} [hostname] * @return {Promise<Http.Server>} * @see https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback */ bootstrapPromise.listen = function listen (port, hostname) { return bootstrapPromise.then((meta) => promisifiedListen(meta.app, port, hostname)) } return bootstrapPromise }
javascript
function bootstrap (bootstrappers) { const bootstrapPromise = bootstrappers.reduce( (metaPromise, bootstrapper) => metaPromise.then((prevMeta) => Promise.resolve(bootstrapper(prevMeta)).then((newMeta) => Object.assign({}, prevMeta, newMeta)) ), Promise.resolve({}) ).then((meta) => checkIfReadyToBoot(meta)) /** * @param {int} [port] * @param {string} [hostname] * @return {Promise<Http.Server>} * @see https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback */ bootstrapPromise.listen = function listen (port, hostname) { return bootstrapPromise.then((meta) => promisifiedListen(meta.app, port, hostname)) } return bootstrapPromise }
[ "function", "bootstrap", "(", "bootstrappers", ")", "{", "const", "bootstrapPromise", "=", "bootstrappers", ".", "reduce", "(", "(", "metaPromise", ",", "bootstrapper", ")", "=>", "metaPromise", ".", "then", "(", "(", "prevMeta", ")", "=>", "Promise", ".", "resolve", "(", "bootstrapper", "(", "prevMeta", ")", ")", ".", "then", "(", "(", "newMeta", ")", "=>", "Object", ".", "assign", "(", "{", "}", ",", "prevMeta", ",", "newMeta", ")", ")", ")", ",", "Promise", ".", "resolve", "(", "{", "}", ")", ")", ".", "then", "(", "(", "meta", ")", "=>", "checkIfReadyToBoot", "(", "meta", ")", ")", "/**\n * @param {int} [port]\n * @param {string} [hostname]\n * @return {Promise<Http.Server>}\n * @see https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback\n */", "bootstrapPromise", ".", "listen", "=", "function", "listen", "(", "port", ",", "hostname", ")", "{", "return", "bootstrapPromise", ".", "then", "(", "(", "meta", ")", "=>", "promisifiedListen", "(", "meta", ".", "app", ",", "port", ",", "hostname", ")", ")", "}", "return", "bootstrapPromise", "}" ]
Takes an array of bootstrapping functions and returns a Promise extended by a `listen` method. @param {Function[]} bootstrappers @return {FluxCapAppPromise} { listen: ([port: int][, hostname: string]) => Promise<Http.Server>, catch: (Error) => Promise, then: (Function) => Promise }
[ "Takes", "an", "array", "of", "bootstrapping", "functions", "and", "returns", "a", "Promise", "extended", "by", "a", "listen", "method", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-boot/src/express/bootstrap.js#L10-L29
35,416
phulas/x-ray-nightmare
index.js
driver
function driver(options, fn) { if ('function' == typeof options) fn = options, options = {}; options = options || {}; fn = fn || electron; var nightmare = new Nightmare(options); return function nightmare_driver(ctx, done) { if (ctx !=null) { debug('goingto %s', ctx.url); nightmare .on('page', function (type, message, stack) { if (type == 'error') debug('page error: %s', message); }) .on('did-fail-load', function (event, errorCode, errorDescription) { debug('failed to load with error %s: %s', errorCode, errorDescription); return done(new Error(errorDescription)) }) .on('did-get-redirect-request', function (event, oldUrl, newUrl, isMainFrame) { if (normalize(oldUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } }) .on('will-navigate', function (url) { if (normalize(url) == normalize(ctx.url)) { debug('redirect: %s', url); ctx.url = url; } }) .on('did-get-response-details', function (event, status, newUrl, originalUrl, httpResponseCode, requestMethod, referrer, headers) { if (normalize(originalUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } ; if (normalize(newUrl) == normalize(ctx.url) && httpResponseCode == 200) { debug('got response from %s: %s', ctx.url, httpResponseCode); ctx.status = httpResponseCode; } ; }) .on('did-finish-load', function () { debug('finished loading %s', ctx.url); }) wrapfn(fn, select)(ctx, nightmare); } function select(err, ret) { if (err) return done(err); nightmare .evaluate(function() { return document.documentElement.outerHTML; }) nightmare .then(function(body) { ctx.body = body; debug('%s - %s', ctx.url, ctx.status); done(null, ctx); }) }; if (ctx == null || ctx == undefined) { debug('attempting to shut down nightmare instance gracefully'); // put bogus message in the queue so nightmare end will execute nightmare.viewport(1,1); // force shutdown and disconnect from electron nightmare. end(). then(function(body) { debug('gracefully shut down nightmare instance '); }); } } }
javascript
function driver(options, fn) { if ('function' == typeof options) fn = options, options = {}; options = options || {}; fn = fn || electron; var nightmare = new Nightmare(options); return function nightmare_driver(ctx, done) { if (ctx !=null) { debug('goingto %s', ctx.url); nightmare .on('page', function (type, message, stack) { if (type == 'error') debug('page error: %s', message); }) .on('did-fail-load', function (event, errorCode, errorDescription) { debug('failed to load with error %s: %s', errorCode, errorDescription); return done(new Error(errorDescription)) }) .on('did-get-redirect-request', function (event, oldUrl, newUrl, isMainFrame) { if (normalize(oldUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } }) .on('will-navigate', function (url) { if (normalize(url) == normalize(ctx.url)) { debug('redirect: %s', url); ctx.url = url; } }) .on('did-get-response-details', function (event, status, newUrl, originalUrl, httpResponseCode, requestMethod, referrer, headers) { if (normalize(originalUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } ; if (normalize(newUrl) == normalize(ctx.url) && httpResponseCode == 200) { debug('got response from %s: %s', ctx.url, httpResponseCode); ctx.status = httpResponseCode; } ; }) .on('did-finish-load', function () { debug('finished loading %s', ctx.url); }) wrapfn(fn, select)(ctx, nightmare); } function select(err, ret) { if (err) return done(err); nightmare .evaluate(function() { return document.documentElement.outerHTML; }) nightmare .then(function(body) { ctx.body = body; debug('%s - %s', ctx.url, ctx.status); done(null, ctx); }) }; if (ctx == null || ctx == undefined) { debug('attempting to shut down nightmare instance gracefully'); // put bogus message in the queue so nightmare end will execute nightmare.viewport(1,1); // force shutdown and disconnect from electron nightmare. end(). then(function(body) { debug('gracefully shut down nightmare instance '); }); } } }
[ "function", "driver", "(", "options", ",", "fn", ")", "{", "if", "(", "'function'", "==", "typeof", "options", ")", "fn", "=", "options", ",", "options", "=", "{", "}", ";", "options", "=", "options", "||", "{", "}", ";", "fn", "=", "fn", "||", "electron", ";", "var", "nightmare", "=", "new", "Nightmare", "(", "options", ")", ";", "return", "function", "nightmare_driver", "(", "ctx", ",", "done", ")", "{", "if", "(", "ctx", "!=", "null", ")", "{", "debug", "(", "'goingto %s'", ",", "ctx", ".", "url", ")", ";", "nightmare", ".", "on", "(", "'page'", ",", "function", "(", "type", ",", "message", ",", "stack", ")", "{", "if", "(", "type", "==", "'error'", ")", "debug", "(", "'page error: %s'", ",", "message", ")", ";", "}", ")", ".", "on", "(", "'did-fail-load'", ",", "function", "(", "event", ",", "errorCode", ",", "errorDescription", ")", "{", "debug", "(", "'failed to load with error %s: %s'", ",", "errorCode", ",", "errorDescription", ")", ";", "return", "done", "(", "new", "Error", "(", "errorDescription", ")", ")", "}", ")", ".", "on", "(", "'did-get-redirect-request'", ",", "function", "(", "event", ",", "oldUrl", ",", "newUrl", ",", "isMainFrame", ")", "{", "if", "(", "normalize", "(", "oldUrl", ")", "==", "normalize", "(", "ctx", ".", "url", ")", ")", "{", "debug", "(", "'redirect: %s'", ",", "newUrl", ")", ";", "ctx", ".", "url", "=", "newUrl", ";", "}", "}", ")", ".", "on", "(", "'will-navigate'", ",", "function", "(", "url", ")", "{", "if", "(", "normalize", "(", "url", ")", "==", "normalize", "(", "ctx", ".", "url", ")", ")", "{", "debug", "(", "'redirect: %s'", ",", "url", ")", ";", "ctx", ".", "url", "=", "url", ";", "}", "}", ")", ".", "on", "(", "'did-get-response-details'", ",", "function", "(", "event", ",", "status", ",", "newUrl", ",", "originalUrl", ",", "httpResponseCode", ",", "requestMethod", ",", "referrer", ",", "headers", ")", "{", "if", "(", "normalize", "(", "originalUrl", ")", "==", "normalize", "(", "ctx", ".", "url", ")", ")", "{", "debug", "(", "'redirect: %s'", ",", "newUrl", ")", ";", "ctx", ".", "url", "=", "newUrl", ";", "}", ";", "if", "(", "normalize", "(", "newUrl", ")", "==", "normalize", "(", "ctx", ".", "url", ")", "&&", "httpResponseCode", "==", "200", ")", "{", "debug", "(", "'got response from %s: %s'", ",", "ctx", ".", "url", ",", "httpResponseCode", ")", ";", "ctx", ".", "status", "=", "httpResponseCode", ";", "}", ";", "}", ")", ".", "on", "(", "'did-finish-load'", ",", "function", "(", ")", "{", "debug", "(", "'finished loading %s'", ",", "ctx", ".", "url", ")", ";", "}", ")", "wrapfn", "(", "fn", ",", "select", ")", "(", "ctx", ",", "nightmare", ")", ";", "}", "function", "select", "(", "err", ",", "ret", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "nightmare", ".", "evaluate", "(", "function", "(", ")", "{", "return", "document", ".", "documentElement", ".", "outerHTML", ";", "}", ")", "nightmare", ".", "then", "(", "function", "(", "body", ")", "{", "ctx", ".", "body", "=", "body", ";", "debug", "(", "'%s - %s'", ",", "ctx", ".", "url", ",", "ctx", ".", "status", ")", ";", "done", "(", "null", ",", "ctx", ")", ";", "}", ")", "}", ";", "if", "(", "ctx", "==", "null", "||", "ctx", "==", "undefined", ")", "{", "debug", "(", "'attempting to shut down nightmare instance gracefully'", ")", ";", "// put bogus message in the queue so nightmare end will execute", "nightmare", ".", "viewport", "(", "1", ",", "1", ")", ";", "// force shutdown and disconnect from electron", "nightmare", ".", "end", "(", ")", ".", "then", "(", "function", "(", "body", ")", "{", "debug", "(", "'gracefully shut down nightmare instance '", ")", ";", "}", ")", ";", "}", "}", "}" ]
Initialize the `driver` with the following `options` @param {Object} options @param {Function} fn @return {Function} @api public
[ "Initialize", "the", "driver", "with", "the", "following", "options" ]
d92f39a46e5e126254cdda6de34d39476fa1f6f8
https://github.com/phulas/x-ray-nightmare/blob/d92f39a46e5e126254cdda6de34d39476fa1f6f8/index.js#L26-L110
35,417
flux-capacitor/flux-capacitor
packages/flux-capacitor/lib/database/combineChangesets.js
combineChangesets
function combineChangesets (changesets) { const actions = changesets.map((changeset) => changeset.apply) const combinedAction = function () { const args = arguments return actions.reduce((promise, action) => ( promise.then(() => action.apply(null, args)) ), Promise.resolve()) } return createChangeset(combinedAction) }
javascript
function combineChangesets (changesets) { const actions = changesets.map((changeset) => changeset.apply) const combinedAction = function () { const args = arguments return actions.reduce((promise, action) => ( promise.then(() => action.apply(null, args)) ), Promise.resolve()) } return createChangeset(combinedAction) }
[ "function", "combineChangesets", "(", "changesets", ")", "{", "const", "actions", "=", "changesets", ".", "map", "(", "(", "changeset", ")", "=>", "changeset", ".", "apply", ")", "const", "combinedAction", "=", "function", "(", ")", "{", "const", "args", "=", "arguments", "return", "actions", ".", "reduce", "(", "(", "promise", ",", "action", ")", "=>", "(", "promise", ".", "then", "(", "(", ")", "=>", "action", ".", "apply", "(", "null", ",", "args", ")", ")", ")", ",", "Promise", ".", "resolve", "(", ")", ")", "}", "return", "createChangeset", "(", "combinedAction", ")", "}" ]
Takes an array of changesets and returns a single changeset that contains all of the input changeset's DB operations. @param {Changeset[]} changesets @return {Changeset}
[ "Takes", "an", "array", "of", "changesets", "and", "returns", "a", "single", "changeset", "that", "contains", "all", "of", "the", "input", "changeset", "s", "DB", "operations", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor/lib/database/combineChangesets.js#L12-L24
35,418
igorski/zCanvas
src/Loader.js
isDataSource
function isDataSource( image ) { const source = (typeof image === "string" ? image : image.src).substr(0, 5); // base 64 string contains data-attribute, the MIME type and then the content, e.g. : // e.g. "data:image/png;base64," for a typical PNG, Blob string contains no MIME, e.g.: // blob:http://localhost:9001/46cc7e56-cf2a-7540-b515-1d99dfcb2ad6 return source === "data:" || source === "blob:"; }
javascript
function isDataSource( image ) { const source = (typeof image === "string" ? image : image.src).substr(0, 5); // base 64 string contains data-attribute, the MIME type and then the content, e.g. : // e.g. "data:image/png;base64," for a typical PNG, Blob string contains no MIME, e.g.: // blob:http://localhost:9001/46cc7e56-cf2a-7540-b515-1d99dfcb2ad6 return source === "data:" || source === "blob:"; }
[ "function", "isDataSource", "(", "image", ")", "{", "const", "source", "=", "(", "typeof", "image", "===", "\"string\"", "?", "image", ":", "image", ".", "src", ")", ".", "substr", "(", "0", ",", "5", ")", ";", "// base 64 string contains data-attribute, the MIME type and then the content, e.g. :", "// e.g. \"data:image/png;base64,\" for a typical PNG, Blob string contains no MIME, e.g.:", "// blob:http://localhost:9001/46cc7e56-cf2a-7540-b515-1d99dfcb2ad6", "return", "source", "===", "\"data:\"", "||", "source", "===", "\"blob:\"", ";", "}" ]
checks whether the contents of an Image are either a base64 encoded string or a Blob @private @param {Image|string} image when string, it is the src attribute of an Image @return {boolean}
[ "checks", "whether", "the", "contents", "of", "an", "Image", "are", "either", "a", "base64", "encoded", "string", "or", "a", "Blob" ]
8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82
https://github.com/igorski/zCanvas/blob/8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82/src/Loader.js#L196-L204
35,419
HarasimowiczKamil/any-base
index.js
anyBase
function anyBase(srcAlphabet, dstAlphabet) { var converter = new Converter(srcAlphabet, dstAlphabet); /** * Convert function * * @param {string|Array} number * * @return {string|Array} number */ return function (number) { return converter.convert(number); } }
javascript
function anyBase(srcAlphabet, dstAlphabet) { var converter = new Converter(srcAlphabet, dstAlphabet); /** * Convert function * * @param {string|Array} number * * @return {string|Array} number */ return function (number) { return converter.convert(number); } }
[ "function", "anyBase", "(", "srcAlphabet", ",", "dstAlphabet", ")", "{", "var", "converter", "=", "new", "Converter", "(", "srcAlphabet", ",", "dstAlphabet", ")", ";", "/**\n * Convert function\n *\n * @param {string|Array} number\n *\n * @return {string|Array} number\n */", "return", "function", "(", "number", ")", "{", "return", "converter", ".", "convert", "(", "number", ")", ";", "}", "}" ]
Function get source and destination alphabet and return convert function @param {string|Array} srcAlphabet @param {string|Array} dstAlphabet @returns {function(number|Array)}
[ "Function", "get", "source", "and", "destination", "alphabet", "and", "return", "convert", "function" ]
7595a7398959618a93cb4edef0bae3e035eb3ce0
https://github.com/HarasimowiczKamil/any-base/blob/7595a7398959618a93cb4edef0bae3e035eb3ce0/index.js#L11-L23
35,420
Cloud9Trader/oanda-adapter
lib/utils.js
function (fn, context, rate, warningThreshold) { var queue = [], timeout; function next () { if (queue.length === 0) { timeout = null; return; } fn.apply(context, queue.shift()); timeout = setTimeout(next, rate); } return function () { if (!timeout) { timeout = setTimeout(next, rate); fn.apply(context, arguments); return; } queue.push(arguments); if (queue.length * rate > warningThreshold) { console.warn("[WARNING] Rate limited function call will be delayed by", ((queue.length * rate) / 1000).toFixed(3), "secs"); } }; }
javascript
function (fn, context, rate, warningThreshold) { var queue = [], timeout; function next () { if (queue.length === 0) { timeout = null; return; } fn.apply(context, queue.shift()); timeout = setTimeout(next, rate); } return function () { if (!timeout) { timeout = setTimeout(next, rate); fn.apply(context, arguments); return; } queue.push(arguments); if (queue.length * rate > warningThreshold) { console.warn("[WARNING] Rate limited function call will be delayed by", ((queue.length * rate) / 1000).toFixed(3), "secs"); } }; }
[ "function", "(", "fn", ",", "context", ",", "rate", ",", "warningThreshold", ")", "{", "var", "queue", "=", "[", "]", ",", "timeout", ";", "function", "next", "(", ")", "{", "if", "(", "queue", ".", "length", "===", "0", ")", "{", "timeout", "=", "null", ";", "return", ";", "}", "fn", ".", "apply", "(", "context", ",", "queue", ".", "shift", "(", ")", ")", ";", "timeout", "=", "setTimeout", "(", "next", ",", "rate", ")", ";", "}", "return", "function", "(", ")", "{", "if", "(", "!", "timeout", ")", "{", "timeout", "=", "setTimeout", "(", "next", ",", "rate", ")", ";", "fn", ".", "apply", "(", "context", ",", "arguments", ")", ";", "return", ";", "}", "queue", ".", "push", "(", "arguments", ")", ";", "if", "(", "queue", ".", "length", "*", "rate", ">", "warningThreshold", ")", "{", "console", ".", "warn", "(", "\"[WARNING] Rate limited function call will be delayed by\"", ",", "(", "(", "queue", ".", "length", "*", "rate", ")", "/", "1000", ")", ".", "toFixed", "(", "3", ")", ",", "\"secs\"", ")", ";", "}", "}", ";", "}" ]
Function wrapper will limit fn invocations to one per rate. All will be queued for delayed execution where limit is exceeded, with warning logged where delay exceeds warningThreshold
[ "Function", "wrapper", "will", "limit", "fn", "invocations", "to", "one", "per", "rate", ".", "All", "will", "be", "queued", "for", "delayed", "execution", "where", "limit", "is", "exceeded", "with", "warning", "logged", "where", "delay", "exceeds", "warningThreshold" ]
33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1
https://github.com/Cloud9Trader/oanda-adapter/blob/33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1/lib/utils.js#L5-L36
35,421
piecioshka/super-event-emitter
src/index.js
function (name, fn, ctx) { assert(isString(name), 'EventEmitter#on: name is not a string'); assert(isFunction(fn), 'EventEmitter#on: fn is not a function'); // If the context is not passed, use `this`. ctx = ctx || this; // Push to private lists of listeners. this._listeners.push({ name: name, fn: fn, ctx: ctx }); return this; }
javascript
function (name, fn, ctx) { assert(isString(name), 'EventEmitter#on: name is not a string'); assert(isFunction(fn), 'EventEmitter#on: fn is not a function'); // If the context is not passed, use `this`. ctx = ctx || this; // Push to private lists of listeners. this._listeners.push({ name: name, fn: fn, ctx: ctx }); return this; }
[ "function", "(", "name", ",", "fn", ",", "ctx", ")", "{", "assert", "(", "isString", "(", "name", ")", ",", "'EventEmitter#on: name is not a string'", ")", ";", "assert", "(", "isFunction", "(", "fn", ")", ",", "'EventEmitter#on: fn is not a function'", ")", ";", "// If the context is not passed, use `this`.", "ctx", "=", "ctx", "||", "this", ";", "// Push to private lists of listeners.", "this", ".", "_listeners", ".", "push", "(", "{", "name", ":", "name", ",", "fn", ":", "fn", ",", "ctx", ":", "ctx", "}", ")", ";", "return", "this", ";", "}" ]
Register listener on concrete name with specified handler. @param {string} name @param {Function} fn @param {Object} [ctx]
[ "Register", "listener", "on", "concrete", "name", "with", "specified", "handler", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L76-L91
35,422
piecioshka/super-event-emitter
src/index.js
function (name, fn, ctx) { // If the context is not passed, use `this`. ctx = ctx || this; var self = this; function onHandler() { fn.apply(ctx, arguments); self.off(name, onHandler); } this.on(name, onHandler, ctx); return this; }
javascript
function (name, fn, ctx) { // If the context is not passed, use `this`. ctx = ctx || this; var self = this; function onHandler() { fn.apply(ctx, arguments); self.off(name, onHandler); } this.on(name, onHandler, ctx); return this; }
[ "function", "(", "name", ",", "fn", ",", "ctx", ")", "{", "// If the context is not passed, use `this`.", "ctx", "=", "ctx", "||", "this", ";", "var", "self", "=", "this", ";", "function", "onHandler", "(", ")", "{", "fn", ".", "apply", "(", "ctx", ",", "arguments", ")", ";", "self", ".", "off", "(", "name", ",", "onHandler", ")", ";", "}", "this", ".", "on", "(", "name", ",", "onHandler", ",", "ctx", ")", ";", "return", "this", ";", "}" ]
Register listener. Remove them after once event triggered. @param {string} name @param {Function} fn @param {Object} [ctx]
[ "Register", "listener", ".", "Remove", "them", "after", "once", "event", "triggered", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L101-L115
35,423
piecioshka/super-event-emitter
src/index.js
function (name, fn) { this._listeners = !name ? [] : filter(this._listeners, function (listener) { if (listener.name !== name) { return true; } else { if (isFunction(fn)) { return listener.fn !== fn; } else { return false; } } }); return this; }
javascript
function (name, fn) { this._listeners = !name ? [] : filter(this._listeners, function (listener) { if (listener.name !== name) { return true; } else { if (isFunction(fn)) { return listener.fn !== fn; } else { return false; } } }); return this; }
[ "function", "(", "name", ",", "fn", ")", "{", "this", ".", "_listeners", "=", "!", "name", "?", "[", "]", ":", "filter", "(", "this", ".", "_listeners", ",", "function", "(", "listener", ")", "{", "if", "(", "listener", ".", "name", "!==", "name", ")", "{", "return", "true", ";", "}", "else", "{", "if", "(", "isFunction", "(", "fn", ")", ")", "{", "return", "listener", ".", "fn", "!==", "fn", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}", ")", ";", "return", "this", ";", "}" ]
Unregister listener. Remove concrete listener by name and itself definition. @param {string} [name] @param {Function} [fn]
[ "Unregister", "listener", ".", "Remove", "concrete", "listener", "by", "name", "and", "itself", "definition", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L124-L140
35,424
piecioshka/super-event-emitter
src/index.js
function (name, params) { assert(isString(name), 'EventEmitter#emit: name is not a string'); forEach(this._listeners, function (event) { if (event.name === name) { event.fn.call(event.ctx, params); } // Special behaviour for wildcard - invoke each event handler. var isWildcard = (/^all|\*$/).test(event.name); if (isWildcard) { event.fn.call(event.ctx, name, params); } }); return this; }
javascript
function (name, params) { assert(isString(name), 'EventEmitter#emit: name is not a string'); forEach(this._listeners, function (event) { if (event.name === name) { event.fn.call(event.ctx, params); } // Special behaviour for wildcard - invoke each event handler. var isWildcard = (/^all|\*$/).test(event.name); if (isWildcard) { event.fn.call(event.ctx, name, params); } }); return this; }
[ "function", "(", "name", ",", "params", ")", "{", "assert", "(", "isString", "(", "name", ")", ",", "'EventEmitter#emit: name is not a string'", ")", ";", "forEach", "(", "this", ".", "_listeners", ",", "function", "(", "event", ")", "{", "if", "(", "event", ".", "name", "===", "name", ")", "{", "event", ".", "fn", ".", "call", "(", "event", ".", "ctx", ",", "params", ")", ";", "}", "// Special behaviour for wildcard - invoke each event handler.", "var", "isWildcard", "=", "(", "/", "^all|\\*$", "/", ")", ".", "test", "(", "event", ".", "name", ")", ";", "if", "(", "isWildcard", ")", "{", "event", ".", "fn", ".", "call", "(", "event", ".", "ctx", ",", "name", ",", "params", ")", ";", "}", "}", ")", ";", "return", "this", ";", "}" ]
Trigger event. All of listeners waiting for emit event will be executed. @param {string} name @param {Object} [params]
[ "Trigger", "event", ".", "All", "of", "listeners", "waiting", "for", "emit", "event", "will", "be", "executed", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L149-L166
35,425
stamoern/wdio-element-screenshot
src/index.js
getElementBoundingRect
function getElementBoundingRect(elementSelector) { /** * @param {Window} win * @param {Object} [dims] * @returns {Object} */ function computeFrameOffset(win, dims) { // initialize our result variable dims = dims || { left: win.pageXOffset, top: win.pageYOffset }; // add the offset & recurse up the frame chain var frame = win.frameElement; if (frame) { var rect = frame.getBoundingClientRect(); dims.left += rect.left + frame.contentWindow.pageXOffset; dims.top += rect.top + frame.contentWindow.pageYOffset; if (win !== window.top) { computeFrameOffset(win.parent, dims); } } return dims; } /** * @param {HTMLElement} element * @param {Object} frameOffset * @returns {Object} */ function computeElementRect(element, frameOffset) { var rect = element.getBoundingClientRect(); return { left: rect.left + frameOffset.left, right: rect.right + frameOffset.left, top: rect.top + frameOffset.top, bottom: rect.bottom + frameOffset.top, width: rect.width, height: rect.height }; } var element = document.querySelectorAll(elementSelector)[0]; if (element) { var frameOffset = computeFrameOffset(window); var elementRect = computeElementRect(element, frameOffset); return elementRect; } }
javascript
function getElementBoundingRect(elementSelector) { /** * @param {Window} win * @param {Object} [dims] * @returns {Object} */ function computeFrameOffset(win, dims) { // initialize our result variable dims = dims || { left: win.pageXOffset, top: win.pageYOffset }; // add the offset & recurse up the frame chain var frame = win.frameElement; if (frame) { var rect = frame.getBoundingClientRect(); dims.left += rect.left + frame.contentWindow.pageXOffset; dims.top += rect.top + frame.contentWindow.pageYOffset; if (win !== window.top) { computeFrameOffset(win.parent, dims); } } return dims; } /** * @param {HTMLElement} element * @param {Object} frameOffset * @returns {Object} */ function computeElementRect(element, frameOffset) { var rect = element.getBoundingClientRect(); return { left: rect.left + frameOffset.left, right: rect.right + frameOffset.left, top: rect.top + frameOffset.top, bottom: rect.bottom + frameOffset.top, width: rect.width, height: rect.height }; } var element = document.querySelectorAll(elementSelector)[0]; if (element) { var frameOffset = computeFrameOffset(window); var elementRect = computeElementRect(element, frameOffset); return elementRect; } }
[ "function", "getElementBoundingRect", "(", "elementSelector", ")", "{", "/**\n * @param {Window} win\n * @param {Object} [dims]\n * @returns {Object}\n */", "function", "computeFrameOffset", "(", "win", ",", "dims", ")", "{", "// initialize our result variable", "dims", "=", "dims", "||", "{", "left", ":", "win", ".", "pageXOffset", ",", "top", ":", "win", ".", "pageYOffset", "}", ";", "// add the offset & recurse up the frame chain", "var", "frame", "=", "win", ".", "frameElement", ";", "if", "(", "frame", ")", "{", "var", "rect", "=", "frame", ".", "getBoundingClientRect", "(", ")", ";", "dims", ".", "left", "+=", "rect", ".", "left", "+", "frame", ".", "contentWindow", ".", "pageXOffset", ";", "dims", ".", "top", "+=", "rect", ".", "top", "+", "frame", ".", "contentWindow", ".", "pageYOffset", ";", "if", "(", "win", "!==", "window", ".", "top", ")", "{", "computeFrameOffset", "(", "win", ".", "parent", ",", "dims", ")", ";", "}", "}", "return", "dims", ";", "}", "/**\n * @param {HTMLElement} element\n * @param {Object} frameOffset\n * @returns {Object}\n */", "function", "computeElementRect", "(", "element", ",", "frameOffset", ")", "{", "var", "rect", "=", "element", ".", "getBoundingClientRect", "(", ")", ";", "return", "{", "left", ":", "rect", ".", "left", "+", "frameOffset", ".", "left", ",", "right", ":", "rect", ".", "right", "+", "frameOffset", ".", "left", ",", "top", ":", "rect", ".", "top", "+", "frameOffset", ".", "top", ",", "bottom", ":", "rect", ".", "bottom", "+", "frameOffset", ".", "top", ",", "width", ":", "rect", ".", "width", ",", "height", ":", "rect", ".", "height", "}", ";", "}", "var", "element", "=", "document", ".", "querySelectorAll", "(", "elementSelector", ")", "[", "0", "]", ";", "if", "(", "element", ")", "{", "var", "frameOffset", "=", "computeFrameOffset", "(", "window", ")", ";", "var", "elementRect", "=", "computeElementRect", "(", "element", ",", "frameOffset", ")", ";", "return", "elementRect", ";", "}", "}" ]
Gets the position and size of an element. This function is run in the browser so its scope must be contained. @param {String} elementSelector @returns {Object|undefined}
[ "Gets", "the", "position", "and", "size", "of", "an", "element", "." ]
afd26c3aff4c53f739b6381ad289544637aac7ce
https://github.com/stamoern/wdio-element-screenshot/blob/afd26c3aff4c53f739b6381ad289544637aac7ce/src/index.js#L96-L149
35,426
flux-capacitor/flux-capacitor
packages/flux-capacitor-reduxify/src/index.js
reduxifyReducer
function reduxifyReducer (reducer, collectionName = null) { return (state = [], action) => { const collection = createReduxifyCollection(state, collectionName) const changeset = reducer(collection, action) // the changesets returned by the reduxify collections are just plain synchronous methods return changeset && changeset !== collection ? applyChangeset(state, changeset) : state } function applyChangeset (state, changeset) { if (typeof changeset !== 'function') { console.error('Reduxify changeset is a plain function. Instead got:', changeset) throw new Error('Reduxify changeset is a plain function.') } // the changesets returned by the reduxify collections are just plain synchronous methods return changeset(state) } }
javascript
function reduxifyReducer (reducer, collectionName = null) { return (state = [], action) => { const collection = createReduxifyCollection(state, collectionName) const changeset = reducer(collection, action) // the changesets returned by the reduxify collections are just plain synchronous methods return changeset && changeset !== collection ? applyChangeset(state, changeset) : state } function applyChangeset (state, changeset) { if (typeof changeset !== 'function') { console.error('Reduxify changeset is a plain function. Instead got:', changeset) throw new Error('Reduxify changeset is a plain function.') } // the changesets returned by the reduxify collections are just plain synchronous methods return changeset(state) } }
[ "function", "reduxifyReducer", "(", "reducer", ",", "collectionName", "=", "null", ")", "{", "return", "(", "state", "=", "[", "]", ",", "action", ")", "=>", "{", "const", "collection", "=", "createReduxifyCollection", "(", "state", ",", "collectionName", ")", "const", "changeset", "=", "reducer", "(", "collection", ",", "action", ")", "// the changesets returned by the reduxify collections are just plain synchronous methods", "return", "changeset", "&&", "changeset", "!==", "collection", "?", "applyChangeset", "(", "state", ",", "changeset", ")", ":", "state", "}", "function", "applyChangeset", "(", "state", ",", "changeset", ")", "{", "if", "(", "typeof", "changeset", "!==", "'function'", ")", "{", "console", ".", "error", "(", "'Reduxify changeset is a plain function. Instead got:'", ",", "changeset", ")", "throw", "new", "Error", "(", "'Reduxify changeset is a plain function.'", ")", "}", "// the changesets returned by the reduxify collections are just plain synchronous methods", "return", "changeset", "(", "state", ")", "}", "}" ]
Takes a rewinddb reducer and turns it into a redux-compatible reducer. @param {Function} reducer (Collection, Event) => Changeset @param {string} [collectionName] @param {Function} (Array<Object>, Action) => Array<Object>
[ "Takes", "a", "rewinddb", "reducer", "and", "turns", "it", "into", "a", "redux", "-", "compatible", "reducer", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-reduxify/src/index.js#L12-L31
35,427
GitbookIO/slate-no-empty
src/index.js
NoEmpty
function NoEmpty(type) { type = typeof type == 'string' ? Block.create({ type, nodes: [ Text.create() ] }) : type; const onBeforeChange = (state) => { const { document } = state; // If document is not empty, it continues if (!document.nodes.isEmpty()) { return; } // Reset the state return State.create({ document: Document.create({ nodes: [type] }) }); }; return { onBeforeChange }; }
javascript
function NoEmpty(type) { type = typeof type == 'string' ? Block.create({ type, nodes: [ Text.create() ] }) : type; const onBeforeChange = (state) => { const { document } = state; // If document is not empty, it continues if (!document.nodes.isEmpty()) { return; } // Reset the state return State.create({ document: Document.create({ nodes: [type] }) }); }; return { onBeforeChange }; }
[ "function", "NoEmpty", "(", "type", ")", "{", "type", "=", "typeof", "type", "==", "'string'", "?", "Block", ".", "create", "(", "{", "type", ",", "nodes", ":", "[", "Text", ".", "create", "(", ")", "]", "}", ")", ":", "type", ";", "const", "onBeforeChange", "=", "(", "state", ")", "=>", "{", "const", "{", "document", "}", "=", "state", ";", "// If document is not empty, it continues", "if", "(", "!", "document", ".", "nodes", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "// Reset the state", "return", "State", ".", "create", "(", "{", "document", ":", "Document", ".", "create", "(", "{", "nodes", ":", "[", "type", "]", "}", ")", "}", ")", ";", "}", ";", "return", "{", "onBeforeChange", "}", ";", "}" ]
Plugin to prevent an empty document. @param {String|Block} type
[ "Plugin", "to", "prevent", "an", "empty", "document", "." ]
9a8f24e4bfe2fea5ab76d0f9e5955587550c3118
https://github.com/GitbookIO/slate-no-empty/blob/9a8f24e4bfe2fea5ab76d0f9e5955587550c3118/src/index.js#L8-L36
35,428
karma-runner/karma-dart
chrome-extension/background.js
onRequest
function onRequest (request, sender, sendResponse) { // Show the page action for the tab that the sender (content script) was on. chrome.pageAction.show(sender.tab.id) var files = request.files if (request.action === 'load') { var rules = [] for (var file in files) { var regex var isKnownFile = prevFiles[sender.tab.id] && prevFiles[sender.tab.id][file] if (isKnownFile) { if (prevFiles[sender.tab.id][file] === files[file]) { // We can skip this rule if the timestamp hasn't change. continue } regex = '^([^\\?]*)\\?' + prevFiles[sender.tab.id][file] + '$' } else { regex = '^([^\\?]*)$' } var actions = [ new chrome.declarativeWebRequest.RedirectByRegEx({ from: regex, to: '$1?' + files[file] }) ] if (!isKnownFile) { // is new file actions.push( new chrome.declarativeWebRequest.RemoveResponseHeader( {name: 'Cache-Control'})) actions.push( new chrome.declarativeWebRequest.AddResponseHeader( {name: 'Cache-Control', value: 'no-cache'})) } rules.push({ conditions: [ new chrome.declarativeWebRequest.RequestMatcher({ url: { pathSuffix: file } }) ], actions: actions }) } prevFiles[sender.tab.id] = files chrome.declarativeWebRequest.onRequest.addRules(rules, function (callback) { // We reply back only when new rules are set. sendResponse({}) }) } // Return nothing to let the connection be cleaned up. }
javascript
function onRequest (request, sender, sendResponse) { // Show the page action for the tab that the sender (content script) was on. chrome.pageAction.show(sender.tab.id) var files = request.files if (request.action === 'load') { var rules = [] for (var file in files) { var regex var isKnownFile = prevFiles[sender.tab.id] && prevFiles[sender.tab.id][file] if (isKnownFile) { if (prevFiles[sender.tab.id][file] === files[file]) { // We can skip this rule if the timestamp hasn't change. continue } regex = '^([^\\?]*)\\?' + prevFiles[sender.tab.id][file] + '$' } else { regex = '^([^\\?]*)$' } var actions = [ new chrome.declarativeWebRequest.RedirectByRegEx({ from: regex, to: '$1?' + files[file] }) ] if (!isKnownFile) { // is new file actions.push( new chrome.declarativeWebRequest.RemoveResponseHeader( {name: 'Cache-Control'})) actions.push( new chrome.declarativeWebRequest.AddResponseHeader( {name: 'Cache-Control', value: 'no-cache'})) } rules.push({ conditions: [ new chrome.declarativeWebRequest.RequestMatcher({ url: { pathSuffix: file } }) ], actions: actions }) } prevFiles[sender.tab.id] = files chrome.declarativeWebRequest.onRequest.addRules(rules, function (callback) { // We reply back only when new rules are set. sendResponse({}) }) } // Return nothing to let the connection be cleaned up. }
[ "function", "onRequest", "(", "request", ",", "sender", ",", "sendResponse", ")", "{", "// Show the page action for the tab that the sender (content script) was on.", "chrome", ".", "pageAction", ".", "show", "(", "sender", ".", "tab", ".", "id", ")", "var", "files", "=", "request", ".", "files", "if", "(", "request", ".", "action", "===", "'load'", ")", "{", "var", "rules", "=", "[", "]", "for", "(", "var", "file", "in", "files", ")", "{", "var", "regex", "var", "isKnownFile", "=", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "&&", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "[", "file", "]", "if", "(", "isKnownFile", ")", "{", "if", "(", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "[", "file", "]", "===", "files", "[", "file", "]", ")", "{", "// We can skip this rule if the timestamp hasn't change.", "continue", "}", "regex", "=", "'^([^\\\\?]*)\\\\?'", "+", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "[", "file", "]", "+", "'$'", "}", "else", "{", "regex", "=", "'^([^\\\\?]*)$'", "}", "var", "actions", "=", "[", "new", "chrome", ".", "declarativeWebRequest", ".", "RedirectByRegEx", "(", "{", "from", ":", "regex", ",", "to", ":", "'$1?'", "+", "files", "[", "file", "]", "}", ")", "]", "if", "(", "!", "isKnownFile", ")", "{", "// is new file", "actions", ".", "push", "(", "new", "chrome", ".", "declarativeWebRequest", ".", "RemoveResponseHeader", "(", "{", "name", ":", "'Cache-Control'", "}", ")", ")", "actions", ".", "push", "(", "new", "chrome", ".", "declarativeWebRequest", ".", "AddResponseHeader", "(", "{", "name", ":", "'Cache-Control'", ",", "value", ":", "'no-cache'", "}", ")", ")", "}", "rules", ".", "push", "(", "{", "conditions", ":", "[", "new", "chrome", ".", "declarativeWebRequest", ".", "RequestMatcher", "(", "{", "url", ":", "{", "pathSuffix", ":", "file", "}", "}", ")", "]", ",", "actions", ":", "actions", "}", ")", "}", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "=", "files", "chrome", ".", "declarativeWebRequest", ".", "onRequest", ".", "addRules", "(", "rules", ",", "function", "(", "callback", ")", "{", "// We reply back only when new rules are set.", "sendResponse", "(", "{", "}", ")", "}", ")", "}", "// Return nothing to let the connection be cleaned up.", "}" ]
Called when a message is passed.
[ "Called", "when", "a", "message", "is", "passed", "." ]
d5bd776928ff86978382c9522a618b468d2fba51
https://github.com/karma-runner/karma-dart/blob/d5bd776928ff86978382c9522a618b468d2fba51/chrome-extension/background.js#L7-L58
35,429
Cloud9Trader/oanda-adapter
lib/Events.js
waitFor
function waitFor (event, listener, context, wait) { var timeout; if (!wait) { throw new Error("[FATAL] waitFor called without wait time"); } var handler = function () { clearTimeout(timeout); listener.apply(context, arguments); }; timeout = setTimeout(function () { this.off(event, handler, context); listener.call(context, "timeout"); }.bind(this), wait); this.once(event, handler, context); }
javascript
function waitFor (event, listener, context, wait) { var timeout; if (!wait) { throw new Error("[FATAL] waitFor called without wait time"); } var handler = function () { clearTimeout(timeout); listener.apply(context, arguments); }; timeout = setTimeout(function () { this.off(event, handler, context); listener.call(context, "timeout"); }.bind(this), wait); this.once(event, handler, context); }
[ "function", "waitFor", "(", "event", ",", "listener", ",", "context", ",", "wait", ")", "{", "var", "timeout", ";", "if", "(", "!", "wait", ")", "{", "throw", "new", "Error", "(", "\"[FATAL] waitFor called without wait time\"", ")", ";", "}", "var", "handler", "=", "function", "(", ")", "{", "clearTimeout", "(", "timeout", ")", ";", "listener", ".", "apply", "(", "context", ",", "arguments", ")", ";", "}", ";", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "this", ".", "off", "(", "event", ",", "handler", ",", "context", ")", ";", "listener", ".", "call", "(", "context", ",", "\"timeout\"", ")", ";", "}", ".", "bind", "(", "this", ")", ",", "wait", ")", ";", "this", ".", "once", "(", "event", ",", "handler", ",", "context", ")", ";", "}" ]
Waits for wait ms for event to fire or calls listener with error, removing listener
[ "Waits", "for", "wait", "ms", "for", "event", "to", "fire", "or", "calls", "listener", "with", "error", "removing", "listener" ]
33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1
https://github.com/Cloud9Trader/oanda-adapter/blob/33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1/lib/Events.js#L20-L34
35,430
Cloud9Trader/oanda-adapter
lib/Events.js
listenFor
function listenFor (event, listener, context, duration) { setTimeout(function () { this.off(event, listener, context); }.bind(this), duration); this.on(event, listener, context); }
javascript
function listenFor (event, listener, context, duration) { setTimeout(function () { this.off(event, listener, context); }.bind(this), duration); this.on(event, listener, context); }
[ "function", "listenFor", "(", "event", ",", "listener", ",", "context", ",", "duration", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "this", ".", "off", "(", "event", ",", "listener", ",", "context", ")", ";", "}", ".", "bind", "(", "this", ")", ",", "duration", ")", ";", "this", ".", "on", "(", "event", ",", "listener", ",", "context", ")", ";", "}" ]
Listens for duration ms for events to fire, then removes listener
[ "Listens", "for", "duration", "ms", "for", "events", "to", "fire", "then", "removes", "listener" ]
33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1
https://github.com/Cloud9Trader/oanda-adapter/blob/33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1/lib/Events.js#L37-L42
35,431
flux-capacitor/flux-capacitor
packages/flux-capacitor-sequelize/lib/connectTo.js
connectTo
function connectTo (connectionSettings, createCollections) { const sequelize = new Sequelize(connectionSettings) const collections = createCollections(sequelize, createCollection) const database = { /** @property {Sequelize} connection */ connection: sequelize, /** @property {Object} collections { [name: string]: Collection } */ collections: collectionsAsKeyValue(collections), applyChangeset (changeset, options) { options = options || { transaction: null } return changeset.apply(options.transaction) }, createEventId () { return uuid.v4() }, transaction (callback) { return sequelize.transaction((sequelizeTransaction) => { const transaction = createTransaction(database, sequelizeTransaction) return callback(transaction) }) } } return sequelize.sync().then(() => database) }
javascript
function connectTo (connectionSettings, createCollections) { const sequelize = new Sequelize(connectionSettings) const collections = createCollections(sequelize, createCollection) const database = { /** @property {Sequelize} connection */ connection: sequelize, /** @property {Object} collections { [name: string]: Collection } */ collections: collectionsAsKeyValue(collections), applyChangeset (changeset, options) { options = options || { transaction: null } return changeset.apply(options.transaction) }, createEventId () { return uuid.v4() }, transaction (callback) { return sequelize.transaction((sequelizeTransaction) => { const transaction = createTransaction(database, sequelizeTransaction) return callback(transaction) }) } } return sequelize.sync().then(() => database) }
[ "function", "connectTo", "(", "connectionSettings", ",", "createCollections", ")", "{", "const", "sequelize", "=", "new", "Sequelize", "(", "connectionSettings", ")", "const", "collections", "=", "createCollections", "(", "sequelize", ",", "createCollection", ")", "const", "database", "=", "{", "/** @property {Sequelize} connection */", "connection", ":", "sequelize", ",", "/** @property {Object} collections { [name: string]: Collection } */", "collections", ":", "collectionsAsKeyValue", "(", "collections", ")", ",", "applyChangeset", "(", "changeset", ",", "options", ")", "{", "options", "=", "options", "||", "{", "transaction", ":", "null", "}", "return", "changeset", ".", "apply", "(", "options", ".", "transaction", ")", "}", ",", "createEventId", "(", ")", "{", "return", "uuid", ".", "v4", "(", ")", "}", ",", "transaction", "(", "callback", ")", "{", "return", "sequelize", ".", "transaction", "(", "(", "sequelizeTransaction", ")", "=>", "{", "const", "transaction", "=", "createTransaction", "(", "database", ",", "sequelizeTransaction", ")", "return", "callback", "(", "transaction", ")", "}", ")", "}", "}", "return", "sequelize", ".", "sync", "(", ")", ".", "then", "(", "(", ")", "=>", "database", ")", "}" ]
Connect to a database using Sequelize ORM. @param {string|object} connectionSettings Connection URL like `sqlite://path/to/db.sqlite` or object: `{ database: string, host: string, dialect: string, ... }` @param {Function} createCollections (sequelize: Sequelize, createCollection: (name: string, model: Sequelize.Model) => Collection) => Array<Collection> @return {Database}
[ "Connect", "to", "a", "database", "using", "Sequelize", "ORM", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-sequelize/lib/connectTo.js#L17-L46
35,432
googlearchive/net-chromeify
examples/client/bundle.js
stringifyObject
function stringifyObject(obj, prefix) { var ret = [] , keys = objectKeys(obj) , key; for (var i = 0, len = keys.length; i < len; ++i) { key = keys[i]; ret.push(stringify(obj[key], prefix ? prefix + '[' + encodeURIComponent(key) + ']' : encodeURIComponent(key))); } return ret.join('&'); }
javascript
function stringifyObject(obj, prefix) { var ret = [] , keys = objectKeys(obj) , key; for (var i = 0, len = keys.length; i < len; ++i) { key = keys[i]; ret.push(stringify(obj[key], prefix ? prefix + '[' + encodeURIComponent(key) + ']' : encodeURIComponent(key))); } return ret.join('&'); }
[ "function", "stringifyObject", "(", "obj", ",", "prefix", ")", "{", "var", "ret", "=", "[", "]", ",", "keys", "=", "objectKeys", "(", "obj", ")", ",", "key", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "keys", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "ret", ".", "push", "(", "stringify", "(", "obj", "[", "key", "]", ",", "prefix", "?", "prefix", "+", "'['", "+", "encodeURIComponent", "(", "key", ")", "+", "']'", ":", "encodeURIComponent", "(", "key", ")", ")", ")", ";", "}", "return", "ret", ".", "join", "(", "'&'", ")", ";", "}" ]
Stringify the given `obj`. @param {Object} obj @param {String} prefix @return {String} @api private
[ "Stringify", "the", "given", "obj", "." ]
566cd7a24e03a5947e8851f338a9eee054a42824
https://github.com/googlearchive/net-chromeify/blob/566cd7a24e03a5947e8851f338a9eee054a42824/examples/client/bundle.js#L3905-L3916
35,433
Esri/geotrigger-js
geotrigger.js
function(target, obj){ for (var attr in obj) { if(obj.hasOwnProperty(attr)){ target[attr] = obj[attr]; } } return target; }
javascript
function(target, obj){ for (var attr in obj) { if(obj.hasOwnProperty(attr)){ target[attr] = obj[attr]; } } return target; }
[ "function", "(", "target", ",", "obj", ")", "{", "for", "(", "var", "attr", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "target", "[", "attr", "]", "=", "obj", "[", "attr", "]", ";", "}", "}", "return", "target", ";", "}" ]
Merge Object 1 and Object 2. Properties from Object 2 will override properties in Object 1. Returns Object 1
[ "Merge", "Object", "1", "and", "Object", "2", ".", "Properties", "from", "Object", "2", "will", "override", "properties", "in", "Object", "1", ".", "Returns", "Object", "1" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/geotrigger.js#L355-L362
35,434
stefanjudis/credits
lib/analyzers/jspm/index.js
getCredits
function getCredits(projectPath, credits) { credits = credits || []; const jspmPath = path.join(projectPath, 'jspm_packages'); globby.sync([`${jspmPath}/npm/*/package.json`, `${jspmPath}/github/*/*/{package.json,bower.json}`]) .forEach(packagePath => { if (path.basename(packagePath) === 'bower.json') { return getBowerCredits(packagePath, credits); } return getNpmCredits(packagePath, credits); }); return credits; }
javascript
function getCredits(projectPath, credits) { credits = credits || []; const jspmPath = path.join(projectPath, 'jspm_packages'); globby.sync([`${jspmPath}/npm/*/package.json`, `${jspmPath}/github/*/*/{package.json,bower.json}`]) .forEach(packagePath => { if (path.basename(packagePath) === 'bower.json') { return getBowerCredits(packagePath, credits); } return getNpmCredits(packagePath, credits); }); return credits; }
[ "function", "getCredits", "(", "projectPath", ",", "credits", ")", "{", "credits", "=", "credits", "||", "[", "]", ";", "const", "jspmPath", "=", "path", ".", "join", "(", "projectPath", ",", "'jspm_packages'", ")", ";", "globby", ".", "sync", "(", "[", "`", "${", "jspmPath", "}", "`", ",", "`", "${", "jspmPath", "}", "`", "]", ")", ".", "forEach", "(", "packagePath", "=>", "{", "if", "(", "path", ".", "basename", "(", "packagePath", ")", "===", "'bower.json'", ")", "{", "return", "getBowerCredits", "(", "packagePath", ",", "credits", ")", ";", "}", "return", "getNpmCredits", "(", "packagePath", ",", "credits", ")", ";", "}", ")", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for jspm modules @param {String} projectPath absolute path to project root @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "jspm", "modules" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/jspm/index.js#L16-L30
35,435
stefanjudis/credits
lib/credit.js
getCredit
function getCredit(credits, author) { const credit = credits.filter(credit => { // Fallback to name when no email // is available if (credit.email && author.email) { return credit.email === author.email; } return credit.name === author.name; }); return credit.length > 0 ? credit[0] : false; }
javascript
function getCredit(credits, author) { const credit = credits.filter(credit => { // Fallback to name when no email // is available if (credit.email && author.email) { return credit.email === author.email; } return credit.name === author.name; }); return credit.length > 0 ? credit[0] : false; }
[ "function", "getCredit", "(", "credits", ",", "author", ")", "{", "const", "credit", "=", "credits", ".", "filter", "(", "credit", "=>", "{", "// Fallback to name when no email", "// is available", "if", "(", "credit", ".", "email", "&&", "author", ".", "email", ")", "{", "return", "credit", ".", "email", "===", "author", ".", "email", ";", "}", "return", "credit", ".", "name", "===", "author", ".", "name", ";", "}", ")", ";", "return", "credit", ".", "length", ">", "0", "?", "credit", "[", "0", "]", ":", "false", ";", "}" ]
Get credit out of running credits list @param {Array} credits list of credits @param {Object} author author @return {Object|false} existing credit or false @tested
[ "Get", "credit", "out", "of", "running", "credits", "list" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/credit.js#L13-L27
35,436
stefanjudis/credits
lib/credit.js
addCreditToCredits
function addCreditToCredits(credits, person, name) { let credit = getCredit(credits, person); if (!credit) { credit = person; credit.packages = []; credits.push(credit); } if (credit.packages.indexOf(name) === -1) { credit.packages.push(name); } return credits; }
javascript
function addCreditToCredits(credits, person, name) { let credit = getCredit(credits, person); if (!credit) { credit = person; credit.packages = []; credits.push(credit); } if (credit.packages.indexOf(name) === -1) { credit.packages.push(name); } return credits; }
[ "function", "addCreditToCredits", "(", "credits", ",", "person", ",", "name", ")", "{", "let", "credit", "=", "getCredit", "(", "credits", ",", "person", ")", ";", "if", "(", "!", "credit", ")", "{", "credit", "=", "person", ";", "credit", ".", "packages", "=", "[", "]", ";", "credits", ".", "push", "(", "credit", ")", ";", "}", "if", "(", "credit", ".", "packages", ".", "indexOf", "(", "name", ")", "===", "-", "1", ")", "{", "credit", ".", "packages", ".", "push", "(", "name", ")", ";", "}", "return", "credits", ";", "}" ]
Add a credit to running credits list @param {Array} credits list of credits @param {Object} person person to give credit @param {String} name project name to attach to person @return {Array} list of credits @tested
[ "Add", "a", "credit", "to", "running", "credits", "list" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/credit.js#L40-L55
35,437
florianheinemann/passwordless-redisstore
lib/redisstore.js
RedisStore
function RedisStore(port, host, options) { port = port || 6379; host = host || '127.0.0.1'; this._options = options || {}; this._options.redisstore = this._options.redisstore || {}; if(this._options.redisstore.database && !isNumber(this._options.redisstore.database)) { throw new Error('database has to be a number (if provided at all)'); } else if(this._options.redisstore.database) { this._database = this._options.redisstore.database; } else { this._database = 0; } this._tokenKey = this._options.redisstore.tokenkey || 'pwdless:'; delete this._options.redisstore; this._client = redis.createClient(port, host, this._options); }
javascript
function RedisStore(port, host, options) { port = port || 6379; host = host || '127.0.0.1'; this._options = options || {}; this._options.redisstore = this._options.redisstore || {}; if(this._options.redisstore.database && !isNumber(this._options.redisstore.database)) { throw new Error('database has to be a number (if provided at all)'); } else if(this._options.redisstore.database) { this._database = this._options.redisstore.database; } else { this._database = 0; } this._tokenKey = this._options.redisstore.tokenkey || 'pwdless:'; delete this._options.redisstore; this._client = redis.createClient(port, host, this._options); }
[ "function", "RedisStore", "(", "port", ",", "host", ",", "options", ")", "{", "port", "=", "port", "||", "6379", ";", "host", "=", "host", "||", "'127.0.0.1'", ";", "this", ".", "_options", "=", "options", "||", "{", "}", ";", "this", ".", "_options", ".", "redisstore", "=", "this", ".", "_options", ".", "redisstore", "||", "{", "}", ";", "if", "(", "this", ".", "_options", ".", "redisstore", ".", "database", "&&", "!", "isNumber", "(", "this", ".", "_options", ".", "redisstore", ".", "database", ")", ")", "{", "throw", "new", "Error", "(", "'database has to be a number (if provided at all)'", ")", ";", "}", "else", "if", "(", "this", ".", "_options", ".", "redisstore", ".", "database", ")", "{", "this", ".", "_database", "=", "this", ".", "_options", ".", "redisstore", ".", "database", ";", "}", "else", "{", "this", ".", "_database", "=", "0", ";", "}", "this", ".", "_tokenKey", "=", "this", ".", "_options", ".", "redisstore", ".", "tokenkey", "||", "'pwdless:'", ";", "delete", "this", ".", "_options", ".", "redisstore", ";", "this", ".", "_client", "=", "redis", ".", "createClient", "(", "port", ",", "host", ",", "this", ".", "_options", ")", ";", "}" ]
Constructor of RedisStore @param {Number} [port] Port of the Redis server (default: 6379) @param {String} [host] Host, e.g. 127.0.0.1 (default: 127.0.0.1) @param {Object} [options] Combines both the options for the Redis client as well as the options for RedisStore. For the Redis options please refer back to the documentation: https://github.com/NodeRedis/node_redis. RedisStore accepts the following options: (1) { redisstore: { database: Number }} number of the Redis database to use (default: 0), (2) { redisstore: { tokenkey: String }} the prefix used for the RedisStore entries in the database (default: 'pwdless:') @constructor
[ "Constructor", "of", "RedisStore" ]
021ffb1dca599884f35c2f7e3e4105799c9aba54
https://github.com/florianheinemann/passwordless-redisstore/blob/021ffb1dca599884f35c2f7e3e4105799c9aba54/lib/redisstore.js#L21-L38
35,438
7digital/7digital-api
lib/oauth.js
createOAuthWrapper
function createOAuthWrapper(oauthkey, oauthsecret, headers) { return new OAuthClient( 'https://api.7digital.com/1.2/oauth/requesttoken', accessTokenUrl, oauthkey, oauthsecret, '1.0', null, 'HMAC-SHA1', 32, headers); }
javascript
function createOAuthWrapper(oauthkey, oauthsecret, headers) { return new OAuthClient( 'https://api.7digital.com/1.2/oauth/requesttoken', accessTokenUrl, oauthkey, oauthsecret, '1.0', null, 'HMAC-SHA1', 32, headers); }
[ "function", "createOAuthWrapper", "(", "oauthkey", ",", "oauthsecret", ",", "headers", ")", "{", "return", "new", "OAuthClient", "(", "'https://api.7digital.com/1.2/oauth/requesttoken'", ",", "accessTokenUrl", ",", "oauthkey", ",", "oauthsecret", ",", "'1.0'", ",", "null", ",", "'HMAC-SHA1'", ",", "32", ",", "headers", ")", ";", "}" ]
Creates an OAuth v1 wrapper configured with the supplied key and secret and the necessary options for authenticating with the 7digital API. - @param {String} oauthkey - @param {String} oauthsecret - @return {OAuth}
[ "Creates", "an", "OAuth", "v1", "wrapper", "configured", "with", "the", "supplied", "key", "and", "secret", "and", "the", "necessary", "options", "for", "authenticating", "with", "the", "7digital", "API", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/oauth.js#L17-L24
35,439
brettz9/miller-columns
dist/index-es.js
breadcrumb
function breadcrumb() { const $breadcrumb = $(`.${namespace}-breadcrumbs`).empty(); chain().each(function () { const $crumb = $(this); $(`<span class="${namespace}-breadcrumb">`).text($crumb.text().trim()).click(function () { $crumb.click(); }).appendTo($breadcrumb); }); }
javascript
function breadcrumb() { const $breadcrumb = $(`.${namespace}-breadcrumbs`).empty(); chain().each(function () { const $crumb = $(this); $(`<span class="${namespace}-breadcrumb">`).text($crumb.text().trim()).click(function () { $crumb.click(); }).appendTo($breadcrumb); }); }
[ "function", "breadcrumb", "(", ")", "{", "const", "$breadcrumb", "=", "$", "(", "`", "${", "namespace", "}", "`", ")", ".", "empty", "(", ")", ";", "chain", "(", ")", ".", "each", "(", "function", "(", ")", "{", "const", "$crumb", "=", "$", "(", "this", ")", ";", "$", "(", "`", "${", "namespace", "}", "`", ")", ".", "text", "(", "$crumb", ".", "text", "(", ")", ".", "trim", "(", ")", ")", ".", "click", "(", "function", "(", ")", "{", "$crumb", ".", "click", "(", ")", ";", "}", ")", ".", "appendTo", "(", "$breadcrumb", ")", ";", "}", ")", ";", "}" ]
Add the breadcrumb path using the chain of selected items.
[ "Add", "the", "breadcrumb", "path", "using", "the", "chain", "of", "selected", "items", "." ]
98f0711d6ccdc198265c47290159a481145517e8
https://github.com/brettz9/miller-columns/blob/98f0711d6ccdc198265c47290159a481145517e8/dist/index-es.js#L120-L129
35,440
brettz9/miller-columns
dist/index-es.js
animation
function animation($column, $columns) { let width = 0; chain().not($column).each(function () { width += $(this).outerWidth(true); }); $columns.stop().animate({ scrollLeft: width }, settings.delay, function () { const last = $columns.find(`.${namespace}-column:not(.${namespace}-collapse)`).last(); // last[0].scrollIntoView(); // Scrolls vertically also unfortunately last[0].scrollLeft = width; if (settings.scroll) { settings.scroll.call(this, $column, $columns); } }); }
javascript
function animation($column, $columns) { let width = 0; chain().not($column).each(function () { width += $(this).outerWidth(true); }); $columns.stop().animate({ scrollLeft: width }, settings.delay, function () { const last = $columns.find(`.${namespace}-column:not(.${namespace}-collapse)`).last(); // last[0].scrollIntoView(); // Scrolls vertically also unfortunately last[0].scrollLeft = width; if (settings.scroll) { settings.scroll.call(this, $column, $columns); } }); }
[ "function", "animation", "(", "$column", ",", "$columns", ")", "{", "let", "width", "=", "0", ";", "chain", "(", ")", ".", "not", "(", "$column", ")", ".", "each", "(", "function", "(", ")", "{", "width", "+=", "$", "(", "this", ")", ".", "outerWidth", "(", "true", ")", ";", "}", ")", ";", "$columns", ".", "stop", "(", ")", ".", "animate", "(", "{", "scrollLeft", ":", "width", "}", ",", "settings", ".", "delay", ",", "function", "(", ")", "{", "const", "last", "=", "$columns", ".", "find", "(", "`", "${", "namespace", "}", "${", "namespace", "}", "`", ")", ".", "last", "(", ")", ";", "// last[0].scrollIntoView(); // Scrolls vertically also unfortunately", "last", "[", "0", "]", ".", "scrollLeft", "=", "width", ";", "if", "(", "settings", ".", "scroll", ")", "{", "settings", ".", "scroll", ".", "call", "(", "this", ",", "$column", ",", "$columns", ")", ";", "}", "}", ")", ";", "}" ]
Ensure the viewport shows the entire newly expanded item.
[ "Ensure", "the", "viewport", "shows", "the", "entire", "newly", "expanded", "item", "." ]
98f0711d6ccdc198265c47290159a481145517e8
https://github.com/brettz9/miller-columns/blob/98f0711d6ccdc198265c47290159a481145517e8/dist/index-es.js#L132-L147
35,441
brettz9/miller-columns
dist/index-es.js
unnest
function unnest($columns) { const queue = []; let $node; // Push the root unordered list item into the queue. queue.push($columns.children()); while (queue.length) { $node = queue.shift(); $node.children(itemSelector).each(function (item, el) { const $this = $(this); const $child = $this.children(columnSelector), $ancestor = $this.parent().parent(); // Retain item hierarchy (because it is lost after flattening). if ($ancestor.length && $this.data(`${namespace}-ancestor`) == null) { // Use addBack to reset all selection chains. $(this).siblings().addBack().data(`${namespace}-ancestor`, $ancestor); } if ($child.length) { queue.push($child); $(this).data(`${namespace}-child`, $child).addClass(`${namespace}-parent`); } // Causes item siblings to have a flattened DOM lineage. $(this).parent(columnSelector).appendTo($columns).addClass(`${namespace}-column`); }); } }
javascript
function unnest($columns) { const queue = []; let $node; // Push the root unordered list item into the queue. queue.push($columns.children()); while (queue.length) { $node = queue.shift(); $node.children(itemSelector).each(function (item, el) { const $this = $(this); const $child = $this.children(columnSelector), $ancestor = $this.parent().parent(); // Retain item hierarchy (because it is lost after flattening). if ($ancestor.length && $this.data(`${namespace}-ancestor`) == null) { // Use addBack to reset all selection chains. $(this).siblings().addBack().data(`${namespace}-ancestor`, $ancestor); } if ($child.length) { queue.push($child); $(this).data(`${namespace}-child`, $child).addClass(`${namespace}-parent`); } // Causes item siblings to have a flattened DOM lineage. $(this).parent(columnSelector).appendTo($columns).addClass(`${namespace}-column`); }); } }
[ "function", "unnest", "(", "$columns", ")", "{", "const", "queue", "=", "[", "]", ";", "let", "$node", ";", "// Push the root unordered list item into the queue.", "queue", ".", "push", "(", "$columns", ".", "children", "(", ")", ")", ";", "while", "(", "queue", ".", "length", ")", "{", "$node", "=", "queue", ".", "shift", "(", ")", ";", "$node", ".", "children", "(", "itemSelector", ")", ".", "each", "(", "function", "(", "item", ",", "el", ")", "{", "const", "$this", "=", "$", "(", "this", ")", ";", "const", "$child", "=", "$this", ".", "children", "(", "columnSelector", ")", ",", "$ancestor", "=", "$this", ".", "parent", "(", ")", ".", "parent", "(", ")", ";", "// Retain item hierarchy (because it is lost after flattening).", "if", "(", "$ancestor", ".", "length", "&&", "$this", ".", "data", "(", "`", "${", "namespace", "}", "`", ")", "==", "null", ")", "{", "// Use addBack to reset all selection chains.", "$", "(", "this", ")", ".", "siblings", "(", ")", ".", "addBack", "(", ")", ".", "data", "(", "`", "${", "namespace", "}", "`", ",", "$ancestor", ")", ";", "}", "if", "(", "$child", ".", "length", ")", "{", "queue", ".", "push", "(", "$child", ")", ";", "$", "(", "this", ")", ".", "data", "(", "`", "${", "namespace", "}", "`", ",", "$child", ")", ".", "addClass", "(", "`", "${", "namespace", "}", "`", ")", ";", "}", "// Causes item siblings to have a flattened DOM lineage.", "$", "(", "this", ")", ".", "parent", "(", "columnSelector", ")", ".", "appendTo", "(", "$columns", ")", ".", "addClass", "(", "`", "${", "namespace", "}", "`", ")", ";", "}", ")", ";", "}", "}" ]
Convert nested lists into columns using breadth-first traversal.
[ "Convert", "nested", "lists", "into", "columns", "using", "breadth", "-", "first", "traversal", "." ]
98f0711d6ccdc198265c47290159a481145517e8
https://github.com/brettz9/miller-columns/blob/98f0711d6ccdc198265c47290159a481145517e8/dist/index-es.js#L150-L180
35,442
stefanjudis/credits
lib/package.js
getAllStar
function getAllStar(person) { // Override properties from all-stars if available const allStar = allStars(person); return allStar ? objectAssign(person, allStar.subset()) : person; }
javascript
function getAllStar(person) { // Override properties from all-stars if available const allStar = allStars(person); return allStar ? objectAssign(person, allStar.subset()) : person; }
[ "function", "getAllStar", "(", "person", ")", "{", "// Override properties from all-stars if available", "const", "allStar", "=", "allStars", "(", "person", ")", ";", "return", "allStar", "?", "objectAssign", "(", "person", ",", "allStar", ".", "subset", "(", ")", ")", ":", "person", ";", "}" ]
Check all-stars db for given person and assign to person if found. @param {Object} person object representing author or maintainer @return {Object} same object given, possibly modified or augmented
[ "Check", "all", "-", "stars", "db", "for", "given", "person", "and", "assign", "to", "person", "if", "found", "." ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L28-L32
35,443
stefanjudis/credits
lib/package.js
getPersonObject
function getPersonObject(personString) { const regex = personString.match(/^(.*?)\s?(<(.*)>)?\s?(\((.*)\))?\s?$/); return getAllStar({ name: regex[1], email: regex[3], url: regex[5] }); }
javascript
function getPersonObject(personString) { const regex = personString.match(/^(.*?)\s?(<(.*)>)?\s?(\((.*)\))?\s?$/); return getAllStar({ name: regex[1], email: regex[3], url: regex[5] }); }
[ "function", "getPersonObject", "(", "personString", ")", "{", "const", "regex", "=", "personString", ".", "match", "(", "/", "^(.*?)\\s?(<(.*)>)?\\s?(\\((.*)\\))?\\s?$", "/", ")", ";", "return", "getAllStar", "(", "{", "name", ":", "regex", "[", "1", "]", ",", "email", ":", "regex", "[", "3", "]", ",", "url", ":", "regex", "[", "5", "]", "}", ")", ";", "}" ]
Parse npm string shorthand into object representation @param {String} personString string shorthand for author or maintainer @return {Object} object representing author or maintainer
[ "Parse", "npm", "string", "shorthand", "into", "object", "representation" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L41-L49
35,444
stefanjudis/credits
lib/package.js
getAuthor
function getAuthor(packageJson) { if (Array.isArray(packageJson.authors)) { packageJson.authors = packageJson.authors.map(author => { if (typeof author === 'string') { return getPersonObject(author); } return getAllStar(author); }); return packageJson.authors ? packageJson.authors : false; } if (typeof packageJson.author === 'string') { return getPersonObject(packageJson.author); } return packageJson.author ? getAllStar(packageJson.author) : false; }
javascript
function getAuthor(packageJson) { if (Array.isArray(packageJson.authors)) { packageJson.authors = packageJson.authors.map(author => { if (typeof author === 'string') { return getPersonObject(author); } return getAllStar(author); }); return packageJson.authors ? packageJson.authors : false; } if (typeof packageJson.author === 'string') { return getPersonObject(packageJson.author); } return packageJson.author ? getAllStar(packageJson.author) : false; }
[ "function", "getAuthor", "(", "packageJson", ")", "{", "if", "(", "Array", ".", "isArray", "(", "packageJson", ".", "authors", ")", ")", "{", "packageJson", ".", "authors", "=", "packageJson", ".", "authors", ".", "map", "(", "author", "=>", "{", "if", "(", "typeof", "author", "===", "'string'", ")", "{", "return", "getPersonObject", "(", "author", ")", ";", "}", "return", "getAllStar", "(", "author", ")", ";", "}", ")", ";", "return", "packageJson", ".", "authors", "?", "packageJson", ".", "authors", ":", "false", ";", "}", "if", "(", "typeof", "packageJson", ".", "author", "===", "'string'", ")", "{", "return", "getPersonObject", "(", "packageJson", ".", "author", ")", ";", "}", "return", "packageJson", ".", "author", "?", "getAllStar", "(", "packageJson", ".", "author", ")", ":", "false", ";", "}" ]
Extract author from package.json content @param {Object} packageJson content of package.json @return {Object|false} author if exists or false @tested
[ "Extract", "author", "from", "package", ".", "json", "content" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L60-L80
35,445
stefanjudis/credits
lib/package.js
getMaintainers
function getMaintainers(packageJson) { if (Array.isArray(packageJson.maintainers)) { packageJson.maintainers = packageJson.maintainers.map(maintainer => { if (typeof maintainer === 'string') { return getPersonObject(maintainer); } return getAllStar(maintainer); }); } // Safety fix for people doing // -> "maintainers" : "Bob <some.email>" if (typeof packageJson.maintainers === 'string') { packageJson.maintainers = [getPersonObject(packageJson.maintainers)]; } return packageJson.maintainers ? packageJson.maintainers : false; }
javascript
function getMaintainers(packageJson) { if (Array.isArray(packageJson.maintainers)) { packageJson.maintainers = packageJson.maintainers.map(maintainer => { if (typeof maintainer === 'string') { return getPersonObject(maintainer); } return getAllStar(maintainer); }); } // Safety fix for people doing // -> "maintainers" : "Bob <some.email>" if (typeof packageJson.maintainers === 'string') { packageJson.maintainers = [getPersonObject(packageJson.maintainers)]; } return packageJson.maintainers ? packageJson.maintainers : false; }
[ "function", "getMaintainers", "(", "packageJson", ")", "{", "if", "(", "Array", ".", "isArray", "(", "packageJson", ".", "maintainers", ")", ")", "{", "packageJson", ".", "maintainers", "=", "packageJson", ".", "maintainers", ".", "map", "(", "maintainer", "=>", "{", "if", "(", "typeof", "maintainer", "===", "'string'", ")", "{", "return", "getPersonObject", "(", "maintainer", ")", ";", "}", "return", "getAllStar", "(", "maintainer", ")", ";", "}", ")", ";", "}", "// Safety fix for people doing", "// -> \"maintainers\" : \"Bob <some.email>\"", "if", "(", "typeof", "packageJson", ".", "maintainers", "===", "'string'", ")", "{", "packageJson", ".", "maintainers", "=", "[", "getPersonObject", "(", "packageJson", ".", "maintainers", ")", "]", ";", "}", "return", "packageJson", ".", "maintainers", "?", "packageJson", ".", "maintainers", ":", "false", ";", "}" ]
Extract maintainers from package.json content @param {Object} packageJson content of package.json @return {Array} maintainers if exists or false @tested
[ "Extract", "maintainers", "from", "package", ".", "json", "content" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L91-L111
35,446
stefanjudis/credits
lib/analyzers/npm/index.js
getNpmCredits
function getNpmCredits(packagePath, credits) { const directoryPath = path.dirname(packagePath); const name = path.basename(path.dirname(packagePath)); if ( name[0] !== '.' && ( fs.lstatSync(directoryPath).isDirectory() || fs.lstatSync(directoryPath).isSymbolicLink() ) ) { const packageJson = packageUtil.readJSONSync(packagePath); const author = packageUtil.getAuthor(packageJson); const maintainers = packageUtil.getMaintainers(packageJson); if (author) { credits = creditUtil.addCreditToCredits(credits, author, name); } if (maintainers) { maintainers.forEach(maintainer => { credits = creditUtil.addCreditToCredits(credits, maintainer, name); }); } } return credits; }
javascript
function getNpmCredits(packagePath, credits) { const directoryPath = path.dirname(packagePath); const name = path.basename(path.dirname(packagePath)); if ( name[0] !== '.' && ( fs.lstatSync(directoryPath).isDirectory() || fs.lstatSync(directoryPath).isSymbolicLink() ) ) { const packageJson = packageUtil.readJSONSync(packagePath); const author = packageUtil.getAuthor(packageJson); const maintainers = packageUtil.getMaintainers(packageJson); if (author) { credits = creditUtil.addCreditToCredits(credits, author, name); } if (maintainers) { maintainers.forEach(maintainer => { credits = creditUtil.addCreditToCredits(credits, maintainer, name); }); } } return credits; }
[ "function", "getNpmCredits", "(", "packagePath", ",", "credits", ")", "{", "const", "directoryPath", "=", "path", ".", "dirname", "(", "packagePath", ")", ";", "const", "name", "=", "path", ".", "basename", "(", "path", ".", "dirname", "(", "packagePath", ")", ")", ";", "if", "(", "name", "[", "0", "]", "!==", "'.'", "&&", "(", "fs", ".", "lstatSync", "(", "directoryPath", ")", ".", "isDirectory", "(", ")", "||", "fs", ".", "lstatSync", "(", "directoryPath", ")", ".", "isSymbolicLink", "(", ")", ")", ")", "{", "const", "packageJson", "=", "packageUtil", ".", "readJSONSync", "(", "packagePath", ")", ";", "const", "author", "=", "packageUtil", ".", "getAuthor", "(", "packageJson", ")", ";", "const", "maintainers", "=", "packageUtil", ".", "getMaintainers", "(", "packageJson", ")", ";", "if", "(", "author", ")", "{", "credits", "=", "creditUtil", ".", "addCreditToCredits", "(", "credits", ",", "author", ",", "name", ")", ";", "}", "if", "(", "maintainers", ")", "{", "maintainers", ".", "forEach", "(", "maintainer", "=>", "{", "credits", "=", "creditUtil", ".", "addCreditToCredits", "(", "credits", ",", "maintainer", ",", "name", ")", ";", "}", ")", ";", "}", "}", "return", "credits", ";", "}" ]
Read and evaluate dependency credits for npm module @param {String} packagePath absolute path to package.json file @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "and", "evaluate", "dependency", "credits", "for", "npm", "module" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/npm/index.js#L17-L44
35,447
stefanjudis/credits
lib/analyzers/npm/index.js
getCredits
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'node_modules'); globby.sync(`${depPath}/**/package.json`) .forEach(packagePath => { getNpmCredits(packagePath, credits); }); return credits; }
javascript
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'node_modules'); globby.sync(`${depPath}/**/package.json`) .forEach(packagePath => { getNpmCredits(packagePath, credits); }); return credits; }
[ "function", "getCredits", "(", "projectPath", ",", "credits", ")", "{", "credits", "=", "credits", "||", "[", "]", ";", "const", "depPath", "=", "path", ".", "join", "(", "projectPath", ",", "'node_modules'", ")", ";", "globby", ".", "sync", "(", "`", "${", "depPath", "}", "`", ")", ".", "forEach", "(", "packagePath", "=>", "{", "getNpmCredits", "(", "packagePath", ",", "credits", ")", ";", "}", ")", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for node modules @param {String} projectPath absolute path to project root @param {Array|undefined} credits list of credits @param {Array|undefined} seen list of already iterated packages @return {Array} list of credits
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "node", "modules" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/npm/index.js#L55-L66
35,448
knockout/tko.provider
src/provider.js
preProcessBindings
function preProcessBindings(bindingString) { var results = []; var bindingHandlers = this.bindingHandlers; var preprocessed; // Check for a Provider.preprocessNode property if (typeof this.preprocessNode === 'function') { preprocessed = this.preprocessNode(bindingString, this); if (preprocessed) { bindingString = preprocessed; } } for (var i = 0, j = this.bindingPreProcessors.length; i < j; ++i) { preprocessed = this.bindingPreProcessors[i](bindingString, this); if (preprocessed) { bindingString = preprocessed; } } function addBinding(name, value) { results.push("'" + name + "':" + value); } function processBinding(key, value) { // Get the "on" binding from "on.click" var handler = bindingHandlers.get(key.split('.')[0]); if (handler && typeof handler.preprocess === 'function') { value = handler.preprocess(value, key, processBinding); } addBinding(key, value); } arrayForEach(parseObjectLiteral(bindingString), function(keyValueItem) { processBinding( keyValueItem.key || keyValueItem.unknown, keyValueItem.value ); }); return results.join(','); }
javascript
function preProcessBindings(bindingString) { var results = []; var bindingHandlers = this.bindingHandlers; var preprocessed; // Check for a Provider.preprocessNode property if (typeof this.preprocessNode === 'function') { preprocessed = this.preprocessNode(bindingString, this); if (preprocessed) { bindingString = preprocessed; } } for (var i = 0, j = this.bindingPreProcessors.length; i < j; ++i) { preprocessed = this.bindingPreProcessors[i](bindingString, this); if (preprocessed) { bindingString = preprocessed; } } function addBinding(name, value) { results.push("'" + name + "':" + value); } function processBinding(key, value) { // Get the "on" binding from "on.click" var handler = bindingHandlers.get(key.split('.')[0]); if (handler && typeof handler.preprocess === 'function') { value = handler.preprocess(value, key, processBinding); } addBinding(key, value); } arrayForEach(parseObjectLiteral(bindingString), function(keyValueItem) { processBinding( keyValueItem.key || keyValueItem.unknown, keyValueItem.value ); }); return results.join(','); }
[ "function", "preProcessBindings", "(", "bindingString", ")", "{", "var", "results", "=", "[", "]", ";", "var", "bindingHandlers", "=", "this", ".", "bindingHandlers", ";", "var", "preprocessed", ";", "// Check for a Provider.preprocessNode property", "if", "(", "typeof", "this", ".", "preprocessNode", "===", "'function'", ")", "{", "preprocessed", "=", "this", ".", "preprocessNode", "(", "bindingString", ",", "this", ")", ";", "if", "(", "preprocessed", ")", "{", "bindingString", "=", "preprocessed", ";", "}", "}", "for", "(", "var", "i", "=", "0", ",", "j", "=", "this", ".", "bindingPreProcessors", ".", "length", ";", "i", "<", "j", ";", "++", "i", ")", "{", "preprocessed", "=", "this", ".", "bindingPreProcessors", "[", "i", "]", "(", "bindingString", ",", "this", ")", ";", "if", "(", "preprocessed", ")", "{", "bindingString", "=", "preprocessed", ";", "}", "}", "function", "addBinding", "(", "name", ",", "value", ")", "{", "results", ".", "push", "(", "\"'\"", "+", "name", "+", "\"':\"", "+", "value", ")", ";", "}", "function", "processBinding", "(", "key", ",", "value", ")", "{", "// Get the \"on\" binding from \"on.click\"", "var", "handler", "=", "bindingHandlers", ".", "get", "(", "key", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", ";", "if", "(", "handler", "&&", "typeof", "handler", ".", "preprocess", "===", "'function'", ")", "{", "value", "=", "handler", ".", "preprocess", "(", "value", ",", "key", ",", "processBinding", ")", ";", "}", "addBinding", "(", "key", ",", "value", ")", ";", "}", "arrayForEach", "(", "parseObjectLiteral", "(", "bindingString", ")", ",", "function", "(", "keyValueItem", ")", "{", "processBinding", "(", "keyValueItem", ".", "key", "||", "keyValueItem", ".", "unknown", ",", "keyValueItem", ".", "value", ")", ";", "}", ")", ";", "return", "results", ".", "join", "(", "','", ")", ";", "}" ]
Call bindingHandler.preprocess on each respective binding string. The `preprocess` property of bindingHandler must be a static function (i.e. on the object or constructor).
[ "Call", "bindingHandler", ".", "preprocess", "on", "each", "respective", "binding", "string", "." ]
a157f31f5ab579b350eb6b64d92c92f9d6d4a385
https://github.com/knockout/tko.provider/blob/a157f31f5ab579b350eb6b64d92c92f9d6d4a385/src/provider.js#L131-L170
35,449
7digital/7digital-api
lib/parameters.js
template
function template(url, params) { var templated = url; var keys = _.keys(params); var loweredKeys = _.map(keys, function (key) { return key.toLowerCase(); }); var keyLookup = _.zipObject(loweredKeys, keys); _.each(templateParams(url), function replaceParam(param) { var normalisedParam = param.toLowerCase().substr(1); if (!keyLookup[normalisedParam]) { throw new Error('Missing ' + normalisedParam); } templated = templated.replace(param, params[keyLookup[normalisedParam]]); delete params[keyLookup[normalisedParam]]; }); return templated; }
javascript
function template(url, params) { var templated = url; var keys = _.keys(params); var loweredKeys = _.map(keys, function (key) { return key.toLowerCase(); }); var keyLookup = _.zipObject(loweredKeys, keys); _.each(templateParams(url), function replaceParam(param) { var normalisedParam = param.toLowerCase().substr(1); if (!keyLookup[normalisedParam]) { throw new Error('Missing ' + normalisedParam); } templated = templated.replace(param, params[keyLookup[normalisedParam]]); delete params[keyLookup[normalisedParam]]; }); return templated; }
[ "function", "template", "(", "url", ",", "params", ")", "{", "var", "templated", "=", "url", ";", "var", "keys", "=", "_", ".", "keys", "(", "params", ")", ";", "var", "loweredKeys", "=", "_", ".", "map", "(", "keys", ",", "function", "(", "key", ")", "{", "return", "key", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "var", "keyLookup", "=", "_", ".", "zipObject", "(", "loweredKeys", ",", "keys", ")", ";", "_", ".", "each", "(", "templateParams", "(", "url", ")", ",", "function", "replaceParam", "(", "param", ")", "{", "var", "normalisedParam", "=", "param", ".", "toLowerCase", "(", ")", ".", "substr", "(", "1", ")", ";", "if", "(", "!", "keyLookup", "[", "normalisedParam", "]", ")", "{", "throw", "new", "Error", "(", "'Missing '", "+", "normalisedParam", ")", ";", "}", "templated", "=", "templated", ".", "replace", "(", "param", ",", "params", "[", "keyLookup", "[", "normalisedParam", "]", "]", ")", ";", "delete", "params", "[", "keyLookup", "[", "normalisedParam", "]", "]", ";", "}", ")", ";", "return", "templated", ";", "}" ]
Given a url and some parameters replaces all named parameters with those supplied. - @param {String} url - the url to be modified - @param {Object} params - a hash of parameters to be put in the URL - @return {String} The url with the parameters replaced
[ "Given", "a", "url", "and", "some", "parameters", "replaces", "all", "named", "parameters", "with", "those", "supplied", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/parameters.js#L21-L42
35,450
stefanjudis/credits
index.js
readDirectory
function readDirectory( projectPath, analyzers ) { var credits = {}; for ( var analyzer in analyzers ) { credits[ analyzer ] = analyzers[ analyzer ]( projectPath ); }; return credits; }
javascript
function readDirectory( projectPath, analyzers ) { var credits = {}; for ( var analyzer in analyzers ) { credits[ analyzer ] = analyzers[ analyzer ]( projectPath ); }; return credits; }
[ "function", "readDirectory", "(", "projectPath", ",", "analyzers", ")", "{", "var", "credits", "=", "{", "}", ";", "for", "(", "var", "analyzer", "in", "analyzers", ")", "{", "credits", "[", "analyzer", "]", "=", "analyzers", "[", "analyzer", "]", "(", "projectPath", ")", ";", "}", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for all supported package managers @param {String} projectPath absolute path to project root @param {Array} analyzers list of availalbe analyzers @return {Array} list of credits @tested
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "all", "supported", "package", "managers" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/index.js#L22-L30
35,451
stefanjudis/credits
lib/analyzers/bower/index.js
getBowerCredits
function getBowerCredits(bowerJsonPath, credits) { const name = path.basename(path.dirname(bowerJsonPath)); const bowerJson = packageUtil.readJSONSync(bowerJsonPath); const authors = packageUtil.getAuthor(bowerJson); if (authors) { authors.forEach(author => { credits = creditUtil.addCreditToCredits(credits, author, name); }); } return credits; }
javascript
function getBowerCredits(bowerJsonPath, credits) { const name = path.basename(path.dirname(bowerJsonPath)); const bowerJson = packageUtil.readJSONSync(bowerJsonPath); const authors = packageUtil.getAuthor(bowerJson); if (authors) { authors.forEach(author => { credits = creditUtil.addCreditToCredits(credits, author, name); }); } return credits; }
[ "function", "getBowerCredits", "(", "bowerJsonPath", ",", "credits", ")", "{", "const", "name", "=", "path", ".", "basename", "(", "path", ".", "dirname", "(", "bowerJsonPath", ")", ")", ";", "const", "bowerJson", "=", "packageUtil", ".", "readJSONSync", "(", "bowerJsonPath", ")", ";", "const", "authors", "=", "packageUtil", ".", "getAuthor", "(", "bowerJson", ")", ";", "if", "(", "authors", ")", "{", "authors", ".", "forEach", "(", "author", "=>", "{", "credits", "=", "creditUtil", ".", "addCreditToCredits", "(", "credits", ",", "author", ",", "name", ")", ";", "}", ")", ";", "}", "return", "credits", ";", "}" ]
Read and evaluate dependency credits for bower module @param {String} bowerJsonPath absolute path to bower file @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "and", "evaluate", "dependency", "credits", "for", "bower", "module" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/bower/index.js#L16-L29
35,452
stefanjudis/credits
lib/analyzers/bower/index.js
getCredits
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'bower_components'); globby.sync([`${depPath}/*/bower.json`]) .forEach(bowerJsonPath => { getBowerCredits(bowerJsonPath, credits); }); return credits; }
javascript
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'bower_components'); globby.sync([`${depPath}/*/bower.json`]) .forEach(bowerJsonPath => { getBowerCredits(bowerJsonPath, credits); }); return credits; }
[ "function", "getCredits", "(", "projectPath", ",", "credits", ")", "{", "credits", "=", "credits", "||", "[", "]", ";", "const", "depPath", "=", "path", ".", "join", "(", "projectPath", ",", "'bower_components'", ")", ";", "globby", ".", "sync", "(", "[", "`", "${", "depPath", "}", "`", "]", ")", ".", "forEach", "(", "bowerJsonPath", "=>", "{", "getBowerCredits", "(", "bowerJsonPath", ",", "credits", ")", ";", "}", ")", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for bower modules @param {String} projectPath absolute path to project root @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "bower", "modules" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/bower/index.js#L38-L49
35,453
Esri/geotrigger-js
spec/SpecHelpers.js
arrySignaturesMatch
function arrySignaturesMatch(array1, array2){ // setup variables var ref, test; // we want to use the shorter array if one is longer if (array1.length >= array2.length) { ref = array2; test = array1; } else { ref = array1; test = array2; } // loop over the shorter array and make sure the corresponding key in the longer array matches for(var key in ref) { if(typeof ref[key] === typeof test[key]) { // if the keys represent an object make sure that it matches if(typeof ref[key] === "object" && typeof test[key] === "object") { if(!objectSignaturesMatch(ref[key], test[key])){ return false; } } // if the keys represent an array make sure that it matches if(typeof ref[key] === "array" && typeof test[key] === "array") { if(!arrySignaturesMatch(ref[key],test[key])){ return false; } } } } return true; }
javascript
function arrySignaturesMatch(array1, array2){ // setup variables var ref, test; // we want to use the shorter array if one is longer if (array1.length >= array2.length) { ref = array2; test = array1; } else { ref = array1; test = array2; } // loop over the shorter array and make sure the corresponding key in the longer array matches for(var key in ref) { if(typeof ref[key] === typeof test[key]) { // if the keys represent an object make sure that it matches if(typeof ref[key] === "object" && typeof test[key] === "object") { if(!objectSignaturesMatch(ref[key], test[key])){ return false; } } // if the keys represent an array make sure that it matches if(typeof ref[key] === "array" && typeof test[key] === "array") { if(!arrySignaturesMatch(ref[key],test[key])){ return false; } } } } return true; }
[ "function", "arrySignaturesMatch", "(", "array1", ",", "array2", ")", "{", "// setup variables", "var", "ref", ",", "test", ";", "// we want to use the shorter array if one is longer", "if", "(", "array1", ".", "length", ">=", "array2", ".", "length", ")", "{", "ref", "=", "array2", ";", "test", "=", "array1", ";", "}", "else", "{", "ref", "=", "array1", ";", "test", "=", "array2", ";", "}", "// loop over the shorter array and make sure the corresponding key in the longer array matches", "for", "(", "var", "key", "in", "ref", ")", "{", "if", "(", "typeof", "ref", "[", "key", "]", "===", "typeof", "test", "[", "key", "]", ")", "{", "// if the keys represent an object make sure that it matches", "if", "(", "typeof", "ref", "[", "key", "]", "===", "\"object\"", "&&", "typeof", "test", "[", "key", "]", "===", "\"object\"", ")", "{", "if", "(", "!", "objectSignaturesMatch", "(", "ref", "[", "key", "]", ",", "test", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "// if the keys represent an array make sure that it matches", "if", "(", "typeof", "ref", "[", "key", "]", "===", "\"array\"", "&&", "typeof", "test", "[", "key", "]", "===", "\"array\"", ")", "{", "if", "(", "!", "arrySignaturesMatch", "(", "ref", "[", "key", "]", ",", "test", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "}", "}", "return", "true", ";", "}" ]
do the types of arguments in each array match?
[ "do", "the", "types", "of", "arguments", "in", "each", "array", "match?" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/spec/SpecHelpers.js#L4-L38
35,454
Esri/geotrigger-js
spec/SpecHelpers.js
objectSignaturesMatch
function objectSignaturesMatch(object1, object2){ // because typeof null is object we need to check for it here before Object.keys if(object1 === null && object2 === null){ return true; } // if the objects have different lengths of keys we should fail immediatly if (Object.keys(object1).length !== Object.keys(object2).length) { return false; } // loop over all the keys in object1 (we know the objects have the same number of keys at this point) for(var key in object1) { // if the keys match keep checking if not we have a mismatch if(typeof object1[key] === typeof object2[key]) { if(typeof object1[key] === null && typeof object2[key] === null) { } // if the keys represent an object make sure that it matches. else if(object1[key] instanceof Array && object2[key] instanceof Array) { if(!arrySignaturesMatch(object1[key],object2[key])){ return false; } } // if the keys represent an array make sure it matches else if(typeof object1[key] === "object" && typeof object2[key] === "object") { if(!objectSignaturesMatch(object1[key],object2[key])){ return false; } } } } return true; }
javascript
function objectSignaturesMatch(object1, object2){ // because typeof null is object we need to check for it here before Object.keys if(object1 === null && object2 === null){ return true; } // if the objects have different lengths of keys we should fail immediatly if (Object.keys(object1).length !== Object.keys(object2).length) { return false; } // loop over all the keys in object1 (we know the objects have the same number of keys at this point) for(var key in object1) { // if the keys match keep checking if not we have a mismatch if(typeof object1[key] === typeof object2[key]) { if(typeof object1[key] === null && typeof object2[key] === null) { } // if the keys represent an object make sure that it matches. else if(object1[key] instanceof Array && object2[key] instanceof Array) { if(!arrySignaturesMatch(object1[key],object2[key])){ return false; } } // if the keys represent an array make sure it matches else if(typeof object1[key] === "object" && typeof object2[key] === "object") { if(!objectSignaturesMatch(object1[key],object2[key])){ return false; } } } } return true; }
[ "function", "objectSignaturesMatch", "(", "object1", ",", "object2", ")", "{", "// because typeof null is object we need to check for it here before Object.keys", "if", "(", "object1", "===", "null", "&&", "object2", "===", "null", ")", "{", "return", "true", ";", "}", "// if the objects have different lengths of keys we should fail immediatly", "if", "(", "Object", ".", "keys", "(", "object1", ")", ".", "length", "!==", "Object", ".", "keys", "(", "object2", ")", ".", "length", ")", "{", "return", "false", ";", "}", "// loop over all the keys in object1 (we know the objects have the same number of keys at this point)", "for", "(", "var", "key", "in", "object1", ")", "{", "// if the keys match keep checking if not we have a mismatch", "if", "(", "typeof", "object1", "[", "key", "]", "===", "typeof", "object2", "[", "key", "]", ")", "{", "if", "(", "typeof", "object1", "[", "key", "]", "===", "null", "&&", "typeof", "object2", "[", "key", "]", "===", "null", ")", "{", "}", "// if the keys represent an object make sure that it matches.", "else", "if", "(", "object1", "[", "key", "]", "instanceof", "Array", "&&", "object2", "[", "key", "]", "instanceof", "Array", ")", "{", "if", "(", "!", "arrySignaturesMatch", "(", "object1", "[", "key", "]", ",", "object2", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "// if the keys represent an array make sure it matches", "else", "if", "(", "typeof", "object1", "[", "key", "]", "===", "\"object\"", "&&", "typeof", "object2", "[", "key", "]", "===", "\"object\"", ")", "{", "if", "(", "!", "objectSignaturesMatch", "(", "object1", "[", "key", "]", ",", "object2", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "}", "}", "return", "true", ";", "}" ]
do the keys in object 1 match object 2?
[ "do", "the", "keys", "in", "object", "1", "match", "object", "2?" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/spec/SpecHelpers.js#L41-L80
35,455
Esri/geotrigger-js
spec/SpecHelpers.js
function() { var refArgs = Array.prototype.slice.call(arguments); var calledArgs = this.actual.mostRecentCall.args; var arg; for(arg in refArgs){ var ref = refArgs[arg]; var test = calledArgs[arg]; // if the types of the objects dont match if(typeof ref !== typeof test) { return false; // if ref and test are objects make then } else if(typeof ref === "object" && typeof test === "object") { if(!objectSignaturesMatch(ref, test)){ return false; } } else if(typeof ref === "array" && typeof test === "array") { if(!arrySignaturesMatch(ref, test)){ return false; } } } return true; }
javascript
function() { var refArgs = Array.prototype.slice.call(arguments); var calledArgs = this.actual.mostRecentCall.args; var arg; for(arg in refArgs){ var ref = refArgs[arg]; var test = calledArgs[arg]; // if the types of the objects dont match if(typeof ref !== typeof test) { return false; // if ref and test are objects make then } else if(typeof ref === "object" && typeof test === "object") { if(!objectSignaturesMatch(ref, test)){ return false; } } else if(typeof ref === "array" && typeof test === "array") { if(!arrySignaturesMatch(ref, test)){ return false; } } } return true; }
[ "function", "(", ")", "{", "var", "refArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "calledArgs", "=", "this", ".", "actual", ".", "mostRecentCall", ".", "args", ";", "var", "arg", ";", "for", "(", "arg", "in", "refArgs", ")", "{", "var", "ref", "=", "refArgs", "[", "arg", "]", ";", "var", "test", "=", "calledArgs", "[", "arg", "]", ";", "// if the types of the objects dont match", "if", "(", "typeof", "ref", "!==", "typeof", "test", ")", "{", "return", "false", ";", "// if ref and test are objects make then", "}", "else", "if", "(", "typeof", "ref", "===", "\"object\"", "&&", "typeof", "test", "===", "\"object\"", ")", "{", "if", "(", "!", "objectSignaturesMatch", "(", "ref", ",", "test", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "typeof", "ref", "===", "\"array\"", "&&", "typeof", "test", "===", "\"array\"", ")", "{", "if", "(", "!", "arrySignaturesMatch", "(", "ref", ",", "test", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
this is a lazy matcher for jasmine spies. it checks that the arguments for the last call made match all the arguments that are passed into the function, but does not care if the values match only that they are the same type. in short this only cares that all teh keys are the same and the types of values are the same, not the values themselves
[ "this", "is", "a", "lazy", "matcher", "for", "jasmine", "spies", ".", "it", "checks", "that", "the", "arguments", "for", "the", "last", "call", "made", "match", "all", "the", "arguments", "that", "are", "passed", "into", "the", "function", "but", "does", "not", "care", "if", "the", "values", "match", "only", "that", "they", "are", "the", "same", "type", ".", "in", "short", "this", "only", "cares", "that", "all", "teh", "keys", "are", "the", "same", "and", "the", "types", "of", "values", "are", "the", "same", "not", "the", "values", "themselves" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/spec/SpecHelpers.js#L91-L115
35,456
stefanjudis/credits
lib/analyzers.js
getAnalyzers
function getAnalyzers(config) { const methods = {}; const basePath = config.filePaths.analyzers; globby.sync(`${basePath}/*`) .forEach(analyzer => { const name = path.basename(analyzer); methods[name] = require(analyzer); }); return methods; }
javascript
function getAnalyzers(config) { const methods = {}; const basePath = config.filePaths.analyzers; globby.sync(`${basePath}/*`) .forEach(analyzer => { const name = path.basename(analyzer); methods[name] = require(analyzer); }); return methods; }
[ "function", "getAnalyzers", "(", "config", ")", "{", "const", "methods", "=", "{", "}", ";", "const", "basePath", "=", "config", ".", "filePaths", ".", "analyzers", ";", "globby", ".", "sync", "(", "`", "${", "basePath", "}", "`", ")", ".", "forEach", "(", "analyzer", "=>", "{", "const", "name", "=", "path", ".", "basename", "(", "analyzer", ")", ";", "methods", "[", "name", "]", "=", "require", "(", "analyzer", ")", ";", "}", ")", ";", "return", "methods", ";", "}" ]
Get all available analyzers @param {Object} config project configuration @return {Array} list of reporter methods
[ "Get", "all", "available", "analyzers" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers.js#L13-L24
35,457
7digital/7digital-api
lib/request.js
prepare
function prepare(data, consumerkey) { var prop; data = data || {}; for (prop in data) { if (data.hasOwnProperty(prop)) { if (_.isDate(data[prop])) { data[prop] = helpers.toYYYYMMDD(data[prop]); } } } data.oauth_consumer_key = consumerkey; return data; }
javascript
function prepare(data, consumerkey) { var prop; data = data || {}; for (prop in data) { if (data.hasOwnProperty(prop)) { if (_.isDate(data[prop])) { data[prop] = helpers.toYYYYMMDD(data[prop]); } } } data.oauth_consumer_key = consumerkey; return data; }
[ "function", "prepare", "(", "data", ",", "consumerkey", ")", "{", "var", "prop", ";", "data", "=", "data", "||", "{", "}", ";", "for", "(", "prop", "in", "data", ")", "{", "if", "(", "data", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "if", "(", "_", ".", "isDate", "(", "data", "[", "prop", "]", ")", ")", "{", "data", "[", "prop", "]", "=", "helpers", ".", "toYYYYMMDD", "(", "data", "[", "prop", "]", ")", ";", "}", "}", "}", "data", ".", "oauth_consumer_key", "=", "consumerkey", ";", "return", "data", ";", "}" ]
Formats request parameters as expected by the API. - @param {Object} data - hash of pararameters - @param {String} consumerkey - consumer key - @return {String} - Encoded parameter string
[ "Formats", "request", "parameters", "as", "expected", "by", "the", "API", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L20-L35
35,458
7digital/7digital-api
lib/request.js
logHeaders
function logHeaders(logger, headers) { return _.each(_.keys(headers), function (key) { logger.info(key + ': ' + headers[key]); }); }
javascript
function logHeaders(logger, headers) { return _.each(_.keys(headers), function (key) { logger.info(key + ': ' + headers[key]); }); }
[ "function", "logHeaders", "(", "logger", ",", "headers", ")", "{", "return", "_", ".", "each", "(", "_", ".", "keys", "(", "headers", ")", ",", "function", "(", "key", ")", "{", "logger", ".", "info", "(", "key", "+", "': '", "+", "headers", "[", "key", "]", ")", ";", "}", ")", ";", "}" ]
Logs out a headers hash - @param {Object} logger - The logger to use - @param {Object} headers - The hash of headers to log
[ "Logs", "out", "a", "headers", "hash", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L51-L55
35,459
7digital/7digital-api
lib/request.js
get
function get(endpointInfo, requestData, headers, credentials, logger, callback) { var normalisedData = prepare(requestData, credentials.consumerkey); var fullUrl = endpointInfo.url + '?' + qs.stringify(normalisedData); var hostInfo = { host: endpointInfo.host, port: endpointInfo.port }; // Decide whether to make an oauth signed request or not if (endpointInfo.authtype) { hostInfo.host = endpointInfo.sslHost; dispatchSecure(endpointInfo.url, 'GET', requestData, headers, endpointInfo.authtype, hostInfo, credentials, logger, callback); } else { dispatch(endpointInfo.url, 'GET', requestData, headers, hostInfo, credentials, logger, callback); } }
javascript
function get(endpointInfo, requestData, headers, credentials, logger, callback) { var normalisedData = prepare(requestData, credentials.consumerkey); var fullUrl = endpointInfo.url + '?' + qs.stringify(normalisedData); var hostInfo = { host: endpointInfo.host, port: endpointInfo.port }; // Decide whether to make an oauth signed request or not if (endpointInfo.authtype) { hostInfo.host = endpointInfo.sslHost; dispatchSecure(endpointInfo.url, 'GET', requestData, headers, endpointInfo.authtype, hostInfo, credentials, logger, callback); } else { dispatch(endpointInfo.url, 'GET', requestData, headers, hostInfo, credentials, logger, callback); } }
[ "function", "get", "(", "endpointInfo", ",", "requestData", ",", "headers", ",", "credentials", ",", "logger", ",", "callback", ")", "{", "var", "normalisedData", "=", "prepare", "(", "requestData", ",", "credentials", ".", "consumerkey", ")", ";", "var", "fullUrl", "=", "endpointInfo", ".", "url", "+", "'?'", "+", "qs", ".", "stringify", "(", "normalisedData", ")", ";", "var", "hostInfo", "=", "{", "host", ":", "endpointInfo", ".", "host", ",", "port", ":", "endpointInfo", ".", "port", "}", ";", "// Decide whether to make an oauth signed request or not", "if", "(", "endpointInfo", ".", "authtype", ")", "{", "hostInfo", ".", "host", "=", "endpointInfo", ".", "sslHost", ";", "dispatchSecure", "(", "endpointInfo", ".", "url", ",", "'GET'", ",", "requestData", ",", "headers", ",", "endpointInfo", ".", "authtype", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", ";", "}", "else", "{", "dispatch", "(", "endpointInfo", ".", "url", ",", "'GET'", ",", "requestData", ",", "headers", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", ";", "}", "}" ]
Makes a GET request to the API. - @param {Object} endpointInfo - Generic metadata about the endpoint to hit. - @param {Object} requestData - Parameters for this specific request. - @param {Object} headers - Custom headers for this request. - @param {Object} credentials - OAuth consumerkey and consumersecret. - @param {Object} logger - An object implementing the npm log levels. - @param {Function} callback - The callback to call with the response.
[ "Makes", "a", "GET", "request", "to", "the", "API", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L65-L85
35,460
7digital/7digital-api
lib/request.js
dispatchSecure
function dispatchSecure(path, httpMethod, requestData, headers, authtype, hostInfo, credentials, logger, callback) { var url; var is2Legged = authtype === '2-legged'; var token = is2Legged ? null : requestData.accesstoken; var secret = is2Legged ? null : requestData.accesssecret; var mergedHeaders = createHeaders(hostInfo.host, headers); var oauthClient = oauthHelper.createOAuthWrapper(credentials.consumerkey, credentials.consumersecret, mergedHeaders); var methodLookup = { 'POST' : oauthClient.post.bind(oauthClient), 'PUT' : oauthClient.put.bind(oauthClient) }; var oauthMethod = methodLookup[httpMethod]; hostInfo.port = hostInfo.port || 443; requestData = prepare(requestData, credentials.consumerkey); if (!is2Legged) { delete requestData.accesstoken; delete requestData.accesssecret; } url = buildSecureUrl(httpMethod, hostInfo, path, requestData); logger.info('token: ' + token + ' secret: ' + secret); logger.info(httpMethod + ': ' + url + ' (' + authtype + ' oauth)'); logHeaders(logger, mergedHeaders); function cbWithDataAndResponse(err, data, response) { var apiError; if (err) { // API server error if (err.statusCode && err.statusCode >= 400) { // non 200 status and string for response body is usually an // oauth error from one of the endpoints if (typeof err.data === 'string' && /oauth/i.test(err.data)) { apiError = new OAuthError(err.data, err.data + ': ' + path); } else { apiError = new ApiHttpError( response.statusCode, err.data, path); } return callback(apiError); } // Something unknown went wrong logger.error(err); return callback(err); } return callback(null, data, response); } if (httpMethod === 'GET') { return oauthClient.get(url, token, secret, cbWithDataAndResponse); } if ( oauthMethod ) { logger.info('DATA: ' + qs.stringify(requestData)); return oauthMethod(url, token, secret, requestData, 'application/x-www-form-urlencoded', cbWithDataAndResponse); } return callback(new Error('Unsupported HTTP verb: ' + httpMethod)); }
javascript
function dispatchSecure(path, httpMethod, requestData, headers, authtype, hostInfo, credentials, logger, callback) { var url; var is2Legged = authtype === '2-legged'; var token = is2Legged ? null : requestData.accesstoken; var secret = is2Legged ? null : requestData.accesssecret; var mergedHeaders = createHeaders(hostInfo.host, headers); var oauthClient = oauthHelper.createOAuthWrapper(credentials.consumerkey, credentials.consumersecret, mergedHeaders); var methodLookup = { 'POST' : oauthClient.post.bind(oauthClient), 'PUT' : oauthClient.put.bind(oauthClient) }; var oauthMethod = methodLookup[httpMethod]; hostInfo.port = hostInfo.port || 443; requestData = prepare(requestData, credentials.consumerkey); if (!is2Legged) { delete requestData.accesstoken; delete requestData.accesssecret; } url = buildSecureUrl(httpMethod, hostInfo, path, requestData); logger.info('token: ' + token + ' secret: ' + secret); logger.info(httpMethod + ': ' + url + ' (' + authtype + ' oauth)'); logHeaders(logger, mergedHeaders); function cbWithDataAndResponse(err, data, response) { var apiError; if (err) { // API server error if (err.statusCode && err.statusCode >= 400) { // non 200 status and string for response body is usually an // oauth error from one of the endpoints if (typeof err.data === 'string' && /oauth/i.test(err.data)) { apiError = new OAuthError(err.data, err.data + ': ' + path); } else { apiError = new ApiHttpError( response.statusCode, err.data, path); } return callback(apiError); } // Something unknown went wrong logger.error(err); return callback(err); } return callback(null, data, response); } if (httpMethod === 'GET') { return oauthClient.get(url, token, secret, cbWithDataAndResponse); } if ( oauthMethod ) { logger.info('DATA: ' + qs.stringify(requestData)); return oauthMethod(url, token, secret, requestData, 'application/x-www-form-urlencoded', cbWithDataAndResponse); } return callback(new Error('Unsupported HTTP verb: ' + httpMethod)); }
[ "function", "dispatchSecure", "(", "path", ",", "httpMethod", ",", "requestData", ",", "headers", ",", "authtype", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", "{", "var", "url", ";", "var", "is2Legged", "=", "authtype", "===", "'2-legged'", ";", "var", "token", "=", "is2Legged", "?", "null", ":", "requestData", ".", "accesstoken", ";", "var", "secret", "=", "is2Legged", "?", "null", ":", "requestData", ".", "accesssecret", ";", "var", "mergedHeaders", "=", "createHeaders", "(", "hostInfo", ".", "host", ",", "headers", ")", ";", "var", "oauthClient", "=", "oauthHelper", ".", "createOAuthWrapper", "(", "credentials", ".", "consumerkey", ",", "credentials", ".", "consumersecret", ",", "mergedHeaders", ")", ";", "var", "methodLookup", "=", "{", "'POST'", ":", "oauthClient", ".", "post", ".", "bind", "(", "oauthClient", ")", ",", "'PUT'", ":", "oauthClient", ".", "put", ".", "bind", "(", "oauthClient", ")", "}", ";", "var", "oauthMethod", "=", "methodLookup", "[", "httpMethod", "]", ";", "hostInfo", ".", "port", "=", "hostInfo", ".", "port", "||", "443", ";", "requestData", "=", "prepare", "(", "requestData", ",", "credentials", ".", "consumerkey", ")", ";", "if", "(", "!", "is2Legged", ")", "{", "delete", "requestData", ".", "accesstoken", ";", "delete", "requestData", ".", "accesssecret", ";", "}", "url", "=", "buildSecureUrl", "(", "httpMethod", ",", "hostInfo", ",", "path", ",", "requestData", ")", ";", "logger", ".", "info", "(", "'token: '", "+", "token", "+", "' secret: '", "+", "secret", ")", ";", "logger", ".", "info", "(", "httpMethod", "+", "': '", "+", "url", "+", "' ('", "+", "authtype", "+", "' oauth)'", ")", ";", "logHeaders", "(", "logger", ",", "mergedHeaders", ")", ";", "function", "cbWithDataAndResponse", "(", "err", ",", "data", ",", "response", ")", "{", "var", "apiError", ";", "if", "(", "err", ")", "{", "// API server error", "if", "(", "err", ".", "statusCode", "&&", "err", ".", "statusCode", ">=", "400", ")", "{", "// non 200 status and string for response body is usually an", "// oauth error from one of the endpoints", "if", "(", "typeof", "err", ".", "data", "===", "'string'", "&&", "/", "oauth", "/", "i", ".", "test", "(", "err", ".", "data", ")", ")", "{", "apiError", "=", "new", "OAuthError", "(", "err", ".", "data", ",", "err", ".", "data", "+", "': '", "+", "path", ")", ";", "}", "else", "{", "apiError", "=", "new", "ApiHttpError", "(", "response", ".", "statusCode", ",", "err", ".", "data", ",", "path", ")", ";", "}", "return", "callback", "(", "apiError", ")", ";", "}", "// Something unknown went wrong", "logger", ".", "error", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "return", "callback", "(", "null", ",", "data", ",", "response", ")", ";", "}", "if", "(", "httpMethod", "===", "'GET'", ")", "{", "return", "oauthClient", ".", "get", "(", "url", ",", "token", ",", "secret", ",", "cbWithDataAndResponse", ")", ";", "}", "if", "(", "oauthMethod", ")", "{", "logger", ".", "info", "(", "'DATA: '", "+", "qs", ".", "stringify", "(", "requestData", ")", ")", ";", "return", "oauthMethod", "(", "url", ",", "token", ",", "secret", ",", "requestData", ",", "'application/x-www-form-urlencoded'", ",", "cbWithDataAndResponse", ")", ";", "}", "return", "callback", "(", "new", "Error", "(", "'Unsupported HTTP verb: '", "+", "httpMethod", ")", ")", ";", "}" ]
Dispatches an oauth signed request to the API - @param {String} url - the path of the API url to request. - @param {String} httpMethod - @param {Object} requestData - hash of the parameters for the request. - @param {Object} headers - Headers for this request. - @param {String} authType - OAuth request type: '2-legged' or '3-legged' - @param {Object} hostInfo - API host information - @param {Function} callback - The callback to call with the response.
[ "Dispatches", "an", "oauth", "signed", "request", "to", "the", "API", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L131-L199
35,461
7digital/7digital-api
lib/request.js
dispatch
function dispatch(url, httpMethod, data, headers, hostInfo, credentials, logger, callback) { hostInfo.port = hostInfo.port || 80; var apiRequest, prop, hasErrored; var mergedHeaders = createHeaders(hostInfo.host, headers); var apiPath = url; data = prepare(data, credentials.consumerkey); // Special case for track previews: we explicitly request to be given // the XML response back instead of a redirect to the track download. if (url.indexOf('track/preview') >= 0) { data.redirect = 'false'; } if (httpMethod === 'GET') { url = url + '?' + qs.stringify(data); } logger.info(util.format('%s: http://%s:%s%s', httpMethod, hostInfo.host, hostInfo.port, url)); logHeaders(logger, mergedHeaders); // Make the request apiRequest = http.request({ method: httpMethod, hostname: hostInfo.host, // Force scheme to http for browserify otherwise it will pick up the // scheme from window.location.protocol which is app:// in firefoxos scheme: 'http', // Set this so browserify doesn't set it to true on the xhr, which // causes an http status of 0 and empty response text as it forces // the XHR to do a pre-flight access-control check and the API // currently does not set CORS headers. withCredentials: false, path: url, port: hostInfo.port, headers: mergedHeaders }, function handleResponse(response) { var responseBuffer = ''; if (typeof response.setEncoding === 'function') { response.setEncoding('utf8'); } response.on('data', function bufferData(chunk) { responseBuffer += chunk; }); response.on('end', function endResponse() { if (+response.statusCode >= 400) { return callback(new ApiHttpError( response.statusCode, responseBuffer, apiPath)); } if (!hasErrored) { return callback(null, responseBuffer, response); } }); }); apiRequest.on('error', function logErrorAndCallback(err) { // Flag that we've errored so we don't call the callback twice // if we get an end event on the response. hasErrored = true; logger.info('Error fetching [' + url + ']. Body:\n' + err); return callback(new RequestError(err, url)); }); if (httpMethod === 'GET') { apiRequest.end(); } else { apiRequest.end(data); } }
javascript
function dispatch(url, httpMethod, data, headers, hostInfo, credentials, logger, callback) { hostInfo.port = hostInfo.port || 80; var apiRequest, prop, hasErrored; var mergedHeaders = createHeaders(hostInfo.host, headers); var apiPath = url; data = prepare(data, credentials.consumerkey); // Special case for track previews: we explicitly request to be given // the XML response back instead of a redirect to the track download. if (url.indexOf('track/preview') >= 0) { data.redirect = 'false'; } if (httpMethod === 'GET') { url = url + '?' + qs.stringify(data); } logger.info(util.format('%s: http://%s:%s%s', httpMethod, hostInfo.host, hostInfo.port, url)); logHeaders(logger, mergedHeaders); // Make the request apiRequest = http.request({ method: httpMethod, hostname: hostInfo.host, // Force scheme to http for browserify otherwise it will pick up the // scheme from window.location.protocol which is app:// in firefoxos scheme: 'http', // Set this so browserify doesn't set it to true on the xhr, which // causes an http status of 0 and empty response text as it forces // the XHR to do a pre-flight access-control check and the API // currently does not set CORS headers. withCredentials: false, path: url, port: hostInfo.port, headers: mergedHeaders }, function handleResponse(response) { var responseBuffer = ''; if (typeof response.setEncoding === 'function') { response.setEncoding('utf8'); } response.on('data', function bufferData(chunk) { responseBuffer += chunk; }); response.on('end', function endResponse() { if (+response.statusCode >= 400) { return callback(new ApiHttpError( response.statusCode, responseBuffer, apiPath)); } if (!hasErrored) { return callback(null, responseBuffer, response); } }); }); apiRequest.on('error', function logErrorAndCallback(err) { // Flag that we've errored so we don't call the callback twice // if we get an end event on the response. hasErrored = true; logger.info('Error fetching [' + url + ']. Body:\n' + err); return callback(new RequestError(err, url)); }); if (httpMethod === 'GET') { apiRequest.end(); } else { apiRequest.end(data); } }
[ "function", "dispatch", "(", "url", ",", "httpMethod", ",", "data", ",", "headers", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", "{", "hostInfo", ".", "port", "=", "hostInfo", ".", "port", "||", "80", ";", "var", "apiRequest", ",", "prop", ",", "hasErrored", ";", "var", "mergedHeaders", "=", "createHeaders", "(", "hostInfo", ".", "host", ",", "headers", ")", ";", "var", "apiPath", "=", "url", ";", "data", "=", "prepare", "(", "data", ",", "credentials", ".", "consumerkey", ")", ";", "// Special case for track previews: we explicitly request to be given", "// the XML response back instead of a redirect to the track download.", "if", "(", "url", ".", "indexOf", "(", "'track/preview'", ")", ">=", "0", ")", "{", "data", ".", "redirect", "=", "'false'", ";", "}", "if", "(", "httpMethod", "===", "'GET'", ")", "{", "url", "=", "url", "+", "'?'", "+", "qs", ".", "stringify", "(", "data", ")", ";", "}", "logger", ".", "info", "(", "util", ".", "format", "(", "'%s: http://%s:%s%s'", ",", "httpMethod", ",", "hostInfo", ".", "host", ",", "hostInfo", ".", "port", ",", "url", ")", ")", ";", "logHeaders", "(", "logger", ",", "mergedHeaders", ")", ";", "// Make the request", "apiRequest", "=", "http", ".", "request", "(", "{", "method", ":", "httpMethod", ",", "hostname", ":", "hostInfo", ".", "host", ",", "// Force scheme to http for browserify otherwise it will pick up the", "// scheme from window.location.protocol which is app:// in firefoxos", "scheme", ":", "'http'", ",", "// Set this so browserify doesn't set it to true on the xhr, which", "// causes an http status of 0 and empty response text as it forces", "// the XHR to do a pre-flight access-control check and the API", "// currently does not set CORS headers.", "withCredentials", ":", "false", ",", "path", ":", "url", ",", "port", ":", "hostInfo", ".", "port", ",", "headers", ":", "mergedHeaders", "}", ",", "function", "handleResponse", "(", "response", ")", "{", "var", "responseBuffer", "=", "''", ";", "if", "(", "typeof", "response", ".", "setEncoding", "===", "'function'", ")", "{", "response", ".", "setEncoding", "(", "'utf8'", ")", ";", "}", "response", ".", "on", "(", "'data'", ",", "function", "bufferData", "(", "chunk", ")", "{", "responseBuffer", "+=", "chunk", ";", "}", ")", ";", "response", ".", "on", "(", "'end'", ",", "function", "endResponse", "(", ")", "{", "if", "(", "+", "response", ".", "statusCode", ">=", "400", ")", "{", "return", "callback", "(", "new", "ApiHttpError", "(", "response", ".", "statusCode", ",", "responseBuffer", ",", "apiPath", ")", ")", ";", "}", "if", "(", "!", "hasErrored", ")", "{", "return", "callback", "(", "null", ",", "responseBuffer", ",", "response", ")", ";", "}", "}", ")", ";", "}", ")", ";", "apiRequest", ".", "on", "(", "'error'", ",", "function", "logErrorAndCallback", "(", "err", ")", "{", "// Flag that we've errored so we don't call the callback twice", "// if we get an end event on the response.", "hasErrored", "=", "true", ";", "logger", ".", "info", "(", "'Error fetching ['", "+", "url", "+", "']. Body:\\n'", "+", "err", ")", ";", "return", "callback", "(", "new", "RequestError", "(", "err", ",", "url", ")", ")", ";", "}", ")", ";", "if", "(", "httpMethod", "===", "'GET'", ")", "{", "apiRequest", ".", "end", "(", ")", ";", "}", "else", "{", "apiRequest", ".", "end", "(", "data", ")", ";", "}", "}" ]
Dispatches requests to the API. Serializes the data in keeping with the API specification and applies approriate HTTP headers. - @param {String} url - the URL on the API to make the request to. - @param {String} httpMethod - @param {Object} data - hash of the parameters for the request. - @param {Object} headers - Headers for this request. - @param {Object} hostInfo - hash of host, port and prefix - @param {Object} credentials - hash of oauth consumer key and secret - @param {Object} logger - an object implementing the npm log levels - @param {Function} callback
[ "Dispatches", "requests", "to", "the", "API", ".", "Serializes", "the", "data", "in", "keeping", "with", "the", "API", "specification", "and", "applies", "approriate", "HTTP", "headers", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L212-L289
35,462
7digital/7digital-api
lib/logger.js
makeLogger
function makeLogger(level, method) { // The logger function to return takes a variable number of arguments // and formats like console.log function logger() { var args = [].slice.call(arguments); var format = level.toUpperCase() + ': (api-client) ' + args.shift(); var logArgs = [format].concat(args); return console[method].apply(console, logArgs); } return (level === 'warn' || level === 'error' || level === 'info') ? logger : function() {}; }
javascript
function makeLogger(level, method) { // The logger function to return takes a variable number of arguments // and formats like console.log function logger() { var args = [].slice.call(arguments); var format = level.toUpperCase() + ': (api-client) ' + args.shift(); var logArgs = [format].concat(args); return console[method].apply(console, logArgs); } return (level === 'warn' || level === 'error' || level === 'info') ? logger : function() {}; }
[ "function", "makeLogger", "(", "level", ",", "method", ")", "{", "// The logger function to return takes a variable number of arguments", "// and formats like console.log", "function", "logger", "(", ")", "{", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "format", "=", "level", ".", "toUpperCase", "(", ")", "+", "': (api-client) '", "+", "args", ".", "shift", "(", ")", ";", "var", "logArgs", "=", "[", "format", "]", ".", "concat", "(", "args", ")", ";", "return", "console", "[", "method", "]", ".", "apply", "(", "console", ",", "logArgs", ")", ";", "}", "return", "(", "level", "===", "'warn'", "||", "level", "===", "'error'", "||", "level", "===", "'info'", ")", "?", "logger", ":", "function", "(", ")", "{", "}", ";", "}" ]
Makes a logger function that formats messages sensibly and logs to either stdout or stderr. - @param {String} level - the log level. - @param {String} method - the method on the console object to call. - @return {Function} - the logging function.
[ "Makes", "a", "logger", "function", "that", "formats", "messages", "sensibly", "and", "logs", "to", "either", "stdout", "or", "stderr", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/logger.js#L9-L23
35,463
7digital/7digital-api
lib/response-cleaners/ensure-collections.js
ensureCollections
function ensureCollections(collectionPaths, response) { var basket; _.each(collectionPaths, function checkLength(item) { var parts = item.split('.'); var allPartsButLast = _.initial(parts); var lastPart = _.last(parts); var parents = _.reduce(allPartsButLast, function (chain, part) { return chain.pluck(part).compact().flatten(); }, _([response])).value(); parents.map(function (parent) { if (parent[lastPart]) { parent[lastPart] = arrayify(parent[lastPart]); } else { parent[lastPart] = []; } }); }); basket = response.basket; if (basket) { if (basket.basketItems.basketItem) { basket.basketItems = basket.basketItems.basketItem; } else { basket.basketItems = []; } } return response; }
javascript
function ensureCollections(collectionPaths, response) { var basket; _.each(collectionPaths, function checkLength(item) { var parts = item.split('.'); var allPartsButLast = _.initial(parts); var lastPart = _.last(parts); var parents = _.reduce(allPartsButLast, function (chain, part) { return chain.pluck(part).compact().flatten(); }, _([response])).value(); parents.map(function (parent) { if (parent[lastPart]) { parent[lastPart] = arrayify(parent[lastPart]); } else { parent[lastPart] = []; } }); }); basket = response.basket; if (basket) { if (basket.basketItems.basketItem) { basket.basketItems = basket.basketItems.basketItem; } else { basket.basketItems = []; } } return response; }
[ "function", "ensureCollections", "(", "collectionPaths", ",", "response", ")", "{", "var", "basket", ";", "_", ".", "each", "(", "collectionPaths", ",", "function", "checkLength", "(", "item", ")", "{", "var", "parts", "=", "item", ".", "split", "(", "'.'", ")", ";", "var", "allPartsButLast", "=", "_", ".", "initial", "(", "parts", ")", ";", "var", "lastPart", "=", "_", ".", "last", "(", "parts", ")", ";", "var", "parents", "=", "_", ".", "reduce", "(", "allPartsButLast", ",", "function", "(", "chain", ",", "part", ")", "{", "return", "chain", ".", "pluck", "(", "part", ")", ".", "compact", "(", ")", ".", "flatten", "(", ")", ";", "}", ",", "_", "(", "[", "response", "]", ")", ")", ".", "value", "(", ")", ";", "parents", ".", "map", "(", "function", "(", "parent", ")", "{", "if", "(", "parent", "[", "lastPart", "]", ")", "{", "parent", "[", "lastPart", "]", "=", "arrayify", "(", "parent", "[", "lastPart", "]", ")", ";", "}", "else", "{", "parent", "[", "lastPart", "]", "=", "[", "]", ";", "}", "}", ")", ";", "}", ")", ";", "basket", "=", "response", ".", "basket", ";", "if", "(", "basket", ")", "{", "if", "(", "basket", ".", "basketItems", ".", "basketItem", ")", "{", "basket", ".", "basketItems", "=", "basket", ".", "basketItems", ".", "basketItem", ";", "}", "else", "{", "basket", ".", "basketItems", "=", "[", "]", ";", "}", "}", "return", "response", ";", "}" ]
The API returns resources as either a single object or an array. This makes responses fiddly to deal with for consumers as they manually check whether the resource has a length an access the property appropriately. This method checks the reponse for the existence of a property path and if it is an object wraps it in an array. - @param {String} collectionPaths - @param {Object} response - @return {Object} the modified response
[ "The", "API", "returns", "resources", "as", "either", "a", "single", "object", "or", "an", "array", ".", "This", "makes", "responses", "fiddly", "to", "deal", "with", "for", "consumers", "as", "they", "manually", "check", "whether", "the", "resource", "has", "a", "length", "an", "access", "the", "property", "appropriately", ".", "This", "method", "checks", "the", "reponse", "for", "the", "existence", "of", "a", "property", "path", "and", "if", "it", "is", "an", "object", "wraps", "it", "in", "an", "array", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/response-cleaners/ensure-collections.js#L18-L47
35,464
7digital/7digital-api
lib/api.js
Api
function Api(options, schema) { var prop, resourceOptions, resourceConstructor; var apiRoot = this; // Set default options for any unsupplied overrides _.defaults(options, config); this.options = options; this.schema = schema; configureSchemaFromEnv(this.schema); // Creates a constructor with the pre-built resource as its prototype // this is syntactic sugar to allow callers to new up the resources. function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; } for (prop in schema.resources) { if (schema.resources.hasOwnProperty(prop)) { resourceOptions = options; resourceOptions.api = this; resourceOptions.resourceDefinition = schema.resources[prop]; this[prop] = createResourceConstructor( new Resource(resourceOptions, schema)); } } this['OAuth'] = createResourceConstructor(new OAuth(options)); }
javascript
function Api(options, schema) { var prop, resourceOptions, resourceConstructor; var apiRoot = this; // Set default options for any unsupplied overrides _.defaults(options, config); this.options = options; this.schema = schema; configureSchemaFromEnv(this.schema); // Creates a constructor with the pre-built resource as its prototype // this is syntactic sugar to allow callers to new up the resources. function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; } for (prop in schema.resources) { if (schema.resources.hasOwnProperty(prop)) { resourceOptions = options; resourceOptions.api = this; resourceOptions.resourceDefinition = schema.resources[prop]; this[prop] = createResourceConstructor( new Resource(resourceOptions, schema)); } } this['OAuth'] = createResourceConstructor(new OAuth(options)); }
[ "function", "Api", "(", "options", ",", "schema", ")", "{", "var", "prop", ",", "resourceOptions", ",", "resourceConstructor", ";", "var", "apiRoot", "=", "this", ";", "// Set default options for any unsupplied overrides", "_", ".", "defaults", "(", "options", ",", "config", ")", ";", "this", ".", "options", "=", "options", ";", "this", ".", "schema", "=", "schema", ";", "configureSchemaFromEnv", "(", "this", ".", "schema", ")", ";", "// Creates a constructor with the pre-built resource as its prototype", "// this is syntactic sugar to allow callers to new up the resources.", "function", "createResourceConstructor", "(", "resourcePrototype", ")", "{", "function", "APIResource", "(", "resourceOptions", ")", "{", "// Allow creating resources without `new` keyword", "if", "(", "!", "(", "this", "instanceof", "APIResource", ")", ")", "{", "return", "new", "APIResource", "(", "resourceOptions", ")", ";", "}", "resourceOptions", "=", "resourceOptions", "||", "{", "}", ";", "// Override any default options for all requests on this resource", "_", ".", "defaults", "(", "resourceOptions", ".", "defaultParams", ",", "apiRoot", ".", "options", ".", "defaultParams", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ".", "headers", ",", "apiRoot", ".", "options", ".", "headers", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ",", "apiRoot", ".", "options", ")", ";", "this", ".", "format", "=", "resourceOptions", ".", "format", ";", "this", ".", "logger", "=", "resourceOptions", ".", "logger", ";", "this", ".", "defaultParams", "=", "resourceOptions", ".", "defaultParams", ";", "this", ".", "headers", "=", "resourceOptions", ".", "headers", ";", "}", "APIResource", ".", "prototype", "=", "resourcePrototype", ";", "return", "APIResource", ";", "}", "for", "(", "prop", "in", "schema", ".", "resources", ")", "{", "if", "(", "schema", ".", "resources", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "resourceOptions", "=", "options", ";", "resourceOptions", ".", "api", "=", "this", ";", "resourceOptions", ".", "resourceDefinition", "=", "schema", ".", "resources", "[", "prop", "]", ";", "this", "[", "prop", "]", "=", "createResourceConstructor", "(", "new", "Resource", "(", "resourceOptions", ",", "schema", ")", ")", ";", "}", "}", "this", "[", "'OAuth'", "]", "=", "createResourceConstructor", "(", "new", "OAuth", "(", "options", ")", ")", ";", "}" ]
API Creates a new API wrapper from a schema definition - @param {Object} options - The API options, see below - @param {Object} schema - The definition of the api resources and actions see the assets/7digital-api-schema json file. - @constructor - @param {Object} options The options parameter should have the following properties: - `consumerkey` your application's oauth consumer key - `consumersecret` your application's oauth consumer secret - `format` the response format - `logger` a logger instance for output
[ "API", "Creates", "a", "new", "API", "wrapper", "from", "a", "schema", "definition", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/api.js#L56-L107
35,465
7digital/7digital-api
lib/api.js
createResourceConstructor
function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; }
javascript
function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; }
[ "function", "createResourceConstructor", "(", "resourcePrototype", ")", "{", "function", "APIResource", "(", "resourceOptions", ")", "{", "// Allow creating resources without `new` keyword", "if", "(", "!", "(", "this", "instanceof", "APIResource", ")", ")", "{", "return", "new", "APIResource", "(", "resourceOptions", ")", ";", "}", "resourceOptions", "=", "resourceOptions", "||", "{", "}", ";", "// Override any default options for all requests on this resource", "_", ".", "defaults", "(", "resourceOptions", ".", "defaultParams", ",", "apiRoot", ".", "options", ".", "defaultParams", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ".", "headers", ",", "apiRoot", ".", "options", ".", "headers", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ",", "apiRoot", ".", "options", ")", ";", "this", ".", "format", "=", "resourceOptions", ".", "format", ";", "this", ".", "logger", "=", "resourceOptions", ".", "logger", ";", "this", ".", "defaultParams", "=", "resourceOptions", ".", "defaultParams", ";", "this", ".", "headers", "=", "resourceOptions", ".", "headers", ";", "}", "APIResource", ".", "prototype", "=", "resourcePrototype", ";", "return", "APIResource", ";", "}" ]
Creates a constructor with the pre-built resource as its prototype this is syntactic sugar to allow callers to new up the resources.
[ "Creates", "a", "constructor", "with", "the", "pre", "-", "built", "resource", "as", "its", "prototype", "this", "is", "syntactic", "sugar", "to", "allow", "callers", "to", "new", "up", "the", "resources", "." ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/api.js#L69-L92
35,466
danillouz/devrant
src/index.js
_getIdByUsername
function _getIdByUsername(username) { const url = `${API}/get-user-id`; const params = { app: 3, username }; return http .GET(url, params) .then(data => data.user_id); }
javascript
function _getIdByUsername(username) { const url = `${API}/get-user-id`; const params = { app: 3, username }; return http .GET(url, params) .then(data => data.user_id); }
[ "function", "_getIdByUsername", "(", "username", ")", "{", "const", "url", "=", "`", "${", "API", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", ",", "username", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "user_id", ")", ";", "}" ]
Retrieve the user id associated with the devRant username. @private @param {String} username - the devRant username @return {Promise} Resolves with the user id
[ "Retrieve", "the", "user", "id", "associated", "with", "the", "devRant", "username", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L47-L57
35,467
danillouz/devrant
src/index.js
rant
function rant(id = _noRantIdError()) { const url = `${API}/devrant/rants/${id}`; const params = { app: 3 }; return http.GET(url, params); }
javascript
function rant(id = _noRantIdError()) { const url = `${API}/devrant/rants/${id}`; const params = { app: 3 }; return http.GET(url, params); }
[ "function", "rant", "(", "id", "=", "_noRantIdError", "(", ")", ")", "{", "const", "url", "=", "`", "${", "API", "}", "${", "id", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ";", "}" ]
Retrieve a single rant from devRant. Use this method to retrieve a rant with its full text and comments. @param {String} id - the rant id @return {Promise} Resolves with the fetched rant
[ "Retrieve", "a", "single", "rant", "from", "devRant", ".", "Use", "this", "method", "to", "retrieve", "a", "rant", "with", "its", "full", "text", "and", "comments", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L67-L72
35,468
danillouz/devrant
src/index.js
rants
function rants({ sort = 'algo', limit = 50, skip = 0 } = {}) { const url = `${API}/devrant/rants`; const params = { app: 3, sort, limit, skip }; return http .GET(url, params) .then(data => data.rants); }
javascript
function rants({ sort = 'algo', limit = 50, skip = 0 } = {}) { const url = `${API}/devrant/rants`; const params = { app: 3, sort, limit, skip }; return http .GET(url, params) .then(data => data.rants); }
[ "function", "rants", "(", "{", "sort", "=", "'algo'", ",", "limit", "=", "50", ",", "skip", "=", "0", "}", "=", "{", "}", ")", "{", "const", "url", "=", "`", "${", "API", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", ",", "sort", ",", "limit", ",", "skip", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "rants", ")", ";", "}" ]
Retrieve rants from devRant. @param {Object} options - sort (by `algo`, `recent` or `top`), limit and skip @return {Promise} Resolves with the fetched rants
[ "Retrieve", "rants", "from", "devRant", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L81-L95
35,469
danillouz/devrant
src/index.js
search
function search(term = _noSearchTermError()) { const url = `${API}/devrant/search`; const params = { app: 3, term }; return http .GET(url, params) .then(data => data.results); }
javascript
function search(term = _noSearchTermError()) { const url = `${API}/devrant/search`; const params = { app: 3, term }; return http .GET(url, params) .then(data => data.results); }
[ "function", "search", "(", "term", "=", "_noSearchTermError", "(", ")", ")", "{", "const", "url", "=", "`", "${", "API", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", ",", "term", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "results", ")", ";", "}" ]
Retrieve rants from devRant that match a specific search term. @param {String} term - the search term @return {Promise} Resolves with the fetched rants
[ "Retrieve", "rants", "from", "devRant", "that", "match", "a", "specific", "search", "term", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L105-L115
35,470
danillouz/devrant
src/index.js
profile
function profile(username = _noUsernameError()) { return co(function *resolveUsername() { const userId = yield _getIdByUsername(username); const url = `${API}/users/${userId}`; const params = { app: 3 }; return http .GET(url, params) .then(data => data.profile); }); }
javascript
function profile(username = _noUsernameError()) { return co(function *resolveUsername() { const userId = yield _getIdByUsername(username); const url = `${API}/users/${userId}`; const params = { app: 3 }; return http .GET(url, params) .then(data => data.profile); }); }
[ "function", "profile", "(", "username", "=", "_noUsernameError", "(", ")", ")", "{", "return", "co", "(", "function", "*", "resolveUsername", "(", ")", "{", "const", "userId", "=", "yield", "_getIdByUsername", "(", "username", ")", ";", "const", "url", "=", "`", "${", "API", "}", "${", "userId", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "profile", ")", ";", "}", ")", ";", "}" ]
Retrieve the profile of a devRant user by username. @param {String} username - the devRant username @return {Promise} Resolves with the fetched user profile
[ "Retrieve", "the", "profile", "of", "a", "devRant", "user", "by", "username", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L124-L134
35,471
moimikey/iso3166-1
src/index.js
to2
function to2 (alpha3) { if (alpha3 && alpha3.length > 1) state = alpha3 if (state.length !== 3) return state return ISOCodes.filter(function (row) { return row.alpha3 === state })[0].alpha2 }
javascript
function to2 (alpha3) { if (alpha3 && alpha3.length > 1) state = alpha3 if (state.length !== 3) return state return ISOCodes.filter(function (row) { return row.alpha3 === state })[0].alpha2 }
[ "function", "to2", "(", "alpha3", ")", "{", "if", "(", "alpha3", "&&", "alpha3", ".", "length", ">", "1", ")", "state", "=", "alpha3", "if", "(", "state", ".", "length", "!==", "3", ")", "return", "state", "return", "ISOCodes", ".", "filter", "(", "function", "(", "row", ")", "{", "return", "row", ".", "alpha3", "===", "state", "}", ")", "[", "0", "]", ".", "alpha2", "}" ]
Convert an ISO 3166-1 alpha-3 code to alpha-2 @param {String} alpha3 USA @return {String}
[ "Convert", "an", "ISO", "3166", "-", "1", "alpha", "-", "3", "code", "to", "alpha", "-", "2" ]
f3596c1957e5c35d2a33f71567265f0a3bf571b7
https://github.com/moimikey/iso3166-1/blob/f3596c1957e5c35d2a33f71567265f0a3bf571b7/src/index.js#L14-L20
35,472
moimikey/iso3166-1
src/index.js
to3
function to3 (alpha2) { if (alpha2 && alpha2.length > 1) state = alpha2 if (state.length !== 2) return state return ISOCodes.filter(function (row) { return row.alpha2 === state })[0].alpha3 }
javascript
function to3 (alpha2) { if (alpha2 && alpha2.length > 1) state = alpha2 if (state.length !== 2) return state return ISOCodes.filter(function (row) { return row.alpha2 === state })[0].alpha3 }
[ "function", "to3", "(", "alpha2", ")", "{", "if", "(", "alpha2", "&&", "alpha2", ".", "length", ">", "1", ")", "state", "=", "alpha2", "if", "(", "state", ".", "length", "!==", "2", ")", "return", "state", "return", "ISOCodes", ".", "filter", "(", "function", "(", "row", ")", "{", "return", "row", ".", "alpha2", "===", "state", "}", ")", "[", "0", "]", ".", "alpha3", "}" ]
Convert an ISO 3166-1 alpha-2 code to alpha-3 @param {String} alpha2 US @return {String}
[ "Convert", "an", "ISO", "3166", "-", "1", "alpha", "-", "2", "code", "to", "alpha", "-", "3" ]
f3596c1957e5c35d2a33f71567265f0a3bf571b7
https://github.com/moimikey/iso3166-1/blob/f3596c1957e5c35d2a33f71567265f0a3bf571b7/src/index.js#L28-L34
35,473
7digital/7digital-api
lib/resource.js
Resource
function Resource(options, schema) { this.logger = options.logger; this.resourceName = options.resourceDefinition.resource; this.host = options.resourceDefinition.host || schema.host; this.sslHost = options.resourceDefinition.sslHost || schema.sslHost; this.port = options.resourceDefinition.port || schema.port; this.prefix = options.resourceDefinition.prefix || schema.prefix; this.consumerkey = options.consumerkey; this.consumersecret = options.consumersecret; if(this.logger.silly) { this.logger.silly('Creating constructor for resource: ' + this.resourceName); } _.each(options.resourceDefinition.actions, function processAction(action) { this.createAction(action, options.userManagement); }, this); }
javascript
function Resource(options, schema) { this.logger = options.logger; this.resourceName = options.resourceDefinition.resource; this.host = options.resourceDefinition.host || schema.host; this.sslHost = options.resourceDefinition.sslHost || schema.sslHost; this.port = options.resourceDefinition.port || schema.port; this.prefix = options.resourceDefinition.prefix || schema.prefix; this.consumerkey = options.consumerkey; this.consumersecret = options.consumersecret; if(this.logger.silly) { this.logger.silly('Creating constructor for resource: ' + this.resourceName); } _.each(options.resourceDefinition.actions, function processAction(action) { this.createAction(action, options.userManagement); }, this); }
[ "function", "Resource", "(", "options", ",", "schema", ")", "{", "this", ".", "logger", "=", "options", ".", "logger", ";", "this", ".", "resourceName", "=", "options", ".", "resourceDefinition", ".", "resource", ";", "this", ".", "host", "=", "options", ".", "resourceDefinition", ".", "host", "||", "schema", ".", "host", ";", "this", ".", "sslHost", "=", "options", ".", "resourceDefinition", ".", "sslHost", "||", "schema", ".", "sslHost", ";", "this", ".", "port", "=", "options", ".", "resourceDefinition", ".", "port", "||", "schema", ".", "port", ";", "this", ".", "prefix", "=", "options", ".", "resourceDefinition", ".", "prefix", "||", "schema", ".", "prefix", ";", "this", ".", "consumerkey", "=", "options", ".", "consumerkey", ";", "this", ".", "consumersecret", "=", "options", ".", "consumersecret", ";", "if", "(", "this", ".", "logger", ".", "silly", ")", "{", "this", ".", "logger", ".", "silly", "(", "'Creating constructor for resource: '", "+", "this", ".", "resourceName", ")", ";", "}", "_", ".", "each", "(", "options", ".", "resourceDefinition", ".", "actions", ",", "function", "processAction", "(", "action", ")", "{", "this", ".", "createAction", "(", "action", ",", "options", ".", "userManagement", ")", ";", "}", ",", "this", ")", ";", "}" ]
A resource on the API, instances of this are used as the prototype of instances of each API resource. This constructor will build up a method for each action that can be performed on the resource. - @param {Object} options - @param {Object} schema The `options` argument should have the following properties: - `resourceDefinition` - the definition of the resource and its actions from the schema definition. - `consumerkey` - the oauth consumerkey - `consumersecret` the oauth consumersecret - `schema` - the schema defintion - `format` - the desired response format - `logger` - for logging output
[ "A", "resource", "on", "the", "API", "instances", "of", "this", "are", "used", "as", "the", "prototype", "of", "instances", "of", "each", "API", "resource", ".", "This", "constructor", "will", "build", "up", "a", "method", "for", "each", "action", "that", "can", "be", "performed", "on", "the", "resource", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/resource.js#L24-L42
35,474
MarkHerhold/palin
palin.js
truncFilename
function truncFilename(path, rootFolderName) { // bail if a string wasn't provided if (typeof path !== 'string') { return path; } var index = path.indexOf(rootFolderName); if (index > 0) { return path.substring(index + rootFolderName.length + 1); } else { return path; } }
javascript
function truncFilename(path, rootFolderName) { // bail if a string wasn't provided if (typeof path !== 'string') { return path; } var index = path.indexOf(rootFolderName); if (index > 0) { return path.substring(index + rootFolderName.length + 1); } else { return path; } }
[ "function", "truncFilename", "(", "path", ",", "rootFolderName", ")", "{", "// bail if a string wasn't provided", "if", "(", "typeof", "path", "!==", "'string'", ")", "{", "return", "path", ";", "}", "var", "index", "=", "path", ".", "indexOf", "(", "rootFolderName", ")", ";", "if", "(", "index", ">", "0", ")", "{", "return", "path", ".", "substring", "(", "index", "+", "rootFolderName", ".", "length", "+", "1", ")", ";", "}", "else", "{", "return", "path", ";", "}", "}" ]
shortens the file name to exclude any path before the project folder name @param path: file path string. e.g. /home/mark/myproj/run.js @param rootFolderName: root folder for the project. e.g. "myproj" @return the shortened file path string
[ "shortens", "the", "file", "name", "to", "exclude", "any", "path", "before", "the", "project", "folder", "name" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L11-L23
35,475
MarkHerhold/palin
palin.js
getTimestampString
function getTimestampString(date) { // all this nasty code is faster (~30k ops/sec) than doing "moment(date).format('HH:mm:ss:SSS')" and means 0 dependencies var hour = '0' + date.getHours(); hour = hour.slice(hour.length - 2); var minute = '0' + date.getMinutes(); minute = minute.slice(minute.length - 2); var second = '0' + date.getSeconds(); second = second.slice(second.length - 2); var ms = '' + date.getMilliseconds(); // https://github.com/MarkHerhold/palin/issues/6 // this is faster than using an actual left-pad algorithm if (ms.length === 1) { ms = '00' + ms; } else if (ms.length === 2) { ms = '0' + ms; } // no modifications for 3 or more digits return chalk.dim(`${hour}:${minute}:${second}:${ms}`); }
javascript
function getTimestampString(date) { // all this nasty code is faster (~30k ops/sec) than doing "moment(date).format('HH:mm:ss:SSS')" and means 0 dependencies var hour = '0' + date.getHours(); hour = hour.slice(hour.length - 2); var minute = '0' + date.getMinutes(); minute = minute.slice(minute.length - 2); var second = '0' + date.getSeconds(); second = second.slice(second.length - 2); var ms = '' + date.getMilliseconds(); // https://github.com/MarkHerhold/palin/issues/6 // this is faster than using an actual left-pad algorithm if (ms.length === 1) { ms = '00' + ms; } else if (ms.length === 2) { ms = '0' + ms; } // no modifications for 3 or more digits return chalk.dim(`${hour}:${minute}:${second}:${ms}`); }
[ "function", "getTimestampString", "(", "date", ")", "{", "// all this nasty code is faster (~30k ops/sec) than doing \"moment(date).format('HH:mm:ss:SSS')\" and means 0 dependencies", "var", "hour", "=", "'0'", "+", "date", ".", "getHours", "(", ")", ";", "hour", "=", "hour", ".", "slice", "(", "hour", ".", "length", "-", "2", ")", ";", "var", "minute", "=", "'0'", "+", "date", ".", "getMinutes", "(", ")", ";", "minute", "=", "minute", ".", "slice", "(", "minute", ".", "length", "-", "2", ")", ";", "var", "second", "=", "'0'", "+", "date", ".", "getSeconds", "(", ")", ";", "second", "=", "second", ".", "slice", "(", "second", ".", "length", "-", "2", ")", ";", "var", "ms", "=", "''", "+", "date", ".", "getMilliseconds", "(", ")", ";", "// https://github.com/MarkHerhold/palin/issues/6", "// this is faster than using an actual left-pad algorithm", "if", "(", "ms", ".", "length", "===", "1", ")", "{", "ms", "=", "'00'", "+", "ms", ";", "}", "else", "if", "(", "ms", ".", "length", "===", "2", ")", "{", "ms", "=", "'0'", "+", "ms", ";", "}", "// no modifications for 3 or more digits", "return", "chalk", ".", "dim", "(", "`", "${", "hour", "}", "${", "minute", "}", "${", "second", "}", "${", "ms", "}", "`", ")", ";", "}" ]
retruns the colorized timestamp string
[ "retruns", "the", "colorized", "timestamp", "string" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L26-L45
35,476
MarkHerhold/palin
palin.js
getColorSeverity
function getColorSeverity(severity) { // get the color associated with the severity level const color = severityMap[severity] || 'white'; return chalk[color].bold(severity.toUpperCase()); }
javascript
function getColorSeverity(severity) { // get the color associated with the severity level const color = severityMap[severity] || 'white'; return chalk[color].bold(severity.toUpperCase()); }
[ "function", "getColorSeverity", "(", "severity", ")", "{", "// get the color associated with the severity level", "const", "color", "=", "severityMap", "[", "severity", "]", "||", "'white'", ";", "return", "chalk", "[", "color", "]", ".", "bold", "(", "severity", ".", "toUpperCase", "(", ")", ")", ";", "}" ]
returns the colorized text for the given severity level
[ "returns", "the", "colorized", "text", "for", "the", "given", "severity", "level" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L56-L60
35,477
MarkHerhold/palin
palin.js
formatter
function formatter(options, severity, date, elems) { /* OPTIONS */ const indent = options.indent || defaultIndent; const objectDepth = options.objectDepth; const timestamp = (function () { if (check.function(options.timestamp)) { return options.timestamp; // user-provided timestamp generating function } else if (options.timestamp === false) { return false; // no timestamp } else { return getTimestampString; // default timestamp generating function } })(); const rootFolderName = options.rootFolderName; /* LOGIC */ // the last element is an aggregate object of all of the additional passed in elements var aggObj = elems[elems.length - 1]; // initial log string var build = ' '; // add the date if (timestamp !== false) { // otherwise, use the default timestamp generator function build += ' ' + timestamp(date); } build += ' ' + getColorSeverity(severity) + ' '; // add the component if provided if (aggObj.scope) { build += getScopeString(aggObj.scope) + ' '; delete aggObj.scope; } // errors are a special case that we absolutely need to keep track of and log the entire stack var errors = []; for (let i = 0; i < elems.length - 1; i++) { // iterate through all elements in the array except the last (obj map of options) let element = elems[i]; // Attempt to determine an appropriate title given the first element if (i === 0) { let elementConsumed = false; if (check.string(element)) { // string is obviously the title build += chalk.blue(element); elementConsumed = true; } else if (check.instance(element, Error)) { // title is the error text representation build += chalk.blue(element.message || '[no message]'); // also store error stacktrace in the aggregate object errors.push(element); elementConsumed = true; } // add on the file and line number, which always go after the title, inline if (aggObj.file && aggObj.line) { aggObj.file = truncFilename(aggObj.file, rootFolderName); build += chalk.dim(` (${aggObj.file}:${aggObj.line})`); delete aggObj.file; delete aggObj.line; } // do not add element 0 to the 'extra' data section if (elementConsumed) { continue; } } // add the element to the errors array if it's an error if (check.instance(element, Error)) { errors.push(element); // the error will be concatinated later so continue to the next element continue; } let objString = '\n' + util.inspect(element, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } if (Object.keys(aggObj).length > 0) { let objString = '\n' + util.inspect(aggObj, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } // iterate through the top-level object keys looking for Errors as well for (let o of Object.keys(aggObj)) { if (check.instance(o, Error)) { errors.push(o); } } // iterate through all the Error objects and print the stacks for (let e of errors) { build += indent + e.stack.replace(/\n/g, indent); } return build; }
javascript
function formatter(options, severity, date, elems) { /* OPTIONS */ const indent = options.indent || defaultIndent; const objectDepth = options.objectDepth; const timestamp = (function () { if (check.function(options.timestamp)) { return options.timestamp; // user-provided timestamp generating function } else if (options.timestamp === false) { return false; // no timestamp } else { return getTimestampString; // default timestamp generating function } })(); const rootFolderName = options.rootFolderName; /* LOGIC */ // the last element is an aggregate object of all of the additional passed in elements var aggObj = elems[elems.length - 1]; // initial log string var build = ' '; // add the date if (timestamp !== false) { // otherwise, use the default timestamp generator function build += ' ' + timestamp(date); } build += ' ' + getColorSeverity(severity) + ' '; // add the component if provided if (aggObj.scope) { build += getScopeString(aggObj.scope) + ' '; delete aggObj.scope; } // errors are a special case that we absolutely need to keep track of and log the entire stack var errors = []; for (let i = 0; i < elems.length - 1; i++) { // iterate through all elements in the array except the last (obj map of options) let element = elems[i]; // Attempt to determine an appropriate title given the first element if (i === 0) { let elementConsumed = false; if (check.string(element)) { // string is obviously the title build += chalk.blue(element); elementConsumed = true; } else if (check.instance(element, Error)) { // title is the error text representation build += chalk.blue(element.message || '[no message]'); // also store error stacktrace in the aggregate object errors.push(element); elementConsumed = true; } // add on the file and line number, which always go after the title, inline if (aggObj.file && aggObj.line) { aggObj.file = truncFilename(aggObj.file, rootFolderName); build += chalk.dim(` (${aggObj.file}:${aggObj.line})`); delete aggObj.file; delete aggObj.line; } // do not add element 0 to the 'extra' data section if (elementConsumed) { continue; } } // add the element to the errors array if it's an error if (check.instance(element, Error)) { errors.push(element); // the error will be concatinated later so continue to the next element continue; } let objString = '\n' + util.inspect(element, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } if (Object.keys(aggObj).length > 0) { let objString = '\n' + util.inspect(aggObj, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } // iterate through the top-level object keys looking for Errors as well for (let o of Object.keys(aggObj)) { if (check.instance(o, Error)) { errors.push(o); } } // iterate through all the Error objects and print the stacks for (let e of errors) { build += indent + e.stack.replace(/\n/g, indent); } return build; }
[ "function", "formatter", "(", "options", ",", "severity", ",", "date", ",", "elems", ")", "{", "/*\n OPTIONS\n */", "const", "indent", "=", "options", ".", "indent", "||", "defaultIndent", ";", "const", "objectDepth", "=", "options", ".", "objectDepth", ";", "const", "timestamp", "=", "(", "function", "(", ")", "{", "if", "(", "check", ".", "function", "(", "options", ".", "timestamp", ")", ")", "{", "return", "options", ".", "timestamp", ";", "// user-provided timestamp generating function", "}", "else", "if", "(", "options", ".", "timestamp", "===", "false", ")", "{", "return", "false", ";", "// no timestamp", "}", "else", "{", "return", "getTimestampString", ";", "// default timestamp generating function", "}", "}", ")", "(", ")", ";", "const", "rootFolderName", "=", "options", ".", "rootFolderName", ";", "/*\n LOGIC\n */", "// the last element is an aggregate object of all of the additional passed in elements", "var", "aggObj", "=", "elems", "[", "elems", ".", "length", "-", "1", "]", ";", "// initial log string", "var", "build", "=", "' '", ";", "// add the date", "if", "(", "timestamp", "!==", "false", ")", "{", "// otherwise, use the default timestamp generator function", "build", "+=", "' '", "+", "timestamp", "(", "date", ")", ";", "}", "build", "+=", "' '", "+", "getColorSeverity", "(", "severity", ")", "+", "' '", ";", "// add the component if provided", "if", "(", "aggObj", ".", "scope", ")", "{", "build", "+=", "getScopeString", "(", "aggObj", ".", "scope", ")", "+", "' '", ";", "delete", "aggObj", ".", "scope", ";", "}", "// errors are a special case that we absolutely need to keep track of and log the entire stack", "var", "errors", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "elems", ".", "length", "-", "1", ";", "i", "++", ")", "{", "// iterate through all elements in the array except the last (obj map of options)", "let", "element", "=", "elems", "[", "i", "]", ";", "// Attempt to determine an appropriate title given the first element", "if", "(", "i", "===", "0", ")", "{", "let", "elementConsumed", "=", "false", ";", "if", "(", "check", ".", "string", "(", "element", ")", ")", "{", "// string is obviously the title", "build", "+=", "chalk", ".", "blue", "(", "element", ")", ";", "elementConsumed", "=", "true", ";", "}", "else", "if", "(", "check", ".", "instance", "(", "element", ",", "Error", ")", ")", "{", "// title is the error text representation", "build", "+=", "chalk", ".", "blue", "(", "element", ".", "message", "||", "'[no message]'", ")", ";", "// also store error stacktrace in the aggregate object", "errors", ".", "push", "(", "element", ")", ";", "elementConsumed", "=", "true", ";", "}", "// add on the file and line number, which always go after the title, inline", "if", "(", "aggObj", ".", "file", "&&", "aggObj", ".", "line", ")", "{", "aggObj", ".", "file", "=", "truncFilename", "(", "aggObj", ".", "file", ",", "rootFolderName", ")", ";", "build", "+=", "chalk", ".", "dim", "(", "`", "${", "aggObj", ".", "file", "}", "${", "aggObj", ".", "line", "}", "`", ")", ";", "delete", "aggObj", ".", "file", ";", "delete", "aggObj", ".", "line", ";", "}", "// do not add element 0 to the 'extra' data section", "if", "(", "elementConsumed", ")", "{", "continue", ";", "}", "}", "// add the element to the errors array if it's an error", "if", "(", "check", ".", "instance", "(", "element", ",", "Error", ")", ")", "{", "errors", ".", "push", "(", "element", ")", ";", "// the error will be concatinated later so continue to the next element", "continue", ";", "}", "let", "objString", "=", "'\\n'", "+", "util", ".", "inspect", "(", "element", ",", "{", "colors", ":", "true", ",", "depth", ":", "objectDepth", "}", ")", ";", "build", "+=", "objString", ".", "replace", "(", "/", "\\n", "/", "g", ",", "indent", ")", ";", "}", "if", "(", "Object", ".", "keys", "(", "aggObj", ")", ".", "length", ">", "0", ")", "{", "let", "objString", "=", "'\\n'", "+", "util", ".", "inspect", "(", "aggObj", ",", "{", "colors", ":", "true", ",", "depth", ":", "objectDepth", "}", ")", ";", "build", "+=", "objString", ".", "replace", "(", "/", "\\n", "/", "g", ",", "indent", ")", ";", "}", "// iterate through the top-level object keys looking for Errors as well", "for", "(", "let", "o", "of", "Object", ".", "keys", "(", "aggObj", ")", ")", "{", "if", "(", "check", ".", "instance", "(", "o", ",", "Error", ")", ")", "{", "errors", ".", "push", "(", "o", ")", ";", "}", "}", "// iterate through all the Error objects and print the stacks", "for", "(", "let", "e", "of", "errors", ")", "{", "build", "+=", "indent", "+", "e", ".", "stack", ".", "replace", "(", "/", "\\n", "/", "g", ",", "indent", ")", ";", "}", "return", "build", ";", "}" ]
the formatter to export
[ "the", "formatter", "to", "export" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L83-L189
35,478
7digital/7digital-api
lib/responseparser.js
parse
function parse(response, opts, callback) { var parser, jsonParseError, result; if (opts.format.toUpperCase() === 'XML') { callback(null, response); return; } if (opts.contentType && opts.contentType.indexOf('json') >= 0) { try { result = JSON.parse(response); } catch (e) { jsonParseError = e; } return validateAndCleanResponse(jsonParseError, { response: result }); } parser = new xml2js.Parser({ mergeAttrs: true, explicitArray: false }); parser.parseString(response, validateAndCleanResponse); function validateAndCleanResponse(err, result) { var cleanedResult; var clean, error, apiError; function makeParseErr(msg) { return new ApiParseError(msg + ' from: ' + opts.url, response); } // Unparsable response text if (err) { return callback(makeParseErr('Unparsable api response')); } if (!result) { return callback(makeParseErr('Empty response')); } if (!result.response) { return callback(makeParseErr('Missing response node')); } // Reponse was a 7digital API error object if (result.response.status === 'error') { error = result.response.error; if (/oauth/i.test(error.errorMessage)) { return callback(new OAuthError(error, error.errorMessage + ': ' + opts.url)); } apiError = new ApiError(error, error.errorMessage + ': ' + opts.url); apiError.params = opts.params; return callback(apiError); } else if (result.response.status !== 'ok') { return callback(new ApiParseError( 'Unexpected response status from: ' + opts.url, response)); } clean = _.compose( cleaners.renameCardTypes, cleaners.ensureCollections.bind(null, cleaners.collectionPaths), cleaners.removeXmlNamespaceKeys, cleaners.nullifyNils); cleanedResult = clean(result.response); return callback(null, cleanedResult); } }
javascript
function parse(response, opts, callback) { var parser, jsonParseError, result; if (opts.format.toUpperCase() === 'XML') { callback(null, response); return; } if (opts.contentType && opts.contentType.indexOf('json') >= 0) { try { result = JSON.parse(response); } catch (e) { jsonParseError = e; } return validateAndCleanResponse(jsonParseError, { response: result }); } parser = new xml2js.Parser({ mergeAttrs: true, explicitArray: false }); parser.parseString(response, validateAndCleanResponse); function validateAndCleanResponse(err, result) { var cleanedResult; var clean, error, apiError; function makeParseErr(msg) { return new ApiParseError(msg + ' from: ' + opts.url, response); } // Unparsable response text if (err) { return callback(makeParseErr('Unparsable api response')); } if (!result) { return callback(makeParseErr('Empty response')); } if (!result.response) { return callback(makeParseErr('Missing response node')); } // Reponse was a 7digital API error object if (result.response.status === 'error') { error = result.response.error; if (/oauth/i.test(error.errorMessage)) { return callback(new OAuthError(error, error.errorMessage + ': ' + opts.url)); } apiError = new ApiError(error, error.errorMessage + ': ' + opts.url); apiError.params = opts.params; return callback(apiError); } else if (result.response.status !== 'ok') { return callback(new ApiParseError( 'Unexpected response status from: ' + opts.url, response)); } clean = _.compose( cleaners.renameCardTypes, cleaners.ensureCollections.bind(null, cleaners.collectionPaths), cleaners.removeXmlNamespaceKeys, cleaners.nullifyNils); cleanedResult = clean(result.response); return callback(null, cleanedResult); } }
[ "function", "parse", "(", "response", ",", "opts", ",", "callback", ")", "{", "var", "parser", ",", "jsonParseError", ",", "result", ";", "if", "(", "opts", ".", "format", ".", "toUpperCase", "(", ")", "===", "'XML'", ")", "{", "callback", "(", "null", ",", "response", ")", ";", "return", ";", "}", "if", "(", "opts", ".", "contentType", "&&", "opts", ".", "contentType", ".", "indexOf", "(", "'json'", ")", ">=", "0", ")", "{", "try", "{", "result", "=", "JSON", ".", "parse", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "jsonParseError", "=", "e", ";", "}", "return", "validateAndCleanResponse", "(", "jsonParseError", ",", "{", "response", ":", "result", "}", ")", ";", "}", "parser", "=", "new", "xml2js", ".", "Parser", "(", "{", "mergeAttrs", ":", "true", ",", "explicitArray", ":", "false", "}", ")", ";", "parser", ".", "parseString", "(", "response", ",", "validateAndCleanResponse", ")", ";", "function", "validateAndCleanResponse", "(", "err", ",", "result", ")", "{", "var", "cleanedResult", ";", "var", "clean", ",", "error", ",", "apiError", ";", "function", "makeParseErr", "(", "msg", ")", "{", "return", "new", "ApiParseError", "(", "msg", "+", "' from: '", "+", "opts", ".", "url", ",", "response", ")", ";", "}", "// Unparsable response text", "if", "(", "err", ")", "{", "return", "callback", "(", "makeParseErr", "(", "'Unparsable api response'", ")", ")", ";", "}", "if", "(", "!", "result", ")", "{", "return", "callback", "(", "makeParseErr", "(", "'Empty response'", ")", ")", ";", "}", "if", "(", "!", "result", ".", "response", ")", "{", "return", "callback", "(", "makeParseErr", "(", "'Missing response node'", ")", ")", ";", "}", "// Reponse was a 7digital API error object", "if", "(", "result", ".", "response", ".", "status", "===", "'error'", ")", "{", "error", "=", "result", ".", "response", ".", "error", ";", "if", "(", "/", "oauth", "/", "i", ".", "test", "(", "error", ".", "errorMessage", ")", ")", "{", "return", "callback", "(", "new", "OAuthError", "(", "error", ",", "error", ".", "errorMessage", "+", "': '", "+", "opts", ".", "url", ")", ")", ";", "}", "apiError", "=", "new", "ApiError", "(", "error", ",", "error", ".", "errorMessage", "+", "': '", "+", "opts", ".", "url", ")", ";", "apiError", ".", "params", "=", "opts", ".", "params", ";", "return", "callback", "(", "apiError", ")", ";", "}", "else", "if", "(", "result", ".", "response", ".", "status", "!==", "'ok'", ")", "{", "return", "callback", "(", "new", "ApiParseError", "(", "'Unexpected response status from: '", "+", "opts", ".", "url", ",", "response", ")", ")", ";", "}", "clean", "=", "_", ".", "compose", "(", "cleaners", ".", "renameCardTypes", ",", "cleaners", ".", "ensureCollections", ".", "bind", "(", "null", ",", "cleaners", ".", "collectionPaths", ")", ",", "cleaners", ".", "removeXmlNamespaceKeys", ",", "cleaners", ".", "nullifyNils", ")", ";", "cleanedResult", "=", "clean", "(", "result", ".", "response", ")", ";", "return", "callback", "(", "null", ",", "cleanedResult", ")", ";", "}", "}" ]
Callback for parsing the XML response return from the API and converting it to JSON and handing control back to the caller. - @param {Function} callback - the caller's callback - @param {String} response - the XML response from the API - @parma {Object} opts - an options hash with the desired format and logger
[ "Callback", "for", "parsing", "the", "XML", "response", "return", "from", "the", "API", "and", "converting", "it", "to", "JSON", "and", "handing", "control", "back", "to", "the", "caller", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/responseparser.js#L17-L86
35,479
7digital/7digital-api
lib/errors.js
ApiHttpError
function ApiHttpError(statusCode, response, message) { this.name = "ApiHttpError"; this.statusCode = statusCode; this.response = response; this.message = message || response || util.format('Unexpected %s status code', statusCode); if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiHttpError); } }
javascript
function ApiHttpError(statusCode, response, message) { this.name = "ApiHttpError"; this.statusCode = statusCode; this.response = response; this.message = message || response || util.format('Unexpected %s status code', statusCode); if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiHttpError); } }
[ "function", "ApiHttpError", "(", "statusCode", ",", "response", ",", "message", ")", "{", "this", ".", "name", "=", "\"ApiHttpError\"", ";", "this", ".", "statusCode", "=", "statusCode", ";", "this", ".", "response", "=", "response", ";", "this", ".", "message", "=", "message", "||", "response", "||", "util", ".", "format", "(", "'Unexpected %s status code'", ",", "statusCode", ")", ";", "if", "(", "Error", ".", "captureStackTrace", "&&", "typeof", "Error", ".", "captureStackTrace", "===", "'function'", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "ApiHttpError", ")", ";", "}", "}" ]
ApiHttpError Creates a new ApiHttpError supplied to callbacks when an error response is received at transport level. - @constructor - @param {Number} statusCode - The HTTP status code of the request. - @param {String} response - (Optional) The response body. - @param {String} message - (Optional) The message
[ "ApiHttpError", "Creates", "a", "new", "ApiHttpError", "supplied", "to", "callbacks", "when", "an", "error", "response", "is", "received", "at", "transport", "level", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L25-L36
35,480
7digital/7digital-api
lib/errors.js
ApiParseError
function ApiParseError(parseErrorMessage, response) { this.name = "ApiParseError"; this.response = response; this.message = parseErrorMessage; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiParseError); } }
javascript
function ApiParseError(parseErrorMessage, response) { this.name = "ApiParseError"; this.response = response; this.message = parseErrorMessage; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiParseError); } }
[ "function", "ApiParseError", "(", "parseErrorMessage", ",", "response", ")", "{", "this", ".", "name", "=", "\"ApiParseError\"", ";", "this", ".", "response", "=", "response", ";", "this", ".", "message", "=", "parseErrorMessage", ";", "if", "(", "Error", ".", "captureStackTrace", "&&", "typeof", "Error", ".", "captureStackTrace", "===", "'function'", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "ApiParseError", ")", ";", "}", "}" ]
ApiParseError Creates a new ApiParseError supplied to callbacks when an invalid or unexpected response is received. - @constructor - @param {String} parseErrorMessage - Custom error message describing the nature of the parse error. - @param {String} response - The response body string.
[ "ApiParseError", "Creates", "a", "new", "ApiParseError", "supplied", "to", "callbacks", "when", "an", "invalid", "or", "unexpected", "response", "is", "received", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L49-L58
35,481
7digital/7digital-api
lib/errors.js
RequestError
function RequestError(err, url) { VError.call(this, err, 'for url %s', url); this.name = RequestError.name; }
javascript
function RequestError(err, url) { VError.call(this, err, 'for url %s', url); this.name = RequestError.name; }
[ "function", "RequestError", "(", "err", ",", "url", ")", "{", "VError", ".", "call", "(", "this", ",", "err", ",", "'for url %s'", ",", "url", ")", ";", "this", ".", "name", "=", "RequestError", ".", "name", ";", "}" ]
RequestError Creates a new RequestError supplied to callbacks when the request to the api fails.
[ "RequestError", "Creates", "a", "new", "RequestError", "supplied", "to", "callbacks", "when", "the", "request", "to", "the", "api", "fails", "." ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L67-L70
35,482
7digital/7digital-api
lib/errors.js
OAuthError
function OAuthError(errorResponse, message) { this.name = "OAuthError"; this.message = message || errorResponse.errorMessage; this.code = errorResponse.code; this.response = errorResponse; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, OAuthError); } }
javascript
function OAuthError(errorResponse, message) { this.name = "OAuthError"; this.message = message || errorResponse.errorMessage; this.code = errorResponse.code; this.response = errorResponse; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, OAuthError); } }
[ "function", "OAuthError", "(", "errorResponse", ",", "message", ")", "{", "this", ".", "name", "=", "\"OAuthError\"", ";", "this", ".", "message", "=", "message", "||", "errorResponse", ".", "errorMessage", ";", "this", ".", "code", "=", "errorResponse", ".", "code", ";", "this", ".", "response", "=", "errorResponse", ";", "if", "(", "Error", ".", "captureStackTrace", "&&", "typeof", "Error", ".", "captureStackTrace", "===", "'function'", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "OAuthError", ")", ";", "}", "}" ]
OAuthError Creates a new ApiError supplied to callbacks when a valid error response is received. - @constructor - @param {Object} errorResponse - The parsed API error response - @param {Object} message - The message
[ "OAuthError", "Creates", "a", "new", "ApiError", "supplied", "to", "callbacks", "when", "a", "valid", "error", "response", "is", "received", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L82-L92
35,483
haroldiedema/joii
src/PrototypeBuilder.js
function(args, data, msg) { if (typeof (args) !== 'object') { args = [args]; } for (var i in args) { if (args.hasOwnProperty(i) === false) continue; if (JOII.Compat.indexOf(data, args[i]) !== -1) { throw msg; } } }
javascript
function(args, data, msg) { if (typeof (args) !== 'object') { args = [args]; } for (var i in args) { if (args.hasOwnProperty(i) === false) continue; if (JOII.Compat.indexOf(data, args[i]) !== -1) { throw msg; } } }
[ "function", "(", "args", ",", "data", ",", "msg", ")", "{", "if", "(", "typeof", "(", "args", ")", "!==", "'object'", ")", "{", "args", "=", "[", "args", "]", ";", "}", "for", "(", "var", "i", "in", "args", ")", "{", "if", "(", "args", ".", "hasOwnProperty", "(", "i", ")", "===", "false", ")", "continue", ";", "if", "(", "JOII", ".", "Compat", ".", "indexOf", "(", "data", ",", "args", "[", "i", "]", ")", "!==", "-", "1", ")", "{", "throw", "msg", ";", "}", "}", "}" ]
Shorthand for validating other flags within the same declaration. If args exists in data, msg is thrown.
[ "Shorthand", "for", "validating", "other", "flags", "within", "the", "same", "declaration", ".", "If", "args", "exists", "in", "data", "msg", "is", "thrown", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/PrototypeBuilder.js#L604-L615
35,484
SamyPesse/octocat.js
src/page.js
parseLinkHeader
function parseLinkHeader(header) { if (!header) { return {}; } // Split parts by comma const parts = header.split(','); const links = {}; // Parse each part into a named link parts.forEach((p) => { const section = p.split(';'); if (section.length != 2) { throw new Error('section could not be split on ";"'); } const url = section[0].replace(/<(.*)>/, '$1').trim(); const name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = url; }); return links; }
javascript
function parseLinkHeader(header) { if (!header) { return {}; } // Split parts by comma const parts = header.split(','); const links = {}; // Parse each part into a named link parts.forEach((p) => { const section = p.split(';'); if (section.length != 2) { throw new Error('section could not be split on ";"'); } const url = section[0].replace(/<(.*)>/, '$1').trim(); const name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = url; }); return links; }
[ "function", "parseLinkHeader", "(", "header", ")", "{", "if", "(", "!", "header", ")", "{", "return", "{", "}", ";", "}", "// Split parts by comma", "const", "parts", "=", "header", ".", "split", "(", "','", ")", ";", "const", "links", "=", "{", "}", ";", "// Parse each part into a named link", "parts", ".", "forEach", "(", "(", "p", ")", "=>", "{", "const", "section", "=", "p", ".", "split", "(", "';'", ")", ";", "if", "(", "section", ".", "length", "!=", "2", ")", "{", "throw", "new", "Error", "(", "'section could not be split on \";\"'", ")", ";", "}", "const", "url", "=", "section", "[", "0", "]", ".", "replace", "(", "/", "<(.*)>", "/", ",", "'$1'", ")", ".", "trim", "(", ")", ";", "const", "name", "=", "section", "[", "1", "]", ".", "replace", "(", "/", "rel=\"(.*)\"", "/", ",", "'$1'", ")", ".", "trim", "(", ")", ";", "links", "[", "name", "]", "=", "url", ";", "}", ")", ";", "return", "links", ";", "}" ]
Extract next and prev from link header @param {String} header @return {Object}
[ "Extract", "next", "and", "prev", "from", "link", "header" ]
1cbc1c499d0f8595db34c4c0df498deba8e4099f
https://github.com/SamyPesse/octocat.js/blob/1cbc1c499d0f8595db34c4c0df498deba8e4099f/src/page.js#L113-L134
35,485
haroldiedema/joii
src/Config.js
function (name) { if (JOII.Config.constructors.indexOf(name) !== -1) { return; } JOII.Config.constructors.push(name); }
javascript
function (name) { if (JOII.Config.constructors.indexOf(name) !== -1) { return; } JOII.Config.constructors.push(name); }
[ "function", "(", "name", ")", "{", "if", "(", "JOII", ".", "Config", ".", "constructors", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "return", ";", "}", "JOII", ".", "Config", ".", "constructors", ".", "push", "(", "name", ")", ";", "}" ]
Adds a constructor method name. The first occurance of a function named like one of these is executed. The rest is ignored to prevent ambiguous behavior. @param {string} name
[ "Adds", "a", "constructor", "method", "name", ".", "The", "first", "occurance", "of", "a", "function", "named", "like", "one", "of", "these", "is", "executed", ".", "The", "rest", "is", "ignored", "to", "prevent", "ambiguous", "behavior", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Config.js#L25-L31
35,486
haroldiedema/joii
src/Config.js
function(name) { if (JOII.Config.constructors.indexOf(name) === -1) { return; } JOII.Config.constructors.splice(JOII.Config.constructors.indexOf(name), 1); }
javascript
function(name) { if (JOII.Config.constructors.indexOf(name) === -1) { return; } JOII.Config.constructors.splice(JOII.Config.constructors.indexOf(name), 1); }
[ "function", "(", "name", ")", "{", "if", "(", "JOII", ".", "Config", ".", "constructors", ".", "indexOf", "(", "name", ")", "===", "-", "1", ")", "{", "return", ";", "}", "JOII", ".", "Config", ".", "constructors", ".", "splice", "(", "JOII", ".", "Config", ".", "constructors", ".", "indexOf", "(", "name", ")", ",", "1", ")", ";", "}" ]
Removes a constructor method name. The first occurance of a function named like one of these is executed. The rest is ignored to prevent ambiguous behavior. @param {string} name
[ "Removes", "a", "constructor", "method", "name", ".", "The", "first", "occurance", "of", "a", "function", "named", "like", "one", "of", "these", "is", "executed", ".", "The", "rest", "is", "ignored", "to", "prevent", "ambiguous", "behavior", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Config.js#L40-L46
35,487
dannymidnight/node-weather
yahoo.js
function(msg) { if (yahoo.logging) { console.log('ERROR: ' + msg); } if (module.exports.error) { module.exports.error(msg); } }
javascript
function(msg) { if (yahoo.logging) { console.log('ERROR: ' + msg); } if (module.exports.error) { module.exports.error(msg); } }
[ "function", "(", "msg", ")", "{", "if", "(", "yahoo", ".", "logging", ")", "{", "console", ".", "log", "(", "'ERROR: '", "+", "msg", ")", ";", "}", "if", "(", "module", ".", "exports", ".", "error", ")", "{", "module", ".", "exports", ".", "error", "(", "msg", ")", ";", "}", "}" ]
Report error.
[ "Report", "error", "." ]
6658662f8641ed272a93c280b327429f23c6d3d8
https://github.com/dannymidnight/node-weather/blob/6658662f8641ed272a93c280b327429f23c6d3d8/yahoo.js#L15-L23
35,488
telligro/opal-nodes
packages/opal-node-email/emailprocess.js
processNewMessage
function processNewMessage(msg, mailMessage) { // msg = JSON.parse(JSON.stringify(msg)); // Clone the message // Populate the msg fields from the content of the email message // that we have just parsed. msg.payload = mailMessage.text; msg.topic = mailMessage.subject; msg.date = mailMessage.date; msg.header = mailMessage.headers; if (mailMessage.html) { msg.html = mailMessage.html; } if (mailMessage.to && mailMessage.from.to > 0) { msg.to = mailMessage.to; } if (mailMessage.cc && mailMessage.from.cc > 0) { msg.cc = mailMessage.cc; } if (mailMessage.bcc && mailMessage.from.bcc > 0) { msg.bcc = mailMessage.bcc; } if (mailMessage.from && mailMessage.from.length > 0) { msg.from = mailMessage.from[0].address; } if (mailMessage.attachments) { msg.attachments = mailMessage.attachments; } else { msg.attachments = []; } n.send(msg); // Propagate the message down the flow }
javascript
function processNewMessage(msg, mailMessage) { // msg = JSON.parse(JSON.stringify(msg)); // Clone the message // Populate the msg fields from the content of the email message // that we have just parsed. msg.payload = mailMessage.text; msg.topic = mailMessage.subject; msg.date = mailMessage.date; msg.header = mailMessage.headers; if (mailMessage.html) { msg.html = mailMessage.html; } if (mailMessage.to && mailMessage.from.to > 0) { msg.to = mailMessage.to; } if (mailMessage.cc && mailMessage.from.cc > 0) { msg.cc = mailMessage.cc; } if (mailMessage.bcc && mailMessage.from.bcc > 0) { msg.bcc = mailMessage.bcc; } if (mailMessage.from && mailMessage.from.length > 0) { msg.from = mailMessage.from[0].address; } if (mailMessage.attachments) { msg.attachments = mailMessage.attachments; } else { msg.attachments = []; } n.send(msg); // Propagate the message down the flow }
[ "function", "processNewMessage", "(", "msg", ",", "mailMessage", ")", "{", "// msg = JSON.parse(JSON.stringify(msg)); // Clone the message", "// Populate the msg fields from the content of the email message", "// that we have just parsed.", "msg", ".", "payload", "=", "mailMessage", ".", "text", ";", "msg", ".", "topic", "=", "mailMessage", ".", "subject", ";", "msg", ".", "date", "=", "mailMessage", ".", "date", ";", "msg", ".", "header", "=", "mailMessage", ".", "headers", ";", "if", "(", "mailMessage", ".", "html", ")", "{", "msg", ".", "html", "=", "mailMessage", ".", "html", ";", "}", "if", "(", "mailMessage", ".", "to", "&&", "mailMessage", ".", "from", ".", "to", ">", "0", ")", "{", "msg", ".", "to", "=", "mailMessage", ".", "to", ";", "}", "if", "(", "mailMessage", ".", "cc", "&&", "mailMessage", ".", "from", ".", "cc", ">", "0", ")", "{", "msg", ".", "cc", "=", "mailMessage", ".", "cc", ";", "}", "if", "(", "mailMessage", ".", "bcc", "&&", "mailMessage", ".", "from", ".", "bcc", ">", "0", ")", "{", "msg", ".", "bcc", "=", "mailMessage", ".", "bcc", ";", "}", "if", "(", "mailMessage", ".", "from", "&&", "mailMessage", ".", "from", ".", "length", ">", "0", ")", "{", "msg", ".", "from", "=", "mailMessage", ".", "from", "[", "0", "]", ".", "address", ";", "}", "if", "(", "mailMessage", ".", "attachments", ")", "{", "msg", ".", "attachments", "=", "mailMessage", ".", "attachments", ";", "}", "else", "{", "msg", ".", "attachments", "=", "[", "]", ";", "}", "n", ".", "send", "(", "msg", ")", ";", "// Propagate the message down the flow", "}" ]
Process a new email message by building a Node-RED message to be passed onwards in the message flow. The parameter called `msg` is the template message we start with while `mailMessage` is an object returned from `mailparser` that will be used to populate the email. Process a new email message by building a Node-RED message to be passed onwards in the message flow. The parameter called `msg` is the template message we start with while `mailMessage` is an object returned from `mailparser` that will be used to populate the email. @param {any} msg __DOCSPLACEHOLDER__ @param {any} mailMessage __DOCSPLACEHOLDER__
[ "Process", "a", "new", "email", "message", "by", "building", "a", "Node", "-", "RED", "message", "to", "be", "passed", "onwards", "in", "the", "message", "flow", ".", "The", "parameter", "called", "msg", "is", "the", "template", "message", "we", "start", "with", "while", "mailMessage", "is", "an", "object", "returned", "from", "mailparser", "that", "will", "be", "used", "to", "populate", "the", "email", ".", "Process", "a", "new", "email", "message", "by", "building", "a", "Node", "-", "RED", "message", "to", "be", "passed", "onwards", "in", "the", "message", "flow", ".", "The", "parameter", "called", "msg", "is", "the", "template", "message", "we", "start", "with", "while", "mailMessage", "is", "an", "object", "returned", "from", "mailparser", "that", "will", "be", "used", "to", "populate", "the", "email", "." ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-email/emailprocess.js#L352-L381
35,489
telligro/opal-nodes
packages/opal-node-email/emailprocess.js
checkPOP3
function checkPOP3(msg) { let currentMessage; let maxMessage; // Form a new connection to our email server using POP3. let pop3Client = new POP3Client( node.port, node.server, {enabletls: node.useSSL} // Should we use SSL to connect to our email server? ); // If we have a next message to retrieve, ask to retrieve it otherwise issue a /** * If we have a next message to retrieve, ask to retrieve it otherwise issue a */ function nextMessage() { if (currentMessage > maxMessage) { pop3Client.quit(); return; } pop3Client.retr(currentMessage); currentMessage++; } // End of nextMessage pop3Client.on('stat', function(status, data) { // Data contains: // { // count: <Number of messages to be read> // octect: <size of messages to be read> // } if (status) { currentMessage = 1; maxMessage = data.count; nextMessage(); } else { node.log(util.format('stat error: %s %j', status, data)); } }); pop3Client.on('error', function(err) { node.log('We caught an error: ' + JSON.stringify(err)); }); pop3Client.on('connect', function() { // node.log("We are now connected"); pop3Client.login(node.userid, node.password); }); pop3Client.on('login', function(status, rawData) { // node.log("login: " + status + ", " + rawData); if (status) { pop3Client.stat(); } else { node.log(util.format('login error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('retr', function(status, msgNumber, data, rawData) { // node.log(util.format("retr: status=%s, msgNumber=%d, data=%j", status, msgNumber, data)); if (status) { // We have now received a new email message. Create an instance of a mail parser // and pass in the email message. The parser will signal when it has parsed the message. let mailparser = new MailParser(); mailparser.on('end', function(mailObject) { // node.log(util.format("mailparser: on(end): %j", mailObject)); processNewMessage(msg, mailObject); }); mailparser.write(data); mailparser.end(); pop3Client.dele(msgNumber); } else { node.log(util.format('retr error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('invalid-state', function(cmd) { node.log('Invalid state: ' + cmd); }); pop3Client.on('locked', function(cmd) { node.log('We were locked: ' + cmd); }); // When we have deleted the last processed message, we can move on to // processing the next message. pop3Client.on('dele', function(status, msgNumber) { nextMessage(); }); }
javascript
function checkPOP3(msg) { let currentMessage; let maxMessage; // Form a new connection to our email server using POP3. let pop3Client = new POP3Client( node.port, node.server, {enabletls: node.useSSL} // Should we use SSL to connect to our email server? ); // If we have a next message to retrieve, ask to retrieve it otherwise issue a /** * If we have a next message to retrieve, ask to retrieve it otherwise issue a */ function nextMessage() { if (currentMessage > maxMessage) { pop3Client.quit(); return; } pop3Client.retr(currentMessage); currentMessage++; } // End of nextMessage pop3Client.on('stat', function(status, data) { // Data contains: // { // count: <Number of messages to be read> // octect: <size of messages to be read> // } if (status) { currentMessage = 1; maxMessage = data.count; nextMessage(); } else { node.log(util.format('stat error: %s %j', status, data)); } }); pop3Client.on('error', function(err) { node.log('We caught an error: ' + JSON.stringify(err)); }); pop3Client.on('connect', function() { // node.log("We are now connected"); pop3Client.login(node.userid, node.password); }); pop3Client.on('login', function(status, rawData) { // node.log("login: " + status + ", " + rawData); if (status) { pop3Client.stat(); } else { node.log(util.format('login error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('retr', function(status, msgNumber, data, rawData) { // node.log(util.format("retr: status=%s, msgNumber=%d, data=%j", status, msgNumber, data)); if (status) { // We have now received a new email message. Create an instance of a mail parser // and pass in the email message. The parser will signal when it has parsed the message. let mailparser = new MailParser(); mailparser.on('end', function(mailObject) { // node.log(util.format("mailparser: on(end): %j", mailObject)); processNewMessage(msg, mailObject); }); mailparser.write(data); mailparser.end(); pop3Client.dele(msgNumber); } else { node.log(util.format('retr error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('invalid-state', function(cmd) { node.log('Invalid state: ' + cmd); }); pop3Client.on('locked', function(cmd) { node.log('We were locked: ' + cmd); }); // When we have deleted the last processed message, we can move on to // processing the next message. pop3Client.on('dele', function(status, msgNumber) { nextMessage(); }); }
[ "function", "checkPOP3", "(", "msg", ")", "{", "let", "currentMessage", ";", "let", "maxMessage", ";", "// Form a new connection to our email server using POP3.", "let", "pop3Client", "=", "new", "POP3Client", "(", "node", ".", "port", ",", "node", ".", "server", ",", "{", "enabletls", ":", "node", ".", "useSSL", "}", "// Should we use SSL to connect to our email server?", ")", ";", "// If we have a next message to retrieve, ask to retrieve it otherwise issue a", "/**\n * If we have a next message to retrieve, ask to retrieve it otherwise issue a\n */", "function", "nextMessage", "(", ")", "{", "if", "(", "currentMessage", ">", "maxMessage", ")", "{", "pop3Client", ".", "quit", "(", ")", ";", "return", ";", "}", "pop3Client", ".", "retr", "(", "currentMessage", ")", ";", "currentMessage", "++", ";", "}", "// End of nextMessage", "pop3Client", ".", "on", "(", "'stat'", ",", "function", "(", "status", ",", "data", ")", "{", "// Data contains:", "// {", "// count: <Number of messages to be read>", "// octect: <size of messages to be read>", "// }", "if", "(", "status", ")", "{", "currentMessage", "=", "1", ";", "maxMessage", "=", "data", ".", "count", ";", "nextMessage", "(", ")", ";", "}", "else", "{", "node", ".", "log", "(", "util", ".", "format", "(", "'stat error: %s %j'", ",", "status", ",", "data", ")", ")", ";", "}", "}", ")", ";", "pop3Client", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "node", ".", "log", "(", "'We caught an error: '", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "}", ")", ";", "pop3Client", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "// node.log(\"We are now connected\");", "pop3Client", ".", "login", "(", "node", ".", "userid", ",", "node", ".", "password", ")", ";", "}", ")", ";", "pop3Client", ".", "on", "(", "'login'", ",", "function", "(", "status", ",", "rawData", ")", "{", "// node.log(\"login: \" + status + \", \" + rawData);", "if", "(", "status", ")", "{", "pop3Client", ".", "stat", "(", ")", ";", "}", "else", "{", "node", ".", "log", "(", "util", ".", "format", "(", "'login error: %s %j'", ",", "status", ",", "rawData", ")", ")", ";", "pop3Client", ".", "quit", "(", ")", ";", "}", "}", ")", ";", "pop3Client", ".", "on", "(", "'retr'", ",", "function", "(", "status", ",", "msgNumber", ",", "data", ",", "rawData", ")", "{", "// node.log(util.format(\"retr: status=%s, msgNumber=%d, data=%j\", status, msgNumber, data));", "if", "(", "status", ")", "{", "// We have now received a new email message. Create an instance of a mail parser", "// and pass in the email message. The parser will signal when it has parsed the message.", "let", "mailparser", "=", "new", "MailParser", "(", ")", ";", "mailparser", ".", "on", "(", "'end'", ",", "function", "(", "mailObject", ")", "{", "// node.log(util.format(\"mailparser: on(end): %j\", mailObject));", "processNewMessage", "(", "msg", ",", "mailObject", ")", ";", "}", ")", ";", "mailparser", ".", "write", "(", "data", ")", ";", "mailparser", ".", "end", "(", ")", ";", "pop3Client", ".", "dele", "(", "msgNumber", ")", ";", "}", "else", "{", "node", ".", "log", "(", "util", ".", "format", "(", "'retr error: %s %j'", ",", "status", ",", "rawData", ")", ")", ";", "pop3Client", ".", "quit", "(", ")", ";", "}", "}", ")", ";", "pop3Client", ".", "on", "(", "'invalid-state'", ",", "function", "(", "cmd", ")", "{", "node", ".", "log", "(", "'Invalid state: '", "+", "cmd", ")", ";", "}", ")", ";", "pop3Client", ".", "on", "(", "'locked'", ",", "function", "(", "cmd", ")", "{", "node", ".", "log", "(", "'We were locked: '", "+", "cmd", ")", ";", "}", ")", ";", "// When we have deleted the last processed message, we can move on to", "// processing the next message.", "pop3Client", ".", "on", "(", "'dele'", ",", "function", "(", "status", ",", "msgNumber", ")", "{", "nextMessage", "(", ")", ";", "}", ")", ";", "}" ]
Check the POP3 email mailbox for any new messages. For any that are found, retrieve each message, call processNewMessage to process it and then delete Check the POP3 email mailbox for any new messages. For any that are found, retrieve each message, call processNewMessage to process it and then delete @param {any} msg __DOCSPLACEHOLDER__
[ "Check", "the", "POP3", "email", "mailbox", "for", "any", "new", "messages", ".", "For", "any", "that", "are", "found", "retrieve", "each", "message", "call", "processNewMessage", "to", "process", "it", "and", "then", "delete", "Check", "the", "POP3", "email", "mailbox", "for", "any", "new", "messages", ".", "For", "any", "that", "are", "found", "retrieve", "each", "message", "call", "processNewMessage", "to", "process", "it", "and", "then", "delete" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-email/emailprocess.js#L391-L480
35,490
telligro/opal-nodes
packages/opal-node-email/emailprocess.js
processValuesFromContext
function processValuesFromContext(node, params, msg, varList) { let pMsg = {}; Object.assign(pMsg, params); varList.forEach((varItem) => { if (varItem.type === undefined || params[varItem.type] === undefined) { pMsg[varItem.name] = params[varItem.name]; } else if (params[varItem.type] === 'flow' || params[varItem.type] === 'global') { pMsg[varItem.name] = RED.util.evaluateNodeProperty(params[varItem.name], params[varItem.type], node, msg); pMsg[varItem.type] = params[varItem.type]; console.log('Inside flow or global'); console.log(varItem.name + ' - - ' + pMsg[varItem.name]); } else { pMsg[varItem.name] = params[varItem.name]; pMsg[varItem.type] = params[varItem.type]; } }); return pMsg; }
javascript
function processValuesFromContext(node, params, msg, varList) { let pMsg = {}; Object.assign(pMsg, params); varList.forEach((varItem) => { if (varItem.type === undefined || params[varItem.type] === undefined) { pMsg[varItem.name] = params[varItem.name]; } else if (params[varItem.type] === 'flow' || params[varItem.type] === 'global') { pMsg[varItem.name] = RED.util.evaluateNodeProperty(params[varItem.name], params[varItem.type], node, msg); pMsg[varItem.type] = params[varItem.type]; console.log('Inside flow or global'); console.log(varItem.name + ' - - ' + pMsg[varItem.name]); } else { pMsg[varItem.name] = params[varItem.name]; pMsg[varItem.type] = params[varItem.type]; } }); return pMsg; }
[ "function", "processValuesFromContext", "(", "node", ",", "params", ",", "msg", ",", "varList", ")", "{", "let", "pMsg", "=", "{", "}", ";", "Object", ".", "assign", "(", "pMsg", ",", "params", ")", ";", "varList", ".", "forEach", "(", "(", "varItem", ")", "=>", "{", "if", "(", "varItem", ".", "type", "===", "undefined", "||", "params", "[", "varItem", ".", "type", "]", "===", "undefined", ")", "{", "pMsg", "[", "varItem", ".", "name", "]", "=", "params", "[", "varItem", ".", "name", "]", ";", "}", "else", "if", "(", "params", "[", "varItem", ".", "type", "]", "===", "'flow'", "||", "params", "[", "varItem", ".", "type", "]", "===", "'global'", ")", "{", "pMsg", "[", "varItem", ".", "name", "]", "=", "RED", ".", "util", ".", "evaluateNodeProperty", "(", "params", "[", "varItem", ".", "name", "]", ",", "params", "[", "varItem", ".", "type", "]", ",", "node", ",", "msg", ")", ";", "pMsg", "[", "varItem", ".", "type", "]", "=", "params", "[", "varItem", ".", "type", "]", ";", "console", ".", "log", "(", "'Inside flow or global'", ")", ";", "console", ".", "log", "(", "varItem", ".", "name", "+", "' - - '", "+", "pMsg", "[", "varItem", ".", "name", "]", ")", ";", "}", "else", "{", "pMsg", "[", "varItem", ".", "name", "]", "=", "params", "[", "varItem", ".", "name", "]", ";", "pMsg", "[", "varItem", ".", "type", "]", "=", "params", "[", "varItem", ".", "type", "]", ";", "}", "}", ")", ";", "return", "pMsg", ";", "}" ]
End of checkEmail proccess values from context @param {any} node __DOCSPLACEHOLDER__ @param {any} params __DOCSPLACEHOLDER__ @param {any} msg __DOCSPLACEHOLDER__ @param {any} varList __DOCSPLACEHOLDER__ @return {object} pMsg
[ "End", "of", "checkEmail", "proccess", "values", "from", "context" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-email/emailprocess.js#L650-L667
35,491
nodebox/g.js
src/g.js
splitRow
function splitRow(s, delimiter) { var row = [], c, col = '', i, inString = false; s = s.trim(); for (i = 0; i < s.length; i += 1) { c = s[i]; if (c === '"') { if (s[i+1] === '"') { col += '"'; i += 1; } else { inString = !inString; } } else if (c === delimiter) { if (!inString) { row.push(col); col = ''; } else { col += c; } } else { col += c; } } row.push(col); return row; }
javascript
function splitRow(s, delimiter) { var row = [], c, col = '', i, inString = false; s = s.trim(); for (i = 0; i < s.length; i += 1) { c = s[i]; if (c === '"') { if (s[i+1] === '"') { col += '"'; i += 1; } else { inString = !inString; } } else if (c === delimiter) { if (!inString) { row.push(col); col = ''; } else { col += c; } } else { col += c; } } row.push(col); return row; }
[ "function", "splitRow", "(", "s", ",", "delimiter", ")", "{", "var", "row", "=", "[", "]", ",", "c", ",", "col", "=", "''", ",", "i", ",", "inString", "=", "false", ";", "s", "=", "s", ".", "trim", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", "i", "+=", "1", ")", "{", "c", "=", "s", "[", "i", "]", ";", "if", "(", "c", "===", "'\"'", ")", "{", "if", "(", "s", "[", "i", "+", "1", "]", "===", "'\"'", ")", "{", "col", "+=", "'\"'", ";", "i", "+=", "1", ";", "}", "else", "{", "inString", "=", "!", "inString", ";", "}", "}", "else", "if", "(", "c", "===", "delimiter", ")", "{", "if", "(", "!", "inString", ")", "{", "row", ".", "push", "(", "col", ")", ";", "col", "=", "''", ";", "}", "else", "{", "col", "+=", "c", ";", "}", "}", "else", "{", "col", "+=", "c", ";", "}", "}", "row", ".", "push", "(", "col", ")", ";", "return", "row", ";", "}" ]
Split the row, taking quotes into account.
[ "Split", "the", "row", "taking", "quotes", "into", "account", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/g.js#L49-L74
35,492
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
javascript
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getProperties", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if a property by the given name exists. @return bool
[ "Returns", "true", "if", "a", "property", "by", "the", "given", "name", "exists", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L106-L114
35,493
haroldiedema/joii
src/Reflection.js
function(filter) { var result = []; for (var i in this.proto) { if (typeof (this.proto[i]) === 'function' && JOII.Compat.indexOf(JOII.InternalPropertyNames, i) === -1) { result.push(new JOII.Reflection.Method(this, i)); } } return result; }
javascript
function(filter) { var result = []; for (var i in this.proto) { if (typeof (this.proto[i]) === 'function' && JOII.Compat.indexOf(JOII.InternalPropertyNames, i) === -1) { result.push(new JOII.Reflection.Method(this, i)); } } return result; }
[ "function", "(", "filter", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "in", "this", ".", "proto", ")", "{", "if", "(", "typeof", "(", "this", ".", "proto", "[", "i", "]", ")", "===", "'function'", "&&", "JOII", ".", "Compat", ".", "indexOf", "(", "JOII", ".", "InternalPropertyNames", ",", "i", ")", "===", "-", "1", ")", "{", "result", ".", "push", "(", "new", "JOII", ".", "Reflection", ".", "Method", "(", "this", ",", "i", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Returns an array of JOII.Reflection.Method based on the methods defined in this class. @param string filter Optional filter for 'private' or 'public'. @return JOII.Reflection.Method[]
[ "Returns", "an", "array", "of", "JOII", ".", "Reflection", ".", "Method", "based", "on", "the", "methods", "defined", "in", "this", "class", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L141-L149
35,494
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
javascript
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getMethods", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if a method by the given name exists. @return bool
[ "Returns", "true", "if", "a", "method", "by", "the", "given", "name", "exists", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L156-L164
35,495
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Method "' + name + '" does not exist.'; }
javascript
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Method "' + name + '" does not exist.'; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getMethods", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "list", "[", "i", "]", ";", "}", "}", "throw", "'Method \"'", "+", "name", "+", "'\" does not exist.'", ";", "}" ]
Returns an instance of JOII.Reflection.Method of a method by the given name. @param string name @return JOII.Reflection.Method
[ "Returns", "an", "instance", "of", "JOII", ".", "Reflection", ".", "Method", "of", "a", "method", "by", "the", "given", "name", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L173-L181
35,496
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Property "' + name + '" does not exist.'; }
javascript
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Property "' + name + '" does not exist.'; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getProperties", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "list", "[", "i", "]", ";", "}", "}", "throw", "'Property \"'", "+", "name", "+", "'\" does not exist.'", ";", "}" ]
Returns an instance of JOII.Reflection.Property of a property by the given name. @param string name @return JOII.Reflection.Property
[ "Returns", "an", "instance", "of", "JOII", ".", "Reflection", ".", "Property", "of", "a", "property", "by", "the", "given", "name", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L207-L215
35,497
haroldiedema/joii
src/Reflection.js
function() { var name_parts = [], proto_ref = this.reflector.getProto()[this.name], name = '', body = ''; if (this.meta.is_abstract) { name_parts.push('abstract'); } if (this.meta.is_final) { name_parts.push('final'); } name_parts.push(this.meta.visibility); if (this.meta.is_static) { name_parts.push('static'); } if (this.meta.is_nullable) { name_parts.push('nullable'); } if (this.meta.is_read_only) { name_parts.push('read'); } // If type === null, attempt to detect it by the predefined value. if (this.meta.type === null) { if (proto_ref === null) { name_parts.push('mixed'); } else { name_parts.push(typeof (proto_ref)); } } else { name_parts.push(this.meta.type); } name_parts.push('"' + this.meta.name + '"'); name = name_parts.join(' '); if (typeof (proto_ref) === 'function') { body = '[Function]'; } else if (typeof (proto_ref) === 'object' && proto_ref !== null) { body = '[Object (' + proto_ref.length + ')]'; } else if (typeof (proto_ref) === 'string') { body = '"' + proto_ref + '"'; } else { body = proto_ref; } return name + ': ' + body; }
javascript
function() { var name_parts = [], proto_ref = this.reflector.getProto()[this.name], name = '', body = ''; if (this.meta.is_abstract) { name_parts.push('abstract'); } if (this.meta.is_final) { name_parts.push('final'); } name_parts.push(this.meta.visibility); if (this.meta.is_static) { name_parts.push('static'); } if (this.meta.is_nullable) { name_parts.push('nullable'); } if (this.meta.is_read_only) { name_parts.push('read'); } // If type === null, attempt to detect it by the predefined value. if (this.meta.type === null) { if (proto_ref === null) { name_parts.push('mixed'); } else { name_parts.push(typeof (proto_ref)); } } else { name_parts.push(this.meta.type); } name_parts.push('"' + this.meta.name + '"'); name = name_parts.join(' '); if (typeof (proto_ref) === 'function') { body = '[Function]'; } else if (typeof (proto_ref) === 'object' && proto_ref !== null) { body = '[Object (' + proto_ref.length + ')]'; } else if (typeof (proto_ref) === 'string') { body = '"' + proto_ref + '"'; } else { body = proto_ref; } return name + ': ' + body; }
[ "function", "(", ")", "{", "var", "name_parts", "=", "[", "]", ",", "proto_ref", "=", "this", ".", "reflector", ".", "getProto", "(", ")", "[", "this", ".", "name", "]", ",", "name", "=", "''", ",", "body", "=", "''", ";", "if", "(", "this", ".", "meta", ".", "is_abstract", ")", "{", "name_parts", ".", "push", "(", "'abstract'", ")", ";", "}", "if", "(", "this", ".", "meta", ".", "is_final", ")", "{", "name_parts", ".", "push", "(", "'final'", ")", ";", "}", "name_parts", ".", "push", "(", "this", ".", "meta", ".", "visibility", ")", ";", "if", "(", "this", ".", "meta", ".", "is_static", ")", "{", "name_parts", ".", "push", "(", "'static'", ")", ";", "}", "if", "(", "this", ".", "meta", ".", "is_nullable", ")", "{", "name_parts", ".", "push", "(", "'nullable'", ")", ";", "}", "if", "(", "this", ".", "meta", ".", "is_read_only", ")", "{", "name_parts", ".", "push", "(", "'read'", ")", ";", "}", "// If type === null, attempt to detect it by the predefined value.", "if", "(", "this", ".", "meta", ".", "type", "===", "null", ")", "{", "if", "(", "proto_ref", "===", "null", ")", "{", "name_parts", ".", "push", "(", "'mixed'", ")", ";", "}", "else", "{", "name_parts", ".", "push", "(", "typeof", "(", "proto_ref", ")", ")", ";", "}", "}", "else", "{", "name_parts", ".", "push", "(", "this", ".", "meta", ".", "type", ")", ";", "}", "name_parts", ".", "push", "(", "'\"'", "+", "this", ".", "meta", ".", "name", "+", "'\"'", ")", ";", "name", "=", "name_parts", ".", "join", "(", "' '", ")", ";", "if", "(", "typeof", "(", "proto_ref", ")", "===", "'function'", ")", "{", "body", "=", "'[Function]'", ";", "}", "else", "if", "(", "typeof", "(", "proto_ref", ")", "===", "'object'", "&&", "proto_ref", "!==", "null", ")", "{", "body", "=", "'[Object ('", "+", "proto_ref", ".", "length", "+", "')]'", ";", "}", "else", "if", "(", "typeof", "(", "proto_ref", ")", "===", "'string'", ")", "{", "body", "=", "'\"'", "+", "proto_ref", "+", "'\"'", ";", "}", "else", "{", "body", "=", "proto_ref", ";", "}", "return", "name", "+", "': '", "+", "body", ";", "}" ]
Returns a string representation of this object. @return string
[ "Returns", "a", "string", "representation", "of", "this", "object", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L392-L432
35,498
haroldiedema/joii
src/Reflection.js
function() { var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m, FN_ARG_SPLIT = /,/, FN_ARG = /^\s*(_?)(\S+?)\1\s*$/, STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, getParams = function(fn) { var fnText, argDecl; var args = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); var r = argDecl[1].split(FN_ARG_SPLIT), repl = function(all, underscore, name) { args.push(name); }; for (var a in r) { var arg = r[a]; arg.replace(FN_ARG, repl); } return args; }; var prototype = this.reflector.getProto(); var overloads = prototype.__joii__.metadata[this.name].overloads; if (!overloads || overloads.length === 0) { // old method for BC (wasn't recognized as a function when prototyping) return getParams(this.reflector.getProto()[this.name]); } else if (overloads.length === 1 && overloads[0].parameters.length === 0) { // old method for BC (was recognized when prototyping, but old style) return getParams(overloads[0].fn); } else { var ret = []; for (var idx = 0; idx < overloads.length; idx++) { var fn_meta = []; var function_parameters_meta = overloads[idx]; var parsed_params = getParams(function_parameters_meta.fn); for (var j = 0; j < function_parameters_meta.parameters.length; j++) { var param = { name: parsed_params.length > j ? parsed_params[j] : null, type: function_parameters_meta.parameters[j] }; fn_meta.push(param); } ret.push(fn_meta); } return ret; } }
javascript
function() { var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m, FN_ARG_SPLIT = /,/, FN_ARG = /^\s*(_?)(\S+?)\1\s*$/, STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, getParams = function(fn) { var fnText, argDecl; var args = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); var r = argDecl[1].split(FN_ARG_SPLIT), repl = function(all, underscore, name) { args.push(name); }; for (var a in r) { var arg = r[a]; arg.replace(FN_ARG, repl); } return args; }; var prototype = this.reflector.getProto(); var overloads = prototype.__joii__.metadata[this.name].overloads; if (!overloads || overloads.length === 0) { // old method for BC (wasn't recognized as a function when prototyping) return getParams(this.reflector.getProto()[this.name]); } else if (overloads.length === 1 && overloads[0].parameters.length === 0) { // old method for BC (was recognized when prototyping, but old style) return getParams(overloads[0].fn); } else { var ret = []; for (var idx = 0; idx < overloads.length; idx++) { var fn_meta = []; var function_parameters_meta = overloads[idx]; var parsed_params = getParams(function_parameters_meta.fn); for (var j = 0; j < function_parameters_meta.parameters.length; j++) { var param = { name: parsed_params.length > j ? parsed_params[j] : null, type: function_parameters_meta.parameters[j] }; fn_meta.push(param); } ret.push(fn_meta); } return ret; } }
[ "function", "(", ")", "{", "var", "FN_ARGS", "=", "/", "^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)", "/", "m", ",", "FN_ARG_SPLIT", "=", "/", ",", "/", ",", "FN_ARG", "=", "/", "^\\s*(_?)(\\S+?)\\1\\s*$", "/", ",", "STRIP_COMMENTS", "=", "/", "((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))", "/", "mg", ",", "getParams", "=", "function", "(", "fn", ")", "{", "var", "fnText", ",", "argDecl", ";", "var", "args", "=", "[", "]", ";", "fnText", "=", "fn", ".", "toString", "(", ")", ".", "replace", "(", "STRIP_COMMENTS", ",", "''", ")", ";", "argDecl", "=", "fnText", ".", "match", "(", "FN_ARGS", ")", ";", "var", "r", "=", "argDecl", "[", "1", "]", ".", "split", "(", "FN_ARG_SPLIT", ")", ",", "repl", "=", "function", "(", "all", ",", "underscore", ",", "name", ")", "{", "args", ".", "push", "(", "name", ")", ";", "}", ";", "for", "(", "var", "a", "in", "r", ")", "{", "var", "arg", "=", "r", "[", "a", "]", ";", "arg", ".", "replace", "(", "FN_ARG", ",", "repl", ")", ";", "}", "return", "args", ";", "}", ";", "var", "prototype", "=", "this", ".", "reflector", ".", "getProto", "(", ")", ";", "var", "overloads", "=", "prototype", ".", "__joii__", ".", "metadata", "[", "this", ".", "name", "]", ".", "overloads", ";", "if", "(", "!", "overloads", "||", "overloads", ".", "length", "===", "0", ")", "{", "// old method for BC (wasn't recognized as a function when prototyping)", "return", "getParams", "(", "this", ".", "reflector", ".", "getProto", "(", ")", "[", "this", ".", "name", "]", ")", ";", "}", "else", "if", "(", "overloads", ".", "length", "===", "1", "&&", "overloads", "[", "0", "]", ".", "parameters", ".", "length", "===", "0", ")", "{", "// old method for BC (was recognized when prototyping, but old style)", "return", "getParams", "(", "overloads", "[", "0", "]", ".", "fn", ")", ";", "}", "else", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "idx", "=", "0", ";", "idx", "<", "overloads", ".", "length", ";", "idx", "++", ")", "{", "var", "fn_meta", "=", "[", "]", ";", "var", "function_parameters_meta", "=", "overloads", "[", "idx", "]", ";", "var", "parsed_params", "=", "getParams", "(", "function_parameters_meta", ".", "fn", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "function_parameters_meta", ".", "parameters", ".", "length", ";", "j", "++", ")", "{", "var", "param", "=", "{", "name", ":", "parsed_params", ".", "length", ">", "j", "?", "parsed_params", "[", "j", "]", ":", "null", ",", "type", ":", "function_parameters_meta", ".", "parameters", "[", "j", "]", "}", ";", "fn_meta", ".", "push", "(", "param", ")", ";", "}", "ret", ".", "push", "(", "fn_meta", ")", ";", "}", "return", "ret", ";", "}", "}" ]
Returns an array of strings based on the parameters defined in the declared function. @return string[]
[ "Returns", "an", "array", "of", "strings", "based", "on", "the", "parameters", "defined", "in", "the", "declared", "function", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L443-L493
35,499
haroldiedema/joii
src/Reflection.js
function(f) { var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, fn_text = this.reflector.getProto()[this.name].toString().replace(STRIP_COMMENTS, ''); return fn_text.substr(fn_text.indexOf('{') + 1, fn_text.lastIndexOf('}') - 4).replace(/}([^}]*)$/, '$1'); }
javascript
function(f) { var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, fn_text = this.reflector.getProto()[this.name].toString().replace(STRIP_COMMENTS, ''); return fn_text.substr(fn_text.indexOf('{') + 1, fn_text.lastIndexOf('}') - 4).replace(/}([^}]*)$/, '$1'); }
[ "function", "(", "f", ")", "{", "var", "STRIP_COMMENTS", "=", "/", "((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))", "/", "mg", ",", "fn_text", "=", "this", ".", "reflector", ".", "getProto", "(", ")", "[", "this", ".", "name", "]", ".", "toString", "(", ")", ".", "replace", "(", "STRIP_COMMENTS", ",", "''", ")", ";", "return", "fn_text", ".", "substr", "(", "fn_text", ".", "indexOf", "(", "'{'", ")", "+", "1", ",", "fn_text", ".", "lastIndexOf", "(", "'}'", ")", "-", "4", ")", ".", "replace", "(", "/", "}([^}]*)$", "/", ",", "'$1'", ")", ";", "}" ]
Returns the body of this method as a string. @return string
[ "Returns", "the", "body", "of", "this", "method", "as", "a", "string", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L500-L505