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
49,800
derdesign/protos
drivers/sqlite.js
SQLite
function SQLite(config) { /*jshint bitwise: false */ var self = this; config = config || {}; config.mode = config.mode || (sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE); if (!config.filename) { // Exit if no filename provided throw new Error("No filename provided for SQLite Driver"); } else if (config.filename != ":memory:" && !fs.existsSync(config.filename)) { // Create file if it doesn't exist fs.writeFileSync(config.filename, '', 'binary'); } this.className = this.constructor.name; this.config = config; // Set client this.client = new sqlite3.Database(config.filename, config.mode); // Assign storage if (typeof config.storage == 'string') { this.storage = app.getResource('storages/' + config.storage); } else if (config.storage instanceof protos.lib.storage) { this.storage = config.storage; } // Set db this.db = config.filename; // Only set important properties enumerable protos.util.onlySetEnumerable(this, ['className', 'db']); }
javascript
function SQLite(config) { /*jshint bitwise: false */ var self = this; config = config || {}; config.mode = config.mode || (sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE); if (!config.filename) { // Exit if no filename provided throw new Error("No filename provided for SQLite Driver"); } else if (config.filename != ":memory:" && !fs.existsSync(config.filename)) { // Create file if it doesn't exist fs.writeFileSync(config.filename, '', 'binary'); } this.className = this.constructor.name; this.config = config; // Set client this.client = new sqlite3.Database(config.filename, config.mode); // Assign storage if (typeof config.storage == 'string') { this.storage = app.getResource('storages/' + config.storage); } else if (config.storage instanceof protos.lib.storage) { this.storage = config.storage; } // Set db this.db = config.filename; // Only set important properties enumerable protos.util.onlySetEnumerable(this, ['className', 'db']); }
[ "function", "SQLite", "(", "config", ")", "{", "/*jshint bitwise: false */", "var", "self", "=", "this", ";", "config", "=", "config", "||", "{", "}", ";", "config", ".", "mode", "=", "config", ".", "mode", "||", "(", "sqlite3", ".", "OPEN_READWRITE", "|", "sqlite3", ".", "OPEN_CREATE", ")", ";", "if", "(", "!", "config", ".", "filename", ")", "{", "// Exit if no filename provided", "throw", "new", "Error", "(", "\"No filename provided for SQLite Driver\"", ")", ";", "}", "else", "if", "(", "config", ".", "filename", "!=", "\":memory:\"", "&&", "!", "fs", ".", "existsSync", "(", "config", ".", "filename", ")", ")", "{", "// Create file if it doesn't exist", "fs", ".", "writeFileSync", "(", "config", ".", "filename", ",", "''", ",", "'binary'", ")", ";", "}", "this", ".", "className", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "config", "=", "config", ";", "// Set client", "this", ".", "client", "=", "new", "sqlite3", ".", "Database", "(", "config", ".", "filename", ",", "config", ".", "mode", ")", ";", "// Assign storage", "if", "(", "typeof", "config", ".", "storage", "==", "'string'", ")", "{", "this", ".", "storage", "=", "app", ".", "getResource", "(", "'storages/'", "+", "config", ".", "storage", ")", ";", "}", "else", "if", "(", "config", ".", "storage", "instanceof", "protos", ".", "lib", ".", "storage", ")", "{", "this", ".", "storage", "=", "config", ".", "storage", ";", "}", "// Set db", "this", ".", "db", "=", "config", ".", "filename", ";", "// Only set important properties enumerable", "protos", ".", "util", ".", "onlySetEnumerable", "(", "this", ",", "[", "'className'", ",", "'db'", "]", ")", ";", "}" ]
SQLite Driver class Driver configuration config: { filename: "data/mydb.sqlite" } @class SQLite @extends Driver @constructor @param {object} app Application instance @param {object} config Driver configuration
[ "SQLite", "Driver", "class" ]
0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9
https://github.com/derdesign/protos/blob/0b679b2a7581dfbb5d065fd4b0914436ef4ef2c9/drivers/sqlite.js#L27-L68
49,801
deftly/node-deftly
src/dispatcher.js
createStacks
function createStacks (state) { const serviceErrors = state.config.service.errors || {} _.each(state.resources, function (resource) { const resourceErrors = resource.errors _.each(resource.actions, function (action, actionName) { action.name = actionName const actionErrors = action.errors var transform const key = [ resource.name, action.name ].join('!') if (state.config.middlewareStack) { const middleware = getStack(state, state.config.middlewareStack, resource, action) state.handlers[ middleware.name ] = middleware } if (state.config.transformStack) { transform = getStack(state, state.config.transformStack, resource, action) } else { transform = state.snap.stack(key) } transform.append(unit) state.transforms[ transform.name ] = transform const errors = Object.assign({}, serviceErrors, resourceErrors, actionErrors) state.errors[ key ] = handleError.bind(null, state, errors) }) }) }
javascript
function createStacks (state) { const serviceErrors = state.config.service.errors || {} _.each(state.resources, function (resource) { const resourceErrors = resource.errors _.each(resource.actions, function (action, actionName) { action.name = actionName const actionErrors = action.errors var transform const key = [ resource.name, action.name ].join('!') if (state.config.middlewareStack) { const middleware = getStack(state, state.config.middlewareStack, resource, action) state.handlers[ middleware.name ] = middleware } if (state.config.transformStack) { transform = getStack(state, state.config.transformStack, resource, action) } else { transform = state.snap.stack(key) } transform.append(unit) state.transforms[ transform.name ] = transform const errors = Object.assign({}, serviceErrors, resourceErrors, actionErrors) state.errors[ key ] = handleError.bind(null, state, errors) }) }) }
[ "function", "createStacks", "(", "state", ")", "{", "const", "serviceErrors", "=", "state", ".", "config", ".", "service", ".", "errors", "||", "{", "}", "_", ".", "each", "(", "state", ".", "resources", ",", "function", "(", "resource", ")", "{", "const", "resourceErrors", "=", "resource", ".", "errors", "_", ".", "each", "(", "resource", ".", "actions", ",", "function", "(", "action", ",", "actionName", ")", "{", "action", ".", "name", "=", "actionName", "const", "actionErrors", "=", "action", ".", "errors", "var", "transform", "const", "key", "=", "[", "resource", ".", "name", ",", "action", ".", "name", "]", ".", "join", "(", "'!'", ")", "if", "(", "state", ".", "config", ".", "middlewareStack", ")", "{", "const", "middleware", "=", "getStack", "(", "state", ",", "state", ".", "config", ".", "middlewareStack", ",", "resource", ",", "action", ")", "state", ".", "handlers", "[", "middleware", ".", "name", "]", "=", "middleware", "}", "if", "(", "state", ".", "config", ".", "transformStack", ")", "{", "transform", "=", "getStack", "(", "state", ",", "state", ".", "config", ".", "transformStack", ",", "resource", ",", "action", ")", "}", "else", "{", "transform", "=", "state", ".", "snap", ".", "stack", "(", "key", ")", "}", "transform", ".", "append", "(", "unit", ")", "state", ".", "transforms", "[", "transform", ".", "name", "]", "=", "transform", "const", "errors", "=", "Object", ".", "assign", "(", "{", "}", ",", "serviceErrors", ",", "resourceErrors", ",", "actionErrors", ")", "state", ".", "errors", "[", "key", "]", "=", "handleError", ".", "bind", "(", "null", ",", "state", ",", "errors", ")", "}", ")", "}", ")", "}" ]
iterate over all resources and actions and create the middleware and transform stacks for each resource!action pair
[ "iterate", "over", "all", "resources", "and", "actions", "and", "create", "the", "middleware", "and", "transform", "stacks", "for", "each", "resource!action", "pair" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/dispatcher.js#L35-L60
49,802
deftly/node-deftly
src/dispatcher.js
defaultErrorStrategy
function defaultErrorStrategy (env, error) { return { status: 500, error: error, data: `An unhandled error of '${error.name}' occurred at ${env.resource} - ${env.action}` } }
javascript
function defaultErrorStrategy (env, error) { return { status: 500, error: error, data: `An unhandled error of '${error.name}' occurred at ${env.resource} - ${env.action}` } }
[ "function", "defaultErrorStrategy", "(", "env", ",", "error", ")", "{", "return", "{", "status", ":", "500", ",", "error", ":", "error", ",", "data", ":", "`", "${", "error", ".", "name", "}", "${", "env", ".", "resource", "}", "${", "env", ".", "action", "}", "`", "}", "}" ]
not ideal perhaps, but something has to happen
[ "not", "ideal", "perhaps", "but", "something", "has", "to", "happen" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/dispatcher.js#L63-L69
49,803
deftly/node-deftly
src/dispatcher.js
getProperty
function getProperty (service, resource, action, propertySpec) { const parts = propertySpec.split('.') var target switch (parts[ 0 ]) { case 'action': target = action break case 'resource': target = resource break default: target = service } const property = parts[ 1 ] return { key: property, value: target ? target[ property ] : null } }
javascript
function getProperty (service, resource, action, propertySpec) { const parts = propertySpec.split('.') var target switch (parts[ 0 ]) { case 'action': target = action break case 'resource': target = resource break default: target = service } const property = parts[ 1 ] return { key: property, value: target ? target[ property ] : null } }
[ "function", "getProperty", "(", "service", ",", "resource", ",", "action", ",", "propertySpec", ")", "{", "const", "parts", "=", "propertySpec", ".", "split", "(", "'.'", ")", "var", "target", "switch", "(", "parts", "[", "0", "]", ")", "{", "case", "'action'", ":", "target", "=", "action", "break", "case", "'resource'", ":", "target", "=", "resource", "break", "default", ":", "target", "=", "service", "}", "const", "property", "=", "parts", "[", "1", "]", "return", "{", "key", ":", "property", ",", "value", ":", "target", "?", "target", "[", "property", "]", ":", "null", "}", "}" ]
given a property specifier "service|resource|action.propertyName" find the property value
[ "given", "a", "property", "specifier", "service|resource|action", ".", "propertyName", "find", "the", "property", "value" ]
0c34205fd6726356b69bcdd6dec4fcba55027af6
https://github.com/deftly/node-deftly/blob/0c34205fd6726356b69bcdd6dec4fcba55027af6/src/dispatcher.js#L110-L125
49,804
bnt44/wykop-es6
dist/index.js
md5
function md5() { var string = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; return crypto.createHash('md5').update(new Buffer(string, 'utf-8')).digest("hex"); }
javascript
function md5() { var string = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; return crypto.createHash('md5').update(new Buffer(string, 'utf-8')).digest("hex"); }
[ "function", "md5", "(", ")", "{", "var", "string", "=", "arguments", ".", "length", "<=", "0", "||", "arguments", "[", "0", "]", "===", "undefined", "?", "''", ":", "arguments", "[", "0", "]", ";", "return", "crypto", ".", "createHash", "(", "'md5'", ")", ".", "update", "(", "new", "Buffer", "(", "string", ",", "'utf-8'", ")", ")", ".", "digest", "(", "\"hex\"", ")", ";", "}" ]
create md5 hash
[ "create", "md5", "hash" ]
56657f4bfff4355276d2e6988be15c661c00c48c
https://github.com/bnt44/wykop-es6/blob/56657f4bfff4355276d2e6988be15c661c00c48c/dist/index.js#L16-L20
49,805
queicherius/lets-fetch
src/index.js
single
function single (url, options = {}) { let tries = 1 // Execute the request and retry if there are errors (and the // retry decider decided that we should try our luck again) const callRequest = () => request(url, options).catch(err => { if (internalRetry(++tries, err)) { return wait(callRequest, internalRetryWait(tries)) } throw err }) return callRequest() }
javascript
function single (url, options = {}) { let tries = 1 // Execute the request and retry if there are errors (and the // retry decider decided that we should try our luck again) const callRequest = () => request(url, options).catch(err => { if (internalRetry(++tries, err)) { return wait(callRequest, internalRetryWait(tries)) } throw err }) return callRequest() }
[ "function", "single", "(", "url", ",", "options", "=", "{", "}", ")", "{", "let", "tries", "=", "1", "// Execute the request and retry if there are errors (and the", "// retry decider decided that we should try our luck again)", "const", "callRequest", "=", "(", ")", "=>", "request", "(", "url", ",", "options", ")", ".", "catch", "(", "err", "=>", "{", "if", "(", "internalRetry", "(", "++", "tries", ",", "err", ")", ")", "{", "return", "wait", "(", "callRequest", ",", "internalRetryWait", "(", "tries", ")", ")", "}", "throw", "err", "}", ")", "return", "callRequest", "(", ")", "}" ]
Request a single url
[ "Request", "a", "single", "url" ]
bee7ad804ecb554e3bac40c2009ff32601902c8e
https://github.com/queicherius/lets-fetch/blob/bee7ad804ecb554e3bac40c2009ff32601902c8e/src/index.js#L29-L43
49,806
queicherius/lets-fetch
src/index.js
request
function request (url, options) { options = Object.assign({}, defaultOptions, options) let savedContent let savedResponse return new Promise((resolve, reject) => { fetch(url, options) .then(handleResponse) .then(handleBody) .catch(handleError) function handleResponse (response) { // Save the response for checking the status later savedResponse = response // Decode the response body switch (options.type) { case 'response': return response case 'json': return response.json() default: return response.text() } } function handleBody (content) { // Bubble an error if the response status is not okay if (savedResponse && savedResponse.status >= 400) { savedContent = content throw new Error(`Response status indicates error`) } // All is well! resolve(content) } function handleError (err) { // Overwrite potential decoding errors when the actual problem was the response if (savedResponse && savedResponse.status >= 400) { err = new Error(`Status ${savedResponse.status}`) } // Enrich the error message with the response and the content let error = new Error(err.message) error.response = savedResponse error.content = savedContent reject(error) } }) }
javascript
function request (url, options) { options = Object.assign({}, defaultOptions, options) let savedContent let savedResponse return new Promise((resolve, reject) => { fetch(url, options) .then(handleResponse) .then(handleBody) .catch(handleError) function handleResponse (response) { // Save the response for checking the status later savedResponse = response // Decode the response body switch (options.type) { case 'response': return response case 'json': return response.json() default: return response.text() } } function handleBody (content) { // Bubble an error if the response status is not okay if (savedResponse && savedResponse.status >= 400) { savedContent = content throw new Error(`Response status indicates error`) } // All is well! resolve(content) } function handleError (err) { // Overwrite potential decoding errors when the actual problem was the response if (savedResponse && savedResponse.status >= 400) { err = new Error(`Status ${savedResponse.status}`) } // Enrich the error message with the response and the content let error = new Error(err.message) error.response = savedResponse error.content = savedContent reject(error) } }) }
[ "function", "request", "(", "url", ",", "options", ")", "{", "options", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultOptions", ",", "options", ")", "let", "savedContent", "let", "savedResponse", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fetch", "(", "url", ",", "options", ")", ".", "then", "(", "handleResponse", ")", ".", "then", "(", "handleBody", ")", ".", "catch", "(", "handleError", ")", "function", "handleResponse", "(", "response", ")", "{", "// Save the response for checking the status later", "savedResponse", "=", "response", "// Decode the response body", "switch", "(", "options", ".", "type", ")", "{", "case", "'response'", ":", "return", "response", "case", "'json'", ":", "return", "response", ".", "json", "(", ")", "default", ":", "return", "response", ".", "text", "(", ")", "}", "}", "function", "handleBody", "(", "content", ")", "{", "// Bubble an error if the response status is not okay", "if", "(", "savedResponse", "&&", "savedResponse", ".", "status", ">=", "400", ")", "{", "savedContent", "=", "content", "throw", "new", "Error", "(", "`", "`", ")", "}", "// All is well!", "resolve", "(", "content", ")", "}", "function", "handleError", "(", "err", ")", "{", "// Overwrite potential decoding errors when the actual problem was the response", "if", "(", "savedResponse", "&&", "savedResponse", ".", "status", ">=", "400", ")", "{", "err", "=", "new", "Error", "(", "`", "${", "savedResponse", ".", "status", "}", "`", ")", "}", "// Enrich the error message with the response and the content", "let", "error", "=", "new", "Error", "(", "err", ".", "message", ")", "error", ".", "response", "=", "savedResponse", "error", ".", "content", "=", "savedContent", "reject", "(", "error", ")", "}", "}", ")", "}" ]
Send a request using the underlying fetch API
[ "Send", "a", "request", "using", "the", "underlying", "fetch", "API" ]
bee7ad804ecb554e3bac40c2009ff32601902c8e
https://github.com/queicherius/lets-fetch/blob/bee7ad804ecb554e3bac40c2009ff32601902c8e/src/index.js#L46-L96
49,807
queicherius/lets-fetch
src/index.js
many
function many (urls, options = {}) { let flowMethod = (options.waitTime) ? flow.series : flow.parallel // Call the single method while respecting the wait time in between tasks const callSingle = (url) => single(url, options) .then(content => wait(() => content, options.waitTime)) // Map over the urls and call them using the method the user chose let promises = urls.map(url => () => callSingle(url)) return flowMethod(promises) }
javascript
function many (urls, options = {}) { let flowMethod = (options.waitTime) ? flow.series : flow.parallel // Call the single method while respecting the wait time in between tasks const callSingle = (url) => single(url, options) .then(content => wait(() => content, options.waitTime)) // Map over the urls and call them using the method the user chose let promises = urls.map(url => () => callSingle(url)) return flowMethod(promises) }
[ "function", "many", "(", "urls", ",", "options", "=", "{", "}", ")", "{", "let", "flowMethod", "=", "(", "options", ".", "waitTime", ")", "?", "flow", ".", "series", ":", "flow", ".", "parallel", "// Call the single method while respecting the wait time in between tasks", "const", "callSingle", "=", "(", "url", ")", "=>", "single", "(", "url", ",", "options", ")", ".", "then", "(", "content", "=>", "wait", "(", "(", ")", "=>", "content", ",", "options", ".", "waitTime", ")", ")", "// Map over the urls and call them using the method the user chose", "let", "promises", "=", "urls", ".", "map", "(", "url", "=>", "(", ")", "=>", "callSingle", "(", "url", ")", ")", "return", "flowMethod", "(", "promises", ")", "}" ]
Request multiple pages
[ "Request", "multiple", "pages" ]
bee7ad804ecb554e3bac40c2009ff32601902c8e
https://github.com/queicherius/lets-fetch/blob/bee7ad804ecb554e3bac40c2009ff32601902c8e/src/index.js#L99-L109
49,808
gethuman/pancakes-recipe
utils/jwt.js
generateForUser
function generateForUser(user, existingToken) { existingToken = existingToken || {}; var privateKey = config.security.token.privateKey; var decryptedToken = _.extend(existingToken, { _id: user._id, authToken: user.authToken }); return jsonwebtoken.sign(decryptedToken, privateKey); }
javascript
function generateForUser(user, existingToken) { existingToken = existingToken || {}; var privateKey = config.security.token.privateKey; var decryptedToken = _.extend(existingToken, { _id: user._id, authToken: user.authToken }); return jsonwebtoken.sign(decryptedToken, privateKey); }
[ "function", "generateForUser", "(", "user", ",", "existingToken", ")", "{", "existingToken", "=", "existingToken", "||", "{", "}", ";", "var", "privateKey", "=", "config", ".", "security", ".", "token", ".", "privateKey", ";", "var", "decryptedToken", "=", "_", ".", "extend", "(", "existingToken", ",", "{", "_id", ":", "user", ".", "_id", ",", "authToken", ":", "user", ".", "authToken", "}", ")", ";", "return", "jsonwebtoken", ".", "sign", "(", "decryptedToken", ",", "privateKey", ")", ";", "}" ]
Simple function to generate a JWT based off a user @param user @param existingToken Optional, pass in if there is an existing token we are adding to @returns {*}
[ "Simple", "function", "to", "generate", "a", "JWT", "based", "off", "a", "user" ]
ea3feb8839e2edaf1b4577c052b8958953db4498
https://github.com/gethuman/pancakes-recipe/blob/ea3feb8839e2edaf1b4577c052b8958953db4498/utils/jwt.js#L15-L22
49,809
redisjs/jsr-server
lib/command/pubsub/psubscribe.js
execute
function execute(req, res) { this.state.pubsub.psubscribe(req.conn, req.args); }
javascript
function execute(req, res) { this.state.pubsub.psubscribe(req.conn, req.args); }
[ "function", "execute", "(", "req", ",", "res", ")", "{", "this", ".", "state", ".", "pubsub", ".", "psubscribe", "(", "req", ".", "conn", ",", "req", ".", "args", ")", ";", "}" ]
Respond to the PSUBSCRIBE command.
[ "Respond", "to", "the", "PSUBSCRIBE", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/pubsub/psubscribe.js#L17-L19
49,810
woyorus/syncsocket
src/channel.js
Channel
function Channel(server, opts) { this.server = server; opts = opts || {}; this.channelId = opts.channelId; this.timeserver = opts.timeserver || this.server.timeserverUrl(); this.clients = []; this.clientStates = {}; // Hackery this.setMaxListeners(150); this.clockClient = new ClockClient(this.timeserver); this.sync(); }
javascript
function Channel(server, opts) { this.server = server; opts = opts || {}; this.channelId = opts.channelId; this.timeserver = opts.timeserver || this.server.timeserverUrl(); this.clients = []; this.clientStates = {}; // Hackery this.setMaxListeners(150); this.clockClient = new ClockClient(this.timeserver); this.sync(); }
[ "function", "Channel", "(", "server", ",", "opts", ")", "{", "this", ".", "server", "=", "server", ";", "opts", "=", "opts", "||", "{", "}", ";", "this", ".", "channelId", "=", "opts", ".", "channelId", ";", "this", ".", "timeserver", "=", "opts", ".", "timeserver", "||", "this", ".", "server", ".", "timeserverUrl", "(", ")", ";", "this", ".", "clients", "=", "[", "]", ";", "this", ".", "clientStates", "=", "{", "}", ";", "// Hackery", "this", ".", "setMaxListeners", "(", "150", ")", ";", "this", ".", "clockClient", "=", "new", "ClockClient", "(", "this", ".", "timeserver", ")", ";", "this", ".", "sync", "(", ")", ";", "}" ]
Channel constructor. @type {Channel} @param {Server} server The server object @param {object} opts Options @param {string} opts.channelId The channel id (string). If not passed, will generate a random one @param {string} opts.timeserver The timeserver which channel will use (if not set, will use the server's default) @param {boolean} opts.autoSyncClients Automatically instruct unsynchronized clients to re-synchronize @constructor @public
[ "Channel", "constructor", "." ]
793c35ed99178055aa8278a3fc006256333503e4
https://github.com/woyorus/syncsocket/blob/793c35ed99178055aa8278a3fc006256333503e4/src/channel.js#L21-L35
49,811
docLoop/core
docloop-error-handling.js
catchAsyncErrors
function catchAsyncErrors(fn) { return async (...args) => { try{ await Promise.resolve(fn(...args)).catch(args[2])} catch(e){ args[2](e) } } }
javascript
function catchAsyncErrors(fn) { return async (...args) => { try{ await Promise.resolve(fn(...args)).catch(args[2])} catch(e){ args[2](e) } } }
[ "function", "catchAsyncErrors", "(", "fn", ")", "{", "return", "async", "(", "...", "args", ")", "=>", "{", "try", "{", "await", "Promise", ".", "resolve", "(", "fn", "(", "...", "args", ")", ")", ".", "catch", "(", "args", "[", "2", "]", ")", "}", "catch", "(", "e", ")", "{", "args", "[", "2", "]", "(", "e", ")", "}", "}", "}" ]
Wrapper for express request handlers to catch rejected promises or async methods. @memberof module:docloop @param {Function} fn Express request handler to wrap @return {Function} Wrapped request handler
[ "Wrapper", "for", "express", "request", "handlers", "to", "catch", "rejected", "promises", "or", "async", "methods", "." ]
111870e3dcc537997fa31dee485e355e487af794
https://github.com/docLoop/core/blob/111870e3dcc537997fa31dee485e355e487af794/docloop-error-handling.js#L39-L44
49,812
BenjaminLykins/command-line-arguments
lib/command-line-arguments.js
isLastLevel
function isLastLevel(arr){ //console.log("isLastLevel(" + arr + ")"); if(!arr){ return true; } for(var i = 0; i < arr.length; i++){ if(typeof arr[i] === 'number'); else if(arr[i].substring(0,1) === '-'){ //console.log("->false"); return false; } } //console.log("-> true"); return true; }
javascript
function isLastLevel(arr){ //console.log("isLastLevel(" + arr + ")"); if(!arr){ return true; } for(var i = 0; i < arr.length; i++){ if(typeof arr[i] === 'number'); else if(arr[i].substring(0,1) === '-'){ //console.log("->false"); return false; } } //console.log("-> true"); return true; }
[ "function", "isLastLevel", "(", "arr", ")", "{", "//console.log(\"isLastLevel(\" + arr + \")\");", "if", "(", "!", "arr", ")", "{", "return", "true", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arr", ".", "length", ";", "i", "++", ")", "{", "if", "(", "typeof", "arr", "[", "i", "]", "===", "'number'", ")", ";", "else", "if", "(", "arr", "[", "i", "]", ".", "substring", "(", "0", ",", "1", ")", "===", "'-'", ")", "{", "//console.log(\"->false\");", "return", "false", ";", "}", "}", "//console.log(\"-> true\");", "return", "true", ";", "}" ]
Returns true if there are no more sublevels after current level
[ "Returns", "true", "if", "there", "are", "no", "more", "sublevels", "after", "current", "level" ]
f8839c55991ac2d9f20477e551529ed706d850f5
https://github.com/BenjaminLykins/command-line-arguments/blob/f8839c55991ac2d9f20477e551529ed706d850f5/lib/command-line-arguments.js#L15-L29
49,813
fullstackers/bus.io-common
lib/message.js
Message
function Message () { if (!(this instanceof Message)) { if (typeof arguments[0] === 'object' && arguments[0] instanceof Message) { debug('message is a message so return it'); return arguments[0]; } else { debug('creating new message and initializing with arguments'); var m = new Message(); Message.prototype.initialize.apply(m, slice.call(arguments)); return m; } } else { this.isMessage = true; if (arguments.length) { debug('initializing with arguments'); Message.prototype.initialize.apply(this, slice.call(arguments)); } } }
javascript
function Message () { if (!(this instanceof Message)) { if (typeof arguments[0] === 'object' && arguments[0] instanceof Message) { debug('message is a message so return it'); return arguments[0]; } else { debug('creating new message and initializing with arguments'); var m = new Message(); Message.prototype.initialize.apply(m, slice.call(arguments)); return m; } } else { this.isMessage = true; if (arguments.length) { debug('initializing with arguments'); Message.prototype.initialize.apply(this, slice.call(arguments)); } } }
[ "function", "Message", "(", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Message", ")", ")", "{", "if", "(", "typeof", "arguments", "[", "0", "]", "===", "'object'", "&&", "arguments", "[", "0", "]", "instanceof", "Message", ")", "{", "debug", "(", "'message is a message so return it'", ")", ";", "return", "arguments", "[", "0", "]", ";", "}", "else", "{", "debug", "(", "'creating new message and initializing with arguments'", ")", ";", "var", "m", "=", "new", "Message", "(", ")", ";", "Message", ".", "prototype", ".", "initialize", ".", "apply", "(", "m", ",", "slice", ".", "call", "(", "arguments", ")", ")", ";", "return", "m", ";", "}", "}", "else", "{", "this", ".", "isMessage", "=", "true", ";", "if", "(", "arguments", ".", "length", ")", "{", "debug", "(", "'initializing with arguments'", ")", ";", "Message", ".", "prototype", ".", "initialize", ".", "apply", "(", "this", ",", "slice", ".", "call", "(", "arguments", ")", ")", ";", "}", "}", "}" ]
A message represents an action performed by an actor on target with the content
[ "A", "message", "represents", "an", "action", "performed", "by", "an", "actor", "on", "target", "with", "the", "content" ]
9e081a15ba40c4233a936d4105465277da8578fd
https://github.com/fullstackers/bus.io-common/blob/9e081a15ba40c4233a936d4105465277da8578fd/lib/message.js#L13-L35
49,814
lemonde/knex-schema-filter
lib/filter.js
filterSchemas
function filterSchemas(schemas, tableNames, callback) { if (! (schemas || []).length || ! (tableNames || []).length) return process.nextTick(_.partial(callback, null, schemas || [])); var schemasMap = _.indexBy(schemas, 'tableName'); var filteredSchemas = _.chain(schemasMap).pick(tableNames).toArray().value(); resolveSchemasDeps(filteredSchemas, schemasMap, callback); }
javascript
function filterSchemas(schemas, tableNames, callback) { if (! (schemas || []).length || ! (tableNames || []).length) return process.nextTick(_.partial(callback, null, schemas || [])); var schemasMap = _.indexBy(schemas, 'tableName'); var filteredSchemas = _.chain(schemasMap).pick(tableNames).toArray().value(); resolveSchemasDeps(filteredSchemas, schemasMap, callback); }
[ "function", "filterSchemas", "(", "schemas", ",", "tableNames", ",", "callback", ")", "{", "if", "(", "!", "(", "schemas", "||", "[", "]", ")", ".", "length", "||", "!", "(", "tableNames", "||", "[", "]", ")", ".", "length", ")", "return", "process", ".", "nextTick", "(", "_", ".", "partial", "(", "callback", ",", "null", ",", "schemas", "||", "[", "]", ")", ")", ";", "var", "schemasMap", "=", "_", ".", "indexBy", "(", "schemas", ",", "'tableName'", ")", ";", "var", "filteredSchemas", "=", "_", ".", "chain", "(", "schemasMap", ")", ".", "pick", "(", "tableNames", ")", ".", "toArray", "(", ")", ".", "value", "(", ")", ";", "resolveSchemasDeps", "(", "filteredSchemas", ",", "schemasMap", ",", "callback", ")", ";", "}" ]
Filter provided schemas using tableNames and include schemas dependencies. @param {[Schema]} schemas @param {[String]} tableNames @param {Function} callback
[ "Filter", "provided", "schemas", "using", "tableNames", "and", "include", "schemas", "dependencies", "." ]
13c65c88de40f7df18332712d1f0e5262a42611e
https://github.com/lemonde/knex-schema-filter/blob/13c65c88de40f7df18332712d1f0e5262a42611e/lib/filter.js#L20-L27
49,815
lemonde/knex-schema-filter
lib/filter.js
resolveSchemasDeps
function resolveSchemasDeps(schemas, schemasMap, callback) { async.reduce(schemas, [], function (result, schema, next) { tryAndDelay(resolveSchemaDeps, result, schema, schemasMap, next); }, function (err, result) { return err ? callback(err) : callback(null, _.uniq(result)); }); }
javascript
function resolveSchemasDeps(schemas, schemasMap, callback) { async.reduce(schemas, [], function (result, schema, next) { tryAndDelay(resolveSchemaDeps, result, schema, schemasMap, next); }, function (err, result) { return err ? callback(err) : callback(null, _.uniq(result)); }); }
[ "function", "resolveSchemasDeps", "(", "schemas", ",", "schemasMap", ",", "callback", ")", "{", "async", ".", "reduce", "(", "schemas", ",", "[", "]", ",", "function", "(", "result", ",", "schema", ",", "next", ")", "{", "tryAndDelay", "(", "resolveSchemaDeps", ",", "result", ",", "schema", ",", "schemasMap", ",", "next", ")", ";", "}", ",", "function", "(", "err", ",", "result", ")", "{", "return", "err", "?", "callback", "(", "err", ")", ":", "callback", "(", "null", ",", "_", ".", "uniq", "(", "result", ")", ")", ";", "}", ")", ";", "}" ]
Resolve provided schemas dependencies. @param {[Schema]} schemas @param {Object} schemasMap @param {Function} callback
[ "Resolve", "provided", "schemas", "dependencies", "." ]
13c65c88de40f7df18332712d1f0e5262a42611e
https://github.com/lemonde/knex-schema-filter/blob/13c65c88de40f7df18332712d1f0e5262a42611e/lib/filter.js#L37-L43
49,816
lemonde/knex-schema-filter
lib/filter.js
resolveSchemaDeps
function resolveSchemaDeps(result, schema, schemasMap) { if (! (schema.deps || []).length) return result.concat([ schema ]); return schema.deps.reduce(function (result, tableName) { return (result.indexOf(schemasMap[tableName]) >= 0) ? result : result.concat(resolveSchemaDeps(result, schemasMap[tableName], schemasMap)); }, result).concat([ schema ]); }
javascript
function resolveSchemaDeps(result, schema, schemasMap) { if (! (schema.deps || []).length) return result.concat([ schema ]); return schema.deps.reduce(function (result, tableName) { return (result.indexOf(schemasMap[tableName]) >= 0) ? result : result.concat(resolveSchemaDeps(result, schemasMap[tableName], schemasMap)); }, result).concat([ schema ]); }
[ "function", "resolveSchemaDeps", "(", "result", ",", "schema", ",", "schemasMap", ")", "{", "if", "(", "!", "(", "schema", ".", "deps", "||", "[", "]", ")", ".", "length", ")", "return", "result", ".", "concat", "(", "[", "schema", "]", ")", ";", "return", "schema", ".", "deps", ".", "reduce", "(", "function", "(", "result", ",", "tableName", ")", "{", "return", "(", "result", ".", "indexOf", "(", "schemasMap", "[", "tableName", "]", ")", ">=", "0", ")", "?", "result", ":", "result", ".", "concat", "(", "resolveSchemaDeps", "(", "result", ",", "schemasMap", "[", "tableName", "]", ",", "schemasMap", ")", ")", ";", "}", ",", "result", ")", ".", "concat", "(", "[", "schema", "]", ")", ";", "}" ]
Resolve provided schema dependencies. @param {[Schema]} result @param {Schema} schema @param {Object} schemasMap @return {[String]} - table names
[ "Resolve", "provided", "schema", "dependencies", "." ]
13c65c88de40f7df18332712d1f0e5262a42611e
https://github.com/lemonde/knex-schema-filter/blob/13c65c88de40f7df18332712d1f0e5262a42611e/lib/filter.js#L54-L62
49,817
lemonde/knex-schema-filter
lib/filter.js
tryAndDelay
function tryAndDelay(fn) { var args = _.chain(arguments).rest().initial().value(); var callback = _.last(arguments); try { process.nextTick(_.partial(callback, null, fn.apply(null, args))); } catch (err) { process.nextTick(_.partial(callback, err)); } }
javascript
function tryAndDelay(fn) { var args = _.chain(arguments).rest().initial().value(); var callback = _.last(arguments); try { process.nextTick(_.partial(callback, null, fn.apply(null, args))); } catch (err) { process.nextTick(_.partial(callback, err)); } }
[ "function", "tryAndDelay", "(", "fn", ")", "{", "var", "args", "=", "_", ".", "chain", "(", "arguments", ")", ".", "rest", "(", ")", ".", "initial", "(", ")", ".", "value", "(", ")", ";", "var", "callback", "=", "_", ".", "last", "(", "arguments", ")", ";", "try", "{", "process", ".", "nextTick", "(", "_", ".", "partial", "(", "callback", ",", "null", ",", "fn", ".", "apply", "(", "null", ",", "args", ")", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "process", ".", "nextTick", "(", "_", ".", "partial", "(", "callback", ",", "err", ")", ")", ";", "}", "}" ]
Execute provided synchrone function as asynchrone. @param {Function} fn @param {*...} args @param {Function} callback
[ "Execute", "provided", "synchrone", "function", "as", "asynchrone", "." ]
13c65c88de40f7df18332712d1f0e5262a42611e
https://github.com/lemonde/knex-schema-filter/blob/13c65c88de40f7df18332712d1f0e5262a42611e/lib/filter.js#L72-L80
49,818
gethuman/pancakes-angular
lib/ngapp/service.helper.js
genServiceMethod
function genServiceMethod(method) { return function (req) { return ajax.send(method.url, method.httpMethod, req, method.resourceName); }; }
javascript
function genServiceMethod(method) { return function (req) { return ajax.send(method.url, method.httpMethod, req, method.resourceName); }; }
[ "function", "genServiceMethod", "(", "method", ")", "{", "return", "function", "(", "req", ")", "{", "return", "ajax", ".", "send", "(", "method", ".", "url", ",", "method", ".", "httpMethod", ",", "req", ",", "method", ".", "resourceName", ")", ";", "}", ";", "}" ]
Generate a service method @param method @returns {Function}
[ "Generate", "a", "service", "method" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/service.helper.js#L14-L18
49,819
gethuman/pancakes-angular
lib/ngapp/service.helper.js
genService
function genService(methods) { var service = {}; for (var methodName in methods) { if (methods.hasOwnProperty(methodName)) { service[methodName] = genServiceMethod(methods[methodName]); } } return service; }
javascript
function genService(methods) { var service = {}; for (var methodName in methods) { if (methods.hasOwnProperty(methodName)) { service[methodName] = genServiceMethod(methods[methodName]); } } return service; }
[ "function", "genService", "(", "methods", ")", "{", "var", "service", "=", "{", "}", ";", "for", "(", "var", "methodName", "in", "methods", ")", "{", "if", "(", "methods", ".", "hasOwnProperty", "(", "methodName", ")", ")", "{", "service", "[", "methodName", "]", "=", "genServiceMethod", "(", "methods", "[", "methodName", "]", ")", ";", "}", "}", "return", "service", ";", "}" ]
Generate a service based on a set of methods @param methods
[ "Generate", "a", "service", "based", "on", "a", "set", "of", "methods" ]
9589b7ba09619843e271293088005c62ed23f355
https://github.com/gethuman/pancakes-angular/blob/9589b7ba09619843e271293088005c62ed23f355/lib/ngapp/service.helper.js#L24-L34
49,820
mattmccray/blam.js
bench/lib/benchmark.js
reverse
function reverse() { var upperIndex, value, index = -1, object = Object(this), length = object.length >>> 0, middle = floor(length / 2); if (length > 1) { while (++index < middle) { upperIndex = length - index - 1; value = upperIndex in object ? object[upperIndex] : uid; if (index in object) { object[upperIndex] = object[index]; } else { delete object[upperIndex]; } if (value != uid) { object[index] = value; } else { delete object[index]; } } } return object; }
javascript
function reverse() { var upperIndex, value, index = -1, object = Object(this), length = object.length >>> 0, middle = floor(length / 2); if (length > 1) { while (++index < middle) { upperIndex = length - index - 1; value = upperIndex in object ? object[upperIndex] : uid; if (index in object) { object[upperIndex] = object[index]; } else { delete object[upperIndex]; } if (value != uid) { object[index] = value; } else { delete object[index]; } } } return object; }
[ "function", "reverse", "(", ")", "{", "var", "upperIndex", ",", "value", ",", "index", "=", "-", "1", ",", "object", "=", "Object", "(", "this", ")", ",", "length", "=", "object", ".", "length", ">>>", "0", ",", "middle", "=", "floor", "(", "length", "/", "2", ")", ";", "if", "(", "length", ">", "1", ")", "{", "while", "(", "++", "index", "<", "middle", ")", "{", "upperIndex", "=", "length", "-", "index", "-", "1", ";", "value", "=", "upperIndex", "in", "object", "?", "object", "[", "upperIndex", "]", ":", "uid", ";", "if", "(", "index", "in", "object", ")", "{", "object", "[", "upperIndex", "]", "=", "object", "[", "index", "]", ";", "}", "else", "{", "delete", "object", "[", "upperIndex", "]", ";", "}", "if", "(", "value", "!=", "uid", ")", "{", "object", "[", "index", "]", "=", "value", ";", "}", "else", "{", "delete", "object", "[", "index", "]", ";", "}", "}", "}", "return", "object", ";", "}" ]
Rearrange the host array's elements in reverse order. @memberOf Benchmark.Suite @returns {Array} The reversed array.
[ "Rearrange", "the", "host", "array", "s", "elements", "in", "reverse", "order", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L602-L627
49,821
mattmccray/blam.js
bench/lib/benchmark.js
slice
function slice(start, end) { var index = -1, object = Object(this), length = object.length >>> 0, result = []; start = toInteger(start); start = start < 0 ? max(length + start, 0) : min(start, length); start--; end = end == null ? length : toInteger(end); end = end < 0 ? max(length + end, 0) : min(end, length); while ((++index, ++start) < end) { if (start in object) { result[index] = object[start]; } } return result; }
javascript
function slice(start, end) { var index = -1, object = Object(this), length = object.length >>> 0, result = []; start = toInteger(start); start = start < 0 ? max(length + start, 0) : min(start, length); start--; end = end == null ? length : toInteger(end); end = end < 0 ? max(length + end, 0) : min(end, length); while ((++index, ++start) < end) { if (start in object) { result[index] = object[start]; } } return result; }
[ "function", "slice", "(", "start", ",", "end", ")", "{", "var", "index", "=", "-", "1", ",", "object", "=", "Object", "(", "this", ")", ",", "length", "=", "object", ".", "length", ">>>", "0", ",", "result", "=", "[", "]", ";", "start", "=", "toInteger", "(", "start", ")", ";", "start", "=", "start", "<", "0", "?", "max", "(", "length", "+", "start", ",", "0", ")", ":", "min", "(", "start", ",", "length", ")", ";", "start", "--", ";", "end", "=", "end", "==", "null", "?", "length", ":", "toInteger", "(", "end", ")", ";", "end", "=", "end", "<", "0", "?", "max", "(", "length", "+", "end", ",", "0", ")", ":", "min", "(", "end", ",", "length", ")", ";", "while", "(", "(", "++", "index", ",", "++", "start", ")", "<", "end", ")", "{", "if", "(", "start", "in", "object", ")", "{", "result", "[", "index", "]", "=", "object", "[", "start", "]", ";", "}", "}", "return", "result", ";", "}" ]
Creates an array of the host array's elements from the start index up to, but not including, the end index. @memberOf Benchmark.Suite @param {Number} start The starting index. @param {Number} end The end index. @returns {Array} The new array.
[ "Creates", "an", "array", "of", "the", "host", "array", "s", "elements", "from", "the", "start", "index", "up", "to", "but", "not", "including", "the", "end", "index", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L648-L666
49,822
mattmccray/blam.js
bench/lib/benchmark.js
toInteger
function toInteger(value) { value = +value; return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1); }
javascript
function toInteger(value) { value = +value; return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1); }
[ "function", "toInteger", "(", "value", ")", "{", "value", "=", "+", "value", ";", "return", "value", "===", "0", "||", "!", "isFinite", "(", "value", ")", "?", "value", "||", "0", ":", "value", "-", "(", "value", "%", "1", ")", ";", "}" ]
Converts the specified `value` to an integer. @private @param {Mixed} value The value to convert. @returns {Number} The resulting integer.
[ "Converts", "the", "specified", "value", "to", "an", "integer", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L695-L698
49,823
mattmccray/blam.js
bench/lib/benchmark.js
isArguments
function isArguments() { // lazy define isArguments = function(value) { return toString.call(value) == '[object Arguments]'; }; if (noArgumentsClass) { isArguments = function(value) { return hasKey(value, 'callee') && !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee')); }; } return isArguments(arguments[0]); }
javascript
function isArguments() { // lazy define isArguments = function(value) { return toString.call(value) == '[object Arguments]'; }; if (noArgumentsClass) { isArguments = function(value) { return hasKey(value, 'callee') && !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee')); }; } return isArguments(arguments[0]); }
[ "function", "isArguments", "(", ")", "{", "// lazy define", "isArguments", "=", "function", "(", "value", ")", "{", "return", "toString", ".", "call", "(", "value", ")", "==", "'[object Arguments]'", ";", "}", ";", "if", "(", "noArgumentsClass", ")", "{", "isArguments", "=", "function", "(", "value", ")", "{", "return", "hasKey", "(", "value", ",", "'callee'", ")", "&&", "!", "(", "propertyIsEnumerable", "&&", "propertyIsEnumerable", ".", "call", "(", "value", ",", "'callee'", ")", ")", ";", "}", ";", "}", "return", "isArguments", "(", "arguments", "[", "0", "]", ")", ";", "}" ]
Checks if a value is an `arguments` object. @private @param {Mixed} value The value to check. @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`.
[ "Checks", "if", "a", "value", "is", "an", "arguments", "object", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L944-L956
49,824
mattmccray/blam.js
bench/lib/benchmark.js
isObject
function isObject(value) { var ctor, result = !!value && toString.call(value) == '[object Object]'; if (result && noArgumentsClass) { // avoid false positives for `arguments` objects in IE < 9 result = !isArguments(value); } if (result) { // IE < 9 presents nodes like `Object` objects: // IE < 8 are missing the node's constructor property // IE 8 node constructors are typeof "object" ctor = value.constructor; // check if the constructor is `Object` as `Object instanceof Object` is `true` if ((result = isClassOf(ctor, 'Function') && ctor instanceof ctor)) { // An object's own properties are iterated before inherited properties. // If the last iterated key belongs to an object's own property then // there are no inherited enumerable properties. forProps(value, function(subValue, subKey) { result = subKey; }); result = result === true || hasKey(value, result); } } return result; }
javascript
function isObject(value) { var ctor, result = !!value && toString.call(value) == '[object Object]'; if (result && noArgumentsClass) { // avoid false positives for `arguments` objects in IE < 9 result = !isArguments(value); } if (result) { // IE < 9 presents nodes like `Object` objects: // IE < 8 are missing the node's constructor property // IE 8 node constructors are typeof "object" ctor = value.constructor; // check if the constructor is `Object` as `Object instanceof Object` is `true` if ((result = isClassOf(ctor, 'Function') && ctor instanceof ctor)) { // An object's own properties are iterated before inherited properties. // If the last iterated key belongs to an object's own property then // there are no inherited enumerable properties. forProps(value, function(subValue, subKey) { result = subKey; }); result = result === true || hasKey(value, result); } } return result; }
[ "function", "isObject", "(", "value", ")", "{", "var", "ctor", ",", "result", "=", "!", "!", "value", "&&", "toString", ".", "call", "(", "value", ")", "==", "'[object Object]'", ";", "if", "(", "result", "&&", "noArgumentsClass", ")", "{", "// avoid false positives for `arguments` objects in IE < 9", "result", "=", "!", "isArguments", "(", "value", ")", ";", "}", "if", "(", "result", ")", "{", "// IE < 9 presents nodes like `Object` objects:", "// IE < 8 are missing the node's constructor property", "// IE 8 node constructors are typeof \"object\"", "ctor", "=", "value", ".", "constructor", ";", "// check if the constructor is `Object` as `Object instanceof Object` is `true`", "if", "(", "(", "result", "=", "isClassOf", "(", "ctor", ",", "'Function'", ")", "&&", "ctor", "instanceof", "ctor", ")", ")", "{", "// An object's own properties are iterated before inherited properties.", "// If the last iterated key belongs to an object's own property then", "// there are no inherited enumerable properties.", "forProps", "(", "value", ",", "function", "(", "subValue", ",", "subKey", ")", "{", "result", "=", "subKey", ";", "}", ")", ";", "result", "=", "result", "===", "true", "||", "hasKey", "(", "value", ",", "result", ")", ";", "}", "}", "return", "result", ";", "}" ]
Checks if the specified `value` is an object created by the `Object` constructor assuming objects created by the `Object` constructor have no inherited enumerable properties and assuming there are no `Object.prototype` extensions. @private @param {Mixed} value The value to check. @returns {Boolean} Returns `true` if `value` is an object, else `false`.
[ "Checks", "if", "the", "specified", "value", "is", "an", "object", "created", "by", "the", "Object", "constructor", "assuming", "objects", "created", "by", "the", "Object", "constructor", "have", "no", "inherited", "enumerable", "properties", "and", "assuming", "there", "are", "no", "Object", ".", "prototype", "extensions", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L996-L1019
49,825
mattmccray/blam.js
bench/lib/benchmark.js
methodize
function methodize(fn) { return function() { var args = [this]; args.push.apply(args, arguments); return fn.apply(null, args); }; }
javascript
function methodize(fn) { return function() { var args = [this]; args.push.apply(args, arguments); return fn.apply(null, args); }; }
[ "function", "methodize", "(", "fn", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "[", "this", "]", ";", "args", ".", "push", ".", "apply", "(", "args", ",", "arguments", ")", ";", "return", "fn", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ";", "}" ]
Wraps a function and passes `this` to the original function as the first argument. @private @param {Function} fn The function to be wrapped. @returns {Function} The new function.
[ "Wraps", "a", "function", "and", "passes", "this", "to", "the", "original", "function", "as", "the", "first", "argument", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1040-L1046
49,826
mattmccray/blam.js
bench/lib/benchmark.js
runScript
function runScript(code) { var anchor = freeDefine ? define.amd : Benchmark, script = doc.createElement('script'), sibling = doc.getElementsByTagName('script')[0], parent = sibling.parentNode, prop = uid + 'runScript', prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; // Firefox 2.0.0.2 cannot use script injection as intended because it executes // asynchronously, but that's OK because script injection is only used to avoid // the previously commented JaegerMonkey bug. try { // remove the inserted script *before* running the code to avoid differences // in the expected script element count/order of the document. script.appendChild(doc.createTextNode(prefix + code)); anchor[prop] = function() { destroyElement(script); }; } catch(e) { parent = parent.cloneNode(false); sibling = null; script.text = code; } parent.insertBefore(script, sibling); delete anchor[prop]; }
javascript
function runScript(code) { var anchor = freeDefine ? define.amd : Benchmark, script = doc.createElement('script'), sibling = doc.getElementsByTagName('script')[0], parent = sibling.parentNode, prop = uid + 'runScript', prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; // Firefox 2.0.0.2 cannot use script injection as intended because it executes // asynchronously, but that's OK because script injection is only used to avoid // the previously commented JaegerMonkey bug. try { // remove the inserted script *before* running the code to avoid differences // in the expected script element count/order of the document. script.appendChild(doc.createTextNode(prefix + code)); anchor[prop] = function() { destroyElement(script); }; } catch(e) { parent = parent.cloneNode(false); sibling = null; script.text = code; } parent.insertBefore(script, sibling); delete anchor[prop]; }
[ "function", "runScript", "(", "code", ")", "{", "var", "anchor", "=", "freeDefine", "?", "define", ".", "amd", ":", "Benchmark", ",", "script", "=", "doc", ".", "createElement", "(", "'script'", ")", ",", "sibling", "=", "doc", ".", "getElementsByTagName", "(", "'script'", ")", "[", "0", "]", ",", "parent", "=", "sibling", ".", "parentNode", ",", "prop", "=", "uid", "+", "'runScript'", ",", "prefix", "=", "'('", "+", "(", "freeDefine", "?", "'define.amd.'", ":", "'Benchmark.'", ")", "+", "prop", "+", "'||function(){})();'", ";", "// Firefox 2.0.0.2 cannot use script injection as intended because it executes", "// asynchronously, but that's OK because script injection is only used to avoid", "// the previously commented JaegerMonkey bug.", "try", "{", "// remove the inserted script *before* running the code to avoid differences", "// in the expected script element count/order of the document.", "script", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "prefix", "+", "code", ")", ")", ";", "anchor", "[", "prop", "]", "=", "function", "(", ")", "{", "destroyElement", "(", "script", ")", ";", "}", ";", "}", "catch", "(", "e", ")", "{", "parent", "=", "parent", ".", "cloneNode", "(", "false", ")", ";", "sibling", "=", "null", ";", "script", ".", "text", "=", "code", ";", "}", "parent", ".", "insertBefore", "(", "script", ",", "sibling", ")", ";", "delete", "anchor", "[", "prop", "]", ";", "}" ]
Runs a snippet of JavaScript via script injection. @private @param {String} code The code to run.
[ "Runs", "a", "snippet", "of", "JavaScript", "via", "script", "injection", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1077-L1100
49,827
mattmccray/blam.js
bench/lib/benchmark.js
getMarkerKey
function getMarkerKey(object) { // avoid collisions with existing keys var result = uid; while (object[result] && object[result].constructor != Marker) { result += 1; } return result; }
javascript
function getMarkerKey(object) { // avoid collisions with existing keys var result = uid; while (object[result] && object[result].constructor != Marker) { result += 1; } return result; }
[ "function", "getMarkerKey", "(", "object", ")", "{", "// avoid collisions with existing keys", "var", "result", "=", "uid", ";", "while", "(", "object", "[", "result", "]", "&&", "object", "[", "result", "]", ".", "constructor", "!=", "Marker", ")", "{", "result", "+=", "1", ";", "}", "return", "result", ";", "}" ]
Gets an available marker key for the given object.
[ "Gets", "an", "available", "marker", "key", "for", "the", "given", "object", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1220-L1227
49,828
mattmccray/blam.js
bench/lib/benchmark.js
each
function each(object, callback, thisArg) { var result = object; object = Object(object); var fn = callback, index = -1, length = object.length, isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)), isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'), isConvertable = isSnapshot || isSplittable || 'item' in object, origObject = object; // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists if (length === length >>> 0) { if (isConvertable) { // the third argument of the callback is the original non-array object callback = function(value, index) { return fn.call(this, value, index, origObject); }; // in IE < 9 strings don't support accessing characters by index if (isSplittable) { object = object.split(''); } else { object = []; while (++index < length) { // in Safari 2 `index in object` is always `false` for NodeLists object[index] = isSnapshot ? result.snapshotItem(index) : result[index]; } } } forEach(object, callback, thisArg); } else { forOwn(object, callback, thisArg); } return result; }
javascript
function each(object, callback, thisArg) { var result = object; object = Object(object); var fn = callback, index = -1, length = object.length, isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)), isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'), isConvertable = isSnapshot || isSplittable || 'item' in object, origObject = object; // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists if (length === length >>> 0) { if (isConvertable) { // the third argument of the callback is the original non-array object callback = function(value, index) { return fn.call(this, value, index, origObject); }; // in IE < 9 strings don't support accessing characters by index if (isSplittable) { object = object.split(''); } else { object = []; while (++index < length) { // in Safari 2 `index in object` is always `false` for NodeLists object[index] = isSnapshot ? result.snapshotItem(index) : result[index]; } } } forEach(object, callback, thisArg); } else { forOwn(object, callback, thisArg); } return result; }
[ "function", "each", "(", "object", ",", "callback", ",", "thisArg", ")", "{", "var", "result", "=", "object", ";", "object", "=", "Object", "(", "object", ")", ";", "var", "fn", "=", "callback", ",", "index", "=", "-", "1", ",", "length", "=", "object", ".", "length", ",", "isSnapshot", "=", "!", "!", "(", "object", ".", "snapshotItem", "&&", "(", "length", "=", "object", ".", "snapshotLength", ")", ")", ",", "isSplittable", "=", "(", "noCharByIndex", "||", "noCharByOwnIndex", ")", "&&", "isClassOf", "(", "object", ",", "'String'", ")", ",", "isConvertable", "=", "isSnapshot", "||", "isSplittable", "||", "'item'", "in", "object", ",", "origObject", "=", "object", ";", "// in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists", "if", "(", "length", "===", "length", ">>>", "0", ")", "{", "if", "(", "isConvertable", ")", "{", "// the third argument of the callback is the original non-array object", "callback", "=", "function", "(", "value", ",", "index", ")", "{", "return", "fn", ".", "call", "(", "this", ",", "value", ",", "index", ",", "origObject", ")", ";", "}", ";", "// in IE < 9 strings don't support accessing characters by index", "if", "(", "isSplittable", ")", "{", "object", "=", "object", ".", "split", "(", "''", ")", ";", "}", "else", "{", "object", "=", "[", "]", ";", "while", "(", "++", "index", "<", "length", ")", "{", "// in Safari 2 `index in object` is always `false` for NodeLists", "object", "[", "index", "]", "=", "isSnapshot", "?", "result", ".", "snapshotItem", "(", "index", ")", ":", "result", "[", "index", "]", ";", "}", "}", "}", "forEach", "(", "object", ",", "callback", ",", "thisArg", ")", ";", "}", "else", "{", "forOwn", "(", "object", ",", "callback", ",", "thisArg", ")", ";", "}", "return", "result", ";", "}" ]
An iteration utility for arrays and objects. Callbacks may terminate the loop by explicitly returning `false`. @static @memberOf Benchmark @param {Array|Object} object The object to iterate over. @param {Function} callback The function called per iteration. @param {Mixed} thisArg The `this` binding for the callback. @returns {Array|Object} Returns the object iterated over.
[ "An", "iteration", "utility", "for", "arrays", "and", "objects", ".", "Callbacks", "may", "terminate", "the", "loop", "by", "explicitly", "returning", "false", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1344-L1379
49,829
mattmccray/blam.js
bench/lib/benchmark.js
hasKey
function hasKey() { // lazy define for worst case fallback (not as accurate) hasKey = function(object, key) { var parent = object != null && (object.constructor || Object).prototype; return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); }; // for modern browsers if (isClassOf(hasOwnProperty, 'Function')) { hasKey = function(object, key) { return object != null && hasOwnProperty.call(object, key); }; } // for Safari 2 else if ({}.__proto__ == Object.prototype) { hasKey = function(object, key) { var result = false; if (object != null) { object = Object(object); object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; } return result; }; } return hasKey.apply(this, arguments); }
javascript
function hasKey() { // lazy define for worst case fallback (not as accurate) hasKey = function(object, key) { var parent = object != null && (object.constructor || Object).prototype; return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); }; // for modern browsers if (isClassOf(hasOwnProperty, 'Function')) { hasKey = function(object, key) { return object != null && hasOwnProperty.call(object, key); }; } // for Safari 2 else if ({}.__proto__ == Object.prototype) { hasKey = function(object, key) { var result = false; if (object != null) { object = Object(object); object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; } return result; }; } return hasKey.apply(this, arguments); }
[ "function", "hasKey", "(", ")", "{", "// lazy define for worst case fallback (not as accurate)", "hasKey", "=", "function", "(", "object", ",", "key", ")", "{", "var", "parent", "=", "object", "!=", "null", "&&", "(", "object", ".", "constructor", "||", "Object", ")", ".", "prototype", ";", "return", "!", "!", "parent", "&&", "key", "in", "Object", "(", "object", ")", "&&", "!", "(", "key", "in", "parent", "&&", "object", "[", "key", "]", "===", "parent", "[", "key", "]", ")", ";", "}", ";", "// for modern browsers", "if", "(", "isClassOf", "(", "hasOwnProperty", ",", "'Function'", ")", ")", "{", "hasKey", "=", "function", "(", "object", ",", "key", ")", "{", "return", "object", "!=", "null", "&&", "hasOwnProperty", ".", "call", "(", "object", ",", "key", ")", ";", "}", ";", "}", "// for Safari 2", "else", "if", "(", "{", "}", ".", "__proto__", "==", "Object", ".", "prototype", ")", "{", "hasKey", "=", "function", "(", "object", ",", "key", ")", "{", "var", "result", "=", "false", ";", "if", "(", "object", "!=", "null", ")", "{", "object", "=", "Object", "(", "object", ")", ";", "object", ".", "__proto__", "=", "[", "object", ".", "__proto__", ",", "object", ".", "__proto__", "=", "null", ",", "result", "=", "key", "in", "object", "]", "[", "0", "]", ";", "}", "return", "result", ";", "}", ";", "}", "return", "hasKey", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}" ]
Checks if an object has the specified key as a direct property. @static @memberOf Benchmark @param {Object} object The object to check. @param {String} key The key to check for. @returns {Boolean} Returns `true` if key is a direct property, else `false`.
[ "Checks", "if", "an", "object", "has", "the", "specified", "key", "as", "a", "direct", "property", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1516-L1540
49,830
mattmccray/blam.js
bench/lib/benchmark.js
interpolate
function interpolate(string, object) { forOwn(object, function(value, key) { // escape regexp special characters in `key` string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value); }); return string; }
javascript
function interpolate(string, object) { forOwn(object, function(value, key) { // escape regexp special characters in `key` string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value); }); return string; }
[ "function", "interpolate", "(", "string", ",", "object", ")", "{", "forOwn", "(", "object", ",", "function", "(", "value", ",", "key", ")", "{", "// escape regexp special characters in `key`", "string", "=", "string", ".", "replace", "(", "RegExp", "(", "'#\\\\{'", "+", "key", ".", "replace", "(", "/", "([.*+?^=!:${}()|[\\]\\/\\\\])", "/", "g", ",", "'\\\\$1'", ")", "+", "'\\\\}'", ",", "'g'", ")", ",", "value", ")", ";", "}", ")", ";", "return", "string", ";", "}" ]
Modify a string by replacing named tokens with matching object property values. @static @memberOf Benchmark @param {String} string The string to modify. @param {Object} object The template object. @returns {String} The modified string.
[ "Modify", "a", "string", "by", "replacing", "named", "tokens", "with", "matching", "object", "property", "values", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1574-L1580
49,831
mattmccray/blam.js
bench/lib/benchmark.js
join
function join(object, separator1, separator2) { var result = [], length = (object = Object(object)).length, arrayLike = length === length >>> 0; separator2 || (separator2 = ': '); each(object, function(value, key) { result.push(arrayLike ? value : key + separator2 + value); }); return result.join(separator1 || ','); }
javascript
function join(object, separator1, separator2) { var result = [], length = (object = Object(object)).length, arrayLike = length === length >>> 0; separator2 || (separator2 = ': '); each(object, function(value, key) { result.push(arrayLike ? value : key + separator2 + value); }); return result.join(separator1 || ','); }
[ "function", "join", "(", "object", ",", "separator1", ",", "separator2", ")", "{", "var", "result", "=", "[", "]", ",", "length", "=", "(", "object", "=", "Object", "(", "object", ")", ")", ".", "length", ",", "arrayLike", "=", "length", "===", "length", ">>>", "0", ";", "separator2", "||", "(", "separator2", "=", "': '", ")", ";", "each", "(", "object", ",", "function", "(", "value", ",", "key", ")", "{", "result", ".", "push", "(", "arrayLike", "?", "value", ":", "key", "+", "separator2", "+", "value", ")", ";", "}", ")", ";", "return", "result", ".", "join", "(", "separator1", "||", "','", ")", ";", "}" ]
Creates a string of joined array values or object key-value pairs. @static @memberOf Benchmark @param {Array|Object} object The object to operate on. @param {String} [separator1=','] The separator used between key-value pairs. @param {String} [separator2=': '] The separator used between keys and values. @returns {String} The joined result.
[ "Creates", "a", "string", "of", "joined", "array", "values", "or", "object", "key", "-", "value", "pairs", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1775-L1785
49,832
mattmccray/blam.js
bench/lib/benchmark.js
pluck
function pluck(array, property) { return map(array, function(object) { return object == null ? undefined : object[property]; }); }
javascript
function pluck(array, property) { return map(array, function(object) { return object == null ? undefined : object[property]; }); }
[ "function", "pluck", "(", "array", ",", "property", ")", "{", "return", "map", "(", "array", ",", "function", "(", "object", ")", "{", "return", "object", "==", "null", "?", "undefined", ":", "object", "[", "property", "]", ";", "}", ")", ";", "}" ]
Retrieves the value of a specified property from all items in an array. @static @memberOf Benchmark @param {Array} array The array to iterate over. @param {String} property The property to pluck. @returns {Array} A new array of property values.
[ "Retrieves", "the", "value", "of", "a", "specified", "property", "from", "all", "items", "in", "an", "array", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L1813-L1817
49,833
mattmccray/blam.js
bench/lib/benchmark.js
enqueue
function enqueue(count) { while (count--) { queue.push(bench.clone({ '_original': bench, 'events': { 'abort': [update], 'cycle': [update], 'error': [update], 'start': [update] } })); } }
javascript
function enqueue(count) { while (count--) { queue.push(bench.clone({ '_original': bench, 'events': { 'abort': [update], 'cycle': [update], 'error': [update], 'start': [update] } })); } }
[ "function", "enqueue", "(", "count", ")", "{", "while", "(", "count", "--", ")", "{", "queue", ".", "push", "(", "bench", ".", "clone", "(", "{", "'_original'", ":", "bench", ",", "'events'", ":", "{", "'abort'", ":", "[", "update", "]", ",", "'cycle'", ":", "[", "update", "]", ",", "'error'", ":", "[", "update", "]", ",", "'start'", ":", "[", "update", "]", "}", "}", ")", ")", ";", "}", "}" ]
Adds a number of clones to the queue.
[ "Adds", "a", "number", "of", "clones", "to", "the", "queue", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L2661-L2673
49,834
mattmccray/blam.js
bench/lib/benchmark.js
evaluate
function evaluate(event) { var critical, df, mean, moe, rme, sd, sem, variance, clone = event.target, done = bench.aborted, now = +new Date, size = sample.push(clone.times.period), maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime, times = bench.times, varOf = function(sum, x) { return sum + pow(x - mean, 2); }; // exit early for aborted or unclockable tests if (done || clone.hz == Infinity) { maxedOut = !(size = sample.length = queue.length = 0); } if (!done) { // sample mean (estimate of the population mean) mean = getMean(sample); // sample variance (estimate of the population variance) variance = reduce(sample, varOf, 0) / (size - 1) || 0; // sample standard deviation (estimate of the population standard deviation) sd = sqrt(variance); // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean) sem = sd / sqrt(size); // degrees of freedom df = size - 1; // critical value critical = tTable[Math.round(df) || 1] || tTable.infinity; // margin of error moe = sem * critical; // relative margin of error rme = (moe / mean) * 100 || 0; extend(bench.stats, { 'deviation': sd, 'mean': mean, 'moe': moe, 'rme': rme, 'sem': sem, 'variance': variance }); // Abort the cycle loop when the minimum sample size has been collected // and the elapsed time exceeds the maximum time allowed per benchmark. // We don't count cycle delays toward the max time because delays may be // increased by browsers that clamp timeouts for inactive tabs. // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs if (maxedOut) { // reset the `initCount` in case the benchmark is rerun bench.initCount = initCount; bench.running = false; done = true; times.elapsed = (now - times.timeStamp) / 1e3; } if (bench.hz != Infinity) { bench.hz = 1 / mean; times.cycle = mean * bench.count; times.period = mean; } } // if time permits, increase sample size to reduce the margin of error if (queue.length < 2 && !maxedOut) { enqueue(1); } // abort the invoke cycle when done event.aborted = done; }
javascript
function evaluate(event) { var critical, df, mean, moe, rme, sd, sem, variance, clone = event.target, done = bench.aborted, now = +new Date, size = sample.push(clone.times.period), maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime, times = bench.times, varOf = function(sum, x) { return sum + pow(x - mean, 2); }; // exit early for aborted or unclockable tests if (done || clone.hz == Infinity) { maxedOut = !(size = sample.length = queue.length = 0); } if (!done) { // sample mean (estimate of the population mean) mean = getMean(sample); // sample variance (estimate of the population variance) variance = reduce(sample, varOf, 0) / (size - 1) || 0; // sample standard deviation (estimate of the population standard deviation) sd = sqrt(variance); // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean) sem = sd / sqrt(size); // degrees of freedom df = size - 1; // critical value critical = tTable[Math.round(df) || 1] || tTable.infinity; // margin of error moe = sem * critical; // relative margin of error rme = (moe / mean) * 100 || 0; extend(bench.stats, { 'deviation': sd, 'mean': mean, 'moe': moe, 'rme': rme, 'sem': sem, 'variance': variance }); // Abort the cycle loop when the minimum sample size has been collected // and the elapsed time exceeds the maximum time allowed per benchmark. // We don't count cycle delays toward the max time because delays may be // increased by browsers that clamp timeouts for inactive tabs. // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs if (maxedOut) { // reset the `initCount` in case the benchmark is rerun bench.initCount = initCount; bench.running = false; done = true; times.elapsed = (now - times.timeStamp) / 1e3; } if (bench.hz != Infinity) { bench.hz = 1 / mean; times.cycle = mean * bench.count; times.period = mean; } } // if time permits, increase sample size to reduce the margin of error if (queue.length < 2 && !maxedOut) { enqueue(1); } // abort the invoke cycle when done event.aborted = done; }
[ "function", "evaluate", "(", "event", ")", "{", "var", "critical", ",", "df", ",", "mean", ",", "moe", ",", "rme", ",", "sd", ",", "sem", ",", "variance", ",", "clone", "=", "event", ".", "target", ",", "done", "=", "bench", ".", "aborted", ",", "now", "=", "+", "new", "Date", ",", "size", "=", "sample", ".", "push", "(", "clone", ".", "times", ".", "period", ")", ",", "maxedOut", "=", "size", ">=", "minSamples", "&&", "(", "elapsed", "+=", "now", "-", "clone", ".", "times", ".", "timeStamp", ")", "/", "1e3", ">", "bench", ".", "maxTime", ",", "times", "=", "bench", ".", "times", ",", "varOf", "=", "function", "(", "sum", ",", "x", ")", "{", "return", "sum", "+", "pow", "(", "x", "-", "mean", ",", "2", ")", ";", "}", ";", "// exit early for aborted or unclockable tests", "if", "(", "done", "||", "clone", ".", "hz", "==", "Infinity", ")", "{", "maxedOut", "=", "!", "(", "size", "=", "sample", ".", "length", "=", "queue", ".", "length", "=", "0", ")", ";", "}", "if", "(", "!", "done", ")", "{", "// sample mean (estimate of the population mean)", "mean", "=", "getMean", "(", "sample", ")", ";", "// sample variance (estimate of the population variance)", "variance", "=", "reduce", "(", "sample", ",", "varOf", ",", "0", ")", "/", "(", "size", "-", "1", ")", "||", "0", ";", "// sample standard deviation (estimate of the population standard deviation)", "sd", "=", "sqrt", "(", "variance", ")", ";", "// standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)", "sem", "=", "sd", "/", "sqrt", "(", "size", ")", ";", "// degrees of freedom", "df", "=", "size", "-", "1", ";", "// critical value", "critical", "=", "tTable", "[", "Math", ".", "round", "(", "df", ")", "||", "1", "]", "||", "tTable", ".", "infinity", ";", "// margin of error", "moe", "=", "sem", "*", "critical", ";", "// relative margin of error", "rme", "=", "(", "moe", "/", "mean", ")", "*", "100", "||", "0", ";", "extend", "(", "bench", ".", "stats", ",", "{", "'deviation'", ":", "sd", ",", "'mean'", ":", "mean", ",", "'moe'", ":", "moe", ",", "'rme'", ":", "rme", ",", "'sem'", ":", "sem", ",", "'variance'", ":", "variance", "}", ")", ";", "// Abort the cycle loop when the minimum sample size has been collected", "// and the elapsed time exceeds the maximum time allowed per benchmark.", "// We don't count cycle delays toward the max time because delays may be", "// increased by browsers that clamp timeouts for inactive tabs.", "// https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs", "if", "(", "maxedOut", ")", "{", "// reset the `initCount` in case the benchmark is rerun", "bench", ".", "initCount", "=", "initCount", ";", "bench", ".", "running", "=", "false", ";", "done", "=", "true", ";", "times", ".", "elapsed", "=", "(", "now", "-", "times", ".", "timeStamp", ")", "/", "1e3", ";", "}", "if", "(", "bench", ".", "hz", "!=", "Infinity", ")", "{", "bench", ".", "hz", "=", "1", "/", "mean", ";", "times", ".", "cycle", "=", "mean", "*", "bench", ".", "count", ";", "times", ".", "period", "=", "mean", ";", "}", "}", "// if time permits, increase sample size to reduce the margin of error", "if", "(", "queue", ".", "length", "<", "2", "&&", "!", "maxedOut", ")", "{", "enqueue", "(", "1", ")", ";", "}", "// abort the invoke cycle when done", "event", ".", "aborted", "=", "done", ";", "}" ]
Determines if more clones should be queued or if cycling should stop.
[ "Determines", "if", "more", "clones", "should", "be", "queued", "or", "if", "cycling", "should", "stop", "." ]
a535b6fe9679b687897ac0dc18b26585a5c3a114
https://github.com/mattmccray/blam.js/blob/a535b6fe9679b687897ac0dc18b26585a5c3a114/bench/lib/benchmark.js#L2709-L2782
49,835
tuunanen/camelton
lib/obs.js
isObjectObject
function isObjectObject(object) { return _.isObject(object) && !_.isArray(object) && !_.isFunction(object); }
javascript
function isObjectObject(object) { return _.isObject(object) && !_.isArray(object) && !_.isFunction(object); }
[ "function", "isObjectObject", "(", "object", ")", "{", "return", "_", ".", "isObject", "(", "object", ")", "&&", "!", "_", ".", "isArray", "(", "object", ")", "&&", "!", "_", ".", "isFunction", "(", "object", ")", ";", "}" ]
Is given variable a plain object, i.e. not a function or Array. @see http://underscorejs.org/#isObject @param {object} object @returns {boolean} Result of the checks.
[ "Is", "given", "variable", "a", "plain", "object", "i", ".", "e", ".", "not", "a", "function", "or", "Array", "." ]
2beee32431e1b2867396e25f560f8dbd53535041
https://github.com/tuunanen/camelton/blob/2beee32431e1b2867396e25f560f8dbd53535041/lib/obs.js#L21-L23
49,836
tuunanen/camelton
lib/obs.js
getObjectSchema
function getObjectSchema(object) { var outputObject = {}; if (isObjectObject(object)) { Object.keys(object).forEach(function(key) { outputObject[key] = isObjectObject(object[key]) ? getObjectSchema(object[key]) : ''; }); } return outputObject; }
javascript
function getObjectSchema(object) { var outputObject = {}; if (isObjectObject(object)) { Object.keys(object).forEach(function(key) { outputObject[key] = isObjectObject(object[key]) ? getObjectSchema(object[key]) : ''; }); } return outputObject; }
[ "function", "getObjectSchema", "(", "object", ")", "{", "var", "outputObject", "=", "{", "}", ";", "if", "(", "isObjectObject", "(", "object", ")", ")", "{", "Object", ".", "keys", "(", "object", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "outputObject", "[", "key", "]", "=", "isObjectObject", "(", "object", "[", "key", "]", ")", "?", "getObjectSchema", "(", "object", "[", "key", "]", ")", ":", "''", ";", "}", ")", ";", "}", "return", "outputObject", ";", "}" ]
Create an object schema - an object with keys and empty strings as values. @param {object} object @returns {object} Object schema. An object with keys and empty strings as values.
[ "Create", "an", "object", "schema", "-", "an", "object", "with", "keys", "and", "empty", "strings", "as", "values", "." ]
2beee32431e1b2867396e25f560f8dbd53535041
https://github.com/tuunanen/camelton/blob/2beee32431e1b2867396e25f560f8dbd53535041/lib/obs.js#L43-L53
49,837
tuunanen/camelton
lib/obs.js
mergeObjectSchema
function mergeObjectSchema(object, other, options) { var settings = options || {}, prune = settings.prune || false, placeholder = settings.placeholder || false, source, sourceKeys, keysDiff, outputObject, i, value; // Don't bother doing anything with non-plain objects. if (!isObjectObject(object) || !isObjectObject(other)) { return object; } outputObject = {}; source = getObjectSchema(other); sourceKeys = Object.keys(source); i = -1; while (++i < sourceKeys.length) { // Original object already has property. if (object.hasOwnProperty(sourceKeys[i])) { // Recurse or copy defined property. if (isObjectObject(object[sourceKeys[i]])) { value = mergeObjectSchema(object[sourceKeys[i]], source[sourceKeys[i]], settings); } // Add placeholder for empty value. else if (placeholder && object[sourceKeys[i]].length === 0) { value = sourceKeys[i]; } // Copy value. else { value = object[sourceKeys[i]]; } } // Original object does not have property. else { // Recurse source property or add empty value. if (isObjectObject(source[sourceKeys[i]])) { value = mergeObjectSchema({}, source[sourceKeys[i]], settings); } else { value = placeholder ? sourceKeys[i] : ''; } } outputObject[sourceKeys[i]] = value; } // Add extra properties found in original object to the end of the object. if (!Boolean(prune)) { keysDiff = _.difference(Object.keys(object), sourceKeys); i = -1; while (++i < keysDiff.length) { outputObject[keysDiff[i]] = object[keysDiff[i]]; } } return outputObject; }
javascript
function mergeObjectSchema(object, other, options) { var settings = options || {}, prune = settings.prune || false, placeholder = settings.placeholder || false, source, sourceKeys, keysDiff, outputObject, i, value; // Don't bother doing anything with non-plain objects. if (!isObjectObject(object) || !isObjectObject(other)) { return object; } outputObject = {}; source = getObjectSchema(other); sourceKeys = Object.keys(source); i = -1; while (++i < sourceKeys.length) { // Original object already has property. if (object.hasOwnProperty(sourceKeys[i])) { // Recurse or copy defined property. if (isObjectObject(object[sourceKeys[i]])) { value = mergeObjectSchema(object[sourceKeys[i]], source[sourceKeys[i]], settings); } // Add placeholder for empty value. else if (placeholder && object[sourceKeys[i]].length === 0) { value = sourceKeys[i]; } // Copy value. else { value = object[sourceKeys[i]]; } } // Original object does not have property. else { // Recurse source property or add empty value. if (isObjectObject(source[sourceKeys[i]])) { value = mergeObjectSchema({}, source[sourceKeys[i]], settings); } else { value = placeholder ? sourceKeys[i] : ''; } } outputObject[sourceKeys[i]] = value; } // Add extra properties found in original object to the end of the object. if (!Boolean(prune)) { keysDiff = _.difference(Object.keys(object), sourceKeys); i = -1; while (++i < keysDiff.length) { outputObject[keysDiff[i]] = object[keysDiff[i]]; } } return outputObject; }
[ "function", "mergeObjectSchema", "(", "object", ",", "other", ",", "options", ")", "{", "var", "settings", "=", "options", "||", "{", "}", ",", "prune", "=", "settings", ".", "prune", "||", "false", ",", "placeholder", "=", "settings", ".", "placeholder", "||", "false", ",", "source", ",", "sourceKeys", ",", "keysDiff", ",", "outputObject", ",", "i", ",", "value", ";", "// Don't bother doing anything with non-plain objects.", "if", "(", "!", "isObjectObject", "(", "object", ")", "||", "!", "isObjectObject", "(", "other", ")", ")", "{", "return", "object", ";", "}", "outputObject", "=", "{", "}", ";", "source", "=", "getObjectSchema", "(", "other", ")", ";", "sourceKeys", "=", "Object", ".", "keys", "(", "source", ")", ";", "i", "=", "-", "1", ";", "while", "(", "++", "i", "<", "sourceKeys", ".", "length", ")", "{", "// Original object already has property.", "if", "(", "object", ".", "hasOwnProperty", "(", "sourceKeys", "[", "i", "]", ")", ")", "{", "// Recurse or copy defined property.", "if", "(", "isObjectObject", "(", "object", "[", "sourceKeys", "[", "i", "]", "]", ")", ")", "{", "value", "=", "mergeObjectSchema", "(", "object", "[", "sourceKeys", "[", "i", "]", "]", ",", "source", "[", "sourceKeys", "[", "i", "]", "]", ",", "settings", ")", ";", "}", "// Add placeholder for empty value.", "else", "if", "(", "placeholder", "&&", "object", "[", "sourceKeys", "[", "i", "]", "]", ".", "length", "===", "0", ")", "{", "value", "=", "sourceKeys", "[", "i", "]", ";", "}", "// Copy value.", "else", "{", "value", "=", "object", "[", "sourceKeys", "[", "i", "]", "]", ";", "}", "}", "// Original object does not have property.", "else", "{", "// Recurse source property or add empty value.", "if", "(", "isObjectObject", "(", "source", "[", "sourceKeys", "[", "i", "]", "]", ")", ")", "{", "value", "=", "mergeObjectSchema", "(", "{", "}", ",", "source", "[", "sourceKeys", "[", "i", "]", "]", ",", "settings", ")", ";", "}", "else", "{", "value", "=", "placeholder", "?", "sourceKeys", "[", "i", "]", ":", "''", ";", "}", "}", "outputObject", "[", "sourceKeys", "[", "i", "]", "]", "=", "value", ";", "}", "// Add extra properties found in original object to the end of the object.", "if", "(", "!", "Boolean", "(", "prune", ")", ")", "{", "keysDiff", "=", "_", ".", "difference", "(", "Object", ".", "keys", "(", "object", ")", ",", "sourceKeys", ")", ";", "i", "=", "-", "1", ";", "while", "(", "++", "i", "<", "keysDiff", ".", "length", ")", "{", "outputObject", "[", "keysDiff", "[", "i", "]", "]", "=", "object", "[", "keysDiff", "[", "i", "]", "]", ";", "}", "}", "return", "outputObject", ";", "}" ]
Merge object schemas together. Original object properties and values are preserved. @param {object} object @param {object} other @param {object} options @param {bool} options.prune - Prune extra properties found in destination objects @param {bool} options.placeholder - Add source object key as a value for empty destination object properties @returns {object} Merged object schema.
[ "Merge", "object", "schemas", "together", ".", "Original", "object", "properties", "and", "values", "are", "preserved", "." ]
2beee32431e1b2867396e25f560f8dbd53535041
https://github.com/tuunanen/camelton/blob/2beee32431e1b2867396e25f560f8dbd53535041/lib/obs.js#L68-L127
49,838
tuunanen/camelton
lib/obs.js
sortObjectSchema
function sortObjectSchema(object, options) { var sort = {asc: sortAsc, desc: sortDesc}, keys = Object.keys(object), outputObject = {}; if (options.sort) { keys.sort(sort[options.sort]); } keys.forEach(function(key, index) { if (isObjectObject(object[key])) { object[key] = sortObjectSchema(object[key], options); } outputObject[keys[index]] = object[keys[index]]; }); return outputObject; }
javascript
function sortObjectSchema(object, options) { var sort = {asc: sortAsc, desc: sortDesc}, keys = Object.keys(object), outputObject = {}; if (options.sort) { keys.sort(sort[options.sort]); } keys.forEach(function(key, index) { if (isObjectObject(object[key])) { object[key] = sortObjectSchema(object[key], options); } outputObject[keys[index]] = object[keys[index]]; }); return outputObject; }
[ "function", "sortObjectSchema", "(", "object", ",", "options", ")", "{", "var", "sort", "=", "{", "asc", ":", "sortAsc", ",", "desc", ":", "sortDesc", "}", ",", "keys", "=", "Object", ".", "keys", "(", "object", ")", ",", "outputObject", "=", "{", "}", ";", "if", "(", "options", ".", "sort", ")", "{", "keys", ".", "sort", "(", "sort", "[", "options", ".", "sort", "]", ")", ";", "}", "keys", ".", "forEach", "(", "function", "(", "key", ",", "index", ")", "{", "if", "(", "isObjectObject", "(", "object", "[", "key", "]", ")", ")", "{", "object", "[", "key", "]", "=", "sortObjectSchema", "(", "object", "[", "key", "]", ",", "options", ")", ";", "}", "outputObject", "[", "keys", "[", "index", "]", "]", "=", "object", "[", "keys", "[", "index", "]", "]", ";", "}", ")", ";", "return", "outputObject", ";", "}" ]
Sort object schema. @param {object} object @param {object} options @returns {object} Sorted object schema.
[ "Sort", "object", "schema", "." ]
2beee32431e1b2867396e25f560f8dbd53535041
https://github.com/tuunanen/camelton/blob/2beee32431e1b2867396e25f560f8dbd53535041/lib/obs.js#L136-L153
49,839
Lindurion/closure-pro-build
lib/dir-manager.js
createOutputDirsAsync
function createOutputDirsAsync(buildOptions) { var outputDirs = new OutputDirs(buildOptions); var tasks = []; tasks.push(makeDirAndParents(outputDirs.tmp)); tasks.push(makeDirAndParents(outputDirs.gen)); tasks.push(makeDirAndParents(outputDirs.build)); return kew.all(tasks) .then(function() { return outputDirs; }); }
javascript
function createOutputDirsAsync(buildOptions) { var outputDirs = new OutputDirs(buildOptions); var tasks = []; tasks.push(makeDirAndParents(outputDirs.tmp)); tasks.push(makeDirAndParents(outputDirs.gen)); tasks.push(makeDirAndParents(outputDirs.build)); return kew.all(tasks) .then(function() { return outputDirs; }); }
[ "function", "createOutputDirsAsync", "(", "buildOptions", ")", "{", "var", "outputDirs", "=", "new", "OutputDirs", "(", "buildOptions", ")", ";", "var", "tasks", "=", "[", "]", ";", "tasks", ".", "push", "(", "makeDirAndParents", "(", "outputDirs", ".", "tmp", ")", ")", ";", "tasks", ".", "push", "(", "makeDirAndParents", "(", "outputDirs", ".", "gen", ")", ")", ";", "tasks", ".", "push", "(", "makeDirAndParents", "(", "outputDirs", ".", "build", ")", ")", ";", "return", "kew", ".", "all", "(", "tasks", ")", ".", "then", "(", "function", "(", ")", "{", "return", "outputDirs", ";", "}", ")", ";", "}" ]
Creates output directories specified by buildOptions and returns a future OutputDirs object with tmp, gen, and build properties for the created paths. @param {!Object} buildOptions Specifies options specific to this build (like debug/release); see README.md for option documentation. @return {!Promise.<!OutputDirs>}
[ "Creates", "output", "directories", "specified", "by", "buildOptions", "and", "returns", "a", "future", "OutputDirs", "object", "with", "tmp", "gen", "and", "build", "properties", "for", "the", "created", "paths", "." ]
c279d0fcc3a65969d2fe965f55e627b074792f1a
https://github.com/Lindurion/closure-pro-build/blob/c279d0fcc3a65969d2fe965f55e627b074792f1a/lib/dir-manager.js#L32-L42
49,840
molecuel/gridfs-uploader
lib/uploadServer.js
GFSuploadServer
function GFSuploadServer(mongoose, port, ssloptions, routes, listen, defaultcallback, authcallback) { this.port = port; this.ssloptions = ssloptions; this.routes = routes; this.listen = listen; this.authcallback = authcallback; this.mongoose = mongoose; if(defaultcallback) { this.defaultcallback = defaultcallback; } else { this.defaultcallback = function(err, result, type, user) { } } this.registerServer(routes); return this; }
javascript
function GFSuploadServer(mongoose, port, ssloptions, routes, listen, defaultcallback, authcallback) { this.port = port; this.ssloptions = ssloptions; this.routes = routes; this.listen = listen; this.authcallback = authcallback; this.mongoose = mongoose; if(defaultcallback) { this.defaultcallback = defaultcallback; } else { this.defaultcallback = function(err, result, type, user) { } } this.registerServer(routes); return this; }
[ "function", "GFSuploadServer", "(", "mongoose", ",", "port", ",", "ssloptions", ",", "routes", ",", "listen", ",", "defaultcallback", ",", "authcallback", ")", "{", "this", ".", "port", "=", "port", ";", "this", ".", "ssloptions", "=", "ssloptions", ";", "this", ".", "routes", "=", "routes", ";", "this", ".", "listen", "=", "listen", ";", "this", ".", "authcallback", "=", "authcallback", ";", "this", ".", "mongoose", "=", "mongoose", ";", "if", "(", "defaultcallback", ")", "{", "this", ".", "defaultcallback", "=", "defaultcallback", ";", "}", "else", "{", "this", ".", "defaultcallback", "=", "function", "(", "err", ",", "result", ",", "type", ",", "user", ")", "{", "}", "}", "this", ".", "registerServer", "(", "routes", ")", ";", "return", "this", ";", "}" ]
Constructor for the module class @this {GFSuploadServer} @constructor @param {Object} mongoose The mongoose object from your application @param {Integer} port The port of the server instance @param {Array} ssloptions Options like certificate etc for the SSL express server instance @param {Array} routes Array of objects for routing information { url: '/import/incidents', prefix: 'import', type: 'incidents'} @param {Array} listen IP addresses to listen on @param {Function} defaultcallback Default function for callback @param {Function} authcallback Callback function to implement custom authentication functions
[ "Constructor", "for", "the", "module", "class" ]
3a0a97d70de39e348881f7eca34a99dd7408454f
https://github.com/molecuel/gridfs-uploader/blob/3a0a97d70de39e348881f7eca34a99dd7408454f/lib/uploadServer.js#L65-L81
49,841
redisjs/jsr-server
lib/command/database/list/lset.js
validate
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var index = parseInt(args[1]) , value = info.db.getKey(args[0], info); if(value === undefined) { throw NoSuchKey; }else if(isNaN(index) || (index < 0 || index >= value.getLength())) { throw IndexRange; } args[1] = index; }
javascript
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var index = parseInt(args[1]) , value = info.db.getKey(args[0], info); if(value === undefined) { throw NoSuchKey; }else if(isNaN(index) || (index < 0 || index >= value.getLength())) { throw IndexRange; } args[1] = index; }
[ "function", "validate", "(", "cmd", ",", "args", ",", "info", ")", "{", "AbstractCommand", ".", "prototype", ".", "validate", ".", "apply", "(", "this", ",", "arguments", ")", ";", "var", "index", "=", "parseInt", "(", "args", "[", "1", "]", ")", ",", "value", "=", "info", ".", "db", ".", "getKey", "(", "args", "[", "0", "]", ",", "info", ")", ";", "if", "(", "value", "===", "undefined", ")", "{", "throw", "NoSuchKey", ";", "}", "else", "if", "(", "isNaN", "(", "index", ")", "||", "(", "index", "<", "0", "||", "index", ">=", "value", ".", "getLength", "(", ")", ")", ")", "{", "throw", "IndexRange", ";", "}", "args", "[", "1", "]", "=", "index", ";", "}" ]
Validate the LSET command.
[ "Validate", "the", "LSET", "command", "." ]
49413052d3039524fbdd2ade0ef9bae26cb4d647
https://github.com/redisjs/jsr-server/blob/49413052d3039524fbdd2ade0ef9bae26cb4d647/lib/command/database/list/lset.js#L20-L30
49,842
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
ConfigParser
function ConfigParser(path) { this.path = path; try { this.doc = xml.parseElementtreeSync(path); this.cdvNamespacePrefix = getCordovaNamespacePrefix(this.doc); et.register_namespace(this.cdvNamespacePrefix, 'http://cordova.apache.org/ns/1.0'); } catch (e) { console.error('Parsing '+path+' failed'); throw e; } var r = this.doc.getroot(); if (r.tag !== 'widget') { throw new CordovaError(path + ' has incorrect root node name (expected "widget", was "' + r.tag + '")'); } }
javascript
function ConfigParser(path) { this.path = path; try { this.doc = xml.parseElementtreeSync(path); this.cdvNamespacePrefix = getCordovaNamespacePrefix(this.doc); et.register_namespace(this.cdvNamespacePrefix, 'http://cordova.apache.org/ns/1.0'); } catch (e) { console.error('Parsing '+path+' failed'); throw e; } var r = this.doc.getroot(); if (r.tag !== 'widget') { throw new CordovaError(path + ' has incorrect root node name (expected "widget", was "' + r.tag + '")'); } }
[ "function", "ConfigParser", "(", "path", ")", "{", "this", ".", "path", "=", "path", ";", "try", "{", "this", ".", "doc", "=", "xml", ".", "parseElementtreeSync", "(", "path", ")", ";", "this", ".", "cdvNamespacePrefix", "=", "getCordovaNamespacePrefix", "(", "this", ".", "doc", ")", ";", "et", ".", "register_namespace", "(", "this", ".", "cdvNamespacePrefix", ",", "'http://cordova.apache.org/ns/1.0'", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "'Parsing '", "+", "path", "+", "' failed'", ")", ";", "throw", "e", ";", "}", "var", "r", "=", "this", ".", "doc", ".", "getroot", "(", ")", ";", "if", "(", "r", ".", "tag", "!==", "'widget'", ")", "{", "throw", "new", "CordovaError", "(", "path", "+", "' has incorrect root node name (expected \"widget\", was \"'", "+", "r", ".", "tag", "+", "'\")'", ")", ";", "}", "}" ]
Wraps a config.xml file
[ "Wraps", "a", "config", ".", "xml", "file" ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L30-L44
49,843
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
findElementAttributeValue
function findElementAttributeValue(attributeName, elems) { elems = Array.isArray(elems) ? elems : [ elems ]; var value = elems.filter(function (elem) { return elem.attrib.name.toLowerCase() === attributeName.toLowerCase(); }).map(function (filteredElems) { return filteredElems.attrib.value; }).pop(); return value ? value : ''; }
javascript
function findElementAttributeValue(attributeName, elems) { elems = Array.isArray(elems) ? elems : [ elems ]; var value = elems.filter(function (elem) { return elem.attrib.name.toLowerCase() === attributeName.toLowerCase(); }).map(function (filteredElems) { return filteredElems.attrib.value; }).pop(); return value ? value : ''; }
[ "function", "findElementAttributeValue", "(", "attributeName", ",", "elems", ")", "{", "elems", "=", "Array", ".", "isArray", "(", "elems", ")", "?", "elems", ":", "[", "elems", "]", ";", "var", "value", "=", "elems", ".", "filter", "(", "function", "(", "elem", ")", "{", "return", "elem", ".", "attrib", ".", "name", ".", "toLowerCase", "(", ")", "===", "attributeName", ".", "toLowerCase", "(", ")", ";", "}", ")", ".", "map", "(", "function", "(", "filteredElems", ")", "{", "return", "filteredElems", ".", "attrib", ".", "value", ";", "}", ")", ".", "pop", "(", ")", ";", "return", "value", "?", "value", ":", "''", ";", "}" ]
Finds the value of an element's attribute @param {String} attributeName Name of the attribute to search for @param {Array} elems An array of ElementTree nodes @return {String}
[ "Finds", "the", "value", "of", "an", "element", "s", "attribute" ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L79-L90
49,844
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
function(platform, resourceName) { var ret = [], staticResources = []; if (platform) { // platform specific icons this.doc.findall('platform[@name=\'' + platform + '\']/' + resourceName).forEach(function(elt){ elt.platform = platform; // mark as platform specific resource staticResources.push(elt); }); } // root level resources staticResources = staticResources.concat(this.doc.findall(resourceName)); // parse resource elements var that = this; staticResources.forEach(function (elt) { var res = {}; res.src = elt.attrib.src; res.target = elt.attrib.target || undefined; res.density = elt.attrib['density'] || elt.attrib[that.cdvNamespacePrefix+':density'] || elt.attrib['gap:density']; res.platform = elt.platform || null; // null means icon represents default icon (shared between platforms) res.width = +elt.attrib.width || undefined; res.height = +elt.attrib.height || undefined; // default icon if (!res.width && !res.height && !res.density) { ret.defaultResource = res; } ret.push(res); }); /** * Returns resource with specified width and/or height. * @param {number} width Width of resource. * @param {number} height Height of resource. * @return {Resource} Resource object or null if not found. */ ret.getBySize = function(width, height) { return ret.filter(function(res) { if (!res.width && !res.height) { return false; } return ((!res.width || (width == res.width)) && (!res.height || (height == res.height))); })[0] || null; }; /** * Returns resource with specified density. * @param {string} density Density of resource. * @return {Resource} Resource object or null if not found. */ ret.getByDensity = function(density) { return ret.filter(function(res) { return res.density == density; })[0] || null; }; /** Returns default icons */ ret.getDefault = function() { return ret.defaultResource; }; return ret; }
javascript
function(platform, resourceName) { var ret = [], staticResources = []; if (platform) { // platform specific icons this.doc.findall('platform[@name=\'' + platform + '\']/' + resourceName).forEach(function(elt){ elt.platform = platform; // mark as platform specific resource staticResources.push(elt); }); } // root level resources staticResources = staticResources.concat(this.doc.findall(resourceName)); // parse resource elements var that = this; staticResources.forEach(function (elt) { var res = {}; res.src = elt.attrib.src; res.target = elt.attrib.target || undefined; res.density = elt.attrib['density'] || elt.attrib[that.cdvNamespacePrefix+':density'] || elt.attrib['gap:density']; res.platform = elt.platform || null; // null means icon represents default icon (shared between platforms) res.width = +elt.attrib.width || undefined; res.height = +elt.attrib.height || undefined; // default icon if (!res.width && !res.height && !res.density) { ret.defaultResource = res; } ret.push(res); }); /** * Returns resource with specified width and/or height. * @param {number} width Width of resource. * @param {number} height Height of resource. * @return {Resource} Resource object or null if not found. */ ret.getBySize = function(width, height) { return ret.filter(function(res) { if (!res.width && !res.height) { return false; } return ((!res.width || (width == res.width)) && (!res.height || (height == res.height))); })[0] || null; }; /** * Returns resource with specified density. * @param {string} density Density of resource. * @return {Resource} Resource object or null if not found. */ ret.getByDensity = function(density) { return ret.filter(function(res) { return res.density == density; })[0] || null; }; /** Returns default icons */ ret.getDefault = function() { return ret.defaultResource; }; return ret; }
[ "function", "(", "platform", ",", "resourceName", ")", "{", "var", "ret", "=", "[", "]", ",", "staticResources", "=", "[", "]", ";", "if", "(", "platform", ")", "{", "// platform specific icons", "this", ".", "doc", ".", "findall", "(", "'platform[@name=\\''", "+", "platform", "+", "'\\']/'", "+", "resourceName", ")", ".", "forEach", "(", "function", "(", "elt", ")", "{", "elt", ".", "platform", "=", "platform", ";", "// mark as platform specific resource", "staticResources", ".", "push", "(", "elt", ")", ";", "}", ")", ";", "}", "// root level resources", "staticResources", "=", "staticResources", ".", "concat", "(", "this", ".", "doc", ".", "findall", "(", "resourceName", ")", ")", ";", "// parse resource elements", "var", "that", "=", "this", ";", "staticResources", ".", "forEach", "(", "function", "(", "elt", ")", "{", "var", "res", "=", "{", "}", ";", "res", ".", "src", "=", "elt", ".", "attrib", ".", "src", ";", "res", ".", "target", "=", "elt", ".", "attrib", ".", "target", "||", "undefined", ";", "res", ".", "density", "=", "elt", ".", "attrib", "[", "'density'", "]", "||", "elt", ".", "attrib", "[", "that", ".", "cdvNamespacePrefix", "+", "':density'", "]", "||", "elt", ".", "attrib", "[", "'gap:density'", "]", ";", "res", ".", "platform", "=", "elt", ".", "platform", "||", "null", ";", "// null means icon represents default icon (shared between platforms)", "res", ".", "width", "=", "+", "elt", ".", "attrib", ".", "width", "||", "undefined", ";", "res", ".", "height", "=", "+", "elt", ".", "attrib", ".", "height", "||", "undefined", ";", "// default icon", "if", "(", "!", "res", ".", "width", "&&", "!", "res", ".", "height", "&&", "!", "res", ".", "density", ")", "{", "ret", ".", "defaultResource", "=", "res", ";", "}", "ret", ".", "push", "(", "res", ")", ";", "}", ")", ";", "/**\n * Returns resource with specified width and/or height.\n * @param {number} width Width of resource.\n * @param {number} height Height of resource.\n * @return {Resource} Resource object or null if not found.\n */", "ret", ".", "getBySize", "=", "function", "(", "width", ",", "height", ")", "{", "return", "ret", ".", "filter", "(", "function", "(", "res", ")", "{", "if", "(", "!", "res", ".", "width", "&&", "!", "res", ".", "height", ")", "{", "return", "false", ";", "}", "return", "(", "(", "!", "res", ".", "width", "||", "(", "width", "==", "res", ".", "width", ")", ")", "&&", "(", "!", "res", ".", "height", "||", "(", "height", "==", "res", ".", "height", ")", ")", ")", ";", "}", ")", "[", "0", "]", "||", "null", ";", "}", ";", "/**\n * Returns resource with specified density.\n * @param {string} density Density of resource.\n * @return {Resource} Resource object or null if not found.\n */", "ret", ".", "getByDensity", "=", "function", "(", "density", ")", "{", "return", "ret", ".", "filter", "(", "function", "(", "res", ")", "{", "return", "res", ".", "density", "==", "density", ";", "}", ")", "[", "0", "]", "||", "null", ";", "}", ";", "/** Returns default icons */", "ret", ".", "getDefault", "=", "function", "(", ")", "{", "return", "ret", ".", "defaultResource", ";", "}", ";", "return", "ret", ";", "}" ]
Returns all resources for the platform specified. @param {String} platform The platform. @param {string} resourceName Type of static resources to return. "icon" and "splash" currently supported. @return {Array} Resources for the platform specified.
[ "Returns", "all", "resources", "for", "the", "platform", "specified", "." ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L177-L239
49,845
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
function (attributes, variables) { if (!attributes && !attributes.name) return; var el = new et.Element('plugin'); el.attrib.name = attributes.name; if (attributes.spec) { el.attrib.spec = attributes.spec; } // support arbitrary object as variables source if (variables && typeof variables === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables) .map(function (variableName) { return {name: variableName, value: variables[variableName]}; }); } if (variables) { variables.forEach(function (variable) { el.append(new et.Element('variable', { name: variable.name, value: variable.value })); }); } this.doc.getroot().append(el); }
javascript
function (attributes, variables) { if (!attributes && !attributes.name) return; var el = new et.Element('plugin'); el.attrib.name = attributes.name; if (attributes.spec) { el.attrib.spec = attributes.spec; } // support arbitrary object as variables source if (variables && typeof variables === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables) .map(function (variableName) { return {name: variableName, value: variables[variableName]}; }); } if (variables) { variables.forEach(function (variable) { el.append(new et.Element('variable', { name: variable.name, value: variable.value })); }); } this.doc.getroot().append(el); }
[ "function", "(", "attributes", ",", "variables", ")", "{", "if", "(", "!", "attributes", "&&", "!", "attributes", ".", "name", ")", "return", ";", "var", "el", "=", "new", "et", ".", "Element", "(", "'plugin'", ")", ";", "el", ".", "attrib", ".", "name", "=", "attributes", ".", "name", ";", "if", "(", "attributes", ".", "spec", ")", "{", "el", ".", "attrib", ".", "spec", "=", "attributes", ".", "spec", ";", "}", "// support arbitrary object as variables source", "if", "(", "variables", "&&", "typeof", "variables", "===", "'object'", "&&", "!", "Array", ".", "isArray", "(", "variables", ")", ")", "{", "variables", "=", "Object", ".", "keys", "(", "variables", ")", ".", "map", "(", "function", "(", "variableName", ")", "{", "return", "{", "name", ":", "variableName", ",", "value", ":", "variables", "[", "variableName", "]", "}", ";", "}", ")", ";", "}", "if", "(", "variables", ")", "{", "variables", ".", "forEach", "(", "function", "(", "variable", ")", "{", "el", ".", "append", "(", "new", "et", ".", "Element", "(", "'variable'", ",", "{", "name", ":", "variable", ".", "name", ",", "value", ":", "variable", ".", "value", "}", ")", ")", ";", "}", ")", ";", "}", "this", ".", "doc", ".", "getroot", "(", ")", ".", "append", "(", "el", ")", ";", "}" ]
Adds a plugin element. Does not check for duplicates. @name addPlugin @function @param {object} attributes name and spec are supported @param {Array|object} variables name, value or arbitary object
[ "Adds", "a", "plugin", "element", ".", "Does", "not", "check", "for", "duplicates", "." ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L314-L336
49,846
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
function(id){ if(!id){ return undefined; } var pluginElement = this.doc.find('./plugin/[@name="' + id + '"]'); if (null === pluginElement) { var legacyFeature = this.doc.find('./feature/param[@name="id"][@value="' + id + '"]/..'); if(legacyFeature){ events.emit('log', 'Found deprecated feature entry for ' + id +' in config.xml.'); return featureToPlugin(legacyFeature); } return undefined; } var plugin = {}; plugin.name = pluginElement.attrib.name; plugin.spec = pluginElement.attrib.spec || pluginElement.attrib.src || pluginElement.attrib.version; plugin.variables = {}; var variableElements = pluginElement.findall('variable'); variableElements.forEach(function(varElement){ var name = varElement.attrib.name; var value = varElement.attrib.value; if(name){ plugin.variables[name] = value; } }); return plugin; }
javascript
function(id){ if(!id){ return undefined; } var pluginElement = this.doc.find('./plugin/[@name="' + id + '"]'); if (null === pluginElement) { var legacyFeature = this.doc.find('./feature/param[@name="id"][@value="' + id + '"]/..'); if(legacyFeature){ events.emit('log', 'Found deprecated feature entry for ' + id +' in config.xml.'); return featureToPlugin(legacyFeature); } return undefined; } var plugin = {}; plugin.name = pluginElement.attrib.name; plugin.spec = pluginElement.attrib.spec || pluginElement.attrib.src || pluginElement.attrib.version; plugin.variables = {}; var variableElements = pluginElement.findall('variable'); variableElements.forEach(function(varElement){ var name = varElement.attrib.name; var value = varElement.attrib.value; if(name){ plugin.variables[name] = value; } }); return plugin; }
[ "function", "(", "id", ")", "{", "if", "(", "!", "id", ")", "{", "return", "undefined", ";", "}", "var", "pluginElement", "=", "this", ".", "doc", ".", "find", "(", "'./plugin/[@name=\"'", "+", "id", "+", "'\"]'", ")", ";", "if", "(", "null", "===", "pluginElement", ")", "{", "var", "legacyFeature", "=", "this", ".", "doc", ".", "find", "(", "'./feature/param[@name=\"id\"][@value=\"'", "+", "id", "+", "'\"]/..'", ")", ";", "if", "(", "legacyFeature", ")", "{", "events", ".", "emit", "(", "'log'", ",", "'Found deprecated feature entry for '", "+", "id", "+", "' in config.xml.'", ")", ";", "return", "featureToPlugin", "(", "legacyFeature", ")", ";", "}", "return", "undefined", ";", "}", "var", "plugin", "=", "{", "}", ";", "plugin", ".", "name", "=", "pluginElement", ".", "attrib", ".", "name", ";", "plugin", ".", "spec", "=", "pluginElement", ".", "attrib", ".", "spec", "||", "pluginElement", ".", "attrib", ".", "src", "||", "pluginElement", ".", "attrib", ".", "version", ";", "plugin", ".", "variables", "=", "{", "}", ";", "var", "variableElements", "=", "pluginElement", ".", "findall", "(", "'variable'", ")", ";", "variableElements", ".", "forEach", "(", "function", "(", "varElement", ")", "{", "var", "name", "=", "varElement", ".", "attrib", ".", "name", ";", "var", "value", "=", "varElement", ".", "attrib", ".", "value", ";", "if", "(", "name", ")", "{", "plugin", ".", "variables", "[", "name", "]", "=", "value", ";", "}", "}", ")", ";", "return", "plugin", ";", "}" ]
Retrives the plugin with the given id or null if not found. This function also returns any plugin's that were defined using the legacy <feature> tags. @name getPlugin @function @param {String} id @returns {object} plugin including any variables
[ "Retrives", "the", "plugin", "with", "the", "given", "id", "or", "null", "if", "not", "found", "." ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L347-L374
49,847
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
function(name, attributes) { var el = et.Element(name); for (var a in attributes) { el.attrib[a] = attributes[a]; } this.doc.getroot().append(el); }
javascript
function(name, attributes) { var el = et.Element(name); for (var a in attributes) { el.attrib[a] = attributes[a]; } this.doc.getroot().append(el); }
[ "function", "(", "name", ",", "attributes", ")", "{", "var", "el", "=", "et", ".", "Element", "(", "name", ")", ";", "for", "(", "var", "a", "in", "attributes", ")", "{", "el", ".", "attrib", "[", "a", "]", "=", "attributes", "[", "a", "]", ";", "}", "this", ".", "doc", ".", "getroot", "(", ")", ".", "append", "(", "el", ")", ";", "}" ]
Add any element to the root
[ "Add", "any", "element", "to", "the", "root" ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L399-L405
49,848
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
function(name, spec){ if(!name) return; var el = et.Element('engine'); el.attrib.name = name; if(spec){ el.attrib.spec = spec; } this.doc.getroot().append(el); }
javascript
function(name, spec){ if(!name) return; var el = et.Element('engine'); el.attrib.name = name; if(spec){ el.attrib.spec = spec; } this.doc.getroot().append(el); }
[ "function", "(", "name", ",", "spec", ")", "{", "if", "(", "!", "name", ")", "return", ";", "var", "el", "=", "et", ".", "Element", "(", "'engine'", ")", ";", "el", ".", "attrib", ".", "name", "=", "name", ";", "if", "(", "spec", ")", "{", "el", ".", "attrib", ".", "spec", "=", "spec", ";", "}", "this", ".", "doc", ".", "getroot", "(", ")", ".", "append", "(", "el", ")", ";", "}" ]
Adds an engine. Does not check for duplicates. @param {String} name the engine name @param {String} spec engine source location or version (optional)
[ "Adds", "an", "engine", ".", "Does", "not", "check", "for", "duplicates", "." ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L412-L420
49,849
vkiding/judpack-common
src/ConfigParser/ConfigParser.js
function(name){ var engines = this.doc.findall('./engine/[@name="' +name+'"]'); for(var i=0; i < engines.length; i++){ var children = this.doc.getroot().getchildren(); var idx = children.indexOf(engines[i]); if(idx > -1){ children.splice(idx,1); } } }
javascript
function(name){ var engines = this.doc.findall('./engine/[@name="' +name+'"]'); for(var i=0; i < engines.length; i++){ var children = this.doc.getroot().getchildren(); var idx = children.indexOf(engines[i]); if(idx > -1){ children.splice(idx,1); } } }
[ "function", "(", "name", ")", "{", "var", "engines", "=", "this", ".", "doc", ".", "findall", "(", "'./engine/[@name=\"'", "+", "name", "+", "'\"]'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "engines", ".", "length", ";", "i", "++", ")", "{", "var", "children", "=", "this", ".", "doc", ".", "getroot", "(", ")", ".", "getchildren", "(", ")", ";", "var", "idx", "=", "children", ".", "indexOf", "(", "engines", "[", "i", "]", ")", ";", "if", "(", "idx", ">", "-", "1", ")", "{", "children", ".", "splice", "(", "idx", ",", "1", ")", ";", "}", "}", "}" ]
Removes all the engines with given name @param {String} name the engine name.
[ "Removes", "all", "the", "engines", "with", "given", "name" ]
5b87d3f1cb10c2c867243e3a692d39b4bb189dd4
https://github.com/vkiding/judpack-common/blob/5b87d3f1cb10c2c867243e3a692d39b4bb189dd4/src/ConfigParser/ConfigParser.js#L425-L434
49,850
akshat1/simian-color-functions
src/index.js
resolveFraction
function resolveFraction(frac) { frac = `${frac}`; if (Patterns.Percentage.test(frac)) { return parseFloat(frac) / 100; } else if (Patterns.Number.test(frac)) { return parseFloat(frac); } else throw new Error('Unknown fraction format: ', inp); }
javascript
function resolveFraction(frac) { frac = `${frac}`; if (Patterns.Percentage.test(frac)) { return parseFloat(frac) / 100; } else if (Patterns.Number.test(frac)) { return parseFloat(frac); } else throw new Error('Unknown fraction format: ', inp); }
[ "function", "resolveFraction", "(", "frac", ")", "{", "frac", "=", "`", "${", "frac", "}", "`", ";", "if", "(", "Patterns", ".", "Percentage", ".", "test", "(", "frac", ")", ")", "{", "return", "parseFloat", "(", "frac", ")", "/", "100", ";", "}", "else", "if", "(", "Patterns", ".", "Number", ".", "test", "(", "frac", ")", ")", "{", "return", "parseFloat", "(", "frac", ")", ";", "}", "else", "throw", "new", "Error", "(", "'Unknown fraction format: '", ",", "inp", ")", ";", "}" ]
Get a decimal value from a percentage or a number. @param {String|Number} frac - the value to be converted to a decimal fraction @return - a decimal value equivalent to the input @example resolveFraction('25%'); // 0.25 resolveFraction('0.25'); // 0.25
[ "Get", "a", "decimal", "value", "from", "a", "percentage", "or", "a", "number", "." ]
824e485d6a9e1eaaa47193153c1ce4133b07d99b
https://github.com/akshat1/simian-color-functions/blob/824e485d6a9e1eaaa47193153c1ce4133b07d99b/src/index.js#L28-L36
49,851
atd-schubert/node-stream-lib
lib/event.js
function (name, data, origin, priority) { this.timestamp = Date.now(); this.name = name; this.data = data; this.origin = origin; this.priority = priority || 1; }
javascript
function (name, data, origin, priority) { this.timestamp = Date.now(); this.name = name; this.data = data; this.origin = origin; this.priority = priority || 1; }
[ "function", "(", "name", ",", "data", ",", "origin", ",", "priority", ")", "{", "this", ".", "timestamp", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "name", "=", "name", ";", "this", ".", "data", "=", "data", ";", "this", ".", "origin", "=", "origin", ";", "this", ".", "priority", "=", "priority", "||", "1", ";", "}" ]
Events piping through streams @author Arne Schubert <[email protected]> @param {String} name - name of the event @param {*} data - On event binded data @param {EventStream} origin - EventStream that sends the data @param {number} [priority=0] - Priority of this message @constructor @memberOf streamLib @augments streamLib.Pipe
[ "Events", "piping", "through", "streams" ]
90f27042fae84d2fbdbf9d28149b0673997f151a
https://github.com/atd-schubert/node-stream-lib/blob/90f27042fae84d2fbdbf9d28149b0673997f151a/lib/event.js#L18-L24
49,852
atd-schubert/node-stream-lib
lib/event.js
streamOn
function streamOn(name, fn) { var str, handle; if (typeof name === 'string') { str = name; name = { test: function (val) { return val === str; } }; } /** * @callback {EventStream.handle} * @param chunk * @type {function} */ handle = function (chunk) { if (name.test(chunk.name)) { fn(chunk.data); } }; this.eventStreamListeners.push(handle); return handle; }
javascript
function streamOn(name, fn) { var str, handle; if (typeof name === 'string') { str = name; name = { test: function (val) { return val === str; } }; } /** * @callback {EventStream.handle} * @param chunk * @type {function} */ handle = function (chunk) { if (name.test(chunk.name)) { fn(chunk.data); } }; this.eventStreamListeners.push(handle); return handle; }
[ "function", "streamOn", "(", "name", ",", "fn", ")", "{", "var", "str", ",", "handle", ";", "if", "(", "typeof", "name", "===", "'string'", ")", "{", "str", "=", "name", ";", "name", "=", "{", "test", ":", "function", "(", "val", ")", "{", "return", "val", "===", "str", ";", "}", "}", ";", "}", "/**\n * @callback {EventStream.handle}\n * @param chunk\n * @type {function}\n */", "handle", "=", "function", "(", "chunk", ")", "{", "if", "(", "name", ".", "test", "(", "chunk", ".", "name", ")", ")", "{", "fn", "(", "chunk", ".", "data", ")", ";", "}", "}", ";", "this", ".", "eventStreamListeners", ".", "push", "(", "handle", ")", ";", "return", "handle", ";", "}" ]
Receive an event from a stream @param {string|RegExp|{test:function}} name - Name of the events that should be listened @param {function} fn - Function to execute when receiving event @returns {EventStream.handle}
[ "Receive", "an", "event", "from", "a", "stream" ]
90f27042fae84d2fbdbf9d28149b0673997f151a
https://github.com/atd-schubert/node-stream-lib/blob/90f27042fae84d2fbdbf9d28149b0673997f151a/lib/event.js#L99-L122
49,853
atd-schubert/node-stream-lib
lib/event.js
function (handle) { var pos = this.eventStreamListeners.indexOf(handle); if (pos === -1) { return false; } this.eventStreamListeners.splice(this.eventStreamListeners.indexOf(handle), 1); return true; }
javascript
function (handle) { var pos = this.eventStreamListeners.indexOf(handle); if (pos === -1) { return false; } this.eventStreamListeners.splice(this.eventStreamListeners.indexOf(handle), 1); return true; }
[ "function", "(", "handle", ")", "{", "var", "pos", "=", "this", ".", "eventStreamListeners", ".", "indexOf", "(", "handle", ")", ";", "if", "(", "pos", "===", "-", "1", ")", "{", "return", "false", ";", "}", "this", ".", "eventStreamListeners", ".", "splice", "(", "this", ".", "eventStreamListeners", ".", "indexOf", "(", "handle", ")", ",", "1", ")", ";", "return", "true", ";", "}" ]
Remove a receiver @param {EventStream.handle} handle - Handle from receiver creation @returns {boolean}
[ "Remove", "a", "receiver" ]
90f27042fae84d2fbdbf9d28149b0673997f151a
https://github.com/atd-schubert/node-stream-lib/blob/90f27042fae84d2fbdbf9d28149b0673997f151a/lib/event.js#L155-L162
49,854
atd-schubert/node-stream-lib
lib/event.js
function (emitter, eventPrefix) { var self = this, oldEmit = emitter.emit; eventPrefix = eventPrefix || ''; emitter.emit = function (name, data) { oldEmit.apply(emitter, arguments); self.send(eventPrefix + name, data); }; return this; }
javascript
function (emitter, eventPrefix) { var self = this, oldEmit = emitter.emit; eventPrefix = eventPrefix || ''; emitter.emit = function (name, data) { oldEmit.apply(emitter, arguments); self.send(eventPrefix + name, data); }; return this; }
[ "function", "(", "emitter", ",", "eventPrefix", ")", "{", "var", "self", "=", "this", ",", "oldEmit", "=", "emitter", ".", "emit", ";", "eventPrefix", "=", "eventPrefix", "||", "''", ";", "emitter", ".", "emit", "=", "function", "(", "name", ",", "data", ")", "{", "oldEmit", ".", "apply", "(", "emitter", ",", "arguments", ")", ";", "self", ".", "send", "(", "eventPrefix", "+", "name", ",", "data", ")", ";", "}", ";", "return", "this", ";", "}" ]
Send emitted events from an event emitter on event stream with prefix @param {events.EventEmitter} emitter - Event Emitter @param {string} [eventPrefix=""] - Prefix events with this prefix on event stream @returns {EventStream}
[ "Send", "emitted", "events", "from", "an", "event", "emitter", "on", "event", "stream", "with", "prefix" ]
90f27042fae84d2fbdbf9d28149b0673997f151a
https://github.com/atd-schubert/node-stream-lib/blob/90f27042fae84d2fbdbf9d28149b0673997f151a/lib/event.js#L170-L181
49,855
atd-schubert/node-stream-lib
lib/event.js
function (listener, eventPrefix) { var lastName; eventPrefix = eventPrefix || ''; this.receive({ test: function (val) { lastName = val; return true; } }, function (data) { listener.emit(eventPrefix + lastName, data); }); return this; }
javascript
function (listener, eventPrefix) { var lastName; eventPrefix = eventPrefix || ''; this.receive({ test: function (val) { lastName = val; return true; } }, function (data) { listener.emit(eventPrefix + lastName, data); }); return this; }
[ "function", "(", "listener", ",", "eventPrefix", ")", "{", "var", "lastName", ";", "eventPrefix", "=", "eventPrefix", "||", "''", ";", "this", ".", "receive", "(", "{", "test", ":", "function", "(", "val", ")", "{", "lastName", "=", "val", ";", "return", "true", ";", "}", "}", ",", "function", "(", "data", ")", "{", "listener", ".", "emit", "(", "eventPrefix", "+", "lastName", ",", "data", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Emits received events from event stream on a normal event emitter with prefix @param {events.EventEmitter} listener - Event Emitter @param {string} [eventPrefix=""] - Prefix streamed events with this prefix on event emitter @returns {EventStream}
[ "Emits", "received", "events", "from", "event", "stream", "on", "a", "normal", "event", "emitter", "with", "prefix" ]
90f27042fae84d2fbdbf9d28149b0673997f151a
https://github.com/atd-schubert/node-stream-lib/blob/90f27042fae84d2fbdbf9d28149b0673997f151a/lib/event.js#L188-L202
49,856
willscott/grunt-jasmine-chromeapp
tasks/jasmine-chromeapp/log.js
captureLogs
function captureLogs() { 'use strict'; console.log('Now capturing logs'); var methods = [ 'debug', 'info', 'log', 'warn', 'error' ]; methods.forEach(function (mthd) { var realMethod = 'real' + mthd, report = captureLog.bind({}, mthd); console[realMethod] = console[mthd]; console[mthd] = function () { report(arguments); console.reallog.apply(console, arguments); }; }); }
javascript
function captureLogs() { 'use strict'; console.log('Now capturing logs'); var methods = [ 'debug', 'info', 'log', 'warn', 'error' ]; methods.forEach(function (mthd) { var realMethod = 'real' + mthd, report = captureLog.bind({}, mthd); console[realMethod] = console[mthd]; console[mthd] = function () { report(arguments); console.reallog.apply(console, arguments); }; }); }
[ "function", "captureLogs", "(", ")", "{", "'use strict'", ";", "console", ".", "log", "(", "'Now capturing logs'", ")", ";", "var", "methods", "=", "[", "'debug'", ",", "'info'", ",", "'log'", ",", "'warn'", ",", "'error'", "]", ";", "methods", ".", "forEach", "(", "function", "(", "mthd", ")", "{", "var", "realMethod", "=", "'real'", "+", "mthd", ",", "report", "=", "captureLog", ".", "bind", "(", "{", "}", ",", "mthd", ")", ";", "console", "[", "realMethod", "]", "=", "console", "[", "mthd", "]", ";", "console", "[", "mthd", "]", "=", "function", "(", ")", "{", "report", "(", "arguments", ")", ";", "console", ".", "reallog", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", ";", "}", ")", ";", "}" ]
This will intercept logs and get their output back to the shell.
[ "This", "will", "intercept", "logs", "and", "get", "their", "output", "back", "to", "the", "shell", "." ]
8582a56e0fd3c559948656fae157082910c45055
https://github.com/willscott/grunt-jasmine-chromeapp/blob/8582a56e0fd3c559948656fae157082910c45055/tasks/jasmine-chromeapp/log.js#L10-L23
49,857
polo2ro/restitute
src/controller.js
saveItemController
function saveItemController(method, path) { restController.call(this, method, path); var ctrl = this; /** * Save item controller use this method to output a service as a rest * service * Output the saved document with the $outcome property * * @param {apiService} service * @param {object} [moreparams] optional additional parameters to give to the service * * @return {Promise} */ this.jsonService = function(service, moreparams) { var params = ctrl.getServiceParameters(ctrl.req); var promise = service.getResultPromise(params); ctrl.outputJsonFromPromise(service, promise); return promise; }; }
javascript
function saveItemController(method, path) { restController.call(this, method, path); var ctrl = this; /** * Save item controller use this method to output a service as a rest * service * Output the saved document with the $outcome property * * @param {apiService} service * @param {object} [moreparams] optional additional parameters to give to the service * * @return {Promise} */ this.jsonService = function(service, moreparams) { var params = ctrl.getServiceParameters(ctrl.req); var promise = service.getResultPromise(params); ctrl.outputJsonFromPromise(service, promise); return promise; }; }
[ "function", "saveItemController", "(", "method", ",", "path", ")", "{", "restController", ".", "call", "(", "this", ",", "method", ",", "path", ")", ";", "var", "ctrl", "=", "this", ";", "/**\n * Save item controller use this method to output a service as a rest\n * service\n * Output the saved document with the $outcome property\n *\n * @param {apiService} service\n * @param {object} [moreparams] optional additional parameters to give to the service\n *\n * @return {Promise}\n */", "this", ".", "jsonService", "=", "function", "(", "service", ",", "moreparams", ")", "{", "var", "params", "=", "ctrl", ".", "getServiceParameters", "(", "ctrl", ".", "req", ")", ";", "var", "promise", "=", "service", ".", "getResultPromise", "(", "params", ")", ";", "ctrl", ".", "outputJsonFromPromise", "(", "service", ",", "promise", ")", ";", "return", "promise", ";", "}", ";", "}" ]
Base class for create or update an item @param {string} method post|put @param {string} path
[ "Base", "class", "for", "create", "or", "update", "an", "item" ]
532f10b01469f76b8a60f5be624ebf562ebfcf55
https://github.com/polo2ro/restitute/blob/532f10b01469f76b8a60f5be624ebf562ebfcf55/src/controller.js#L358-L382
49,858
polo2ro/restitute
src/controller.js
deleteItemController
function deleteItemController(path) { restController.call(this, 'delete', path); var ctrl = this; /** * Delete controller use this method to output a service as a rest * service * Output the deleted document with the $outcome property * * @param {apiService} service * * @return {Promise} */ this.jsonService = function(service) { var params = ctrl.getServiceParameters(ctrl.req); var promise = service.getResultPromise(params); ctrl.outputJsonFromPromise(service, promise); return promise; }; }
javascript
function deleteItemController(path) { restController.call(this, 'delete', path); var ctrl = this; /** * Delete controller use this method to output a service as a rest * service * Output the deleted document with the $outcome property * * @param {apiService} service * * @return {Promise} */ this.jsonService = function(service) { var params = ctrl.getServiceParameters(ctrl.req); var promise = service.getResultPromise(params); ctrl.outputJsonFromPromise(service, promise); return promise; }; }
[ "function", "deleteItemController", "(", "path", ")", "{", "restController", ".", "call", "(", "this", ",", "'delete'", ",", "path", ")", ";", "var", "ctrl", "=", "this", ";", "/**\n * Delete controller use this method to output a service as a rest\n * service\n * Output the deleted document with the $outcome property\n *\n * @param {apiService} service\n *\n * @return {Promise}\n */", "this", ".", "jsonService", "=", "function", "(", "service", ")", "{", "var", "params", "=", "ctrl", ".", "getServiceParameters", "(", "ctrl", ".", "req", ")", ";", "var", "promise", "=", "service", ".", "getResultPromise", "(", "params", ")", ";", "ctrl", ".", "outputJsonFromPromise", "(", "service", ",", "promise", ")", ";", "return", "promise", ";", "}", ";", "}" ]
DELETE request with an id output json with the deleted item data and outcome informations @param {String} path
[ "DELETE", "request", "with", "an", "id", "output", "json", "with", "the", "deleted", "item", "data", "and", "outcome", "informations" ]
532f10b01469f76b8a60f5be624ebf562ebfcf55
https://github.com/polo2ro/restitute/blob/532f10b01469f76b8a60f5be624ebf562ebfcf55/src/controller.js#L421-L444
49,859
elliot-a/grunt-git-batch-clone
tasks/batch_git_clone.js
deleteOldFiles
function deleteOldFiles(path){ var deferred = Q.defer(); // Don't delete existing files & folders if overwrite is off if(options.overWrite !== false){ grunt.log.writeln('---> Deleting folder ==> '+path); rimraf(path, function(err){ if(err) { grunt.log.warn('---> There was an error deleting the existing repo folder : '+path+', error : '+err); deferred.reject(err); }else{ deferred.resolve(); } }); }else{ if(grunt.file.isDir(path)){ grunt.log.writeln('---> Folder exists so plugin will not overwrite ==> '+path); } deferred.resolve(); } return deferred.promise; }
javascript
function deleteOldFiles(path){ var deferred = Q.defer(); // Don't delete existing files & folders if overwrite is off if(options.overWrite !== false){ grunt.log.writeln('---> Deleting folder ==> '+path); rimraf(path, function(err){ if(err) { grunt.log.warn('---> There was an error deleting the existing repo folder : '+path+', error : '+err); deferred.reject(err); }else{ deferred.resolve(); } }); }else{ if(grunt.file.isDir(path)){ grunt.log.writeln('---> Folder exists so plugin will not overwrite ==> '+path); } deferred.resolve(); } return deferred.promise; }
[ "function", "deleteOldFiles", "(", "path", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "// Don't delete existing files & folders if overwrite is off", "if", "(", "options", ".", "overWrite", "!==", "false", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "'---> Deleting folder ==> '", "+", "path", ")", ";", "rimraf", "(", "path", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "grunt", ".", "log", ".", "warn", "(", "'---> There was an error deleting the existing repo folder : '", "+", "path", "+", "', error : '", "+", "err", ")", ";", "deferred", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "deferred", ".", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", "else", "{", "if", "(", "grunt", ".", "file", ".", "isDir", "(", "path", ")", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "'---> Folder exists so plugin will not overwrite ==> '", "+", "path", ")", ";", "}", "deferred", ".", "resolve", "(", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
delete the repo folder before repopulating it
[ "delete", "the", "repo", "folder", "before", "repopulating", "it" ]
3419d6366f78286e978f568783cbb5dabe8fd219
https://github.com/elliot-a/grunt-git-batch-clone/blob/3419d6366f78286e978f568783cbb5dabe8fd219/tasks/batch_git_clone.js#L60-L87
49,860
elliot-a/grunt-git-batch-clone
tasks/batch_git_clone.js
performCmd
function performCmd(repoURL, path){ var deferred = Q.defer(); if(errorOccured === true){ deferred.reject(); return deferred.promise; } if(grunt.file.isDir(path) && options.overWrite === false){ deferred.resolve(false); return deferred.promise; } var msg = '---> Cloning "'+repoURL+'" ==> '+path; var execString = 'git clone '+repoURL+' '+path; if(options.depth > 0){ execString += ' --depth '+options.depth; } if(options.postClone !== ''){ msg += ' THEN executing "'+options.postClone+'"'; execString += ' && cd '+path+' && '+options.postClone; } grunt.log.writeln(msg); var child = exec(execString); // add events for logging child.stdout.on('data', function(data) { grunt.log.writeln(data); }); child.stderr.on('data', function(data) { grunt.verbose.writeln(data); }); child.on('close', function(code) { deferred.resolve(true); }); return deferred.promise; }
javascript
function performCmd(repoURL, path){ var deferred = Q.defer(); if(errorOccured === true){ deferred.reject(); return deferred.promise; } if(grunt.file.isDir(path) && options.overWrite === false){ deferred.resolve(false); return deferred.promise; } var msg = '---> Cloning "'+repoURL+'" ==> '+path; var execString = 'git clone '+repoURL+' '+path; if(options.depth > 0){ execString += ' --depth '+options.depth; } if(options.postClone !== ''){ msg += ' THEN executing "'+options.postClone+'"'; execString += ' && cd '+path+' && '+options.postClone; } grunt.log.writeln(msg); var child = exec(execString); // add events for logging child.stdout.on('data', function(data) { grunt.log.writeln(data); }); child.stderr.on('data', function(data) { grunt.verbose.writeln(data); }); child.on('close', function(code) { deferred.resolve(true); }); return deferred.promise; }
[ "function", "performCmd", "(", "repoURL", ",", "path", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "if", "(", "errorOccured", "===", "true", ")", "{", "deferred", ".", "reject", "(", ")", ";", "return", "deferred", ".", "promise", ";", "}", "if", "(", "grunt", ".", "file", ".", "isDir", "(", "path", ")", "&&", "options", ".", "overWrite", "===", "false", ")", "{", "deferred", ".", "resolve", "(", "false", ")", ";", "return", "deferred", ".", "promise", ";", "}", "var", "msg", "=", "'---> Cloning \"'", "+", "repoURL", "+", "'\" ==> '", "+", "path", ";", "var", "execString", "=", "'git clone '", "+", "repoURL", "+", "' '", "+", "path", ";", "if", "(", "options", ".", "depth", ">", "0", ")", "{", "execString", "+=", "' --depth '", "+", "options", ".", "depth", ";", "}", "if", "(", "options", ".", "postClone", "!==", "''", ")", "{", "msg", "+=", "' THEN executing \"'", "+", "options", ".", "postClone", "+", "'\"'", ";", "execString", "+=", "' && cd '", "+", "path", "+", "' && '", "+", "options", ".", "postClone", ";", "}", "grunt", ".", "log", ".", "writeln", "(", "msg", ")", ";", "var", "child", "=", "exec", "(", "execString", ")", ";", "// add events for logging", "child", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "data", ")", ";", "}", ")", ";", "child", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "data", ")", ";", "}", ")", ";", "child", ".", "on", "(", "'close'", ",", "function", "(", "code", ")", "{", "deferred", ".", "resolve", "(", "true", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
performs the clone command
[ "performs", "the", "clone", "command" ]
3419d6366f78286e978f568783cbb5dabe8fd219
https://github.com/elliot-a/grunt-git-batch-clone/blob/3419d6366f78286e978f568783cbb5dabe8fd219/tasks/batch_git_clone.js#L91-L134
49,861
elliot-a/grunt-git-batch-clone
tasks/batch_git_clone.js
cloneRepo
function cloneRepo(item){ var deferred = Q.defer(); var repoURL = item.repo; var path = item.path; deleteOldFiles(path). then(function(){ return performCmd(repoURL, path); }).then(function(success){ return npmInstall(path, success); }).then(function(success){ return bowerInstall(path, success); }).then(function(){ deferred.resolve(); }); return deferred.promise; }
javascript
function cloneRepo(item){ var deferred = Q.defer(); var repoURL = item.repo; var path = item.path; deleteOldFiles(path). then(function(){ return performCmd(repoURL, path); }).then(function(success){ return npmInstall(path, success); }).then(function(success){ return bowerInstall(path, success); }).then(function(){ deferred.resolve(); }); return deferred.promise; }
[ "function", "cloneRepo", "(", "item", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "var", "repoURL", "=", "item", ".", "repo", ";", "var", "path", "=", "item", ".", "path", ";", "deleteOldFiles", "(", "path", ")", ".", "then", "(", "function", "(", ")", "{", "return", "performCmd", "(", "repoURL", ",", "path", ")", ";", "}", ")", ".", "then", "(", "function", "(", "success", ")", "{", "return", "npmInstall", "(", "path", ",", "success", ")", ";", "}", ")", ".", "then", "(", "function", "(", "success", ")", "{", "return", "bowerInstall", "(", "path", ",", "success", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "deferred", ".", "resolve", "(", ")", ";", "}", ")", ";", "return", "deferred", ".", "promise", ";", "}" ]
creates a spawn process and clones the repos
[ "creates", "a", "spawn", "process", "and", "clones", "the", "repos" ]
3419d6366f78286e978f568783cbb5dabe8fd219
https://github.com/elliot-a/grunt-git-batch-clone/blob/3419d6366f78286e978f568783cbb5dabe8fd219/tasks/batch_git_clone.js#L138-L157
49,862
elliot-a/grunt-git-batch-clone
tasks/batch_git_clone.js
getItemList
function getItemList(object, path){ for (var prop in object){ if(typeof object[prop] === 'object'){ var newPath = path + (prop+'/'); getItemList(object[prop], newPath); }else{ var item = { path : path+prop, repo : object[prop] }; repoList.push(item); } } }
javascript
function getItemList(object, path){ for (var prop in object){ if(typeof object[prop] === 'object'){ var newPath = path + (prop+'/'); getItemList(object[prop], newPath); }else{ var item = { path : path+prop, repo : object[prop] }; repoList.push(item); } } }
[ "function", "getItemList", "(", "object", ",", "path", ")", "{", "for", "(", "var", "prop", "in", "object", ")", "{", "if", "(", "typeof", "object", "[", "prop", "]", "===", "'object'", ")", "{", "var", "newPath", "=", "path", "+", "(", "prop", "+", "'/'", ")", ";", "getItemList", "(", "object", "[", "prop", "]", ",", "newPath", ")", ";", "}", "else", "{", "var", "item", "=", "{", "path", ":", "path", "+", "prop", ",", "repo", ":", "object", "[", "prop", "]", "}", ";", "repoList", ".", "push", "(", "item", ")", ";", "}", "}", "}" ]
converts the json object into an array of items with paths
[ "converts", "the", "json", "object", "into", "an", "array", "of", "items", "with", "paths" ]
3419d6366f78286e978f568783cbb5dabe8fd219
https://github.com/elliot-a/grunt-git-batch-clone/blob/3419d6366f78286e978f568783cbb5dabe8fd219/tasks/batch_git_clone.js#L160-L177
49,863
elliot-a/grunt-git-batch-clone
tasks/batch_git_clone.js
npmInstall
function npmInstall(path, success){ var deferred = Q.defer(); // 'success' is a flag passed from the perform cmd function which states whether the function ran if(success === false){ deferred.resolve(success); return deferred.promise; } var hasPackage = grunt.file.isFile(path+'/package.json'); if(options.npmInstall === true && hasPackage){ var msg = '---> Install npm dependencies ==> '+path; var execString = 'cd '+path+' && npm install'; grunt.log.writeln(msg); var child = exec(execString); // add events for logging child.stdout.on('data', function(data) { grunt.log.writeln(data); }); child.stderr.on('data', function(data) { grunt.verbose.writeln(data); }); child.on('close', function(code) { deferred.resolve(success); }); }else{ if(options.npmInstall === true) { var msg = '---> Skipping npm install as no package JSON was detected ==> ' + path; grunt.log.writeln(msg); } deferred.resolve(); } return deferred.promise; }
javascript
function npmInstall(path, success){ var deferred = Q.defer(); // 'success' is a flag passed from the perform cmd function which states whether the function ran if(success === false){ deferred.resolve(success); return deferred.promise; } var hasPackage = grunt.file.isFile(path+'/package.json'); if(options.npmInstall === true && hasPackage){ var msg = '---> Install npm dependencies ==> '+path; var execString = 'cd '+path+' && npm install'; grunt.log.writeln(msg); var child = exec(execString); // add events for logging child.stdout.on('data', function(data) { grunt.log.writeln(data); }); child.stderr.on('data', function(data) { grunt.verbose.writeln(data); }); child.on('close', function(code) { deferred.resolve(success); }); }else{ if(options.npmInstall === true) { var msg = '---> Skipping npm install as no package JSON was detected ==> ' + path; grunt.log.writeln(msg); } deferred.resolve(); } return deferred.promise; }
[ "function", "npmInstall", "(", "path", ",", "success", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "// 'success' is a flag passed from the perform cmd function which states whether the function ran", "if", "(", "success", "===", "false", ")", "{", "deferred", ".", "resolve", "(", "success", ")", ";", "return", "deferred", ".", "promise", ";", "}", "var", "hasPackage", "=", "grunt", ".", "file", ".", "isFile", "(", "path", "+", "'/package.json'", ")", ";", "if", "(", "options", ".", "npmInstall", "===", "true", "&&", "hasPackage", ")", "{", "var", "msg", "=", "'---> Install npm dependencies ==> '", "+", "path", ";", "var", "execString", "=", "'cd '", "+", "path", "+", "' && npm install'", ";", "grunt", ".", "log", ".", "writeln", "(", "msg", ")", ";", "var", "child", "=", "exec", "(", "execString", ")", ";", "// add events for logging", "child", ".", "stdout", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "data", ")", ";", "}", ")", ";", "child", ".", "stderr", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "data", ")", ";", "}", ")", ";", "child", ".", "on", "(", "'close'", ",", "function", "(", "code", ")", "{", "deferred", ".", "resolve", "(", "success", ")", ";", "}", ")", ";", "}", "else", "{", "if", "(", "options", ".", "npmInstall", "===", "true", ")", "{", "var", "msg", "=", "'---> Skipping npm install as no package JSON was detected ==> '", "+", "path", ";", "grunt", ".", "log", ".", "writeln", "(", "msg", ")", ";", "}", "deferred", ".", "resolve", "(", ")", ";", "}", "return", "deferred", ".", "promise", ";", "}" ]
checks for a package.json then runs npm install if there is one.
[ "checks", "for", "a", "package", ".", "json", "then", "runs", "npm", "install", "if", "there", "is", "one", "." ]
3419d6366f78286e978f568783cbb5dabe8fd219
https://github.com/elliot-a/grunt-git-batch-clone/blob/3419d6366f78286e978f568783cbb5dabe8fd219/tasks/batch_git_clone.js#L180-L225
49,864
henrytseng/argr
lib/argr.js
function(data, param, value) { if(_definition[param]) { var paramInstance = Param(param, value, _definition[param]); _definition[param].param.forEach(function(p) { data[p] = paramInstance; }); } else { // Unsupported if operating in strict mode if(_useStrict) { throw(new Error('Invalid argument syntax ('+param+')')); } else { data[param] = Param(param, value); } } }
javascript
function(data, param, value) { if(_definition[param]) { var paramInstance = Param(param, value, _definition[param]); _definition[param].param.forEach(function(p) { data[p] = paramInstance; }); } else { // Unsupported if operating in strict mode if(_useStrict) { throw(new Error('Invalid argument syntax ('+param+')')); } else { data[param] = Param(param, value); } } }
[ "function", "(", "data", ",", "param", ",", "value", ")", "{", "if", "(", "_definition", "[", "param", "]", ")", "{", "var", "paramInstance", "=", "Param", "(", "param", ",", "value", ",", "_definition", "[", "param", "]", ")", ";", "_definition", "[", "param", "]", ".", "param", ".", "forEach", "(", "function", "(", "p", ")", "{", "data", "[", "p", "]", "=", "paramInstance", ";", "}", ")", ";", "}", "else", "{", "// Unsupported if operating in strict mode", "if", "(", "_useStrict", ")", "{", "throw", "(", "new", "Error", "(", "'Invalid argument syntax ('", "+", "param", "+", "')'", ")", ")", ";", "}", "else", "{", "data", "[", "param", "]", "=", "Param", "(", "param", ",", "value", ")", ";", "}", "}", "}" ]
Associate a parameter with its short and long, if it exists @param {Object} data A data object to setup @param {String} param A short/long parameter name @param {Mixed} value A value object
[ "Associate", "a", "parameter", "with", "its", "short", "and", "long", "if", "it", "exists" ]
e082f099a60d73508fb6d68095849a71d4315dda
https://github.com/henrytseng/argr/blob/e082f099a60d73508fb6d68095849a71d4315dda/lib/argr.js#L54-L70
49,865
henrytseng/argr
lib/argr.js
function() { var options = []; Object.keys(_definition).forEach((key, i, list) => { if(options.indexOf(_definition[key]) == -1) { options.push(_definition[key]); } }); return options; }
javascript
function() { var options = []; Object.keys(_definition).forEach((key, i, list) => { if(options.indexOf(_definition[key]) == -1) { options.push(_definition[key]); } }); return options; }
[ "function", "(", ")", "{", "var", "options", "=", "[", "]", ";", "Object", ".", "keys", "(", "_definition", ")", ".", "forEach", "(", "(", "key", ",", "i", ",", "list", ")", "=>", "{", "if", "(", "options", ".", "indexOf", "(", "_definition", "[", "key", "]", ")", "==", "-", "1", ")", "{", "options", ".", "push", "(", "_definition", "[", "key", "]", ")", ";", "}", "}", ")", ";", "return", "options", ";", "}" ]
Get list of options @return {Array} List of options
[ "Get", "list", "of", "options" ]
e082f099a60d73508fb6d68095849a71d4315dda
https://github.com/henrytseng/argr/blob/e082f099a60d73508fb6d68095849a71d4315dda/lib/argr.js#L237-L245
49,866
henrytseng/argr
lib/argr.js
function(name) { // Parse once if(!_data) _data = _parse(_args); // Fallback to defaults var param = _data[name] || _definition[name]; // False for not provided return (!param) ? false : param.value(); }
javascript
function(name) { // Parse once if(!_data) _data = _parse(_args); // Fallback to defaults var param = _data[name] || _definition[name]; // False for not provided return (!param) ? false : param.value(); }
[ "function", "(", "name", ")", "{", "// Parse once", "if", "(", "!", "_data", ")", "_data", "=", "_parse", "(", "_args", ")", ";", "// Fallback to defaults", "var", "param", "=", "_data", "[", "name", "]", "||", "_definition", "[", "name", "]", ";", "// False for not provided", "return", "(", "!", "param", ")", "?", "false", ":", "param", ".", "value", "(", ")", ";", "}" ]
Get a value associated with argument @param {Mixed} name A parameter name (short or long) @return {Object} A data object associated with the value
[ "Get", "a", "value", "associated", "with", "argument" ]
e082f099a60d73508fb6d68095849a71d4315dda
https://github.com/henrytseng/argr/blob/e082f099a60d73508fb6d68095849a71d4315dda/lib/argr.js#L275-L284
49,867
marcojonker/data-elevator
lib/elevator-engine/elevator-engine.js
function(config, level, floor, callback) { var floors = []; var fromIdentifier = level ? level.identifier : null; var options = FloorSelectionOptions.createFromIdentifiers(fromIdentifier, floor); try{ floors = FloorController.getFloors(config.floorsDir, options); return callback(null, floors, options); } catch(error) { return callback(error); } }
javascript
function(config, level, floor, callback) { var floors = []; var fromIdentifier = level ? level.identifier : null; var options = FloorSelectionOptions.createFromIdentifiers(fromIdentifier, floor); try{ floors = FloorController.getFloors(config.floorsDir, options); return callback(null, floors, options); } catch(error) { return callback(error); } }
[ "function", "(", "config", ",", "level", ",", "floor", ",", "callback", ")", "{", "var", "floors", "=", "[", "]", ";", "var", "fromIdentifier", "=", "level", "?", "level", ".", "identifier", ":", "null", ";", "var", "options", "=", "FloorSelectionOptions", ".", "createFromIdentifiers", "(", "fromIdentifier", ",", "floor", ")", ";", "try", "{", "floors", "=", "FloorController", ".", "getFloors", "(", "config", ".", "floorsDir", ",", "options", ")", ";", "return", "callback", "(", "null", ",", "floors", ",", "options", ")", ";", "}", "catch", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", "}" ]
Get floors for selected destination @param config @param level @param floor @param callback(error, floors)
[ "Get", "floors", "for", "selected", "destination" ]
7d56e5b2e8ca24b9576066e5265713db6452f289
https://github.com/marcojonker/data-elevator/blob/7d56e5b2e8ca24b9576066e5265713db6452f289/lib/elevator-engine/elevator-engine.js#L30-L41
49,868
marcojonker/data-elevator
lib/elevator-engine/elevator-engine.js
function(config, floors, ascending, logger, levelController, callback) { var self = this; //Itterate migrations files async.eachSeries(floors, function(floor, callback) { var parameters = new FloorWorkerParameters(config, logger, floor); var floorWorker = require(floor.filePath); var directionText = (ascending === true) ? 'Up' : 'Down'; //Checkf if function is available in migration file if(floorWorker['on' + directionText]) { async.waterfall([ function(callback) { floorWorker['on' + directionText](parameters, function(error) { if(error) { logger.error('>>>> Stuck at floor ' + floor.getLongName()); } else { logger.info('>>>> Migrating ' + directionText.toLowerCase() + ' floor: ' + floor.getLongName()); } return callback(error); }); }, function(callback) { levelController.saveCurrentLevel(Level.create(floor.identifier), function(error) { if(error) { logger.error('>>>> Stuck at floor ' + floor.identifier + '. Failed to store the current level'); } return callback(error); }); } ], function(error) { return callback(error); }) } else { return callback(Errors.generalError('>>>> Invalid floor ' + floor.filePath)); } }, function(error) { return callback(error); }) }
javascript
function(config, floors, ascending, logger, levelController, callback) { var self = this; //Itterate migrations files async.eachSeries(floors, function(floor, callback) { var parameters = new FloorWorkerParameters(config, logger, floor); var floorWorker = require(floor.filePath); var directionText = (ascending === true) ? 'Up' : 'Down'; //Checkf if function is available in migration file if(floorWorker['on' + directionText]) { async.waterfall([ function(callback) { floorWorker['on' + directionText](parameters, function(error) { if(error) { logger.error('>>>> Stuck at floor ' + floor.getLongName()); } else { logger.info('>>>> Migrating ' + directionText.toLowerCase() + ' floor: ' + floor.getLongName()); } return callback(error); }); }, function(callback) { levelController.saveCurrentLevel(Level.create(floor.identifier), function(error) { if(error) { logger.error('>>>> Stuck at floor ' + floor.identifier + '. Failed to store the current level'); } return callback(error); }); } ], function(error) { return callback(error); }) } else { return callback(Errors.generalError('>>>> Invalid floor ' + floor.filePath)); } }, function(error) { return callback(error); }) }
[ "function", "(", "config", ",", "floors", ",", "ascending", ",", "logger", ",", "levelController", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "//Itterate migrations files", "async", ".", "eachSeries", "(", "floors", ",", "function", "(", "floor", ",", "callback", ")", "{", "var", "parameters", "=", "new", "FloorWorkerParameters", "(", "config", ",", "logger", ",", "floor", ")", ";", "var", "floorWorker", "=", "require", "(", "floor", ".", "filePath", ")", ";", "var", "directionText", "=", "(", "ascending", "===", "true", ")", "?", "'Up'", ":", "'Down'", ";", "//Checkf if function is available in migration file", "if", "(", "floorWorker", "[", "'on'", "+", "directionText", "]", ")", "{", "async", ".", "waterfall", "(", "[", "function", "(", "callback", ")", "{", "floorWorker", "[", "'on'", "+", "directionText", "]", "(", "parameters", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "logger", ".", "error", "(", "'>>>> Stuck at floor '", "+", "floor", ".", "getLongName", "(", ")", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "'>>>> Migrating '", "+", "directionText", ".", "toLowerCase", "(", ")", "+", "' floor: '", "+", "floor", ".", "getLongName", "(", ")", ")", ";", "}", "return", "callback", "(", "error", ")", ";", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "levelController", ".", "saveCurrentLevel", "(", "Level", ".", "create", "(", "floor", ".", "identifier", ")", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "logger", ".", "error", "(", "'>>>> Stuck at floor '", "+", "floor", ".", "identifier", "+", "'. Failed to store the current level'", ")", ";", "}", "return", "callback", "(", "error", ")", ";", "}", ")", ";", "}", "]", ",", "function", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", ")", "}", "else", "{", "return", "callback", "(", "Errors", ".", "generalError", "(", "'>>>> Invalid floor '", "+", "floor", ".", "filePath", ")", ")", ";", "}", "}", ",", "function", "(", "error", ")", "{", "return", "callback", "(", "error", ")", ";", "}", ")", "}" ]
Migrate an array of migration files @param config @param floors @param ascending @param logger @param levelController - Object derived from BaseLevelController to do custom level storage @param callback(error)
[ "Migrate", "an", "array", "of", "migration", "files" ]
7d56e5b2e8ca24b9576066e5265713db6452f289
https://github.com/marcojonker/data-elevator/blob/7d56e5b2e8ca24b9576066e5265713db6452f289/lib/elevator-engine/elevator-engine.js#L52-L91
49,869
marcojonker/data-elevator
lib/elevator-engine/elevator-engine.js
function(level, callback) { _getFloors(config, level, floor, function(error, floors, options) { return callback(error, floors, options); }) }
javascript
function(level, callback) { _getFloors(config, level, floor, function(error, floors, options) { return callback(error, floors, options); }) }
[ "function", "(", "level", ",", "callback", ")", "{", "_getFloors", "(", "config", ",", "level", ",", "floor", ",", "function", "(", "error", ",", "floors", ",", "options", ")", "{", "return", "callback", "(", "error", ",", "floors", ",", "options", ")", ";", "}", ")", "}" ]
Get the migration files that need to be applied
[ "Get", "the", "migration", "files", "that", "need", "to", "be", "applied" ]
7d56e5b2e8ca24b9576066e5265713db6452f289
https://github.com/marcojonker/data-elevator/blob/7d56e5b2e8ca24b9576066e5265713db6452f289/lib/elevator-engine/elevator-engine.js#L134-L138
49,870
marcojonker/data-elevator
lib/elevator-engine/elevator-engine.js
function(floors, options, callback) { if(floors != null && floors.length > 0) { _moveElevator(config, floors, options.ascending, logger, levelController, function(error) { return callback(error, floors, options); }); } else { return callback(null, null, null); } }
javascript
function(floors, options, callback) { if(floors != null && floors.length > 0) { _moveElevator(config, floors, options.ascending, logger, levelController, function(error) { return callback(error, floors, options); }); } else { return callback(null, null, null); } }
[ "function", "(", "floors", ",", "options", ",", "callback", ")", "{", "if", "(", "floors", "!=", "null", "&&", "floors", ".", "length", ">", "0", ")", "{", "_moveElevator", "(", "config", ",", "floors", ",", "options", ".", "ascending", ",", "logger", ",", "levelController", ",", "function", "(", "error", ")", "{", "return", "callback", "(", "error", ",", "floors", ",", "options", ")", ";", "}", ")", ";", "}", "else", "{", "return", "callback", "(", "null", ",", "null", ",", "null", ")", ";", "}", "}" ]
Migrate the files
[ "Migrate", "the", "files" ]
7d56e5b2e8ca24b9576066e5265713db6452f289
https://github.com/marcojonker/data-elevator/blob/7d56e5b2e8ca24b9576066e5265713db6452f289/lib/elevator-engine/elevator-engine.js#L140-L148
49,871
marcojonker/data-elevator
lib/elevator-engine/elevator-engine.js
function(floors, options, callback) { if(floors && options && options.ascending === false) { levelController.saveCurrentLevel(Level.create(options.identifierRange.min), function(error) { if(error) { logger.error('>>>> Stuck at floor ' + options.identifierRange.min + '. Failed to store the current level.'); } return callback(error); }); } else { return callback(null); } }
javascript
function(floors, options, callback) { if(floors && options && options.ascending === false) { levelController.saveCurrentLevel(Level.create(options.identifierRange.min), function(error) { if(error) { logger.error('>>>> Stuck at floor ' + options.identifierRange.min + '. Failed to store the current level.'); } return callback(error); }); } else { return callback(null); } }
[ "function", "(", "floors", ",", "options", ",", "callback", ")", "{", "if", "(", "floors", "&&", "options", "&&", "options", ".", "ascending", "===", "false", ")", "{", "levelController", ".", "saveCurrentLevel", "(", "Level", ".", "create", "(", "options", ".", "identifierRange", ".", "min", ")", ",", "function", "(", "error", ")", "{", "if", "(", "error", ")", "{", "logger", ".", "error", "(", "'>>>> Stuck at floor '", "+", "options", ".", "identifierRange", ".", "min", "+", "'. Failed to store the current level.'", ")", ";", "}", "return", "callback", "(", "error", ")", ";", "}", ")", ";", "}", "else", "{", "return", "callback", "(", "null", ")", ";", "}", "}" ]
Save the last level if going down, because the last level is not stored yet
[ "Save", "the", "last", "level", "if", "going", "down", "because", "the", "last", "level", "is", "not", "stored", "yet" ]
7d56e5b2e8ca24b9576066e5265713db6452f289
https://github.com/marcojonker/data-elevator/blob/7d56e5b2e8ca24b9576066e5265713db6452f289/lib/elevator-engine/elevator-engine.js#L150-L161
49,872
shippjs/shipp-server
lib/bundler.js
compile
function compile(emit) { self.bundler.run(function(err, stats) { // Error handling if (err || stats.compilation.errors.length) { // Over time we expect webpack's resolution system to change. We choose to attempt // package installations by catching errors so as to maximize forward-compability. // Should the error reporting format change, we will need to update our resolution system. var errors = stats.toJson({ errorDetails: true }).errors; var recompile = errors.reduce(function(recompile, err) { if (Resolver.isMissingModuleError(err)) recompile = Resolver.installPackageFromError(err); return recompile; }, false); if (recompile) return compile(); if (err) global.shipp.logger.error(err); if (stats.compilation.errors.length) global.shipp.logger.error(stats.toString({ errorDetails: true })); return; } global.shipp.log("Bundled", self.path); if (emit) global.shipp.emit("route:refresh", { route: self.path }); }); }
javascript
function compile(emit) { self.bundler.run(function(err, stats) { // Error handling if (err || stats.compilation.errors.length) { // Over time we expect webpack's resolution system to change. We choose to attempt // package installations by catching errors so as to maximize forward-compability. // Should the error reporting format change, we will need to update our resolution system. var errors = stats.toJson({ errorDetails: true }).errors; var recompile = errors.reduce(function(recompile, err) { if (Resolver.isMissingModuleError(err)) recompile = Resolver.installPackageFromError(err); return recompile; }, false); if (recompile) return compile(); if (err) global.shipp.logger.error(err); if (stats.compilation.errors.length) global.shipp.logger.error(stats.toString({ errorDetails: true })); return; } global.shipp.log("Bundled", self.path); if (emit) global.shipp.emit("route:refresh", { route: self.path }); }); }
[ "function", "compile", "(", "emit", ")", "{", "self", ".", "bundler", ".", "run", "(", "function", "(", "err", ",", "stats", ")", "{", "// Error handling", "if", "(", "err", "||", "stats", ".", "compilation", ".", "errors", ".", "length", ")", "{", "// Over time we expect webpack's resolution system to change. We choose to attempt", "// package installations by catching errors so as to maximize forward-compability.", "// Should the error reporting format change, we will need to update our resolution system.", "var", "errors", "=", "stats", ".", "toJson", "(", "{", "errorDetails", ":", "true", "}", ")", ".", "errors", ";", "var", "recompile", "=", "errors", ".", "reduce", "(", "function", "(", "recompile", ",", "err", ")", "{", "if", "(", "Resolver", ".", "isMissingModuleError", "(", "err", ")", ")", "recompile", "=", "Resolver", ".", "installPackageFromError", "(", "err", ")", ";", "return", "recompile", ";", "}", ",", "false", ")", ";", "if", "(", "recompile", ")", "return", "compile", "(", ")", ";", "if", "(", "err", ")", "global", ".", "shipp", ".", "logger", ".", "error", "(", "err", ")", ";", "if", "(", "stats", ".", "compilation", ".", "errors", ".", "length", ")", "global", ".", "shipp", ".", "logger", ".", "error", "(", "stats", ".", "toString", "(", "{", "errorDetails", ":", "true", "}", ")", ")", ";", "return", ";", "}", "global", ".", "shipp", ".", "log", "(", "\"Bundled\"", ",", "self", ".", "path", ")", ";", "if", "(", "emit", ")", "global", ".", "shipp", ".", "emit", "(", "\"route:refresh\"", ",", "{", "route", ":", "self", ".", "path", "}", ")", ";", "}", ")", ";", "}" ]
Wrap compilation in order to promisify and log bundling. We cannot use "promisify" since we require the "stats" object in our error callback.
[ "Wrap", "compilation", "in", "order", "to", "promisify", "and", "log", "bundling", ".", "We", "cannot", "use", "promisify", "since", "we", "require", "the", "stats", "object", "in", "our", "error", "callback", "." ]
7fdf1a96cc4e489f646f71bd3544b68f26ee16aa
https://github.com/shippjs/shipp-server/blob/7fdf1a96cc4e489f646f71bd3544b68f26ee16aa/lib/bundler.js#L84-L112
49,873
Eagerod/nodeunit-mock
lib/mock.js
mock
function mock(test, object, functionName, newFunction) { if (typeof object === "undefined") { throw Error("Attempting to mock function " + functionName + " of undefined.") } // Allow test writers to still let methods pass through, in case that's needed. var unmockedName = "unmocked_" + functionName; // Check to see if this object owns the property, or if it's possibly a class we're mocking. if (object.prototype && object.prototype[functionName] && !object.hasOwnProperty(functionName)) { object = object.prototype; } else if (!(functionName in object)) { throw new Error("No function found named (" + functionName + ")"); } object[unmockedName] = object[functionName]; // Actual function mock. object[functionName] = function() { ++object[functionName].callCount; var args = Array.prototype.slice.call(arguments); object[functionName].callArguments.push(args); if (newFunction) { return newFunction.apply(this, args); } else if (newFunction === undefined) { // if null, don't call anything. return object[unmockedName].apply(this, args); } }; object[functionName].callCount = 0; object[functionName].callArguments = []; // Clean up in test.done() var oldDone = test.done; test.done = function() { object[functionName] = object[unmockedName]; delete object[unmockedName]; oldDone.apply(this, Array.prototype.slice.call(arguments)); }; return object[functionName]; }
javascript
function mock(test, object, functionName, newFunction) { if (typeof object === "undefined") { throw Error("Attempting to mock function " + functionName + " of undefined.") } // Allow test writers to still let methods pass through, in case that's needed. var unmockedName = "unmocked_" + functionName; // Check to see if this object owns the property, or if it's possibly a class we're mocking. if (object.prototype && object.prototype[functionName] && !object.hasOwnProperty(functionName)) { object = object.prototype; } else if (!(functionName in object)) { throw new Error("No function found named (" + functionName + ")"); } object[unmockedName] = object[functionName]; // Actual function mock. object[functionName] = function() { ++object[functionName].callCount; var args = Array.prototype.slice.call(arguments); object[functionName].callArguments.push(args); if (newFunction) { return newFunction.apply(this, args); } else if (newFunction === undefined) { // if null, don't call anything. return object[unmockedName].apply(this, args); } }; object[functionName].callCount = 0; object[functionName].callArguments = []; // Clean up in test.done() var oldDone = test.done; test.done = function() { object[functionName] = object[unmockedName]; delete object[unmockedName]; oldDone.apply(this, Array.prototype.slice.call(arguments)); }; return object[functionName]; }
[ "function", "mock", "(", "test", ",", "object", ",", "functionName", ",", "newFunction", ")", "{", "if", "(", "typeof", "object", "===", "\"undefined\"", ")", "{", "throw", "Error", "(", "\"Attempting to mock function \"", "+", "functionName", "+", "\" of undefined.\"", ")", "}", "// Allow test writers to still let methods pass through, in case that's needed.", "var", "unmockedName", "=", "\"unmocked_\"", "+", "functionName", ";", "// Check to see if this object owns the property, or if it's possibly a class we're mocking.", "if", "(", "object", ".", "prototype", "&&", "object", ".", "prototype", "[", "functionName", "]", "&&", "!", "object", ".", "hasOwnProperty", "(", "functionName", ")", ")", "{", "object", "=", "object", ".", "prototype", ";", "}", "else", "if", "(", "!", "(", "functionName", "in", "object", ")", ")", "{", "throw", "new", "Error", "(", "\"No function found named (\"", "+", "functionName", "+", "\")\"", ")", ";", "}", "object", "[", "unmockedName", "]", "=", "object", "[", "functionName", "]", ";", "// Actual function mock.", "object", "[", "functionName", "]", "=", "function", "(", ")", "{", "++", "object", "[", "functionName", "]", ".", "callCount", ";", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "object", "[", "functionName", "]", ".", "callArguments", ".", "push", "(", "args", ")", ";", "if", "(", "newFunction", ")", "{", "return", "newFunction", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "else", "if", "(", "newFunction", "===", "undefined", ")", "{", "// if null, don't call anything.", "return", "object", "[", "unmockedName", "]", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "}", ";", "object", "[", "functionName", "]", ".", "callCount", "=", "0", ";", "object", "[", "functionName", "]", ".", "callArguments", "=", "[", "]", ";", "// Clean up in test.done()", "var", "oldDone", "=", "test", ".", "done", ";", "test", ".", "done", "=", "function", "(", ")", "{", "object", "[", "functionName", "]", "=", "object", "[", "unmockedName", "]", ";", "delete", "object", "[", "unmockedName", "]", ";", "oldDone", ".", "apply", "(", "this", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ")", ";", "}", ";", "return", "object", "[", "functionName", "]", ";", "}" ]
Sets up a mocked function on the provided object that allows you to test things like the number of calls that were made on a function and the parameters that came into it. Should typically be used to prevent outgoing network calls, so that tests can be run in isolation without affecting any services.
[ "Sets", "up", "a", "mocked", "function", "on", "the", "provided", "object", "that", "allows", "you", "to", "test", "things", "like", "the", "number", "of", "calls", "that", "were", "made", "on", "a", "function", "and", "the", "parameters", "that", "came", "into", "it", ".", "Should", "typically", "be", "used", "to", "prevent", "outgoing", "network", "calls", "so", "that", "tests", "can", "be", "run", "in", "isolation", "without", "affecting", "any", "services", "." ]
598282fc8b6218f8eefc3b247e476ab0543c1cd8
https://github.com/Eagerod/nodeunit-mock/blob/598282fc8b6218f8eefc3b247e476ab0543c1cd8/lib/mock.js#L10-L51
49,874
Layer3DLab/heimdallr-validator
lib/heimdallr-validator.js
validUUID
function validUUID(uuid) { // xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is a hexadecimal digit and // y is 8,9, A, or B var uuidRegex = /^[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12}$/i, result; result = uuidRegex.exec(uuid); return result !== null; }
javascript
function validUUID(uuid) { // xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is a hexadecimal digit and // y is 8,9, A, or B var uuidRegex = /^[0-9a-f]{8}\-[0-9a-f]{4}\-4[0-9a-f]{3}\-[89ab][0-9a-f]{3}\-[0-9a-f]{12}$/i, result; result = uuidRegex.exec(uuid); return result !== null; }
[ "function", "validUUID", "(", "uuid", ")", "{", "// xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is a hexadecimal digit and", "// y is 8,9, A, or B", "var", "uuidRegex", "=", "/", "^[0-9a-f]{8}\\-[0-9a-f]{4}\\-4[0-9a-f]{3}\\-[89ab][0-9a-f]{3}\\-[0-9a-f]{12}$", "/", "i", ",", "result", ";", "result", "=", "uuidRegex", ".", "exec", "(", "uuid", ")", ";", "return", "result", "!==", "null", ";", "}" ]
Verifies that the input string follows the RFC 4122 v4 UUID standard. @arg {string} uuid - The UUID to validate. @return {boolean} True if <tt>uuid</tt> is a valid v4 UUID.
[ "Verifies", "that", "the", "input", "string", "follows", "the", "RFC", "4122", "v4", "UUID", "standard", "." ]
fa9cbc332c10af836eba461a2f965267a8064e0a
https://github.com/Layer3DLab/heimdallr-validator/blob/fa9cbc332c10af836eba461a2f965267a8064e0a/lib/heimdallr-validator.js#L50-L59
49,875
Layer3DLab/heimdallr-validator
lib/heimdallr-validator.js
validTimestamp
function validTimestamp(timestamp) { // ^year-month-day(Thour:min:secms?timezone)?$ var year = /((?:[1-9][0-9]*)?[0-9]{4})/, month = /(1[0-2]|0[1-9])/, day = /(3[01]|0[1-9]|[12][0-9])/, hour = /(2[0-3]|[01][0-9])/, minute = /([0-5][0-9])/, second = /([0-5][0-9])/, ms = /(\.[0-9]+)/, timezone = /(Z|[+\-](?:2[0-3]|[01][0-9]):[0-5][0-9])/, date = [year.source, month.source, day.source].join('-'), time = [hour.source, minute.source, second.source].join(':'), timestampRegex, result; timestampRegex = new RegExp( '^' + date + '(T' + time + ms.source + '?' + timezone.source + ')?$' ); result = timestampRegex.exec(timestamp); return result !== null; }
javascript
function validTimestamp(timestamp) { // ^year-month-day(Thour:min:secms?timezone)?$ var year = /((?:[1-9][0-9]*)?[0-9]{4})/, month = /(1[0-2]|0[1-9])/, day = /(3[01]|0[1-9]|[12][0-9])/, hour = /(2[0-3]|[01][0-9])/, minute = /([0-5][0-9])/, second = /([0-5][0-9])/, ms = /(\.[0-9]+)/, timezone = /(Z|[+\-](?:2[0-3]|[01][0-9]):[0-5][0-9])/, date = [year.source, month.source, day.source].join('-'), time = [hour.source, minute.source, second.source].join(':'), timestampRegex, result; timestampRegex = new RegExp( '^' + date + '(T' + time + ms.source + '?' + timezone.source + ')?$' ); result = timestampRegex.exec(timestamp); return result !== null; }
[ "function", "validTimestamp", "(", "timestamp", ")", "{", "// ^year-month-day(Thour:min:secms?timezone)?$", "var", "year", "=", "/", "((?:[1-9][0-9]*)?[0-9]{4})", "/", ",", "month", "=", "/", "(1[0-2]|0[1-9])", "/", ",", "day", "=", "/", "(3[01]|0[1-9]|[12][0-9])", "/", ",", "hour", "=", "/", "(2[0-3]|[01][0-9])", "/", ",", "minute", "=", "/", "([0-5][0-9])", "/", ",", "second", "=", "/", "([0-5][0-9])", "/", ",", "ms", "=", "/", "(\\.[0-9]+)", "/", ",", "timezone", "=", "/", "(Z|[+\\-](?:2[0-3]|[01][0-9]):[0-5][0-9])", "/", ",", "date", "=", "[", "year", ".", "source", ",", "month", ".", "source", ",", "day", ".", "source", "]", ".", "join", "(", "'-'", ")", ",", "time", "=", "[", "hour", ".", "source", ",", "minute", ".", "source", ",", "second", ".", "source", "]", ".", "join", "(", "':'", ")", ",", "timestampRegex", ",", "result", ";", "timestampRegex", "=", "new", "RegExp", "(", "'^'", "+", "date", "+", "'(T'", "+", "time", "+", "ms", ".", "source", "+", "'?'", "+", "timezone", ".", "source", "+", "')?$'", ")", ";", "result", "=", "timestampRegex", ".", "exec", "(", "timestamp", ")", ";", "return", "result", "!==", "null", ";", "}" ]
Verifies that the input string follows the ISO 8601 standard. @arg {string} timestamp - The timestamp to validate. @return {boolean} True if <tt>timestamp</tt> is a valid ISO 8601 string.
[ "Verifies", "that", "the", "input", "string", "follows", "the", "ISO", "8601", "standard", "." ]
fa9cbc332c10af836eba461a2f965267a8064e0a
https://github.com/Layer3DLab/heimdallr-validator/blob/fa9cbc332c10af836eba461a2f965267a8064e0a/lib/heimdallr-validator.js#L67-L89
49,876
Layer3DLab/heimdallr-validator
lib/heimdallr-validator.js
validatePacket
function validatePacket(type, packet, fn) { debug('Type:', type); debug('Packet:', packet); if (!tv4.validate(packet, defaultSchemas[type])) { return fn(tv4.error); } if (packet.hasOwnProperty('provider') && !validUUID(packet.provider)) { return fn(new Error('`provider` must be a valid UUID')); } if (packet.hasOwnProperty('t') && !validTimestamp(packet.t)) { return fn(new Error('`t` must ba an ISO 8601 timestamp')); } return fn(null, true); }
javascript
function validatePacket(type, packet, fn) { debug('Type:', type); debug('Packet:', packet); if (!tv4.validate(packet, defaultSchemas[type])) { return fn(tv4.error); } if (packet.hasOwnProperty('provider') && !validUUID(packet.provider)) { return fn(new Error('`provider` must be a valid UUID')); } if (packet.hasOwnProperty('t') && !validTimestamp(packet.t)) { return fn(new Error('`t` must ba an ISO 8601 timestamp')); } return fn(null, true); }
[ "function", "validatePacket", "(", "type", ",", "packet", ",", "fn", ")", "{", "debug", "(", "'Type:'", ",", "type", ")", ";", "debug", "(", "'Packet:'", ",", "packet", ")", ";", "if", "(", "!", "tv4", ".", "validate", "(", "packet", ",", "defaultSchemas", "[", "type", "]", ")", ")", "{", "return", "fn", "(", "tv4", ".", "error", ")", ";", "}", "if", "(", "packet", ".", "hasOwnProperty", "(", "'provider'", ")", "&&", "!", "validUUID", "(", "packet", ".", "provider", ")", ")", "{", "return", "fn", "(", "new", "Error", "(", "'`provider` must be a valid UUID'", ")", ")", ";", "}", "if", "(", "packet", ".", "hasOwnProperty", "(", "'t'", ")", "&&", "!", "validTimestamp", "(", "packet", ".", "t", ")", ")", "{", "return", "fn", "(", "new", "Error", "(", "'`t` must ba an ISO 8601 timestamp'", ")", ")", ";", "}", "return", "fn", "(", "null", ",", "true", ")", ";", "}" ]
Verifies that the packet conforms to the correct structure for the given type. It first checks if the packet violates the schema for the type then if there is a provider field and it is not a valid UUID then if there is a t field and it is not a valid ISO 8601 timestamp. @arg {string} type - The type of Heimdallr packet. Must be 'event', 'sensor', or 'control'. @arg {object} packet - The packet to validate. @arg {function} fn - Node-style callback that will be passed an error as the first argument if the packet is invalid.
[ "Verifies", "that", "the", "packet", "conforms", "to", "the", "correct", "structure", "for", "the", "given", "type", ".", "It", "first", "checks", "if", "the", "packet", "violates", "the", "schema", "for", "the", "type", "then", "if", "there", "is", "a", "provider", "field", "and", "it", "is", "not", "a", "valid", "UUID", "then", "if", "there", "is", "a", "t", "field", "and", "it", "is", "not", "a", "valid", "ISO", "8601", "timestamp", "." ]
fa9cbc332c10af836eba461a2f965267a8064e0a
https://github.com/Layer3DLab/heimdallr-validator/blob/fa9cbc332c10af836eba461a2f965267a8064e0a/lib/heimdallr-validator.js#L104-L121
49,877
Layer3DLab/heimdallr-validator
lib/heimdallr-validator.js
validateData
function validateData(data, schema, fn) { debug('Schema:', schema); debug('Data:', data); if (!tv4.validate(data, schema)) { return fn(tv4.error); } return fn(null, true); }
javascript
function validateData(data, schema, fn) { debug('Schema:', schema); debug('Data:', data); if (!tv4.validate(data, schema)) { return fn(tv4.error); } return fn(null, true); }
[ "function", "validateData", "(", "data", ",", "schema", ",", "fn", ")", "{", "debug", "(", "'Schema:'", ",", "schema", ")", ";", "debug", "(", "'Data:'", ",", "data", ")", ";", "if", "(", "!", "tv4", ".", "validate", "(", "data", ",", "schema", ")", ")", "{", "return", "fn", "(", "tv4", ".", "error", ")", ";", "}", "return", "fn", "(", "null", ",", "true", ")", ";", "}" ]
Verifies that the data conforms to the schema. @arg {} data - The data to validate. @arg {object} schema - Valid JSON schema. @arg {function} fn - Node-style callback that will be passed an error as the first argument if the packet is invalid.
[ "Verifies", "that", "the", "data", "conforms", "to", "the", "schema", "." ]
fa9cbc332c10af836eba461a2f965267a8064e0a
https://github.com/Layer3DLab/heimdallr-validator/blob/fa9cbc332c10af836eba461a2f965267a8064e0a/lib/heimdallr-validator.js#L131-L140
49,878
fin-hypergrid/client-module-wrapper
index.js
Wrapper
function Wrapper(manifest) { var header = manifest.header || '(function(require, module, exports) { // ${name}@${version}\n\n' + (manifest.isJSON ? 'module.exports = ' : ''); var footer = manifest.footer || (manifest.isJSON ? ';' : '') + '\n\n})(fin.Hypergrid.require, fin.Hypergrid.modules, fin.Hypergrid.modules.exports = {});\n' + 'fin.Hypergrid.modules.exports.\$\$VERSION = \'${version}\';\n' + 'fin.Hypergrid.modules[\'${name}\'] = fin.Hypergrid.modules.exports;\n' + 'delete fin.Hypergrid.modules.exports;\n\n'; this.header = merge(header); this.footer = merge(footer); function merge(s) { return s.replace(/\$\{(\w+)\}/g, function(match, p1) { if (!(p1 in manifest)) { throw new Error('Expected manifest.' + p1 +' to be defined.'); } return manifest[p1]; }); } }
javascript
function Wrapper(manifest) { var header = manifest.header || '(function(require, module, exports) { // ${name}@${version}\n\n' + (manifest.isJSON ? 'module.exports = ' : ''); var footer = manifest.footer || (manifest.isJSON ? ';' : '') + '\n\n})(fin.Hypergrid.require, fin.Hypergrid.modules, fin.Hypergrid.modules.exports = {});\n' + 'fin.Hypergrid.modules.exports.\$\$VERSION = \'${version}\';\n' + 'fin.Hypergrid.modules[\'${name}\'] = fin.Hypergrid.modules.exports;\n' + 'delete fin.Hypergrid.modules.exports;\n\n'; this.header = merge(header); this.footer = merge(footer); function merge(s) { return s.replace(/\$\{(\w+)\}/g, function(match, p1) { if (!(p1 in manifest)) { throw new Error('Expected manifest.' + p1 +' to be defined.'); } return manifest[p1]; }); } }
[ "function", "Wrapper", "(", "manifest", ")", "{", "var", "header", "=", "manifest", ".", "header", "||", "'(function(require, module, exports) { // ${name}@${version}\\n\\n'", "+", "(", "manifest", ".", "isJSON", "?", "'module.exports = '", ":", "''", ")", ";", "var", "footer", "=", "manifest", ".", "footer", "||", "(", "manifest", ".", "isJSON", "?", "';'", ":", "''", ")", "+", "'\\n\\n})(fin.Hypergrid.require, fin.Hypergrid.modules, fin.Hypergrid.modules.exports = {});\\n'", "+", "'fin.Hypergrid.modules.exports.\\$\\$VERSION = \\'${version}\\';\\n'", "+", "'fin.Hypergrid.modules[\\'${name}\\'] = fin.Hypergrid.modules.exports;\\n'", "+", "'delete fin.Hypergrid.modules.exports;\\n\\n'", ";", "this", ".", "header", "=", "merge", "(", "header", ")", ";", "this", ".", "footer", "=", "merge", "(", "footer", ")", ";", "function", "merge", "(", "s", ")", "{", "return", "s", ".", "replace", "(", "/", "\\$\\{(\\w+)\\}", "/", "g", ",", "function", "(", "match", ",", "p1", ")", "{", "if", "(", "!", "(", "p1", "in", "manifest", ")", ")", "{", "throw", "new", "Error", "(", "'Expected manifest.'", "+", "p1", "+", "' to be defined.'", ")", ";", "}", "return", "manifest", "[", "p1", "]", ";", "}", ")", ";", "}", "}" ]
Create wrapper strings. @param {object} manifest @param {string} manifest.name - module name @param {string} manifest.version - Merged into standard header and footer. @param {boolean} [manifest.isJSON] - If truthy, wraps contents in `module.exports=` and `;`. @param {string} [manifest.header] - Custom header (typically paired with a custom footer). @param {string} [manifest.footer] - Custom footer (typically paired with a custom header). @constructor
[ "Create", "wrapper", "strings", "." ]
961f2fe1d037803f1647fa1c5dd9774e71de14ee
https://github.com/fin-hypergrid/client-module-wrapper/blob/961f2fe1d037803f1647fa1c5dd9774e71de14ee/index.js#L11-L35
49,879
tilmanjusten/inventory-object
index.js
getDefaultOptions
function getDefaultOptions() { const resources = { classnames: { root: '', body: '' }, meta: [], scriptsFoot: { files: [], inline: [] }, scriptsHead: { files: [], inline: [] }, stylesHead: { files: [], inline: [] } }; return { indent: ' ', origin: '', resources: resources, wrap: {before: '', after: ''} } }
javascript
function getDefaultOptions() { const resources = { classnames: { root: '', body: '' }, meta: [], scriptsFoot: { files: [], inline: [] }, scriptsHead: { files: [], inline: [] }, stylesHead: { files: [], inline: [] } }; return { indent: ' ', origin: '', resources: resources, wrap: {before: '', after: ''} } }
[ "function", "getDefaultOptions", "(", ")", "{", "const", "resources", "=", "{", "classnames", ":", "{", "root", ":", "''", ",", "body", ":", "''", "}", ",", "meta", ":", "[", "]", ",", "scriptsFoot", ":", "{", "files", ":", "[", "]", ",", "inline", ":", "[", "]", "}", ",", "scriptsHead", ":", "{", "files", ":", "[", "]", ",", "inline", ":", "[", "]", "}", ",", "stylesHead", ":", "{", "files", ":", "[", "]", ",", "inline", ":", "[", "]", "}", "}", ";", "return", "{", "indent", ":", "' '", ",", "origin", ":", "''", ",", "resources", ":", "resources", ",", "wrap", ":", "{", "before", ":", "''", ",", "after", ":", "''", "}", "}", "}" ]
get default options, scope as function instead of "public" property @returns {{indent: string, origin: string, resources: {classnames: {root: string, body: string}, meta: Array, scriptsFoot: {files: Array, inline: Array}, scriptsHead: {files: Array, inline: Array}, stylesHead: {files: Array, inline: Array}}, wrap: {before: string, after: string}}}
[ "get", "default", "options", "scope", "as", "function", "instead", "of", "public", "property" ]
8c746d88d4f4e9631085e918fe003c73f05ae0dd
https://github.com/tilmanjusten/inventory-object/blob/8c746d88d4f4e9631085e918fe003c73f05ae0dd/index.js#L13-L40
49,880
tilmanjusten/inventory-object
index.js
raiseIndent
function raiseIndent(lines, offset) { offset = offset || ' '; return lines.map((line) => offset + line); }
javascript
function raiseIndent(lines, offset) { offset = offset || ' '; return lines.map((line) => offset + line); }
[ "function", "raiseIndent", "(", "lines", ",", "offset", ")", "{", "offset", "=", "offset", "||", "' '", ";", "return", "lines", ".", "map", "(", "(", "line", ")", "=>", "offset", "+", "line", ")", ";", "}" ]
raise offset in lines @param lines @param offset @returns {Array|*|{}}
[ "raise", "offset", "in", "lines" ]
8c746d88d4f4e9631085e918fe003c73f05ae0dd
https://github.com/tilmanjusten/inventory-object/blob/8c746d88d4f4e9631085e918fe003c73f05ae0dd/index.js#L82-L86
49,881
tilmanjusten/inventory-object
index.js
formalizeWrap
function formalizeWrap(wrap) { const result = {before: '', after: ''}; if ((typeof wrap === 'string' && wrap.length > 0) || typeof wrap === 'number') { result.before = result.after = wrap; } else if (Array.isArray(wrap) && wrap.length > 0) { result.before = [].slice.call(wrap, 0, 1)[0]; result.after = wrap.length > 1 ? [].slice.call(wrap, 1, 2)[0] : result.before; } else if (_.isPlainObject(wrap)) { let i = 0; // crappy method getting the value of the first and second item in object for (let el in wrap) { if (!wrap.hasOwnProperty(el)) { continue; } if (i < 2) { result.before = wrap[el]; } i++; } // set value of after to the value of before if after is empty result.after = result.after.length < 1 ? result.before : result.after; } return result; }
javascript
function formalizeWrap(wrap) { const result = {before: '', after: ''}; if ((typeof wrap === 'string' && wrap.length > 0) || typeof wrap === 'number') { result.before = result.after = wrap; } else if (Array.isArray(wrap) && wrap.length > 0) { result.before = [].slice.call(wrap, 0, 1)[0]; result.after = wrap.length > 1 ? [].slice.call(wrap, 1, 2)[0] : result.before; } else if (_.isPlainObject(wrap)) { let i = 0; // crappy method getting the value of the first and second item in object for (let el in wrap) { if (!wrap.hasOwnProperty(el)) { continue; } if (i < 2) { result.before = wrap[el]; } i++; } // set value of after to the value of before if after is empty result.after = result.after.length < 1 ? result.before : result.after; } return result; }
[ "function", "formalizeWrap", "(", "wrap", ")", "{", "const", "result", "=", "{", "before", ":", "''", ",", "after", ":", "''", "}", ";", "if", "(", "(", "typeof", "wrap", "===", "'string'", "&&", "wrap", ".", "length", ">", "0", ")", "||", "typeof", "wrap", "===", "'number'", ")", "{", "result", ".", "before", "=", "result", ".", "after", "=", "wrap", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "wrap", ")", "&&", "wrap", ".", "length", ">", "0", ")", "{", "result", ".", "before", "=", "[", "]", ".", "slice", ".", "call", "(", "wrap", ",", "0", ",", "1", ")", "[", "0", "]", ";", "result", ".", "after", "=", "wrap", ".", "length", ">", "1", "?", "[", "]", ".", "slice", ".", "call", "(", "wrap", ",", "1", ",", "2", ")", "[", "0", "]", ":", "result", ".", "before", ";", "}", "else", "if", "(", "_", ".", "isPlainObject", "(", "wrap", ")", ")", "{", "let", "i", "=", "0", ";", "// crappy method getting the value of the first and second item in object", "for", "(", "let", "el", "in", "wrap", ")", "{", "if", "(", "!", "wrap", ".", "hasOwnProperty", "(", "el", ")", ")", "{", "continue", ";", "}", "if", "(", "i", "<", "2", ")", "{", "result", ".", "before", "=", "wrap", "[", "el", "]", ";", "}", "i", "++", ";", "}", "// set value of after to the value of before if after is empty", "result", ".", "after", "=", "result", ".", "after", ".", "length", "<", "1", "?", "result", ".", "before", ":", "result", ".", "after", ";", "}", "return", "result", ";", "}" ]
Formalize any given value as wrap object @param wrap @returns {{before: '', after: ''}}
[ "Formalize", "any", "given", "value", "as", "wrap", "object" ]
8c746d88d4f4e9631085e918fe003c73f05ae0dd
https://github.com/tilmanjusten/inventory-object/blob/8c746d88d4f4e9631085e918fe003c73f05ae0dd/index.js#L94-L123
49,882
tilmanjusten/inventory-object
index.js
getBlockOptions
function getBlockOptions(annotation, defaults) { const optionValues = annotation.split(/\w+\:/) .map((item) => item.replace(/<!--\s?|\s?-->|^\s+|\s+$/, '')) .filter((item) => !!item.length); const optionKeys = annotation.match(/(\w+)\:/gi).map((item) => item.replace(/[^\w]/, '')); defaults = defaults || { wrap: {before: '', after: ''} }; const opts = {}; optionValues.forEach((v, i) => { const k = optionKeys[i]; if (typeof k !== 'string') { return; } // Treat option value as array if it has a colon // @todo: Allow escaped colons to be ignored // RegEx lookbehind negate does not work :( // Should be /(?<!\\):/ if (v.indexOf(':') > -1) { v = v.split(':'); } opts[k] = v; }); // Process options opts.wrap = formalizeWrap(opts.wrap || defaults.wrap); return opts; }
javascript
function getBlockOptions(annotation, defaults) { const optionValues = annotation.split(/\w+\:/) .map((item) => item.replace(/<!--\s?|\s?-->|^\s+|\s+$/, '')) .filter((item) => !!item.length); const optionKeys = annotation.match(/(\w+)\:/gi).map((item) => item.replace(/[^\w]/, '')); defaults = defaults || { wrap: {before: '', after: ''} }; const opts = {}; optionValues.forEach((v, i) => { const k = optionKeys[i]; if (typeof k !== 'string') { return; } // Treat option value as array if it has a colon // @todo: Allow escaped colons to be ignored // RegEx lookbehind negate does not work :( // Should be /(?<!\\):/ if (v.indexOf(':') > -1) { v = v.split(':'); } opts[k] = v; }); // Process options opts.wrap = formalizeWrap(opts.wrap || defaults.wrap); return opts; }
[ "function", "getBlockOptions", "(", "annotation", ",", "defaults", ")", "{", "const", "optionValues", "=", "annotation", ".", "split", "(", "/", "\\w+\\:", "/", ")", ".", "map", "(", "(", "item", ")", "=>", "item", ".", "replace", "(", "/", "<!--\\s?|\\s?-->|^\\s+|\\s+$", "/", ",", "''", ")", ")", ".", "filter", "(", "(", "item", ")", "=>", "!", "!", "item", ".", "length", ")", ";", "const", "optionKeys", "=", "annotation", ".", "match", "(", "/", "(\\w+)\\:", "/", "gi", ")", ".", "map", "(", "(", "item", ")", "=>", "item", ".", "replace", "(", "/", "[^\\w]", "/", ",", "''", ")", ")", ";", "defaults", "=", "defaults", "||", "{", "wrap", ":", "{", "before", ":", "''", ",", "after", ":", "''", "}", "}", ";", "const", "opts", "=", "{", "}", ";", "optionValues", ".", "forEach", "(", "(", "v", ",", "i", ")", "=>", "{", "const", "k", "=", "optionKeys", "[", "i", "]", ";", "if", "(", "typeof", "k", "!==", "'string'", ")", "{", "return", ";", "}", "// Treat option value as array if it has a colon", "// @todo: Allow escaped colons to be ignored", "// RegEx lookbehind negate does not work :(", "// Should be /(?<!\\\\):/", "if", "(", "v", ".", "indexOf", "(", "':'", ")", ">", "-", "1", ")", "{", "v", "=", "v", ".", "split", "(", "':'", ")", ";", "}", "opts", "[", "k", "]", "=", "v", ";", "}", ")", ";", "// Process options", "opts", ".", "wrap", "=", "formalizeWrap", "(", "opts", ".", "wrap", "||", "defaults", ".", "wrap", ")", ";", "return", "opts", ";", "}" ]
read options from annotation e.g.: <!-- extract:content/element.html wrap:<div class="wrapper-element">:</div> --> becomes: { extract: 'content/element.html', wrap: {before: '<div class="wrapper-element">', after: '</div>'} } @param annotation @param defaults @returns {{}}
[ "read", "options", "from", "annotation" ]
8c746d88d4f4e9631085e918fe003c73f05ae0dd
https://github.com/tilmanjusten/inventory-object/blob/8c746d88d4f4e9631085e918fe003c73f05ae0dd/index.js#L139-L173
49,883
stuartpb/endex
index.js
convertResponse
function convertResponse(response) { var results = {tables: [], indexes: []}; var i=0; var start=0; if (dbName) { results.db = response[0]; start++; i++; } while (i < start + tableNames.length) { tableName = tableNames[i-start]; results.tables[i-start]=response[i]; i++; } start = start + tableNames.length; if (tableNames.length > 0) { var j = 0; var indexNames = Object.keys(tables[tableNames[j]].indexOpts); var indexResults; indexResults = []; results.indexes[j] = indexResults; while (i < response.length) { indexResults[i-start] = response[i]; i++; while (i-start >= indexNames.length && i < response.length){ j++; indexNames = Object.keys(tables[tableNames[j]].indexOpts); indexResults = []; results.indexes[j] = indexResults; start = i; } } } return results; }
javascript
function convertResponse(response) { var results = {tables: [], indexes: []}; var i=0; var start=0; if (dbName) { results.db = response[0]; start++; i++; } while (i < start + tableNames.length) { tableName = tableNames[i-start]; results.tables[i-start]=response[i]; i++; } start = start + tableNames.length; if (tableNames.length > 0) { var j = 0; var indexNames = Object.keys(tables[tableNames[j]].indexOpts); var indexResults; indexResults = []; results.indexes[j] = indexResults; while (i < response.length) { indexResults[i-start] = response[i]; i++; while (i-start >= indexNames.length && i < response.length){ j++; indexNames = Object.keys(tables[tableNames[j]].indexOpts); indexResults = []; results.indexes[j] = indexResults; start = i; } } } return results; }
[ "function", "convertResponse", "(", "response", ")", "{", "var", "results", "=", "{", "tables", ":", "[", "]", ",", "indexes", ":", "[", "]", "}", ";", "var", "i", "=", "0", ";", "var", "start", "=", "0", ";", "if", "(", "dbName", ")", "{", "results", ".", "db", "=", "response", "[", "0", "]", ";", "start", "++", ";", "i", "++", ";", "}", "while", "(", "i", "<", "start", "+", "tableNames", ".", "length", ")", "{", "tableName", "=", "tableNames", "[", "i", "-", "start", "]", ";", "results", ".", "tables", "[", "i", "-", "start", "]", "=", "response", "[", "i", "]", ";", "i", "++", ";", "}", "start", "=", "start", "+", "tableNames", ".", "length", ";", "if", "(", "tableNames", ".", "length", ">", "0", ")", "{", "var", "j", "=", "0", ";", "var", "indexNames", "=", "Object", ".", "keys", "(", "tables", "[", "tableNames", "[", "j", "]", "]", ".", "indexOpts", ")", ";", "var", "indexResults", ";", "indexResults", "=", "[", "]", ";", "results", ".", "indexes", "[", "j", "]", "=", "indexResults", ";", "while", "(", "i", "<", "response", ".", "length", ")", "{", "indexResults", "[", "i", "-", "start", "]", "=", "response", "[", "i", "]", ";", "i", "++", ";", "while", "(", "i", "-", "start", ">=", "indexNames", ".", "length", "&&", "i", "<", "response", ".", "length", ")", "{", "j", "++", ";", "indexNames", "=", "Object", ".", "keys", "(", "tables", "[", "tableNames", "[", "j", "]", "]", ".", "indexOpts", ")", ";", "indexResults", "=", "[", "]", ";", "results", ".", "indexes", "[", "j", "]", "=", "indexResults", ";", "start", "=", "i", ";", "}", "}", "}", "return", "results", ";", "}" ]
Convert the expr response to something simpler
[ "Convert", "the", "expr", "response", "to", "something", "simpler" ]
ca5af19e2511d9461bd219e6c117b1206b1ae0f8
https://github.com/stuartpb/endex/blob/ca5af19e2511d9461bd219e6c117b1206b1ae0f8/index.js#L92-L126
49,884
SandJS/riak
lib/Client.js
delegate
function delegate(client, fn) { // Add this function to the current client // and wrap with a connection check client[fn] = function(...args) { let self = this; let p = null; if (sand.profiler && sand.profiler.enabled) { // Build the profiler request let req = `riak ${fn} `; if (args[0].bucketType) { req += `types/${args[0].bucketType} `; } if (args[0].bucket) { req += `bucket/${args[0].bucket} `; } if (args[0].indexName) { req += `search/${args[0].indexName} `; } if (args[0].q) { req += `query/${args[0].q.replace(/(\w+):\w+/ig, '$1:*')}` } p = sand.profiler.profile(req.trim()); } return new Promise(function(resolve, reject) { function returnResult(err, response, data) { p && p.stop(); if (err) { err = new Error(err); err.data = data; err.req = `${fn}: ${args[0]}`; sand.riak.error(`${err.message} ${fn}:`, ...args); return reject(err); } resolve(response); } client.client[fn](...args, returnResult); }).catch(sand.error); }; }
javascript
function delegate(client, fn) { // Add this function to the current client // and wrap with a connection check client[fn] = function(...args) { let self = this; let p = null; if (sand.profiler && sand.profiler.enabled) { // Build the profiler request let req = `riak ${fn} `; if (args[0].bucketType) { req += `types/${args[0].bucketType} `; } if (args[0].bucket) { req += `bucket/${args[0].bucket} `; } if (args[0].indexName) { req += `search/${args[0].indexName} `; } if (args[0].q) { req += `query/${args[0].q.replace(/(\w+):\w+/ig, '$1:*')}` } p = sand.profiler.profile(req.trim()); } return new Promise(function(resolve, reject) { function returnResult(err, response, data) { p && p.stop(); if (err) { err = new Error(err); err.data = data; err.req = `${fn}: ${args[0]}`; sand.riak.error(`${err.message} ${fn}:`, ...args); return reject(err); } resolve(response); } client.client[fn](...args, returnResult); }).catch(sand.error); }; }
[ "function", "delegate", "(", "client", ",", "fn", ")", "{", "// Add this function to the current client", "// and wrap with a connection check", "client", "[", "fn", "]", "=", "function", "(", "...", "args", ")", "{", "let", "self", "=", "this", ";", "let", "p", "=", "null", ";", "if", "(", "sand", ".", "profiler", "&&", "sand", ".", "profiler", ".", "enabled", ")", "{", "// Build the profiler request", "let", "req", "=", "`", "${", "fn", "}", "`", ";", "if", "(", "args", "[", "0", "]", ".", "bucketType", ")", "{", "req", "+=", "`", "${", "args", "[", "0", "]", ".", "bucketType", "}", "`", ";", "}", "if", "(", "args", "[", "0", "]", ".", "bucket", ")", "{", "req", "+=", "`", "${", "args", "[", "0", "]", ".", "bucket", "}", "`", ";", "}", "if", "(", "args", "[", "0", "]", ".", "indexName", ")", "{", "req", "+=", "`", "${", "args", "[", "0", "]", ".", "indexName", "}", "`", ";", "}", "if", "(", "args", "[", "0", "]", ".", "q", ")", "{", "req", "+=", "`", "${", "args", "[", "0", "]", ".", "q", ".", "replace", "(", "/", "(\\w+):\\w+", "/", "ig", ",", "'$1:*'", ")", "}", "`", "}", "p", "=", "sand", ".", "profiler", ".", "profile", "(", "req", ".", "trim", "(", ")", ")", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "function", "returnResult", "(", "err", ",", "response", ",", "data", ")", "{", "p", "&&", "p", ".", "stop", "(", ")", ";", "if", "(", "err", ")", "{", "err", "=", "new", "Error", "(", "err", ")", ";", "err", ".", "data", "=", "data", ";", "err", ".", "req", "=", "`", "${", "fn", "}", "${", "args", "[", "0", "]", "}", "`", ";", "sand", ".", "riak", ".", "error", "(", "`", "${", "err", ".", "message", "}", "${", "fn", "}", "`", ",", "...", "args", ")", ";", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "response", ")", ";", "}", "client", ".", "client", "[", "fn", "]", "(", "...", "args", ",", "returnResult", ")", ";", "}", ")", ".", "catch", "(", "sand", ".", "error", ")", ";", "}", ";", "}" ]
Delegate the function to the client, but add a connection check first @param {Client} client - the sand-riak client @param {string} fn - function name
[ "Delegate", "the", "function", "to", "the", "client", "but", "add", "a", "connection", "check", "first" ]
9a45ce3bebb91a1bd85ff89f56574dd7ac0876ab
https://github.com/SandJS/riak/blob/9a45ce3bebb91a1bd85ff89f56574dd7ac0876ab/lib/Client.js#L84-L130
49,885
wallacegibbon/newredis-node
lib/conn.js
adjustCommandArgument
function adjustCommandArgument(argObj) { if (typeof argObj === "number") { return argObj.toString() } else if (typeof argObj === "string") { return argObj } else if (!argObj) { return "" } else { throw new RedisCommandError(`Argument: ${inspect(argObj)}`) } }
javascript
function adjustCommandArgument(argObj) { if (typeof argObj === "number") { return argObj.toString() } else if (typeof argObj === "string") { return argObj } else if (!argObj) { return "" } else { throw new RedisCommandError(`Argument: ${inspect(argObj)}`) } }
[ "function", "adjustCommandArgument", "(", "argObj", ")", "{", "if", "(", "typeof", "argObj", "===", "\"number\"", ")", "{", "return", "argObj", ".", "toString", "(", ")", "}", "else", "if", "(", "typeof", "argObj", "===", "\"string\"", ")", "{", "return", "argObj", "}", "else", "if", "(", "!", "argObj", ")", "{", "return", "\"\"", "}", "else", "{", "throw", "new", "RedisCommandError", "(", "`", "${", "inspect", "(", "argObj", ")", "}", "`", ")", "}", "}" ]
Only strings and numbers are valid redis arguments, other type of data will be treated as error.
[ "Only", "strings", "and", "numbers", "are", "valid", "redis", "arguments", "other", "type", "of", "data", "will", "be", "treated", "as", "error", "." ]
c4d6ae78bc80cfd545ab8ff6606e8c88fc6dd24b
https://github.com/wallacegibbon/newredis-node/blob/c4d6ae78bc80cfd545ab8ff6606e8c88fc6dd24b/lib/conn.js#L175-L185
49,886
espadrine/travel-scrapper
main.js
combineSearch
function combineSearch(tp1, tp2) { return tp1.map(travelPlan => { let arrival = new Date(travelPlan.legs[travelPlan.legs.length - 1].arrival) let bestWaitTime = Infinity let bestTravelPlan2 = tp2[0] // Find the most appropriate corresponding second travel plan. for (let i = 0; i < tp2.length; i++) { let travelPlan2 = tp2[i] let departure = new Date(travelPlan2.legs[0].departure) let waitTime = departure - arrival if (waitTime > 0) { if (waitTime < bestWaitTime) { bestWaitTime = waitTime bestTravelPlan2 = travelPlan2 } } } return { fares: combineFares(travelPlan.fares, bestTravelPlan2.fares), legs: travelPlan.legs.slice().concat(bestTravelPlan2.legs.slice()), } }) }
javascript
function combineSearch(tp1, tp2) { return tp1.map(travelPlan => { let arrival = new Date(travelPlan.legs[travelPlan.legs.length - 1].arrival) let bestWaitTime = Infinity let bestTravelPlan2 = tp2[0] // Find the most appropriate corresponding second travel plan. for (let i = 0; i < tp2.length; i++) { let travelPlan2 = tp2[i] let departure = new Date(travelPlan2.legs[0].departure) let waitTime = departure - arrival if (waitTime > 0) { if (waitTime < bestWaitTime) { bestWaitTime = waitTime bestTravelPlan2 = travelPlan2 } } } return { fares: combineFares(travelPlan.fares, bestTravelPlan2.fares), legs: travelPlan.legs.slice().concat(bestTravelPlan2.legs.slice()), } }) }
[ "function", "combineSearch", "(", "tp1", ",", "tp2", ")", "{", "return", "tp1", ".", "map", "(", "travelPlan", "=>", "{", "let", "arrival", "=", "new", "Date", "(", "travelPlan", ".", "legs", "[", "travelPlan", ".", "legs", ".", "length", "-", "1", "]", ".", "arrival", ")", "let", "bestWaitTime", "=", "Infinity", "let", "bestTravelPlan2", "=", "tp2", "[", "0", "]", "// Find the most appropriate corresponding second travel plan.", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tp2", ".", "length", ";", "i", "++", ")", "{", "let", "travelPlan2", "=", "tp2", "[", "i", "]", "let", "departure", "=", "new", "Date", "(", "travelPlan2", ".", "legs", "[", "0", "]", ".", "departure", ")", "let", "waitTime", "=", "departure", "-", "arrival", "if", "(", "waitTime", ">", "0", ")", "{", "if", "(", "waitTime", "<", "bestWaitTime", ")", "{", "bestWaitTime", "=", "waitTime", "bestTravelPlan2", "=", "travelPlan2", "}", "}", "}", "return", "{", "fares", ":", "combineFares", "(", "travelPlan", ".", "fares", ",", "bestTravelPlan2", ".", "fares", ")", ",", "legs", ":", "travelPlan", ".", "legs", ".", "slice", "(", ")", ".", "concat", "(", "bestTravelPlan2", ".", "legs", ".", "slice", "(", ")", ")", ",", "}", "}", ")", "}" ]
Take two travel plans, combine them so that one is the first part of the journey of the other. We assume that the last station of the first travel plans is the first station of the second travel plans.
[ "Take", "two", "travel", "plans", "combine", "them", "so", "that", "one", "is", "the", "first", "part", "of", "the", "journey", "of", "the", "other", ".", "We", "assume", "that", "the", "last", "station", "of", "the", "first", "travel", "plans", "is", "the", "first", "station", "of", "the", "second", "travel", "plans", "." ]
5ed137e967a8a2de67f988922ec66222f464ea96
https://github.com/espadrine/travel-scrapper/blob/5ed137e967a8a2de67f988922ec66222f464ea96/main.js#L55-L77
49,887
PeerioTechnologies/peerio-updater
size.js
verifySize
function verifySize(correctSize, filepath) { return calculateSize(filepath).then(size => { if (size !== correctSize) { throw new Error(`Incorrect file size: expected ${correctSize}, got ${size}`); } return true; }); }
javascript
function verifySize(correctSize, filepath) { return calculateSize(filepath).then(size => { if (size !== correctSize) { throw new Error(`Incorrect file size: expected ${correctSize}, got ${size}`); } return true; }); }
[ "function", "verifySize", "(", "correctSize", ",", "filepath", ")", "{", "return", "calculateSize", "(", "filepath", ")", ".", "then", "(", "size", "=>", "{", "if", "(", "size", "!==", "correctSize", ")", "{", "throw", "new", "Error", "(", "`", "${", "correctSize", "}", "${", "size", "}", "`", ")", ";", "}", "return", "true", ";", "}", ")", ";", "}" ]
Calculates file size and compares it to the provided one. Returns a promise which rejects if the size is incorrect, otherwise resolves to true. @param {number} correctSize expected file size @param {string} filepath file path @returns {Promise<boolean>}
[ "Calculates", "file", "size", "and", "compares", "it", "to", "the", "provided", "one", "." ]
9d6fedeec727f16a31653e4bbd4efe164e0957cb
https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/size.js#L15-L22
49,888
PeerioTechnologies/peerio-updater
size.js
calculateSize
function calculateSize(filepath) { return new Promise((fulfill, reject) => { fs.stat(filepath, (err, stats) => { if (err) return reject(err); fulfill(stats.size); }); }); }
javascript
function calculateSize(filepath) { return new Promise((fulfill, reject) => { fs.stat(filepath, (err, stats) => { if (err) return reject(err); fulfill(stats.size); }); }); }
[ "function", "calculateSize", "(", "filepath", ")", "{", "return", "new", "Promise", "(", "(", "fulfill", ",", "reject", ")", "=>", "{", "fs", ".", "stat", "(", "filepath", ",", "(", "err", ",", "stats", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "fulfill", "(", "stats", ".", "size", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Calculates size of the file at the given path. @param {string} filepath @returns Promise<number> hex encoded hash
[ "Calculates", "size", "of", "the", "file", "at", "the", "given", "path", "." ]
9d6fedeec727f16a31653e4bbd4efe164e0957cb
https://github.com/PeerioTechnologies/peerio-updater/blob/9d6fedeec727f16a31653e4bbd4efe164e0957cb/size.js#L30-L37
49,889
pattern-library/pattern-library-utilities
lib/gulp-tasks/file-glob-inject.js
function () { 'use strict'; var options = { config: { relative: true }, src: './index.html', // source file with types of files to be glob-injected files: [// relative paths to files to be globbed '!./node_modules/**/*', '!./_gulp/*', './**/*' ], dest: './', // destination directory where we'll write our ammended source file taskName: 'file-glob-inject', // default task name dependencies: [] // gulp tasks which should be run before this task }; return options; }
javascript
function () { 'use strict'; var options = { config: { relative: true }, src: './index.html', // source file with types of files to be glob-injected files: [// relative paths to files to be globbed '!./node_modules/**/*', '!./_gulp/*', './**/*' ], dest: './', // destination directory where we'll write our ammended source file taskName: 'file-glob-inject', // default task name dependencies: [] // gulp tasks which should be run before this task }; return options; }
[ "function", "(", ")", "{", "'use strict'", ";", "var", "options", "=", "{", "config", ":", "{", "relative", ":", "true", "}", ",", "src", ":", "'./index.html'", ",", "// source file with types of files to be glob-injected", "files", ":", "[", "// relative paths to files to be globbed", "'!./node_modules/**/*'", ",", "'!./_gulp/*'", ",", "'./**/*'", "]", ",", "dest", ":", "'./'", ",", "// destination directory where we'll write our ammended source file", "taskName", ":", "'file-glob-inject'", ",", "// default task name", "dependencies", ":", "[", "]", "// gulp tasks which should be run before this task", "}", ";", "return", "options", ";", "}" ]
Function to get default options for an implementation of gulp-inject @return {Object} options an object of options
[ "Function", "to", "get", "default", "options", "for", "an", "implementation", "of", "gulp", "-", "inject" ]
a0198f7bb698eb5b859576b11afa3d0ebd3e5911
https://github.com/pattern-library/pattern-library-utilities/blob/a0198f7bb698eb5b859576b11afa3d0ebd3e5911/lib/gulp-tasks/file-glob-inject.js#L35-L54
49,890
pattern-library/pattern-library-utilities
lib/gulp-tasks/file-glob-inject.js
function () { 'use strict'; var options = { config: { starttag: '// inject:{{ext}}', endtag: '// endinject', addRootSlash: false, relative: true, transform: function (filepath) { return '@import \'' + filepath + '\';'; } }, src: './styles/style.scss', files: [// Application scss files '!./node_modules/**/*', '!./styles/style.scss', './**/*.scss' ], dest: './styles', taskName: 'scss-glob-inject', // default task name dependencies: [] }; return options; }
javascript
function () { 'use strict'; var options = { config: { starttag: '// inject:{{ext}}', endtag: '// endinject', addRootSlash: false, relative: true, transform: function (filepath) { return '@import \'' + filepath + '\';'; } }, src: './styles/style.scss', files: [// Application scss files '!./node_modules/**/*', '!./styles/style.scss', './**/*.scss' ], dest: './styles', taskName: 'scss-glob-inject', // default task name dependencies: [] }; return options; }
[ "function", "(", ")", "{", "'use strict'", ";", "var", "options", "=", "{", "config", ":", "{", "starttag", ":", "'// inject:{{ext}}'", ",", "endtag", ":", "'// endinject'", ",", "addRootSlash", ":", "false", ",", "relative", ":", "true", ",", "transform", ":", "function", "(", "filepath", ")", "{", "return", "'@import \\''", "+", "filepath", "+", "'\\';'", ";", "}", "}", ",", "src", ":", "'./styles/style.scss'", ",", "files", ":", "[", "// Application scss files", "'!./node_modules/**/*'", ",", "'!./styles/style.scss'", ",", "'./**/*.scss'", "]", ",", "dest", ":", "'./styles'", ",", "taskName", ":", "'scss-glob-inject'", ",", "// default task name", "dependencies", ":", "[", "]", "}", ";", "return", "options", ";", "}" ]
Function to get default options for globbing scss files with gulp-inject @return {Object} options an object of default options
[ "Function", "to", "get", "default", "options", "for", "globbing", "scss", "files", "with", "gulp", "-", "inject" ]
a0198f7bb698eb5b859576b11afa3d0ebd3e5911
https://github.com/pattern-library/pattern-library-utilities/blob/a0198f7bb698eb5b859576b11afa3d0ebd3e5911/lib/gulp-tasks/file-glob-inject.js#L81-L105
49,891
iLib-js/ilib-webpack-plugin
ilib-webpack-plugin.js
toArray
function toArray(set) { var ret = []; set.forEach(function(element) { ret.push(element); }); return ret; }
javascript
function toArray(set) { var ret = []; set.forEach(function(element) { ret.push(element); }); return ret; }
[ "function", "toArray", "(", "set", ")", "{", "var", "ret", "=", "[", "]", ";", "set", ".", "forEach", "(", "function", "(", "element", ")", "{", "ret", ".", "push", "(", "element", ")", ";", "}", ")", ";", "return", "ret", ";", "}" ]
Convert a set to an array. @param {Set} set to convert @returns an array with the contents of the set
[ "Convert", "a", "set", "to", "an", "array", "." ]
ba31ce1175bbf36c139c0fbde1c5bbe6674c941c
https://github.com/iLib-js/ilib-webpack-plugin/blob/ba31ce1175bbf36c139c0fbde1c5bbe6674c941c/ilib-webpack-plugin.js#L73-L79
49,892
lyfeyaj/ovt
lib/types/alternatives.js
function() { let schemas = utils.parseArg(arguments); schemas.forEach(function(schema) { utils.assert(schema.isOvt, `${utils.obj2Str(schema)} is not a valid ovt schema`); }); }
javascript
function() { let schemas = utils.parseArg(arguments); schemas.forEach(function(schema) { utils.assert(schema.isOvt, `${utils.obj2Str(schema)} is not a valid ovt schema`); }); }
[ "function", "(", ")", "{", "let", "schemas", "=", "utils", ".", "parseArg", "(", "arguments", ")", ";", "schemas", ".", "forEach", "(", "function", "(", "schema", ")", "{", "utils", ".", "assert", "(", "schema", ".", "isOvt", ",", "`", "${", "utils", ".", "obj2Str", "(", "schema", ")", "}", "`", ")", ";", "}", ")", ";", "}" ]
Using chainingBehaviour to check whether schemas are valid
[ "Using", "chainingBehaviour", "to", "check", "whether", "schemas", "are", "valid" ]
ebd50a3531f1504cd356c869dda91200ad2f6539
https://github.com/lyfeyaj/ovt/blob/ebd50a3531f1504cd356c869dda91200ad2f6539/lib/types/alternatives.js#L49-L54
49,893
artdecocode/idio
build/index.js
_default
async function _default(config, routesConfig) { const res = await (0, _startApp.default)(config); const { url, app, router, middleware, connect } = res; let methods; if (routesConfig) { methods = await (0, _routes.initRoutes2)(routesConfig, middleware, router); const routes = router.routes(); app.use(routes); } return { url, app, connect, methods, router }; }
javascript
async function _default(config, routesConfig) { const res = await (0, _startApp.default)(config); const { url, app, router, middleware, connect } = res; let methods; if (routesConfig) { methods = await (0, _routes.initRoutes2)(routesConfig, middleware, router); const routes = router.routes(); app.use(routes); } return { url, app, connect, methods, router }; }
[ "async", "function", "_default", "(", "config", ",", "routesConfig", ")", "{", "const", "res", "=", "await", "(", "0", ",", "_startApp", ".", "default", ")", "(", "config", ")", ";", "const", "{", "url", ",", "app", ",", "router", ",", "middleware", ",", "connect", "}", "=", "res", ";", "let", "methods", ";", "if", "(", "routesConfig", ")", "{", "methods", "=", "await", "(", "0", ",", "_routes", ".", "initRoutes2", ")", "(", "routesConfig", ",", "middleware", ",", "router", ")", ";", "const", "routes", "=", "router", ".", "routes", "(", ")", ";", "app", ".", "use", "(", "routes", ")", ";", "}", "return", "{", "url", ",", "app", ",", "connect", ",", "methods", ",", "router", "}", ";", "}" ]
eslint-disable-line eslint-disable-line Start the server. @param {Config} config A configuration object. @param {RoutesConfig} [routesConfig] A configuration object for the router.
[ "eslint", "-", "disable", "-", "line", "eslint", "-", "disable", "-", "line", "Start", "the", "server", "." ]
6fbf9bbd63eafe609e550532801ea33910ff95c7
https://github.com/artdecocode/idio/blob/6fbf9bbd63eafe609e550532801ea33910ff95c7/build/index.js#L38-L62
49,894
hex7c0/logger-request-cli
lib/out.js
ip
function ip(input, output) { var i = 0; var event = input[0]; var out = [ output ]; for ( var ips in event) { ++i; out.push([ ips, cyan + event[ips].counter + close ]); } if (i === 0) { return []; } out.push('', [ 'unique ip', ansi.underline.open + i + ansi.underline.close ], ''); return out; }
javascript
function ip(input, output) { var i = 0; var event = input[0]; var out = [ output ]; for ( var ips in event) { ++i; out.push([ ips, cyan + event[ips].counter + close ]); } if (i === 0) { return []; } out.push('', [ 'unique ip', ansi.underline.open + i + ansi.underline.close ], ''); return out; }
[ "function", "ip", "(", "input", ",", "output", ")", "{", "var", "i", "=", "0", ";", "var", "event", "=", "input", "[", "0", "]", ";", "var", "out", "=", "[", "output", "]", ";", "for", "(", "var", "ips", "in", "event", ")", "{", "++", "i", ";", "out", ".", "push", "(", "[", "ips", ",", "cyan", "+", "event", "[", "ips", "]", ".", "counter", "+", "close", "]", ")", ";", "}", "if", "(", "i", "===", "0", ")", "{", "return", "[", "]", ";", "}", "out", ".", "push", "(", "''", ",", "[", "'unique ip'", ",", "ansi", ".", "underline", ".", "open", "+", "i", "+", "ansi", ".", "underline", ".", "close", "]", ",", "''", ")", ";", "return", "out", ";", "}" ]
output for ip @function ip @param {Array} input - line parsed @param {String} output - header @return {Array}
[ "output", "for", "ip" ]
b1110592dd62e673561a1a4e1c4e122a2a93890a
https://github.com/hex7c0/logger-request-cli/blob/b1110592dd62e673561a1a4e1c4e122a2a93890a/lib/out.js#L64-L79
49,895
hex7c0/logger-request-cli
lib/out.js
cc
function cc(input, output) { var event = input[0]; var out = [ output ]; for ( var a in event) { if (a != 'undefined') { out.push([ a, cyan + event[a].counter + close ]); } } if (out.length < 2) { return []; } out.push(''); return out; }
javascript
function cc(input, output) { var event = input[0]; var out = [ output ]; for ( var a in event) { if (a != 'undefined') { out.push([ a, cyan + event[a].counter + close ]); } } if (out.length < 2) { return []; } out.push(''); return out; }
[ "function", "cc", "(", "input", ",", "output", ")", "{", "var", "event", "=", "input", "[", "0", "]", ";", "var", "out", "=", "[", "output", "]", ";", "for", "(", "var", "a", "in", "event", ")", "{", "if", "(", "a", "!=", "'undefined'", ")", "{", "out", ".", "push", "(", "[", "a", ",", "cyan", "+", "event", "[", "a", "]", ".", "counter", "+", "close", "]", ")", ";", "}", "}", "if", "(", "out", ".", "length", "<", "2", ")", "{", "return", "[", "]", ";", "}", "out", ".", "push", "(", "''", ")", ";", "return", "out", ";", "}" ]
output for counter @function cc @param {Array} input - line parsed @param {String} output - header @return {Array}
[ "output", "for", "counter" ]
b1110592dd62e673561a1a4e1c4e122a2a93890a
https://github.com/hex7c0/logger-request-cli/blob/b1110592dd62e673561a1a4e1c4e122a2a93890a/lib/out.js#L89-L103
49,896
hex7c0/logger-request-cli
lib/out.js
avg
function avg(input, output) { var event = input[0]; if (event.what === 0 && event.total === 0) { return []; } return [ output, [ 'total', cyan + event.what.toFixed(3) + close ], [ 'average', cyan + (event.what / event.total).toFixed(3) + close ], [ 'max', cyan + event.max.toFixed(3) + close ], [ 'min', cyan + event.min.toFixed(3) + close ], [ '' ] ]; }
javascript
function avg(input, output) { var event = input[0]; if (event.what === 0 && event.total === 0) { return []; } return [ output, [ 'total', cyan + event.what.toFixed(3) + close ], [ 'average', cyan + (event.what / event.total).toFixed(3) + close ], [ 'max', cyan + event.max.toFixed(3) + close ], [ 'min', cyan + event.min.toFixed(3) + close ], [ '' ] ]; }
[ "function", "avg", "(", "input", ",", "output", ")", "{", "var", "event", "=", "input", "[", "0", "]", ";", "if", "(", "event", ".", "what", "===", "0", "&&", "event", ".", "total", "===", "0", ")", "{", "return", "[", "]", ";", "}", "return", "[", "output", ",", "[", "'total'", ",", "cyan", "+", "event", ".", "what", ".", "toFixed", "(", "3", ")", "+", "close", "]", ",", "[", "'average'", ",", "cyan", "+", "(", "event", ".", "what", "/", "event", ".", "total", ")", ".", "toFixed", "(", "3", ")", "+", "close", "]", ",", "[", "'max'", ",", "cyan", "+", "event", ".", "max", ".", "toFixed", "(", "3", ")", "+", "close", "]", ",", "[", "'min'", ",", "cyan", "+", "event", ".", "min", ".", "toFixed", "(", "3", ")", "+", "close", "]", ",", "[", "''", "]", "]", ";", "}" ]
output for average @function avg @param {Array} input - line parsed @param {String} output - header @return {Array}
[ "output", "for", "average" ]
b1110592dd62e673561a1a4e1c4e122a2a93890a
https://github.com/hex7c0/logger-request-cli/blob/b1110592dd62e673561a1a4e1c4e122a2a93890a/lib/out.js#L113-L123
49,897
nattreid/tracking
assets/nTracker.js
addParameter
function addParameter(data, parameter) { var regex = '(' + parameter + '=[a-z0-9-]+)'; var search = window.location.search.match(regex); if (search) { data.push(search[1]); } var hash = window.location.hash.match(regex); if (hash) { data.push(hash[1]); } }
javascript
function addParameter(data, parameter) { var regex = '(' + parameter + '=[a-z0-9-]+)'; var search = window.location.search.match(regex); if (search) { data.push(search[1]); } var hash = window.location.hash.match(regex); if (hash) { data.push(hash[1]); } }
[ "function", "addParameter", "(", "data", ",", "parameter", ")", "{", "var", "regex", "=", "'('", "+", "parameter", "+", "'=[a-z0-9-]+)'", ";", "var", "search", "=", "window", ".", "location", ".", "search", ".", "match", "(", "regex", ")", ";", "if", "(", "search", ")", "{", "data", ".", "push", "(", "search", "[", "1", "]", ")", ";", "}", "var", "hash", "=", "window", ".", "location", ".", "hash", ".", "match", "(", "regex", ")", ";", "if", "(", "hash", ")", "{", "data", ".", "push", "(", "hash", "[", "1", "]", ")", ";", "}", "}" ]
Add parameter from window.search do data @param {array} data @param {string} parameter
[ "Add", "parameter", "from", "window", ".", "search", "do", "data" ]
5fc7c993c08774945405c79a393584ef2ed589f7
https://github.com/nattreid/tracking/blob/5fc7c993c08774945405c79a393584ef2ed589f7/assets/nTracker.js#L67-L77
49,898
nattreid/tracking
assets/nTracker.js
getClickDataset
function getClickDataset(path) { var el; for (var i = 0; i < path.length; i++) { el = path[i]; if (el.dataset.nctr !== undefined) { return el.dataset; } } return null; }
javascript
function getClickDataset(path) { var el; for (var i = 0; i < path.length; i++) { el = path[i]; if (el.dataset.nctr !== undefined) { return el.dataset; } } return null; }
[ "function", "getClickDataset", "(", "path", ")", "{", "var", "el", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "path", ".", "length", ";", "i", "++", ")", "{", "el", "=", "path", "[", "i", "]", ";", "if", "(", "el", ".", "dataset", ".", "nctr", "!==", "undefined", ")", "{", "return", "el", ".", "dataset", ";", "}", "}", "return", "null", ";", "}" ]
Get click dataset @param {array} path @returns {array|null}
[ "Get", "click", "dataset" ]
5fc7c993c08774945405c79a393584ef2ed589f7
https://github.com/nattreid/tracking/blob/5fc7c993c08774945405c79a393584ef2ed589f7/assets/nTracker.js#L106-L115
49,899
nattreid/tracking
assets/nTracker.js
leave
function leave() { var data = []; data.push('leave=' + Math.floor(Math.random() * 10000)); post(data.join('&'), trackingUrl); }
javascript
function leave() { var data = []; data.push('leave=' + Math.floor(Math.random() * 10000)); post(data.join('&'), trackingUrl); }
[ "function", "leave", "(", ")", "{", "var", "data", "=", "[", "]", ";", "data", ".", "push", "(", "'leave='", "+", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "10000", ")", ")", ";", "post", "(", "data", ".", "join", "(", "'&'", ")", ",", "trackingUrl", ")", ";", "}" ]
Track leave page
[ "Track", "leave", "page" ]
5fc7c993c08774945405c79a393584ef2ed589f7
https://github.com/nattreid/tracking/blob/5fc7c993c08774945405c79a393584ef2ed589f7/assets/nTracker.js#L149-L154