repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
phulas/x-ray-nightmare
index.js
driver
function driver(options, fn) { if ('function' == typeof options) fn = options, options = {}; options = options || {}; fn = fn || electron; var nightmare = new Nightmare(options); return function nightmare_driver(ctx, done) { if (ctx !=null) { debug('goingto %s', ctx.url); nightmare .on('page', function (type, message, stack) { if (type == 'error') debug('page error: %s', message); }) .on('did-fail-load', function (event, errorCode, errorDescription) { debug('failed to load with error %s: %s', errorCode, errorDescription); return done(new Error(errorDescription)) }) .on('did-get-redirect-request', function (event, oldUrl, newUrl, isMainFrame) { if (normalize(oldUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } }) .on('will-navigate', function (url) { if (normalize(url) == normalize(ctx.url)) { debug('redirect: %s', url); ctx.url = url; } }) .on('did-get-response-details', function (event, status, newUrl, originalUrl, httpResponseCode, requestMethod, referrer, headers) { if (normalize(originalUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } ; if (normalize(newUrl) == normalize(ctx.url) && httpResponseCode == 200) { debug('got response from %s: %s', ctx.url, httpResponseCode); ctx.status = httpResponseCode; } ; }) .on('did-finish-load', function () { debug('finished loading %s', ctx.url); }) wrapfn(fn, select)(ctx, nightmare); } function select(err, ret) { if (err) return done(err); nightmare .evaluate(function() { return document.documentElement.outerHTML; }) nightmare .then(function(body) { ctx.body = body; debug('%s - %s', ctx.url, ctx.status); done(null, ctx); }) }; if (ctx == null || ctx == undefined) { debug('attempting to shut down nightmare instance gracefully'); // put bogus message in the queue so nightmare end will execute nightmare.viewport(1,1); // force shutdown and disconnect from electron nightmare. end(). then(function(body) { debug('gracefully shut down nightmare instance '); }); } } }
javascript
function driver(options, fn) { if ('function' == typeof options) fn = options, options = {}; options = options || {}; fn = fn || electron; var nightmare = new Nightmare(options); return function nightmare_driver(ctx, done) { if (ctx !=null) { debug('goingto %s', ctx.url); nightmare .on('page', function (type, message, stack) { if (type == 'error') debug('page error: %s', message); }) .on('did-fail-load', function (event, errorCode, errorDescription) { debug('failed to load with error %s: %s', errorCode, errorDescription); return done(new Error(errorDescription)) }) .on('did-get-redirect-request', function (event, oldUrl, newUrl, isMainFrame) { if (normalize(oldUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } }) .on('will-navigate', function (url) { if (normalize(url) == normalize(ctx.url)) { debug('redirect: %s', url); ctx.url = url; } }) .on('did-get-response-details', function (event, status, newUrl, originalUrl, httpResponseCode, requestMethod, referrer, headers) { if (normalize(originalUrl) == normalize(ctx.url)) { debug('redirect: %s', newUrl); ctx.url = newUrl; } ; if (normalize(newUrl) == normalize(ctx.url) && httpResponseCode == 200) { debug('got response from %s: %s', ctx.url, httpResponseCode); ctx.status = httpResponseCode; } ; }) .on('did-finish-load', function () { debug('finished loading %s', ctx.url); }) wrapfn(fn, select)(ctx, nightmare); } function select(err, ret) { if (err) return done(err); nightmare .evaluate(function() { return document.documentElement.outerHTML; }) nightmare .then(function(body) { ctx.body = body; debug('%s - %s', ctx.url, ctx.status); done(null, ctx); }) }; if (ctx == null || ctx == undefined) { debug('attempting to shut down nightmare instance gracefully'); // put bogus message in the queue so nightmare end will execute nightmare.viewport(1,1); // force shutdown and disconnect from electron nightmare. end(). then(function(body) { debug('gracefully shut down nightmare instance '); }); } } }
[ "function", "driver", "(", "options", ",", "fn", ")", "{", "if", "(", "'function'", "==", "typeof", "options", ")", "fn", "=", "options", ",", "options", "=", "{", "}", ";", "options", "=", "options", "||", "{", "}", ";", "fn", "=", "fn", "||", "electron", ";", "var", "nightmare", "=", "new", "Nightmare", "(", "options", ")", ";", "return", "function", "nightmare_driver", "(", "ctx", ",", "done", ")", "{", "if", "(", "ctx", "!=", "null", ")", "{", "debug", "(", "'goingto %s'", ",", "ctx", ".", "url", ")", ";", "nightmare", ".", "on", "(", "'page'", ",", "function", "(", "type", ",", "message", ",", "stack", ")", "{", "if", "(", "type", "==", "'error'", ")", "debug", "(", "'page error: %s'", ",", "message", ")", ";", "}", ")", ".", "on", "(", "'did-fail-load'", ",", "function", "(", "event", ",", "errorCode", ",", "errorDescription", ")", "{", "debug", "(", "'failed to load with error %s: %s'", ",", "errorCode", ",", "errorDescription", ")", ";", "return", "done", "(", "new", "Error", "(", "errorDescription", ")", ")", "}", ")", ".", "on", "(", "'did-get-redirect-request'", ",", "function", "(", "event", ",", "oldUrl", ",", "newUrl", ",", "isMainFrame", ")", "{", "if", "(", "normalize", "(", "oldUrl", ")", "==", "normalize", "(", "ctx", ".", "url", ")", ")", "{", "debug", "(", "'redirect: %s'", ",", "newUrl", ")", ";", "ctx", ".", "url", "=", "newUrl", ";", "}", "}", ")", ".", "on", "(", "'will-navigate'", ",", "function", "(", "url", ")", "{", "if", "(", "normalize", "(", "url", ")", "==", "normalize", "(", "ctx", ".", "url", ")", ")", "{", "debug", "(", "'redirect: %s'", ",", "url", ")", ";", "ctx", ".", "url", "=", "url", ";", "}", "}", ")", ".", "on", "(", "'did-get-response-details'", ",", "function", "(", "event", ",", "status", ",", "newUrl", ",", "originalUrl", ",", "httpResponseCode", ",", "requestMethod", ",", "referrer", ",", "headers", ")", "{", "if", "(", "normalize", "(", "originalUrl", ")", "==", "normalize", "(", "ctx", ".", "url", ")", ")", "{", "debug", "(", "'redirect: %s'", ",", "newUrl", ")", ";", "ctx", ".", "url", "=", "newUrl", ";", "}", ";", "if", "(", "normalize", "(", "newUrl", ")", "==", "normalize", "(", "ctx", ".", "url", ")", "&&", "httpResponseCode", "==", "200", ")", "{", "debug", "(", "'got response from %s: %s'", ",", "ctx", ".", "url", ",", "httpResponseCode", ")", ";", "ctx", ".", "status", "=", "httpResponseCode", ";", "}", ";", "}", ")", ".", "on", "(", "'did-finish-load'", ",", "function", "(", ")", "{", "debug", "(", "'finished loading %s'", ",", "ctx", ".", "url", ")", ";", "}", ")", "wrapfn", "(", "fn", ",", "select", ")", "(", "ctx", ",", "nightmare", ")", ";", "}", "function", "select", "(", "err", ",", "ret", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "nightmare", ".", "evaluate", "(", "function", "(", ")", "{", "return", "document", ".", "documentElement", ".", "outerHTML", ";", "}", ")", "nightmare", ".", "then", "(", "function", "(", "body", ")", "{", "ctx", ".", "body", "=", "body", ";", "debug", "(", "'%s - %s'", ",", "ctx", ".", "url", ",", "ctx", ".", "status", ")", ";", "done", "(", "null", ",", "ctx", ")", ";", "}", ")", "}", ";", "if", "(", "ctx", "==", "null", "||", "ctx", "==", "undefined", ")", "{", "debug", "(", "'attempting to shut down nightmare instance gracefully'", ")", ";", "nightmare", ".", "viewport", "(", "1", ",", "1", ")", ";", "nightmare", ".", "end", "(", ")", ".", "then", "(", "function", "(", "body", ")", "{", "debug", "(", "'gracefully shut down nightmare instance '", ")", ";", "}", ")", ";", "}", "}", "}" ]
Initialize the `driver` with the following `options` @param {Object} options @param {Function} fn @return {Function} @api public
[ "Initialize", "the", "driver", "with", "the", "following", "options" ]
d92f39a46e5e126254cdda6de34d39476fa1f6f8
https://github.com/phulas/x-ray-nightmare/blob/d92f39a46e5e126254cdda6de34d39476fa1f6f8/index.js#L26-L110
train
flux-capacitor/flux-capacitor
packages/flux-capacitor/lib/database/combineChangesets.js
combineChangesets
function combineChangesets (changesets) { const actions = changesets.map((changeset) => changeset.apply) const combinedAction = function () { const args = arguments return actions.reduce((promise, action) => ( promise.then(() => action.apply(null, args)) ), Promise.resolve()) } return createChangeset(combinedAction) }
javascript
function combineChangesets (changesets) { const actions = changesets.map((changeset) => changeset.apply) const combinedAction = function () { const args = arguments return actions.reduce((promise, action) => ( promise.then(() => action.apply(null, args)) ), Promise.resolve()) } return createChangeset(combinedAction) }
[ "function", "combineChangesets", "(", "changesets", ")", "{", "const", "actions", "=", "changesets", ".", "map", "(", "(", "changeset", ")", "=>", "changeset", ".", "apply", ")", "const", "combinedAction", "=", "function", "(", ")", "{", "const", "args", "=", "arguments", "return", "actions", ".", "reduce", "(", "(", "promise", ",", "action", ")", "=>", "(", "promise", ".", "then", "(", "(", ")", "=>", "action", ".", "apply", "(", "null", ",", "args", ")", ")", ")", ",", "Promise", ".", "resolve", "(", ")", ")", "}", "return", "createChangeset", "(", "combinedAction", ")", "}" ]
Takes an array of changesets and returns a single changeset that contains all of the input changeset's DB operations. @param {Changeset[]} changesets @return {Changeset}
[ "Takes", "an", "array", "of", "changesets", "and", "returns", "a", "single", "changeset", "that", "contains", "all", "of", "the", "input", "changeset", "s", "DB", "operations", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor/lib/database/combineChangesets.js#L12-L24
train
igorski/zCanvas
src/Loader.js
isDataSource
function isDataSource( image ) { const source = (typeof image === "string" ? image : image.src).substr(0, 5); // base 64 string contains data-attribute, the MIME type and then the content, e.g. : // e.g. "data:image/png;base64," for a typical PNG, Blob string contains no MIME, e.g.: // blob:http://localhost:9001/46cc7e56-cf2a-7540-b515-1d99dfcb2ad6 return source === "data:" || source === "blob:"; }
javascript
function isDataSource( image ) { const source = (typeof image === "string" ? image : image.src).substr(0, 5); // base 64 string contains data-attribute, the MIME type and then the content, e.g. : // e.g. "data:image/png;base64," for a typical PNG, Blob string contains no MIME, e.g.: // blob:http://localhost:9001/46cc7e56-cf2a-7540-b515-1d99dfcb2ad6 return source === "data:" || source === "blob:"; }
[ "function", "isDataSource", "(", "image", ")", "{", "const", "source", "=", "(", "typeof", "image", "===", "\"string\"", "?", "image", ":", "image", ".", "src", ")", ".", "substr", "(", "0", ",", "5", ")", ";", "return", "source", "===", "\"data:\"", "||", "source", "===", "\"blob:\"", ";", "}" ]
checks whether the contents of an Image are either a base64 encoded string or a Blob @private @param {Image|string} image when string, it is the src attribute of an Image @return {boolean}
[ "checks", "whether", "the", "contents", "of", "an", "Image", "are", "either", "a", "base64", "encoded", "string", "or", "a", "Blob" ]
8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82
https://github.com/igorski/zCanvas/blob/8b5cd8e195178a80a9bc4ace7ea0b94dfe6b3f82/src/Loader.js#L196-L204
train
HarasimowiczKamil/any-base
index.js
anyBase
function anyBase(srcAlphabet, dstAlphabet) { var converter = new Converter(srcAlphabet, dstAlphabet); /** * Convert function * * @param {string|Array} number * * @return {string|Array} number */ return function (number) { return converter.convert(number); } }
javascript
function anyBase(srcAlphabet, dstAlphabet) { var converter = new Converter(srcAlphabet, dstAlphabet); /** * Convert function * * @param {string|Array} number * * @return {string|Array} number */ return function (number) { return converter.convert(number); } }
[ "function", "anyBase", "(", "srcAlphabet", ",", "dstAlphabet", ")", "{", "var", "converter", "=", "new", "Converter", "(", "srcAlphabet", ",", "dstAlphabet", ")", ";", "return", "function", "(", "number", ")", "{", "return", "converter", ".", "convert", "(", "number", ")", ";", "}", "}" ]
Function get source and destination alphabet and return convert function @param {string|Array} srcAlphabet @param {string|Array} dstAlphabet @returns {function(number|Array)}
[ "Function", "get", "source", "and", "destination", "alphabet", "and", "return", "convert", "function" ]
7595a7398959618a93cb4edef0bae3e035eb3ce0
https://github.com/HarasimowiczKamil/any-base/blob/7595a7398959618a93cb4edef0bae3e035eb3ce0/index.js#L11-L23
train
Cloud9Trader/oanda-adapter
lib/utils.js
function (fn, context, rate, warningThreshold) { var queue = [], timeout; function next () { if (queue.length === 0) { timeout = null; return; } fn.apply(context, queue.shift()); timeout = setTimeout(next, rate); } return function () { if (!timeout) { timeout = setTimeout(next, rate); fn.apply(context, arguments); return; } queue.push(arguments); if (queue.length * rate > warningThreshold) { console.warn("[WARNING] Rate limited function call will be delayed by", ((queue.length * rate) / 1000).toFixed(3), "secs"); } }; }
javascript
function (fn, context, rate, warningThreshold) { var queue = [], timeout; function next () { if (queue.length === 0) { timeout = null; return; } fn.apply(context, queue.shift()); timeout = setTimeout(next, rate); } return function () { if (!timeout) { timeout = setTimeout(next, rate); fn.apply(context, arguments); return; } queue.push(arguments); if (queue.length * rate > warningThreshold) { console.warn("[WARNING] Rate limited function call will be delayed by", ((queue.length * rate) / 1000).toFixed(3), "secs"); } }; }
[ "function", "(", "fn", ",", "context", ",", "rate", ",", "warningThreshold", ")", "{", "var", "queue", "=", "[", "]", ",", "timeout", ";", "function", "next", "(", ")", "{", "if", "(", "queue", ".", "length", "===", "0", ")", "{", "timeout", "=", "null", ";", "return", ";", "}", "fn", ".", "apply", "(", "context", ",", "queue", ".", "shift", "(", ")", ")", ";", "timeout", "=", "setTimeout", "(", "next", ",", "rate", ")", ";", "}", "return", "function", "(", ")", "{", "if", "(", "!", "timeout", ")", "{", "timeout", "=", "setTimeout", "(", "next", ",", "rate", ")", ";", "fn", ".", "apply", "(", "context", ",", "arguments", ")", ";", "return", ";", "}", "queue", ".", "push", "(", "arguments", ")", ";", "if", "(", "queue", ".", "length", "*", "rate", ">", "warningThreshold", ")", "{", "console", ".", "warn", "(", "\"[WARNING] Rate limited function call will be delayed by\"", ",", "(", "(", "queue", ".", "length", "*", "rate", ")", "/", "1000", ")", ".", "toFixed", "(", "3", ")", ",", "\"secs\"", ")", ";", "}", "}", ";", "}" ]
Function wrapper will limit fn invocations to one per rate. All will be queued for delayed execution where limit is exceeded, with warning logged where delay exceeds warningThreshold
[ "Function", "wrapper", "will", "limit", "fn", "invocations", "to", "one", "per", "rate", ".", "All", "will", "be", "queued", "for", "delayed", "execution", "where", "limit", "is", "exceeded", "with", "warning", "logged", "where", "delay", "exceeds", "warningThreshold" ]
33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1
https://github.com/Cloud9Trader/oanda-adapter/blob/33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1/lib/utils.js#L5-L36
train
piecioshka/super-event-emitter
src/index.js
function (name, fn, ctx) { assert(isString(name), 'EventEmitter#on: name is not a string'); assert(isFunction(fn), 'EventEmitter#on: fn is not a function'); // If the context is not passed, use `this`. ctx = ctx || this; // Push to private lists of listeners. this._listeners.push({ name: name, fn: fn, ctx: ctx }); return this; }
javascript
function (name, fn, ctx) { assert(isString(name), 'EventEmitter#on: name is not a string'); assert(isFunction(fn), 'EventEmitter#on: fn is not a function'); // If the context is not passed, use `this`. ctx = ctx || this; // Push to private lists of listeners. this._listeners.push({ name: name, fn: fn, ctx: ctx }); return this; }
[ "function", "(", "name", ",", "fn", ",", "ctx", ")", "{", "assert", "(", "isString", "(", "name", ")", ",", "'EventEmitter#on: name is not a string'", ")", ";", "assert", "(", "isFunction", "(", "fn", ")", ",", "'EventEmitter#on: fn is not a function'", ")", ";", "ctx", "=", "ctx", "||", "this", ";", "this", ".", "_listeners", ".", "push", "(", "{", "name", ":", "name", ",", "fn", ":", "fn", ",", "ctx", ":", "ctx", "}", ")", ";", "return", "this", ";", "}" ]
Register listener on concrete name with specified handler. @param {string} name @param {Function} fn @param {Object} [ctx]
[ "Register", "listener", "on", "concrete", "name", "with", "specified", "handler", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L76-L91
train
piecioshka/super-event-emitter
src/index.js
function (name, fn, ctx) { // If the context is not passed, use `this`. ctx = ctx || this; var self = this; function onHandler() { fn.apply(ctx, arguments); self.off(name, onHandler); } this.on(name, onHandler, ctx); return this; }
javascript
function (name, fn, ctx) { // If the context is not passed, use `this`. ctx = ctx || this; var self = this; function onHandler() { fn.apply(ctx, arguments); self.off(name, onHandler); } this.on(name, onHandler, ctx); return this; }
[ "function", "(", "name", ",", "fn", ",", "ctx", ")", "{", "ctx", "=", "ctx", "||", "this", ";", "var", "self", "=", "this", ";", "function", "onHandler", "(", ")", "{", "fn", ".", "apply", "(", "ctx", ",", "arguments", ")", ";", "self", ".", "off", "(", "name", ",", "onHandler", ")", ";", "}", "this", ".", "on", "(", "name", ",", "onHandler", ",", "ctx", ")", ";", "return", "this", ";", "}" ]
Register listener. Remove them after once event triggered. @param {string} name @param {Function} fn @param {Object} [ctx]
[ "Register", "listener", ".", "Remove", "them", "after", "once", "event", "triggered", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L101-L115
train
piecioshka/super-event-emitter
src/index.js
function (name, fn) { this._listeners = !name ? [] : filter(this._listeners, function (listener) { if (listener.name !== name) { return true; } else { if (isFunction(fn)) { return listener.fn !== fn; } else { return false; } } }); return this; }
javascript
function (name, fn) { this._listeners = !name ? [] : filter(this._listeners, function (listener) { if (listener.name !== name) { return true; } else { if (isFunction(fn)) { return listener.fn !== fn; } else { return false; } } }); return this; }
[ "function", "(", "name", ",", "fn", ")", "{", "this", ".", "_listeners", "=", "!", "name", "?", "[", "]", ":", "filter", "(", "this", ".", "_listeners", ",", "function", "(", "listener", ")", "{", "if", "(", "listener", ".", "name", "!==", "name", ")", "{", "return", "true", ";", "}", "else", "{", "if", "(", "isFunction", "(", "fn", ")", ")", "{", "return", "listener", ".", "fn", "!==", "fn", ";", "}", "else", "{", "return", "false", ";", "}", "}", "}", ")", ";", "return", "this", ";", "}" ]
Unregister listener. Remove concrete listener by name and itself definition. @param {string} [name] @param {Function} [fn]
[ "Unregister", "listener", ".", "Remove", "concrete", "listener", "by", "name", "and", "itself", "definition", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L124-L140
train
piecioshka/super-event-emitter
src/index.js
function (name, params) { assert(isString(name), 'EventEmitter#emit: name is not a string'); forEach(this._listeners, function (event) { if (event.name === name) { event.fn.call(event.ctx, params); } // Special behaviour for wildcard - invoke each event handler. var isWildcard = (/^all|\*$/).test(event.name); if (isWildcard) { event.fn.call(event.ctx, name, params); } }); return this; }
javascript
function (name, params) { assert(isString(name), 'EventEmitter#emit: name is not a string'); forEach(this._listeners, function (event) { if (event.name === name) { event.fn.call(event.ctx, params); } // Special behaviour for wildcard - invoke each event handler. var isWildcard = (/^all|\*$/).test(event.name); if (isWildcard) { event.fn.call(event.ctx, name, params); } }); return this; }
[ "function", "(", "name", ",", "params", ")", "{", "assert", "(", "isString", "(", "name", ")", ",", "'EventEmitter#emit: name is not a string'", ")", ";", "forEach", "(", "this", ".", "_listeners", ",", "function", "(", "event", ")", "{", "if", "(", "event", ".", "name", "===", "name", ")", "{", "event", ".", "fn", ".", "call", "(", "event", ".", "ctx", ",", "params", ")", ";", "}", "var", "isWildcard", "=", "(", "/", "^all|\\*$", "/", ")", ".", "test", "(", "event", ".", "name", ")", ";", "if", "(", "isWildcard", ")", "{", "event", ".", "fn", ".", "call", "(", "event", ".", "ctx", ",", "name", ",", "params", ")", ";", "}", "}", ")", ";", "return", "this", ";", "}" ]
Trigger event. All of listeners waiting for emit event will be executed. @param {string} name @param {Object} [params]
[ "Trigger", "event", ".", "All", "of", "listeners", "waiting", "for", "emit", "event", "will", "be", "executed", "." ]
4115220f468721e0f8249fcbf37091557cbc6e09
https://github.com/piecioshka/super-event-emitter/blob/4115220f468721e0f8249fcbf37091557cbc6e09/src/index.js#L149-L166
train
stamoern/wdio-element-screenshot
src/index.js
getElementBoundingRect
function getElementBoundingRect(elementSelector) { /** * @param {Window} win * @param {Object} [dims] * @returns {Object} */ function computeFrameOffset(win, dims) { // initialize our result variable dims = dims || { left: win.pageXOffset, top: win.pageYOffset }; // add the offset & recurse up the frame chain var frame = win.frameElement; if (frame) { var rect = frame.getBoundingClientRect(); dims.left += rect.left + frame.contentWindow.pageXOffset; dims.top += rect.top + frame.contentWindow.pageYOffset; if (win !== window.top) { computeFrameOffset(win.parent, dims); } } return dims; } /** * @param {HTMLElement} element * @param {Object} frameOffset * @returns {Object} */ function computeElementRect(element, frameOffset) { var rect = element.getBoundingClientRect(); return { left: rect.left + frameOffset.left, right: rect.right + frameOffset.left, top: rect.top + frameOffset.top, bottom: rect.bottom + frameOffset.top, width: rect.width, height: rect.height }; } var element = document.querySelectorAll(elementSelector)[0]; if (element) { var frameOffset = computeFrameOffset(window); var elementRect = computeElementRect(element, frameOffset); return elementRect; } }
javascript
function getElementBoundingRect(elementSelector) { /** * @param {Window} win * @param {Object} [dims] * @returns {Object} */ function computeFrameOffset(win, dims) { // initialize our result variable dims = dims || { left: win.pageXOffset, top: win.pageYOffset }; // add the offset & recurse up the frame chain var frame = win.frameElement; if (frame) { var rect = frame.getBoundingClientRect(); dims.left += rect.left + frame.contentWindow.pageXOffset; dims.top += rect.top + frame.contentWindow.pageYOffset; if (win !== window.top) { computeFrameOffset(win.parent, dims); } } return dims; } /** * @param {HTMLElement} element * @param {Object} frameOffset * @returns {Object} */ function computeElementRect(element, frameOffset) { var rect = element.getBoundingClientRect(); return { left: rect.left + frameOffset.left, right: rect.right + frameOffset.left, top: rect.top + frameOffset.top, bottom: rect.bottom + frameOffset.top, width: rect.width, height: rect.height }; } var element = document.querySelectorAll(elementSelector)[0]; if (element) { var frameOffset = computeFrameOffset(window); var elementRect = computeElementRect(element, frameOffset); return elementRect; } }
[ "function", "getElementBoundingRect", "(", "elementSelector", ")", "{", "function", "computeFrameOffset", "(", "win", ",", "dims", ")", "{", "dims", "=", "dims", "||", "{", "left", ":", "win", ".", "pageXOffset", ",", "top", ":", "win", ".", "pageYOffset", "}", ";", "var", "frame", "=", "win", ".", "frameElement", ";", "if", "(", "frame", ")", "{", "var", "rect", "=", "frame", ".", "getBoundingClientRect", "(", ")", ";", "dims", ".", "left", "+=", "rect", ".", "left", "+", "frame", ".", "contentWindow", ".", "pageXOffset", ";", "dims", ".", "top", "+=", "rect", ".", "top", "+", "frame", ".", "contentWindow", ".", "pageYOffset", ";", "if", "(", "win", "!==", "window", ".", "top", ")", "{", "computeFrameOffset", "(", "win", ".", "parent", ",", "dims", ")", ";", "}", "}", "return", "dims", ";", "}", "function", "computeElementRect", "(", "element", ",", "frameOffset", ")", "{", "var", "rect", "=", "element", ".", "getBoundingClientRect", "(", ")", ";", "return", "{", "left", ":", "rect", ".", "left", "+", "frameOffset", ".", "left", ",", "right", ":", "rect", ".", "right", "+", "frameOffset", ".", "left", ",", "top", ":", "rect", ".", "top", "+", "frameOffset", ".", "top", ",", "bottom", ":", "rect", ".", "bottom", "+", "frameOffset", ".", "top", ",", "width", ":", "rect", ".", "width", ",", "height", ":", "rect", ".", "height", "}", ";", "}", "var", "element", "=", "document", ".", "querySelectorAll", "(", "elementSelector", ")", "[", "0", "]", ";", "if", "(", "element", ")", "{", "var", "frameOffset", "=", "computeFrameOffset", "(", "window", ")", ";", "var", "elementRect", "=", "computeElementRect", "(", "element", ",", "frameOffset", ")", ";", "return", "elementRect", ";", "}", "}" ]
Gets the position and size of an element. This function is run in the browser so its scope must be contained. @param {String} elementSelector @returns {Object|undefined}
[ "Gets", "the", "position", "and", "size", "of", "an", "element", "." ]
afd26c3aff4c53f739b6381ad289544637aac7ce
https://github.com/stamoern/wdio-element-screenshot/blob/afd26c3aff4c53f739b6381ad289544637aac7ce/src/index.js#L96-L149
train
flux-capacitor/flux-capacitor
packages/flux-capacitor-reduxify/src/index.js
reduxifyReducer
function reduxifyReducer (reducer, collectionName = null) { return (state = [], action) => { const collection = createReduxifyCollection(state, collectionName) const changeset = reducer(collection, action) // the changesets returned by the reduxify collections are just plain synchronous methods return changeset && changeset !== collection ? applyChangeset(state, changeset) : state } function applyChangeset (state, changeset) { if (typeof changeset !== 'function') { console.error('Reduxify changeset is a plain function. Instead got:', changeset) throw new Error('Reduxify changeset is a plain function.') } // the changesets returned by the reduxify collections are just plain synchronous methods return changeset(state) } }
javascript
function reduxifyReducer (reducer, collectionName = null) { return (state = [], action) => { const collection = createReduxifyCollection(state, collectionName) const changeset = reducer(collection, action) // the changesets returned by the reduxify collections are just plain synchronous methods return changeset && changeset !== collection ? applyChangeset(state, changeset) : state } function applyChangeset (state, changeset) { if (typeof changeset !== 'function') { console.error('Reduxify changeset is a plain function. Instead got:', changeset) throw new Error('Reduxify changeset is a plain function.') } // the changesets returned by the reduxify collections are just plain synchronous methods return changeset(state) } }
[ "function", "reduxifyReducer", "(", "reducer", ",", "collectionName", "=", "null", ")", "{", "return", "(", "state", "=", "[", "]", ",", "action", ")", "=>", "{", "const", "collection", "=", "createReduxifyCollection", "(", "state", ",", "collectionName", ")", "const", "changeset", "=", "reducer", "(", "collection", ",", "action", ")", "return", "changeset", "&&", "changeset", "!==", "collection", "?", "applyChangeset", "(", "state", ",", "changeset", ")", ":", "state", "}", "function", "applyChangeset", "(", "state", ",", "changeset", ")", "{", "if", "(", "typeof", "changeset", "!==", "'function'", ")", "{", "console", ".", "error", "(", "'Reduxify changeset is a plain function. Instead got:'", ",", "changeset", ")", "throw", "new", "Error", "(", "'Reduxify changeset is a plain function.'", ")", "}", "return", "changeset", "(", "state", ")", "}", "}" ]
Takes a rewinddb reducer and turns it into a redux-compatible reducer. @param {Function} reducer (Collection, Event) => Changeset @param {string} [collectionName] @param {Function} (Array<Object>, Action) => Array<Object>
[ "Takes", "a", "rewinddb", "reducer", "and", "turns", "it", "into", "a", "redux", "-", "compatible", "reducer", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-reduxify/src/index.js#L12-L31
train
GitbookIO/slate-no-empty
src/index.js
NoEmpty
function NoEmpty(type) { type = typeof type == 'string' ? Block.create({ type, nodes: [ Text.create() ] }) : type; const onBeforeChange = (state) => { const { document } = state; // If document is not empty, it continues if (!document.nodes.isEmpty()) { return; } // Reset the state return State.create({ document: Document.create({ nodes: [type] }) }); }; return { onBeforeChange }; }
javascript
function NoEmpty(type) { type = typeof type == 'string' ? Block.create({ type, nodes: [ Text.create() ] }) : type; const onBeforeChange = (state) => { const { document } = state; // If document is not empty, it continues if (!document.nodes.isEmpty()) { return; } // Reset the state return State.create({ document: Document.create({ nodes: [type] }) }); }; return { onBeforeChange }; }
[ "function", "NoEmpty", "(", "type", ")", "{", "type", "=", "typeof", "type", "==", "'string'", "?", "Block", ".", "create", "(", "{", "type", ",", "nodes", ":", "[", "Text", ".", "create", "(", ")", "]", "}", ")", ":", "type", ";", "const", "onBeforeChange", "=", "(", "state", ")", "=>", "{", "const", "{", "document", "}", "=", "state", ";", "if", "(", "!", "document", ".", "nodes", ".", "isEmpty", "(", ")", ")", "{", "return", ";", "}", "return", "State", ".", "create", "(", "{", "document", ":", "Document", ".", "create", "(", "{", "nodes", ":", "[", "type", "]", "}", ")", "}", ")", ";", "}", ";", "return", "{", "onBeforeChange", "}", ";", "}" ]
Plugin to prevent an empty document. @param {String|Block} type
[ "Plugin", "to", "prevent", "an", "empty", "document", "." ]
9a8f24e4bfe2fea5ab76d0f9e5955587550c3118
https://github.com/GitbookIO/slate-no-empty/blob/9a8f24e4bfe2fea5ab76d0f9e5955587550c3118/src/index.js#L8-L36
train
karma-runner/karma-dart
chrome-extension/background.js
onRequest
function onRequest (request, sender, sendResponse) { // Show the page action for the tab that the sender (content script) was on. chrome.pageAction.show(sender.tab.id) var files = request.files if (request.action === 'load') { var rules = [] for (var file in files) { var regex var isKnownFile = prevFiles[sender.tab.id] && prevFiles[sender.tab.id][file] if (isKnownFile) { if (prevFiles[sender.tab.id][file] === files[file]) { // We can skip this rule if the timestamp hasn't change. continue } regex = '^([^\\?]*)\\?' + prevFiles[sender.tab.id][file] + '$' } else { regex = '^([^\\?]*)$' } var actions = [ new chrome.declarativeWebRequest.RedirectByRegEx({ from: regex, to: '$1?' + files[file] }) ] if (!isKnownFile) { // is new file actions.push( new chrome.declarativeWebRequest.RemoveResponseHeader( {name: 'Cache-Control'})) actions.push( new chrome.declarativeWebRequest.AddResponseHeader( {name: 'Cache-Control', value: 'no-cache'})) } rules.push({ conditions: [ new chrome.declarativeWebRequest.RequestMatcher({ url: { pathSuffix: file } }) ], actions: actions }) } prevFiles[sender.tab.id] = files chrome.declarativeWebRequest.onRequest.addRules(rules, function (callback) { // We reply back only when new rules are set. sendResponse({}) }) } // Return nothing to let the connection be cleaned up. }
javascript
function onRequest (request, sender, sendResponse) { // Show the page action for the tab that the sender (content script) was on. chrome.pageAction.show(sender.tab.id) var files = request.files if (request.action === 'load') { var rules = [] for (var file in files) { var regex var isKnownFile = prevFiles[sender.tab.id] && prevFiles[sender.tab.id][file] if (isKnownFile) { if (prevFiles[sender.tab.id][file] === files[file]) { // We can skip this rule if the timestamp hasn't change. continue } regex = '^([^\\?]*)\\?' + prevFiles[sender.tab.id][file] + '$' } else { regex = '^([^\\?]*)$' } var actions = [ new chrome.declarativeWebRequest.RedirectByRegEx({ from: regex, to: '$1?' + files[file] }) ] if (!isKnownFile) { // is new file actions.push( new chrome.declarativeWebRequest.RemoveResponseHeader( {name: 'Cache-Control'})) actions.push( new chrome.declarativeWebRequest.AddResponseHeader( {name: 'Cache-Control', value: 'no-cache'})) } rules.push({ conditions: [ new chrome.declarativeWebRequest.RequestMatcher({ url: { pathSuffix: file } }) ], actions: actions }) } prevFiles[sender.tab.id] = files chrome.declarativeWebRequest.onRequest.addRules(rules, function (callback) { // We reply back only when new rules are set. sendResponse({}) }) } // Return nothing to let the connection be cleaned up. }
[ "function", "onRequest", "(", "request", ",", "sender", ",", "sendResponse", ")", "{", "chrome", ".", "pageAction", ".", "show", "(", "sender", ".", "tab", ".", "id", ")", "var", "files", "=", "request", ".", "files", "if", "(", "request", ".", "action", "===", "'load'", ")", "{", "var", "rules", "=", "[", "]", "for", "(", "var", "file", "in", "files", ")", "{", "var", "regex", "var", "isKnownFile", "=", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "&&", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "[", "file", "]", "if", "(", "isKnownFile", ")", "{", "if", "(", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "[", "file", "]", "===", "files", "[", "file", "]", ")", "{", "continue", "}", "regex", "=", "'^([^\\\\?]*)\\\\?'", "+", "\\\\", "+", "\\\\", "}", "else", "prevFiles", "[", "sender", ".", "tab", ".", "id", "]", "[", "file", "]", "'$'", "{", "regex", "=", "'^([^\\\\?]*)$'", "}", "\\\\", "}", "var", "actions", "=", "[", "new", "chrome", ".", "declarativeWebRequest", ".", "RedirectByRegEx", "(", "{", "from", ":", "regex", ",", "to", ":", "'$1?'", "+", "files", "[", "file", "]", "}", ")", "]", "if", "(", "!", "isKnownFile", ")", "{", "actions", ".", "push", "(", "new", "chrome", ".", "declarativeWebRequest", ".", "RemoveResponseHeader", "(", "{", "name", ":", "'Cache-Control'", "}", ")", ")", "actions", ".", "push", "(", "new", "chrome", ".", "declarativeWebRequest", ".", "AddResponseHeader", "(", "{", "name", ":", "'Cache-Control'", ",", "value", ":", "'no-cache'", "}", ")", ")", "}", "}", "}" ]
Called when a message is passed.
[ "Called", "when", "a", "message", "is", "passed", "." ]
d5bd776928ff86978382c9522a618b468d2fba51
https://github.com/karma-runner/karma-dart/blob/d5bd776928ff86978382c9522a618b468d2fba51/chrome-extension/background.js#L7-L58
train
Cloud9Trader/oanda-adapter
lib/Events.js
waitFor
function waitFor (event, listener, context, wait) { var timeout; if (!wait) { throw new Error("[FATAL] waitFor called without wait time"); } var handler = function () { clearTimeout(timeout); listener.apply(context, arguments); }; timeout = setTimeout(function () { this.off(event, handler, context); listener.call(context, "timeout"); }.bind(this), wait); this.once(event, handler, context); }
javascript
function waitFor (event, listener, context, wait) { var timeout; if (!wait) { throw new Error("[FATAL] waitFor called without wait time"); } var handler = function () { clearTimeout(timeout); listener.apply(context, arguments); }; timeout = setTimeout(function () { this.off(event, handler, context); listener.call(context, "timeout"); }.bind(this), wait); this.once(event, handler, context); }
[ "function", "waitFor", "(", "event", ",", "listener", ",", "context", ",", "wait", ")", "{", "var", "timeout", ";", "if", "(", "!", "wait", ")", "{", "throw", "new", "Error", "(", "\"[FATAL] waitFor called without wait time\"", ")", ";", "}", "var", "handler", "=", "function", "(", ")", "{", "clearTimeout", "(", "timeout", ")", ";", "listener", ".", "apply", "(", "context", ",", "arguments", ")", ";", "}", ";", "timeout", "=", "setTimeout", "(", "function", "(", ")", "{", "this", ".", "off", "(", "event", ",", "handler", ",", "context", ")", ";", "listener", ".", "call", "(", "context", ",", "\"timeout\"", ")", ";", "}", ".", "bind", "(", "this", ")", ",", "wait", ")", ";", "this", ".", "once", "(", "event", ",", "handler", ",", "context", ")", ";", "}" ]
Waits for wait ms for event to fire or calls listener with error, removing listener
[ "Waits", "for", "wait", "ms", "for", "event", "to", "fire", "or", "calls", "listener", "with", "error", "removing", "listener" ]
33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1
https://github.com/Cloud9Trader/oanda-adapter/blob/33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1/lib/Events.js#L20-L34
train
Cloud9Trader/oanda-adapter
lib/Events.js
listenFor
function listenFor (event, listener, context, duration) { setTimeout(function () { this.off(event, listener, context); }.bind(this), duration); this.on(event, listener, context); }
javascript
function listenFor (event, listener, context, duration) { setTimeout(function () { this.off(event, listener, context); }.bind(this), duration); this.on(event, listener, context); }
[ "function", "listenFor", "(", "event", ",", "listener", ",", "context", ",", "duration", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "this", ".", "off", "(", "event", ",", "listener", ",", "context", ")", ";", "}", ".", "bind", "(", "this", ")", ",", "duration", ")", ";", "this", ".", "on", "(", "event", ",", "listener", ",", "context", ")", ";", "}" ]
Listens for duration ms for events to fire, then removes listener
[ "Listens", "for", "duration", "ms", "for", "events", "to", "fire", "then", "removes", "listener" ]
33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1
https://github.com/Cloud9Trader/oanda-adapter/blob/33dcc3955ec965b0d7724fd8804ac2f0bf6f89c1/lib/Events.js#L37-L42
train
flux-capacitor/flux-capacitor
packages/flux-capacitor-sequelize/lib/connectTo.js
connectTo
function connectTo (connectionSettings, createCollections) { const sequelize = new Sequelize(connectionSettings) const collections = createCollections(sequelize, createCollection) const database = { /** @property {Sequelize} connection */ connection: sequelize, /** @property {Object} collections { [name: string]: Collection } */ collections: collectionsAsKeyValue(collections), applyChangeset (changeset, options) { options = options || { transaction: null } return changeset.apply(options.transaction) }, createEventId () { return uuid.v4() }, transaction (callback) { return sequelize.transaction((sequelizeTransaction) => { const transaction = createTransaction(database, sequelizeTransaction) return callback(transaction) }) } } return sequelize.sync().then(() => database) }
javascript
function connectTo (connectionSettings, createCollections) { const sequelize = new Sequelize(connectionSettings) const collections = createCollections(sequelize, createCollection) const database = { /** @property {Sequelize} connection */ connection: sequelize, /** @property {Object} collections { [name: string]: Collection } */ collections: collectionsAsKeyValue(collections), applyChangeset (changeset, options) { options = options || { transaction: null } return changeset.apply(options.transaction) }, createEventId () { return uuid.v4() }, transaction (callback) { return sequelize.transaction((sequelizeTransaction) => { const transaction = createTransaction(database, sequelizeTransaction) return callback(transaction) }) } } return sequelize.sync().then(() => database) }
[ "function", "connectTo", "(", "connectionSettings", ",", "createCollections", ")", "{", "const", "sequelize", "=", "new", "Sequelize", "(", "connectionSettings", ")", "const", "collections", "=", "createCollections", "(", "sequelize", ",", "createCollection", ")", "const", "database", "=", "{", "connection", ":", "sequelize", ",", "collections", ":", "collectionsAsKeyValue", "(", "collections", ")", ",", "applyChangeset", "(", "changeset", ",", "options", ")", "{", "options", "=", "options", "||", "{", "transaction", ":", "null", "}", "return", "changeset", ".", "apply", "(", "options", ".", "transaction", ")", "}", ",", "createEventId", "(", ")", "{", "return", "uuid", ".", "v4", "(", ")", "}", ",", "transaction", "(", "callback", ")", "{", "return", "sequelize", ".", "transaction", "(", "(", "sequelizeTransaction", ")", "=>", "{", "const", "transaction", "=", "createTransaction", "(", "database", ",", "sequelizeTransaction", ")", "return", "callback", "(", "transaction", ")", "}", ")", "}", "}", "return", "sequelize", ".", "sync", "(", ")", ".", "then", "(", "(", ")", "=>", "database", ")", "}" ]
Connect to a database using Sequelize ORM. @param {string|object} connectionSettings Connection URL like `sqlite://path/to/db.sqlite` or object: `{ database: string, host: string, dialect: string, ... }` @param {Function} createCollections (sequelize: Sequelize, createCollection: (name: string, model: Sequelize.Model) => Collection) => Array<Collection> @return {Database}
[ "Connect", "to", "a", "database", "using", "Sequelize", "ORM", "." ]
66393138ecdff9c1ba81d88b53144220e593584f
https://github.com/flux-capacitor/flux-capacitor/blob/66393138ecdff9c1ba81d88b53144220e593584f/packages/flux-capacitor-sequelize/lib/connectTo.js#L17-L46
train
googlearchive/net-chromeify
examples/client/bundle.js
stringifyObject
function stringifyObject(obj, prefix) { var ret = [] , keys = objectKeys(obj) , key; for (var i = 0, len = keys.length; i < len; ++i) { key = keys[i]; ret.push(stringify(obj[key], prefix ? prefix + '[' + encodeURIComponent(key) + ']' : encodeURIComponent(key))); } return ret.join('&'); }
javascript
function stringifyObject(obj, prefix) { var ret = [] , keys = objectKeys(obj) , key; for (var i = 0, len = keys.length; i < len; ++i) { key = keys[i]; ret.push(stringify(obj[key], prefix ? prefix + '[' + encodeURIComponent(key) + ']' : encodeURIComponent(key))); } return ret.join('&'); }
[ "function", "stringifyObject", "(", "obj", ",", "prefix", ")", "{", "var", "ret", "=", "[", "]", ",", "keys", "=", "objectKeys", "(", "obj", ")", ",", "key", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "keys", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "key", "=", "keys", "[", "i", "]", ";", "ret", ".", "push", "(", "stringify", "(", "obj", "[", "key", "]", ",", "prefix", "?", "prefix", "+", "'['", "+", "encodeURIComponent", "(", "key", ")", "+", "']'", ":", "encodeURIComponent", "(", "key", ")", ")", ")", ";", "}", "return", "ret", ".", "join", "(", "'&'", ")", ";", "}" ]
Stringify the given `obj`. @param {Object} obj @param {String} prefix @return {String} @api private
[ "Stringify", "the", "given", "obj", "." ]
566cd7a24e03a5947e8851f338a9eee054a42824
https://github.com/googlearchive/net-chromeify/blob/566cd7a24e03a5947e8851f338a9eee054a42824/examples/client/bundle.js#L3905-L3916
train
Esri/geotrigger-js
geotrigger.js
function(target, obj){ for (var attr in obj) { if(obj.hasOwnProperty(attr)){ target[attr] = obj[attr]; } } return target; }
javascript
function(target, obj){ for (var attr in obj) { if(obj.hasOwnProperty(attr)){ target[attr] = obj[attr]; } } return target; }
[ "function", "(", "target", ",", "obj", ")", "{", "for", "(", "var", "attr", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "target", "[", "attr", "]", "=", "obj", "[", "attr", "]", ";", "}", "}", "return", "target", ";", "}" ]
Merge Object 1 and Object 2. Properties from Object 2 will override properties in Object 1. Returns Object 1
[ "Merge", "Object", "1", "and", "Object", "2", ".", "Properties", "from", "Object", "2", "will", "override", "properties", "in", "Object", "1", ".", "Returns", "Object", "1" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/geotrigger.js#L355-L362
train
stefanjudis/credits
lib/analyzers/jspm/index.js
getCredits
function getCredits(projectPath, credits) { credits = credits || []; const jspmPath = path.join(projectPath, 'jspm_packages'); globby.sync([`${jspmPath}/npm/*/package.json`, `${jspmPath}/github/*/*/{package.json,bower.json}`]) .forEach(packagePath => { if (path.basename(packagePath) === 'bower.json') { return getBowerCredits(packagePath, credits); } return getNpmCredits(packagePath, credits); }); return credits; }
javascript
function getCredits(projectPath, credits) { credits = credits || []; const jspmPath = path.join(projectPath, 'jspm_packages'); globby.sync([`${jspmPath}/npm/*/package.json`, `${jspmPath}/github/*/*/{package.json,bower.json}`]) .forEach(packagePath => { if (path.basename(packagePath) === 'bower.json') { return getBowerCredits(packagePath, credits); } return getNpmCredits(packagePath, credits); }); return credits; }
[ "function", "getCredits", "(", "projectPath", ",", "credits", ")", "{", "credits", "=", "credits", "||", "[", "]", ";", "const", "jspmPath", "=", "path", ".", "join", "(", "projectPath", ",", "'jspm_packages'", ")", ";", "globby", ".", "sync", "(", "[", "`", "${", "jspmPath", "}", "`", ",", "`", "${", "jspmPath", "}", "`", "]", ")", ".", "forEach", "(", "packagePath", "=>", "{", "if", "(", "path", ".", "basename", "(", "packagePath", ")", "===", "'bower.json'", ")", "{", "return", "getBowerCredits", "(", "packagePath", ",", "credits", ")", ";", "}", "return", "getNpmCredits", "(", "packagePath", ",", "credits", ")", ";", "}", ")", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for jspm modules @param {String} projectPath absolute path to project root @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "jspm", "modules" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/jspm/index.js#L16-L30
train
stefanjudis/credits
lib/credit.js
getCredit
function getCredit(credits, author) { const credit = credits.filter(credit => { // Fallback to name when no email // is available if (credit.email && author.email) { return credit.email === author.email; } return credit.name === author.name; }); return credit.length > 0 ? credit[0] : false; }
javascript
function getCredit(credits, author) { const credit = credits.filter(credit => { // Fallback to name when no email // is available if (credit.email && author.email) { return credit.email === author.email; } return credit.name === author.name; }); return credit.length > 0 ? credit[0] : false; }
[ "function", "getCredit", "(", "credits", ",", "author", ")", "{", "const", "credit", "=", "credits", ".", "filter", "(", "credit", "=>", "{", "if", "(", "credit", ".", "email", "&&", "author", ".", "email", ")", "{", "return", "credit", ".", "email", "===", "author", ".", "email", ";", "}", "return", "credit", ".", "name", "===", "author", ".", "name", ";", "}", ")", ";", "return", "credit", ".", "length", ">", "0", "?", "credit", "[", "0", "]", ":", "false", ";", "}" ]
Get credit out of running credits list @param {Array} credits list of credits @param {Object} author author @return {Object|false} existing credit or false @tested
[ "Get", "credit", "out", "of", "running", "credits", "list" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/credit.js#L13-L27
train
stefanjudis/credits
lib/credit.js
addCreditToCredits
function addCreditToCredits(credits, person, name) { let credit = getCredit(credits, person); if (!credit) { credit = person; credit.packages = []; credits.push(credit); } if (credit.packages.indexOf(name) === -1) { credit.packages.push(name); } return credits; }
javascript
function addCreditToCredits(credits, person, name) { let credit = getCredit(credits, person); if (!credit) { credit = person; credit.packages = []; credits.push(credit); } if (credit.packages.indexOf(name) === -1) { credit.packages.push(name); } return credits; }
[ "function", "addCreditToCredits", "(", "credits", ",", "person", ",", "name", ")", "{", "let", "credit", "=", "getCredit", "(", "credits", ",", "person", ")", ";", "if", "(", "!", "credit", ")", "{", "credit", "=", "person", ";", "credit", ".", "packages", "=", "[", "]", ";", "credits", ".", "push", "(", "credit", ")", ";", "}", "if", "(", "credit", ".", "packages", ".", "indexOf", "(", "name", ")", "===", "-", "1", ")", "{", "credit", ".", "packages", ".", "push", "(", "name", ")", ";", "}", "return", "credits", ";", "}" ]
Add a credit to running credits list @param {Array} credits list of credits @param {Object} person person to give credit @param {String} name project name to attach to person @return {Array} list of credits @tested
[ "Add", "a", "credit", "to", "running", "credits", "list" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/credit.js#L40-L55
train
florianheinemann/passwordless-redisstore
lib/redisstore.js
RedisStore
function RedisStore(port, host, options) { port = port || 6379; host = host || '127.0.0.1'; this._options = options || {}; this._options.redisstore = this._options.redisstore || {}; if(this._options.redisstore.database && !isNumber(this._options.redisstore.database)) { throw new Error('database has to be a number (if provided at all)'); } else if(this._options.redisstore.database) { this._database = this._options.redisstore.database; } else { this._database = 0; } this._tokenKey = this._options.redisstore.tokenkey || 'pwdless:'; delete this._options.redisstore; this._client = redis.createClient(port, host, this._options); }
javascript
function RedisStore(port, host, options) { port = port || 6379; host = host || '127.0.0.1'; this._options = options || {}; this._options.redisstore = this._options.redisstore || {}; if(this._options.redisstore.database && !isNumber(this._options.redisstore.database)) { throw new Error('database has to be a number (if provided at all)'); } else if(this._options.redisstore.database) { this._database = this._options.redisstore.database; } else { this._database = 0; } this._tokenKey = this._options.redisstore.tokenkey || 'pwdless:'; delete this._options.redisstore; this._client = redis.createClient(port, host, this._options); }
[ "function", "RedisStore", "(", "port", ",", "host", ",", "options", ")", "{", "port", "=", "port", "||", "6379", ";", "host", "=", "host", "||", "'127.0.0.1'", ";", "this", ".", "_options", "=", "options", "||", "{", "}", ";", "this", ".", "_options", ".", "redisstore", "=", "this", ".", "_options", ".", "redisstore", "||", "{", "}", ";", "if", "(", "this", ".", "_options", ".", "redisstore", ".", "database", "&&", "!", "isNumber", "(", "this", ".", "_options", ".", "redisstore", ".", "database", ")", ")", "{", "throw", "new", "Error", "(", "'database has to be a number (if provided at all)'", ")", ";", "}", "else", "if", "(", "this", ".", "_options", ".", "redisstore", ".", "database", ")", "{", "this", ".", "_database", "=", "this", ".", "_options", ".", "redisstore", ".", "database", ";", "}", "else", "{", "this", ".", "_database", "=", "0", ";", "}", "this", ".", "_tokenKey", "=", "this", ".", "_options", ".", "redisstore", ".", "tokenkey", "||", "'pwdless:'", ";", "delete", "this", ".", "_options", ".", "redisstore", ";", "this", ".", "_client", "=", "redis", ".", "createClient", "(", "port", ",", "host", ",", "this", ".", "_options", ")", ";", "}" ]
Constructor of RedisStore @param {Number} [port] Port of the Redis server (default: 6379) @param {String} [host] Host, e.g. 127.0.0.1 (default: 127.0.0.1) @param {Object} [options] Combines both the options for the Redis client as well as the options for RedisStore. For the Redis options please refer back to the documentation: https://github.com/NodeRedis/node_redis. RedisStore accepts the following options: (1) { redisstore: { database: Number }} number of the Redis database to use (default: 0), (2) { redisstore: { tokenkey: String }} the prefix used for the RedisStore entries in the database (default: 'pwdless:') @constructor
[ "Constructor", "of", "RedisStore" ]
021ffb1dca599884f35c2f7e3e4105799c9aba54
https://github.com/florianheinemann/passwordless-redisstore/blob/021ffb1dca599884f35c2f7e3e4105799c9aba54/lib/redisstore.js#L21-L38
train
7digital/7digital-api
lib/oauth.js
createOAuthWrapper
function createOAuthWrapper(oauthkey, oauthsecret, headers) { return new OAuthClient( 'https://api.7digital.com/1.2/oauth/requesttoken', accessTokenUrl, oauthkey, oauthsecret, '1.0', null, 'HMAC-SHA1', 32, headers); }
javascript
function createOAuthWrapper(oauthkey, oauthsecret, headers) { return new OAuthClient( 'https://api.7digital.com/1.2/oauth/requesttoken', accessTokenUrl, oauthkey, oauthsecret, '1.0', null, 'HMAC-SHA1', 32, headers); }
[ "function", "createOAuthWrapper", "(", "oauthkey", ",", "oauthsecret", ",", "headers", ")", "{", "return", "new", "OAuthClient", "(", "'https://api.7digital.com/1.2/oauth/requesttoken'", ",", "accessTokenUrl", ",", "oauthkey", ",", "oauthsecret", ",", "'1.0'", ",", "null", ",", "'HMAC-SHA1'", ",", "32", ",", "headers", ")", ";", "}" ]
Creates an OAuth v1 wrapper configured with the supplied key and secret and the necessary options for authenticating with the 7digital API. - @param {String} oauthkey - @param {String} oauthsecret - @return {OAuth}
[ "Creates", "an", "OAuth", "v1", "wrapper", "configured", "with", "the", "supplied", "key", "and", "secret", "and", "the", "necessary", "options", "for", "authenticating", "with", "the", "7digital", "API", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/oauth.js#L17-L24
train
brettz9/miller-columns
dist/index-es.js
breadcrumb
function breadcrumb() { const $breadcrumb = $(`.${namespace}-breadcrumbs`).empty(); chain().each(function () { const $crumb = $(this); $(`<span class="${namespace}-breadcrumb">`).text($crumb.text().trim()).click(function () { $crumb.click(); }).appendTo($breadcrumb); }); }
javascript
function breadcrumb() { const $breadcrumb = $(`.${namespace}-breadcrumbs`).empty(); chain().each(function () { const $crumb = $(this); $(`<span class="${namespace}-breadcrumb">`).text($crumb.text().trim()).click(function () { $crumb.click(); }).appendTo($breadcrumb); }); }
[ "function", "breadcrumb", "(", ")", "{", "const", "$breadcrumb", "=", "$", "(", "`", "${", "namespace", "}", "`", ")", ".", "empty", "(", ")", ";", "chain", "(", ")", ".", "each", "(", "function", "(", ")", "{", "const", "$crumb", "=", "$", "(", "this", ")", ";", "$", "(", "`", "${", "namespace", "}", "`", ")", ".", "text", "(", "$crumb", ".", "text", "(", ")", ".", "trim", "(", ")", ")", ".", "click", "(", "function", "(", ")", "{", "$crumb", ".", "click", "(", ")", ";", "}", ")", ".", "appendTo", "(", "$breadcrumb", ")", ";", "}", ")", ";", "}" ]
Add the breadcrumb path using the chain of selected items.
[ "Add", "the", "breadcrumb", "path", "using", "the", "chain", "of", "selected", "items", "." ]
98f0711d6ccdc198265c47290159a481145517e8
https://github.com/brettz9/miller-columns/blob/98f0711d6ccdc198265c47290159a481145517e8/dist/index-es.js#L120-L129
train
brettz9/miller-columns
dist/index-es.js
animation
function animation($column, $columns) { let width = 0; chain().not($column).each(function () { width += $(this).outerWidth(true); }); $columns.stop().animate({ scrollLeft: width }, settings.delay, function () { const last = $columns.find(`.${namespace}-column:not(.${namespace}-collapse)`).last(); // last[0].scrollIntoView(); // Scrolls vertically also unfortunately last[0].scrollLeft = width; if (settings.scroll) { settings.scroll.call(this, $column, $columns); } }); }
javascript
function animation($column, $columns) { let width = 0; chain().not($column).each(function () { width += $(this).outerWidth(true); }); $columns.stop().animate({ scrollLeft: width }, settings.delay, function () { const last = $columns.find(`.${namespace}-column:not(.${namespace}-collapse)`).last(); // last[0].scrollIntoView(); // Scrolls vertically also unfortunately last[0].scrollLeft = width; if (settings.scroll) { settings.scroll.call(this, $column, $columns); } }); }
[ "function", "animation", "(", "$column", ",", "$columns", ")", "{", "let", "width", "=", "0", ";", "chain", "(", ")", ".", "not", "(", "$column", ")", ".", "each", "(", "function", "(", ")", "{", "width", "+=", "$", "(", "this", ")", ".", "outerWidth", "(", "true", ")", ";", "}", ")", ";", "$columns", ".", "stop", "(", ")", ".", "animate", "(", "{", "scrollLeft", ":", "width", "}", ",", "settings", ".", "delay", ",", "function", "(", ")", "{", "const", "last", "=", "$columns", ".", "find", "(", "`", "${", "namespace", "}", "${", "namespace", "}", "`", ")", ".", "last", "(", ")", ";", "last", "[", "0", "]", ".", "scrollLeft", "=", "width", ";", "if", "(", "settings", ".", "scroll", ")", "{", "settings", ".", "scroll", ".", "call", "(", "this", ",", "$column", ",", "$columns", ")", ";", "}", "}", ")", ";", "}" ]
Ensure the viewport shows the entire newly expanded item.
[ "Ensure", "the", "viewport", "shows", "the", "entire", "newly", "expanded", "item", "." ]
98f0711d6ccdc198265c47290159a481145517e8
https://github.com/brettz9/miller-columns/blob/98f0711d6ccdc198265c47290159a481145517e8/dist/index-es.js#L132-L147
train
brettz9/miller-columns
dist/index-es.js
unnest
function unnest($columns) { const queue = []; let $node; // Push the root unordered list item into the queue. queue.push($columns.children()); while (queue.length) { $node = queue.shift(); $node.children(itemSelector).each(function (item, el) { const $this = $(this); const $child = $this.children(columnSelector), $ancestor = $this.parent().parent(); // Retain item hierarchy (because it is lost after flattening). if ($ancestor.length && $this.data(`${namespace}-ancestor`) == null) { // Use addBack to reset all selection chains. $(this).siblings().addBack().data(`${namespace}-ancestor`, $ancestor); } if ($child.length) { queue.push($child); $(this).data(`${namespace}-child`, $child).addClass(`${namespace}-parent`); } // Causes item siblings to have a flattened DOM lineage. $(this).parent(columnSelector).appendTo($columns).addClass(`${namespace}-column`); }); } }
javascript
function unnest($columns) { const queue = []; let $node; // Push the root unordered list item into the queue. queue.push($columns.children()); while (queue.length) { $node = queue.shift(); $node.children(itemSelector).each(function (item, el) { const $this = $(this); const $child = $this.children(columnSelector), $ancestor = $this.parent().parent(); // Retain item hierarchy (because it is lost after flattening). if ($ancestor.length && $this.data(`${namespace}-ancestor`) == null) { // Use addBack to reset all selection chains. $(this).siblings().addBack().data(`${namespace}-ancestor`, $ancestor); } if ($child.length) { queue.push($child); $(this).data(`${namespace}-child`, $child).addClass(`${namespace}-parent`); } // Causes item siblings to have a flattened DOM lineage. $(this).parent(columnSelector).appendTo($columns).addClass(`${namespace}-column`); }); } }
[ "function", "unnest", "(", "$columns", ")", "{", "const", "queue", "=", "[", "]", ";", "let", "$node", ";", "queue", ".", "push", "(", "$columns", ".", "children", "(", ")", ")", ";", "while", "(", "queue", ".", "length", ")", "{", "$node", "=", "queue", ".", "shift", "(", ")", ";", "$node", ".", "children", "(", "itemSelector", ")", ".", "each", "(", "function", "(", "item", ",", "el", ")", "{", "const", "$this", "=", "$", "(", "this", ")", ";", "const", "$child", "=", "$this", ".", "children", "(", "columnSelector", ")", ",", "$ancestor", "=", "$this", ".", "parent", "(", ")", ".", "parent", "(", ")", ";", "if", "(", "$ancestor", ".", "length", "&&", "$this", ".", "data", "(", "`", "${", "namespace", "}", "`", ")", "==", "null", ")", "{", "$", "(", "this", ")", ".", "siblings", "(", ")", ".", "addBack", "(", ")", ".", "data", "(", "`", "${", "namespace", "}", "`", ",", "$ancestor", ")", ";", "}", "if", "(", "$child", ".", "length", ")", "{", "queue", ".", "push", "(", "$child", ")", ";", "$", "(", "this", ")", ".", "data", "(", "`", "${", "namespace", "}", "`", ",", "$child", ")", ".", "addClass", "(", "`", "${", "namespace", "}", "`", ")", ";", "}", "$", "(", "this", ")", ".", "parent", "(", "columnSelector", ")", ".", "appendTo", "(", "$columns", ")", ".", "addClass", "(", "`", "${", "namespace", "}", "`", ")", ";", "}", ")", ";", "}", "}" ]
Convert nested lists into columns using breadth-first traversal.
[ "Convert", "nested", "lists", "into", "columns", "using", "breadth", "-", "first", "traversal", "." ]
98f0711d6ccdc198265c47290159a481145517e8
https://github.com/brettz9/miller-columns/blob/98f0711d6ccdc198265c47290159a481145517e8/dist/index-es.js#L150-L180
train
stefanjudis/credits
lib/package.js
getAllStar
function getAllStar(person) { // Override properties from all-stars if available const allStar = allStars(person); return allStar ? objectAssign(person, allStar.subset()) : person; }
javascript
function getAllStar(person) { // Override properties from all-stars if available const allStar = allStars(person); return allStar ? objectAssign(person, allStar.subset()) : person; }
[ "function", "getAllStar", "(", "person", ")", "{", "const", "allStar", "=", "allStars", "(", "person", ")", ";", "return", "allStar", "?", "objectAssign", "(", "person", ",", "allStar", ".", "subset", "(", ")", ")", ":", "person", ";", "}" ]
Check all-stars db for given person and assign to person if found. @param {Object} person object representing author or maintainer @return {Object} same object given, possibly modified or augmented
[ "Check", "all", "-", "stars", "db", "for", "given", "person", "and", "assign", "to", "person", "if", "found", "." ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L28-L32
train
stefanjudis/credits
lib/package.js
getPersonObject
function getPersonObject(personString) { const regex = personString.match(/^(.*?)\s?(<(.*)>)?\s?(\((.*)\))?\s?$/); return getAllStar({ name: regex[1], email: regex[3], url: regex[5] }); }
javascript
function getPersonObject(personString) { const regex = personString.match(/^(.*?)\s?(<(.*)>)?\s?(\((.*)\))?\s?$/); return getAllStar({ name: regex[1], email: regex[3], url: regex[5] }); }
[ "function", "getPersonObject", "(", "personString", ")", "{", "const", "regex", "=", "personString", ".", "match", "(", "/", "^(.*?)\\s?(<(.*)>)?\\s?(\\((.*)\\))?\\s?$", "/", ")", ";", "return", "getAllStar", "(", "{", "name", ":", "regex", "[", "1", "]", ",", "email", ":", "regex", "[", "3", "]", ",", "url", ":", "regex", "[", "5", "]", "}", ")", ";", "}" ]
Parse npm string shorthand into object representation @param {String} personString string shorthand for author or maintainer @return {Object} object representing author or maintainer
[ "Parse", "npm", "string", "shorthand", "into", "object", "representation" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L41-L49
train
stefanjudis/credits
lib/package.js
getAuthor
function getAuthor(packageJson) { if (Array.isArray(packageJson.authors)) { packageJson.authors = packageJson.authors.map(author => { if (typeof author === 'string') { return getPersonObject(author); } return getAllStar(author); }); return packageJson.authors ? packageJson.authors : false; } if (typeof packageJson.author === 'string') { return getPersonObject(packageJson.author); } return packageJson.author ? getAllStar(packageJson.author) : false; }
javascript
function getAuthor(packageJson) { if (Array.isArray(packageJson.authors)) { packageJson.authors = packageJson.authors.map(author => { if (typeof author === 'string') { return getPersonObject(author); } return getAllStar(author); }); return packageJson.authors ? packageJson.authors : false; } if (typeof packageJson.author === 'string') { return getPersonObject(packageJson.author); } return packageJson.author ? getAllStar(packageJson.author) : false; }
[ "function", "getAuthor", "(", "packageJson", ")", "{", "if", "(", "Array", ".", "isArray", "(", "packageJson", ".", "authors", ")", ")", "{", "packageJson", ".", "authors", "=", "packageJson", ".", "authors", ".", "map", "(", "author", "=>", "{", "if", "(", "typeof", "author", "===", "'string'", ")", "{", "return", "getPersonObject", "(", "author", ")", ";", "}", "return", "getAllStar", "(", "author", ")", ";", "}", ")", ";", "return", "packageJson", ".", "authors", "?", "packageJson", ".", "authors", ":", "false", ";", "}", "if", "(", "typeof", "packageJson", ".", "author", "===", "'string'", ")", "{", "return", "getPersonObject", "(", "packageJson", ".", "author", ")", ";", "}", "return", "packageJson", ".", "author", "?", "getAllStar", "(", "packageJson", ".", "author", ")", ":", "false", ";", "}" ]
Extract author from package.json content @param {Object} packageJson content of package.json @return {Object|false} author if exists or false @tested
[ "Extract", "author", "from", "package", ".", "json", "content" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L60-L80
train
stefanjudis/credits
lib/package.js
getMaintainers
function getMaintainers(packageJson) { if (Array.isArray(packageJson.maintainers)) { packageJson.maintainers = packageJson.maintainers.map(maintainer => { if (typeof maintainer === 'string') { return getPersonObject(maintainer); } return getAllStar(maintainer); }); } // Safety fix for people doing // -> "maintainers" : "Bob <some.email>" if (typeof packageJson.maintainers === 'string') { packageJson.maintainers = [getPersonObject(packageJson.maintainers)]; } return packageJson.maintainers ? packageJson.maintainers : false; }
javascript
function getMaintainers(packageJson) { if (Array.isArray(packageJson.maintainers)) { packageJson.maintainers = packageJson.maintainers.map(maintainer => { if (typeof maintainer === 'string') { return getPersonObject(maintainer); } return getAllStar(maintainer); }); } // Safety fix for people doing // -> "maintainers" : "Bob <some.email>" if (typeof packageJson.maintainers === 'string') { packageJson.maintainers = [getPersonObject(packageJson.maintainers)]; } return packageJson.maintainers ? packageJson.maintainers : false; }
[ "function", "getMaintainers", "(", "packageJson", ")", "{", "if", "(", "Array", ".", "isArray", "(", "packageJson", ".", "maintainers", ")", ")", "{", "packageJson", ".", "maintainers", "=", "packageJson", ".", "maintainers", ".", "map", "(", "maintainer", "=>", "{", "if", "(", "typeof", "maintainer", "===", "'string'", ")", "{", "return", "getPersonObject", "(", "maintainer", ")", ";", "}", "return", "getAllStar", "(", "maintainer", ")", ";", "}", ")", ";", "}", "if", "(", "typeof", "packageJson", ".", "maintainers", "===", "'string'", ")", "{", "packageJson", ".", "maintainers", "=", "[", "getPersonObject", "(", "packageJson", ".", "maintainers", ")", "]", ";", "}", "return", "packageJson", ".", "maintainers", "?", "packageJson", ".", "maintainers", ":", "false", ";", "}" ]
Extract maintainers from package.json content @param {Object} packageJson content of package.json @return {Array} maintainers if exists or false @tested
[ "Extract", "maintainers", "from", "package", ".", "json", "content" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/package.js#L91-L111
train
stefanjudis/credits
lib/analyzers/npm/index.js
getNpmCredits
function getNpmCredits(packagePath, credits) { const directoryPath = path.dirname(packagePath); const name = path.basename(path.dirname(packagePath)); if ( name[0] !== '.' && ( fs.lstatSync(directoryPath).isDirectory() || fs.lstatSync(directoryPath).isSymbolicLink() ) ) { const packageJson = packageUtil.readJSONSync(packagePath); const author = packageUtil.getAuthor(packageJson); const maintainers = packageUtil.getMaintainers(packageJson); if (author) { credits = creditUtil.addCreditToCredits(credits, author, name); } if (maintainers) { maintainers.forEach(maintainer => { credits = creditUtil.addCreditToCredits(credits, maintainer, name); }); } } return credits; }
javascript
function getNpmCredits(packagePath, credits) { const directoryPath = path.dirname(packagePath); const name = path.basename(path.dirname(packagePath)); if ( name[0] !== '.' && ( fs.lstatSync(directoryPath).isDirectory() || fs.lstatSync(directoryPath).isSymbolicLink() ) ) { const packageJson = packageUtil.readJSONSync(packagePath); const author = packageUtil.getAuthor(packageJson); const maintainers = packageUtil.getMaintainers(packageJson); if (author) { credits = creditUtil.addCreditToCredits(credits, author, name); } if (maintainers) { maintainers.forEach(maintainer => { credits = creditUtil.addCreditToCredits(credits, maintainer, name); }); } } return credits; }
[ "function", "getNpmCredits", "(", "packagePath", ",", "credits", ")", "{", "const", "directoryPath", "=", "path", ".", "dirname", "(", "packagePath", ")", ";", "const", "name", "=", "path", ".", "basename", "(", "path", ".", "dirname", "(", "packagePath", ")", ")", ";", "if", "(", "name", "[", "0", "]", "!==", "'.'", "&&", "(", "fs", ".", "lstatSync", "(", "directoryPath", ")", ".", "isDirectory", "(", ")", "||", "fs", ".", "lstatSync", "(", "directoryPath", ")", ".", "isSymbolicLink", "(", ")", ")", ")", "{", "const", "packageJson", "=", "packageUtil", ".", "readJSONSync", "(", "packagePath", ")", ";", "const", "author", "=", "packageUtil", ".", "getAuthor", "(", "packageJson", ")", ";", "const", "maintainers", "=", "packageUtil", ".", "getMaintainers", "(", "packageJson", ")", ";", "if", "(", "author", ")", "{", "credits", "=", "creditUtil", ".", "addCreditToCredits", "(", "credits", ",", "author", ",", "name", ")", ";", "}", "if", "(", "maintainers", ")", "{", "maintainers", ".", "forEach", "(", "maintainer", "=>", "{", "credits", "=", "creditUtil", ".", "addCreditToCredits", "(", "credits", ",", "maintainer", ",", "name", ")", ";", "}", ")", ";", "}", "}", "return", "credits", ";", "}" ]
Read and evaluate dependency credits for npm module @param {String} packagePath absolute path to package.json file @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "and", "evaluate", "dependency", "credits", "for", "npm", "module" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/npm/index.js#L17-L44
train
stefanjudis/credits
lib/analyzers/npm/index.js
getCredits
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'node_modules'); globby.sync(`${depPath}/**/package.json`) .forEach(packagePath => { getNpmCredits(packagePath, credits); }); return credits; }
javascript
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'node_modules'); globby.sync(`${depPath}/**/package.json`) .forEach(packagePath => { getNpmCredits(packagePath, credits); }); return credits; }
[ "function", "getCredits", "(", "projectPath", ",", "credits", ")", "{", "credits", "=", "credits", "||", "[", "]", ";", "const", "depPath", "=", "path", ".", "join", "(", "projectPath", ",", "'node_modules'", ")", ";", "globby", ".", "sync", "(", "`", "${", "depPath", "}", "`", ")", ".", "forEach", "(", "packagePath", "=>", "{", "getNpmCredits", "(", "packagePath", ",", "credits", ")", ";", "}", ")", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for node modules @param {String} projectPath absolute path to project root @param {Array|undefined} credits list of credits @param {Array|undefined} seen list of already iterated packages @return {Array} list of credits
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "node", "modules" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/npm/index.js#L55-L66
train
knockout/tko.provider
src/provider.js
preProcessBindings
function preProcessBindings(bindingString) { var results = []; var bindingHandlers = this.bindingHandlers; var preprocessed; // Check for a Provider.preprocessNode property if (typeof this.preprocessNode === 'function') { preprocessed = this.preprocessNode(bindingString, this); if (preprocessed) { bindingString = preprocessed; } } for (var i = 0, j = this.bindingPreProcessors.length; i < j; ++i) { preprocessed = this.bindingPreProcessors[i](bindingString, this); if (preprocessed) { bindingString = preprocessed; } } function addBinding(name, value) { results.push("'" + name + "':" + value); } function processBinding(key, value) { // Get the "on" binding from "on.click" var handler = bindingHandlers.get(key.split('.')[0]); if (handler && typeof handler.preprocess === 'function') { value = handler.preprocess(value, key, processBinding); } addBinding(key, value); } arrayForEach(parseObjectLiteral(bindingString), function(keyValueItem) { processBinding( keyValueItem.key || keyValueItem.unknown, keyValueItem.value ); }); return results.join(','); }
javascript
function preProcessBindings(bindingString) { var results = []; var bindingHandlers = this.bindingHandlers; var preprocessed; // Check for a Provider.preprocessNode property if (typeof this.preprocessNode === 'function') { preprocessed = this.preprocessNode(bindingString, this); if (preprocessed) { bindingString = preprocessed; } } for (var i = 0, j = this.bindingPreProcessors.length; i < j; ++i) { preprocessed = this.bindingPreProcessors[i](bindingString, this); if (preprocessed) { bindingString = preprocessed; } } function addBinding(name, value) { results.push("'" + name + "':" + value); } function processBinding(key, value) { // Get the "on" binding from "on.click" var handler = bindingHandlers.get(key.split('.')[0]); if (handler && typeof handler.preprocess === 'function') { value = handler.preprocess(value, key, processBinding); } addBinding(key, value); } arrayForEach(parseObjectLiteral(bindingString), function(keyValueItem) { processBinding( keyValueItem.key || keyValueItem.unknown, keyValueItem.value ); }); return results.join(','); }
[ "function", "preProcessBindings", "(", "bindingString", ")", "{", "var", "results", "=", "[", "]", ";", "var", "bindingHandlers", "=", "this", ".", "bindingHandlers", ";", "var", "preprocessed", ";", "if", "(", "typeof", "this", ".", "preprocessNode", "===", "'function'", ")", "{", "preprocessed", "=", "this", ".", "preprocessNode", "(", "bindingString", ",", "this", ")", ";", "if", "(", "preprocessed", ")", "{", "bindingString", "=", "preprocessed", ";", "}", "}", "for", "(", "var", "i", "=", "0", ",", "j", "=", "this", ".", "bindingPreProcessors", ".", "length", ";", "i", "<", "j", ";", "++", "i", ")", "{", "preprocessed", "=", "this", ".", "bindingPreProcessors", "[", "i", "]", "(", "bindingString", ",", "this", ")", ";", "if", "(", "preprocessed", ")", "{", "bindingString", "=", "preprocessed", ";", "}", "}", "function", "addBinding", "(", "name", ",", "value", ")", "{", "results", ".", "push", "(", "\"'\"", "+", "name", "+", "\"':\"", "+", "value", ")", ";", "}", "function", "processBinding", "(", "key", ",", "value", ")", "{", "var", "handler", "=", "bindingHandlers", ".", "get", "(", "key", ".", "split", "(", "'.'", ")", "[", "0", "]", ")", ";", "if", "(", "handler", "&&", "typeof", "handler", ".", "preprocess", "===", "'function'", ")", "{", "value", "=", "handler", ".", "preprocess", "(", "value", ",", "key", ",", "processBinding", ")", ";", "}", "addBinding", "(", "key", ",", "value", ")", ";", "}", "arrayForEach", "(", "parseObjectLiteral", "(", "bindingString", ")", ",", "function", "(", "keyValueItem", ")", "{", "processBinding", "(", "keyValueItem", ".", "key", "||", "keyValueItem", ".", "unknown", ",", "keyValueItem", ".", "value", ")", ";", "}", ")", ";", "return", "results", ".", "join", "(", "','", ")", ";", "}" ]
Call bindingHandler.preprocess on each respective binding string. The `preprocess` property of bindingHandler must be a static function (i.e. on the object or constructor).
[ "Call", "bindingHandler", ".", "preprocess", "on", "each", "respective", "binding", "string", "." ]
a157f31f5ab579b350eb6b64d92c92f9d6d4a385
https://github.com/knockout/tko.provider/blob/a157f31f5ab579b350eb6b64d92c92f9d6d4a385/src/provider.js#L131-L170
train
7digital/7digital-api
lib/parameters.js
template
function template(url, params) { var templated = url; var keys = _.keys(params); var loweredKeys = _.map(keys, function (key) { return key.toLowerCase(); }); var keyLookup = _.zipObject(loweredKeys, keys); _.each(templateParams(url), function replaceParam(param) { var normalisedParam = param.toLowerCase().substr(1); if (!keyLookup[normalisedParam]) { throw new Error('Missing ' + normalisedParam); } templated = templated.replace(param, params[keyLookup[normalisedParam]]); delete params[keyLookup[normalisedParam]]; }); return templated; }
javascript
function template(url, params) { var templated = url; var keys = _.keys(params); var loweredKeys = _.map(keys, function (key) { return key.toLowerCase(); }); var keyLookup = _.zipObject(loweredKeys, keys); _.each(templateParams(url), function replaceParam(param) { var normalisedParam = param.toLowerCase().substr(1); if (!keyLookup[normalisedParam]) { throw new Error('Missing ' + normalisedParam); } templated = templated.replace(param, params[keyLookup[normalisedParam]]); delete params[keyLookup[normalisedParam]]; }); return templated; }
[ "function", "template", "(", "url", ",", "params", ")", "{", "var", "templated", "=", "url", ";", "var", "keys", "=", "_", ".", "keys", "(", "params", ")", ";", "var", "loweredKeys", "=", "_", ".", "map", "(", "keys", ",", "function", "(", "key", ")", "{", "return", "key", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "var", "keyLookup", "=", "_", ".", "zipObject", "(", "loweredKeys", ",", "keys", ")", ";", "_", ".", "each", "(", "templateParams", "(", "url", ")", ",", "function", "replaceParam", "(", "param", ")", "{", "var", "normalisedParam", "=", "param", ".", "toLowerCase", "(", ")", ".", "substr", "(", "1", ")", ";", "if", "(", "!", "keyLookup", "[", "normalisedParam", "]", ")", "{", "throw", "new", "Error", "(", "'Missing '", "+", "normalisedParam", ")", ";", "}", "templated", "=", "templated", ".", "replace", "(", "param", ",", "params", "[", "keyLookup", "[", "normalisedParam", "]", "]", ")", ";", "delete", "params", "[", "keyLookup", "[", "normalisedParam", "]", "]", ";", "}", ")", ";", "return", "templated", ";", "}" ]
Given a url and some parameters replaces all named parameters with those supplied. - @param {String} url - the url to be modified - @param {Object} params - a hash of parameters to be put in the URL - @return {String} The url with the parameters replaced
[ "Given", "a", "url", "and", "some", "parameters", "replaces", "all", "named", "parameters", "with", "those", "supplied", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/parameters.js#L21-L42
train
stefanjudis/credits
index.js
readDirectory
function readDirectory( projectPath, analyzers ) { var credits = {}; for ( var analyzer in analyzers ) { credits[ analyzer ] = analyzers[ analyzer ]( projectPath ); }; return credits; }
javascript
function readDirectory( projectPath, analyzers ) { var credits = {}; for ( var analyzer in analyzers ) { credits[ analyzer ] = analyzers[ analyzer ]( projectPath ); }; return credits; }
[ "function", "readDirectory", "(", "projectPath", ",", "analyzers", ")", "{", "var", "credits", "=", "{", "}", ";", "for", "(", "var", "analyzer", "in", "analyzers", ")", "{", "credits", "[", "analyzer", "]", "=", "analyzers", "[", "analyzer", "]", "(", "projectPath", ")", ";", "}", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for all supported package managers @param {String} projectPath absolute path to project root @param {Array} analyzers list of availalbe analyzers @return {Array} list of credits @tested
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "all", "supported", "package", "managers" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/index.js#L22-L30
train
stefanjudis/credits
lib/analyzers/bower/index.js
getBowerCredits
function getBowerCredits(bowerJsonPath, credits) { const name = path.basename(path.dirname(bowerJsonPath)); const bowerJson = packageUtil.readJSONSync(bowerJsonPath); const authors = packageUtil.getAuthor(bowerJson); if (authors) { authors.forEach(author => { credits = creditUtil.addCreditToCredits(credits, author, name); }); } return credits; }
javascript
function getBowerCredits(bowerJsonPath, credits) { const name = path.basename(path.dirname(bowerJsonPath)); const bowerJson = packageUtil.readJSONSync(bowerJsonPath); const authors = packageUtil.getAuthor(bowerJson); if (authors) { authors.forEach(author => { credits = creditUtil.addCreditToCredits(credits, author, name); }); } return credits; }
[ "function", "getBowerCredits", "(", "bowerJsonPath", ",", "credits", ")", "{", "const", "name", "=", "path", ".", "basename", "(", "path", ".", "dirname", "(", "bowerJsonPath", ")", ")", ";", "const", "bowerJson", "=", "packageUtil", ".", "readJSONSync", "(", "bowerJsonPath", ")", ";", "const", "authors", "=", "packageUtil", ".", "getAuthor", "(", "bowerJson", ")", ";", "if", "(", "authors", ")", "{", "authors", ".", "forEach", "(", "author", "=>", "{", "credits", "=", "creditUtil", ".", "addCreditToCredits", "(", "credits", ",", "author", ",", "name", ")", ";", "}", ")", ";", "}", "return", "credits", ";", "}" ]
Read and evaluate dependency credits for bower module @param {String} bowerJsonPath absolute path to bower file @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "and", "evaluate", "dependency", "credits", "for", "bower", "module" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/bower/index.js#L16-L29
train
stefanjudis/credits
lib/analyzers/bower/index.js
getCredits
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'bower_components'); globby.sync([`${depPath}/*/bower.json`]) .forEach(bowerJsonPath => { getBowerCredits(bowerJsonPath, credits); }); return credits; }
javascript
function getCredits(projectPath, credits) { credits = credits || []; const depPath = path.join(projectPath, 'bower_components'); globby.sync([`${depPath}/*/bower.json`]) .forEach(bowerJsonPath => { getBowerCredits(bowerJsonPath, credits); }); return credits; }
[ "function", "getCredits", "(", "projectPath", ",", "credits", ")", "{", "credits", "=", "credits", "||", "[", "]", ";", "const", "depPath", "=", "path", ".", "join", "(", "projectPath", ",", "'bower_components'", ")", ";", "globby", ".", "sync", "(", "[", "`", "${", "depPath", "}", "`", "]", ")", ".", "forEach", "(", "bowerJsonPath", "=>", "{", "getBowerCredits", "(", "bowerJsonPath", ",", "credits", ")", ";", "}", ")", ";", "return", "credits", ";", "}" ]
Read project root and evaluate dependency credits for bower modules @param {String} projectPath absolute path to project root @param {Array} credits list of credits to append to @return {Array} list of credits
[ "Read", "project", "root", "and", "evaluate", "dependency", "credits", "for", "bower", "modules" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers/bower/index.js#L38-L49
train
Esri/geotrigger-js
spec/SpecHelpers.js
arrySignaturesMatch
function arrySignaturesMatch(array1, array2){ // setup variables var ref, test; // we want to use the shorter array if one is longer if (array1.length >= array2.length) { ref = array2; test = array1; } else { ref = array1; test = array2; } // loop over the shorter array and make sure the corresponding key in the longer array matches for(var key in ref) { if(typeof ref[key] === typeof test[key]) { // if the keys represent an object make sure that it matches if(typeof ref[key] === "object" && typeof test[key] === "object") { if(!objectSignaturesMatch(ref[key], test[key])){ return false; } } // if the keys represent an array make sure that it matches if(typeof ref[key] === "array" && typeof test[key] === "array") { if(!arrySignaturesMatch(ref[key],test[key])){ return false; } } } } return true; }
javascript
function arrySignaturesMatch(array1, array2){ // setup variables var ref, test; // we want to use the shorter array if one is longer if (array1.length >= array2.length) { ref = array2; test = array1; } else { ref = array1; test = array2; } // loop over the shorter array and make sure the corresponding key in the longer array matches for(var key in ref) { if(typeof ref[key] === typeof test[key]) { // if the keys represent an object make sure that it matches if(typeof ref[key] === "object" && typeof test[key] === "object") { if(!objectSignaturesMatch(ref[key], test[key])){ return false; } } // if the keys represent an array make sure that it matches if(typeof ref[key] === "array" && typeof test[key] === "array") { if(!arrySignaturesMatch(ref[key],test[key])){ return false; } } } } return true; }
[ "function", "arrySignaturesMatch", "(", "array1", ",", "array2", ")", "{", "var", "ref", ",", "test", ";", "if", "(", "array1", ".", "length", ">=", "array2", ".", "length", ")", "{", "ref", "=", "array2", ";", "test", "=", "array1", ";", "}", "else", "{", "ref", "=", "array1", ";", "test", "=", "array2", ";", "}", "for", "(", "var", "key", "in", "ref", ")", "{", "if", "(", "typeof", "ref", "[", "key", "]", "===", "typeof", "test", "[", "key", "]", ")", "{", "if", "(", "typeof", "ref", "[", "key", "]", "===", "\"object\"", "&&", "typeof", "test", "[", "key", "]", "===", "\"object\"", ")", "{", "if", "(", "!", "objectSignaturesMatch", "(", "ref", "[", "key", "]", ",", "test", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "typeof", "ref", "[", "key", "]", "===", "\"array\"", "&&", "typeof", "test", "[", "key", "]", "===", "\"array\"", ")", "{", "if", "(", "!", "arrySignaturesMatch", "(", "ref", "[", "key", "]", ",", "test", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "}", "}", "return", "true", ";", "}" ]
do the types of arguments in each array match?
[ "do", "the", "types", "of", "arguments", "in", "each", "array", "match?" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/spec/SpecHelpers.js#L4-L38
train
Esri/geotrigger-js
spec/SpecHelpers.js
objectSignaturesMatch
function objectSignaturesMatch(object1, object2){ // because typeof null is object we need to check for it here before Object.keys if(object1 === null && object2 === null){ return true; } // if the objects have different lengths of keys we should fail immediatly if (Object.keys(object1).length !== Object.keys(object2).length) { return false; } // loop over all the keys in object1 (we know the objects have the same number of keys at this point) for(var key in object1) { // if the keys match keep checking if not we have a mismatch if(typeof object1[key] === typeof object2[key]) { if(typeof object1[key] === null && typeof object2[key] === null) { } // if the keys represent an object make sure that it matches. else if(object1[key] instanceof Array && object2[key] instanceof Array) { if(!arrySignaturesMatch(object1[key],object2[key])){ return false; } } // if the keys represent an array make sure it matches else if(typeof object1[key] === "object" && typeof object2[key] === "object") { if(!objectSignaturesMatch(object1[key],object2[key])){ return false; } } } } return true; }
javascript
function objectSignaturesMatch(object1, object2){ // because typeof null is object we need to check for it here before Object.keys if(object1 === null && object2 === null){ return true; } // if the objects have different lengths of keys we should fail immediatly if (Object.keys(object1).length !== Object.keys(object2).length) { return false; } // loop over all the keys in object1 (we know the objects have the same number of keys at this point) for(var key in object1) { // if the keys match keep checking if not we have a mismatch if(typeof object1[key] === typeof object2[key]) { if(typeof object1[key] === null && typeof object2[key] === null) { } // if the keys represent an object make sure that it matches. else if(object1[key] instanceof Array && object2[key] instanceof Array) { if(!arrySignaturesMatch(object1[key],object2[key])){ return false; } } // if the keys represent an array make sure it matches else if(typeof object1[key] === "object" && typeof object2[key] === "object") { if(!objectSignaturesMatch(object1[key],object2[key])){ return false; } } } } return true; }
[ "function", "objectSignaturesMatch", "(", "object1", ",", "object2", ")", "{", "if", "(", "object1", "===", "null", "&&", "object2", "===", "null", ")", "{", "return", "true", ";", "}", "if", "(", "Object", ".", "keys", "(", "object1", ")", ".", "length", "!==", "Object", ".", "keys", "(", "object2", ")", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "var", "key", "in", "object1", ")", "{", "if", "(", "typeof", "object1", "[", "key", "]", "===", "typeof", "object2", "[", "key", "]", ")", "{", "if", "(", "typeof", "object1", "[", "key", "]", "===", "null", "&&", "typeof", "object2", "[", "key", "]", "===", "null", ")", "{", "}", "else", "if", "(", "object1", "[", "key", "]", "instanceof", "Array", "&&", "object2", "[", "key", "]", "instanceof", "Array", ")", "{", "if", "(", "!", "arrySignaturesMatch", "(", "object1", "[", "key", "]", ",", "object2", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "typeof", "object1", "[", "key", "]", "===", "\"object\"", "&&", "typeof", "object2", "[", "key", "]", "===", "\"object\"", ")", "{", "if", "(", "!", "objectSignaturesMatch", "(", "object1", "[", "key", "]", ",", "object2", "[", "key", "]", ")", ")", "{", "return", "false", ";", "}", "}", "}", "}", "return", "true", ";", "}" ]
do the keys in object 1 match object 2?
[ "do", "the", "keys", "in", "object", "1", "match", "object", "2?" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/spec/SpecHelpers.js#L41-L80
train
Esri/geotrigger-js
spec/SpecHelpers.js
function() { var refArgs = Array.prototype.slice.call(arguments); var calledArgs = this.actual.mostRecentCall.args; var arg; for(arg in refArgs){ var ref = refArgs[arg]; var test = calledArgs[arg]; // if the types of the objects dont match if(typeof ref !== typeof test) { return false; // if ref and test are objects make then } else if(typeof ref === "object" && typeof test === "object") { if(!objectSignaturesMatch(ref, test)){ return false; } } else if(typeof ref === "array" && typeof test === "array") { if(!arrySignaturesMatch(ref, test)){ return false; } } } return true; }
javascript
function() { var refArgs = Array.prototype.slice.call(arguments); var calledArgs = this.actual.mostRecentCall.args; var arg; for(arg in refArgs){ var ref = refArgs[arg]; var test = calledArgs[arg]; // if the types of the objects dont match if(typeof ref !== typeof test) { return false; // if ref and test are objects make then } else if(typeof ref === "object" && typeof test === "object") { if(!objectSignaturesMatch(ref, test)){ return false; } } else if(typeof ref === "array" && typeof test === "array") { if(!arrySignaturesMatch(ref, test)){ return false; } } } return true; }
[ "function", "(", ")", "{", "var", "refArgs", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "calledArgs", "=", "this", ".", "actual", ".", "mostRecentCall", ".", "args", ";", "var", "arg", ";", "for", "(", "arg", "in", "refArgs", ")", "{", "var", "ref", "=", "refArgs", "[", "arg", "]", ";", "var", "test", "=", "calledArgs", "[", "arg", "]", ";", "if", "(", "typeof", "ref", "!==", "typeof", "test", ")", "{", "return", "false", ";", "}", "else", "if", "(", "typeof", "ref", "===", "\"object\"", "&&", "typeof", "test", "===", "\"object\"", ")", "{", "if", "(", "!", "objectSignaturesMatch", "(", "ref", ",", "test", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "typeof", "ref", "===", "\"array\"", "&&", "typeof", "test", "===", "\"array\"", ")", "{", "if", "(", "!", "arrySignaturesMatch", "(", "ref", ",", "test", ")", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
this is a lazy matcher for jasmine spies. it checks that the arguments for the last call made match all the arguments that are passed into the function, but does not care if the values match only that they are the same type. in short this only cares that all teh keys are the same and the types of values are the same, not the values themselves
[ "this", "is", "a", "lazy", "matcher", "for", "jasmine", "spies", ".", "it", "checks", "that", "the", "arguments", "for", "the", "last", "call", "made", "match", "all", "the", "arguments", "that", "are", "passed", "into", "the", "function", "but", "does", "not", "care", "if", "the", "values", "match", "only", "that", "they", "are", "the", "same", "type", ".", "in", "short", "this", "only", "cares", "that", "all", "teh", "keys", "are", "the", "same", "and", "the", "types", "of", "values", "are", "the", "same", "not", "the", "values", "themselves" ]
35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26
https://github.com/Esri/geotrigger-js/blob/35f4724c0d6e6b8f1a6b054b99fbd2b270e70a26/spec/SpecHelpers.js#L91-L115
train
stefanjudis/credits
lib/analyzers.js
getAnalyzers
function getAnalyzers(config) { const methods = {}; const basePath = config.filePaths.analyzers; globby.sync(`${basePath}/*`) .forEach(analyzer => { const name = path.basename(analyzer); methods[name] = require(analyzer); }); return methods; }
javascript
function getAnalyzers(config) { const methods = {}; const basePath = config.filePaths.analyzers; globby.sync(`${basePath}/*`) .forEach(analyzer => { const name = path.basename(analyzer); methods[name] = require(analyzer); }); return methods; }
[ "function", "getAnalyzers", "(", "config", ")", "{", "const", "methods", "=", "{", "}", ";", "const", "basePath", "=", "config", ".", "filePaths", ".", "analyzers", ";", "globby", ".", "sync", "(", "`", "${", "basePath", "}", "`", ")", ".", "forEach", "(", "analyzer", "=>", "{", "const", "name", "=", "path", ".", "basename", "(", "analyzer", ")", ";", "methods", "[", "name", "]", "=", "require", "(", "analyzer", ")", ";", "}", ")", ";", "return", "methods", ";", "}" ]
Get all available analyzers @param {Object} config project configuration @return {Array} list of reporter methods
[ "Get", "all", "available", "analyzers" ]
b5e75518ca62d819e7f2145eeea30de2ea6043ce
https://github.com/stefanjudis/credits/blob/b5e75518ca62d819e7f2145eeea30de2ea6043ce/lib/analyzers.js#L13-L24
train
7digital/7digital-api
lib/request.js
prepare
function prepare(data, consumerkey) { var prop; data = data || {}; for (prop in data) { if (data.hasOwnProperty(prop)) { if (_.isDate(data[prop])) { data[prop] = helpers.toYYYYMMDD(data[prop]); } } } data.oauth_consumer_key = consumerkey; return data; }
javascript
function prepare(data, consumerkey) { var prop; data = data || {}; for (prop in data) { if (data.hasOwnProperty(prop)) { if (_.isDate(data[prop])) { data[prop] = helpers.toYYYYMMDD(data[prop]); } } } data.oauth_consumer_key = consumerkey; return data; }
[ "function", "prepare", "(", "data", ",", "consumerkey", ")", "{", "var", "prop", ";", "data", "=", "data", "||", "{", "}", ";", "for", "(", "prop", "in", "data", ")", "{", "if", "(", "data", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "if", "(", "_", ".", "isDate", "(", "data", "[", "prop", "]", ")", ")", "{", "data", "[", "prop", "]", "=", "helpers", ".", "toYYYYMMDD", "(", "data", "[", "prop", "]", ")", ";", "}", "}", "}", "data", ".", "oauth_consumer_key", "=", "consumerkey", ";", "return", "data", ";", "}" ]
Formats request parameters as expected by the API. - @param {Object} data - hash of pararameters - @param {String} consumerkey - consumer key - @return {String} - Encoded parameter string
[ "Formats", "request", "parameters", "as", "expected", "by", "the", "API", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L20-L35
train
7digital/7digital-api
lib/request.js
logHeaders
function logHeaders(logger, headers) { return _.each(_.keys(headers), function (key) { logger.info(key + ': ' + headers[key]); }); }
javascript
function logHeaders(logger, headers) { return _.each(_.keys(headers), function (key) { logger.info(key + ': ' + headers[key]); }); }
[ "function", "logHeaders", "(", "logger", ",", "headers", ")", "{", "return", "_", ".", "each", "(", "_", ".", "keys", "(", "headers", ")", ",", "function", "(", "key", ")", "{", "logger", ".", "info", "(", "key", "+", "': '", "+", "headers", "[", "key", "]", ")", ";", "}", ")", ";", "}" ]
Logs out a headers hash - @param {Object} logger - The logger to use - @param {Object} headers - The hash of headers to log
[ "Logs", "out", "a", "headers", "hash", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L51-L55
train
7digital/7digital-api
lib/request.js
get
function get(endpointInfo, requestData, headers, credentials, logger, callback) { var normalisedData = prepare(requestData, credentials.consumerkey); var fullUrl = endpointInfo.url + '?' + qs.stringify(normalisedData); var hostInfo = { host: endpointInfo.host, port: endpointInfo.port }; // Decide whether to make an oauth signed request or not if (endpointInfo.authtype) { hostInfo.host = endpointInfo.sslHost; dispatchSecure(endpointInfo.url, 'GET', requestData, headers, endpointInfo.authtype, hostInfo, credentials, logger, callback); } else { dispatch(endpointInfo.url, 'GET', requestData, headers, hostInfo, credentials, logger, callback); } }
javascript
function get(endpointInfo, requestData, headers, credentials, logger, callback) { var normalisedData = prepare(requestData, credentials.consumerkey); var fullUrl = endpointInfo.url + '?' + qs.stringify(normalisedData); var hostInfo = { host: endpointInfo.host, port: endpointInfo.port }; // Decide whether to make an oauth signed request or not if (endpointInfo.authtype) { hostInfo.host = endpointInfo.sslHost; dispatchSecure(endpointInfo.url, 'GET', requestData, headers, endpointInfo.authtype, hostInfo, credentials, logger, callback); } else { dispatch(endpointInfo.url, 'GET', requestData, headers, hostInfo, credentials, logger, callback); } }
[ "function", "get", "(", "endpointInfo", ",", "requestData", ",", "headers", ",", "credentials", ",", "logger", ",", "callback", ")", "{", "var", "normalisedData", "=", "prepare", "(", "requestData", ",", "credentials", ".", "consumerkey", ")", ";", "var", "fullUrl", "=", "endpointInfo", ".", "url", "+", "'?'", "+", "qs", ".", "stringify", "(", "normalisedData", ")", ";", "var", "hostInfo", "=", "{", "host", ":", "endpointInfo", ".", "host", ",", "port", ":", "endpointInfo", ".", "port", "}", ";", "if", "(", "endpointInfo", ".", "authtype", ")", "{", "hostInfo", ".", "host", "=", "endpointInfo", ".", "sslHost", ";", "dispatchSecure", "(", "endpointInfo", ".", "url", ",", "'GET'", ",", "requestData", ",", "headers", ",", "endpointInfo", ".", "authtype", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", ";", "}", "else", "{", "dispatch", "(", "endpointInfo", ".", "url", ",", "'GET'", ",", "requestData", ",", "headers", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", ";", "}", "}" ]
Makes a GET request to the API. - @param {Object} endpointInfo - Generic metadata about the endpoint to hit. - @param {Object} requestData - Parameters for this specific request. - @param {Object} headers - Custom headers for this request. - @param {Object} credentials - OAuth consumerkey and consumersecret. - @param {Object} logger - An object implementing the npm log levels. - @param {Function} callback - The callback to call with the response.
[ "Makes", "a", "GET", "request", "to", "the", "API", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L65-L85
train
7digital/7digital-api
lib/request.js
dispatchSecure
function dispatchSecure(path, httpMethod, requestData, headers, authtype, hostInfo, credentials, logger, callback) { var url; var is2Legged = authtype === '2-legged'; var token = is2Legged ? null : requestData.accesstoken; var secret = is2Legged ? null : requestData.accesssecret; var mergedHeaders = createHeaders(hostInfo.host, headers); var oauthClient = oauthHelper.createOAuthWrapper(credentials.consumerkey, credentials.consumersecret, mergedHeaders); var methodLookup = { 'POST' : oauthClient.post.bind(oauthClient), 'PUT' : oauthClient.put.bind(oauthClient) }; var oauthMethod = methodLookup[httpMethod]; hostInfo.port = hostInfo.port || 443; requestData = prepare(requestData, credentials.consumerkey); if (!is2Legged) { delete requestData.accesstoken; delete requestData.accesssecret; } url = buildSecureUrl(httpMethod, hostInfo, path, requestData); logger.info('token: ' + token + ' secret: ' + secret); logger.info(httpMethod + ': ' + url + ' (' + authtype + ' oauth)'); logHeaders(logger, mergedHeaders); function cbWithDataAndResponse(err, data, response) { var apiError; if (err) { // API server error if (err.statusCode && err.statusCode >= 400) { // non 200 status and string for response body is usually an // oauth error from one of the endpoints if (typeof err.data === 'string' && /oauth/i.test(err.data)) { apiError = new OAuthError(err.data, err.data + ': ' + path); } else { apiError = new ApiHttpError( response.statusCode, err.data, path); } return callback(apiError); } // Something unknown went wrong logger.error(err); return callback(err); } return callback(null, data, response); } if (httpMethod === 'GET') { return oauthClient.get(url, token, secret, cbWithDataAndResponse); } if ( oauthMethod ) { logger.info('DATA: ' + qs.stringify(requestData)); return oauthMethod(url, token, secret, requestData, 'application/x-www-form-urlencoded', cbWithDataAndResponse); } return callback(new Error('Unsupported HTTP verb: ' + httpMethod)); }
javascript
function dispatchSecure(path, httpMethod, requestData, headers, authtype, hostInfo, credentials, logger, callback) { var url; var is2Legged = authtype === '2-legged'; var token = is2Legged ? null : requestData.accesstoken; var secret = is2Legged ? null : requestData.accesssecret; var mergedHeaders = createHeaders(hostInfo.host, headers); var oauthClient = oauthHelper.createOAuthWrapper(credentials.consumerkey, credentials.consumersecret, mergedHeaders); var methodLookup = { 'POST' : oauthClient.post.bind(oauthClient), 'PUT' : oauthClient.put.bind(oauthClient) }; var oauthMethod = methodLookup[httpMethod]; hostInfo.port = hostInfo.port || 443; requestData = prepare(requestData, credentials.consumerkey); if (!is2Legged) { delete requestData.accesstoken; delete requestData.accesssecret; } url = buildSecureUrl(httpMethod, hostInfo, path, requestData); logger.info('token: ' + token + ' secret: ' + secret); logger.info(httpMethod + ': ' + url + ' (' + authtype + ' oauth)'); logHeaders(logger, mergedHeaders); function cbWithDataAndResponse(err, data, response) { var apiError; if (err) { // API server error if (err.statusCode && err.statusCode >= 400) { // non 200 status and string for response body is usually an // oauth error from one of the endpoints if (typeof err.data === 'string' && /oauth/i.test(err.data)) { apiError = new OAuthError(err.data, err.data + ': ' + path); } else { apiError = new ApiHttpError( response.statusCode, err.data, path); } return callback(apiError); } // Something unknown went wrong logger.error(err); return callback(err); } return callback(null, data, response); } if (httpMethod === 'GET') { return oauthClient.get(url, token, secret, cbWithDataAndResponse); } if ( oauthMethod ) { logger.info('DATA: ' + qs.stringify(requestData)); return oauthMethod(url, token, secret, requestData, 'application/x-www-form-urlencoded', cbWithDataAndResponse); } return callback(new Error('Unsupported HTTP verb: ' + httpMethod)); }
[ "function", "dispatchSecure", "(", "path", ",", "httpMethod", ",", "requestData", ",", "headers", ",", "authtype", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", "{", "var", "url", ";", "var", "is2Legged", "=", "authtype", "===", "'2-legged'", ";", "var", "token", "=", "is2Legged", "?", "null", ":", "requestData", ".", "accesstoken", ";", "var", "secret", "=", "is2Legged", "?", "null", ":", "requestData", ".", "accesssecret", ";", "var", "mergedHeaders", "=", "createHeaders", "(", "hostInfo", ".", "host", ",", "headers", ")", ";", "var", "oauthClient", "=", "oauthHelper", ".", "createOAuthWrapper", "(", "credentials", ".", "consumerkey", ",", "credentials", ".", "consumersecret", ",", "mergedHeaders", ")", ";", "var", "methodLookup", "=", "{", "'POST'", ":", "oauthClient", ".", "post", ".", "bind", "(", "oauthClient", ")", ",", "'PUT'", ":", "oauthClient", ".", "put", ".", "bind", "(", "oauthClient", ")", "}", ";", "var", "oauthMethod", "=", "methodLookup", "[", "httpMethod", "]", ";", "hostInfo", ".", "port", "=", "hostInfo", ".", "port", "||", "443", ";", "requestData", "=", "prepare", "(", "requestData", ",", "credentials", ".", "consumerkey", ")", ";", "if", "(", "!", "is2Legged", ")", "{", "delete", "requestData", ".", "accesstoken", ";", "delete", "requestData", ".", "accesssecret", ";", "}", "url", "=", "buildSecureUrl", "(", "httpMethod", ",", "hostInfo", ",", "path", ",", "requestData", ")", ";", "logger", ".", "info", "(", "'token: '", "+", "token", "+", "' secret: '", "+", "secret", ")", ";", "logger", ".", "info", "(", "httpMethod", "+", "': '", "+", "url", "+", "' ('", "+", "authtype", "+", "' oauth)'", ")", ";", "logHeaders", "(", "logger", ",", "mergedHeaders", ")", ";", "function", "cbWithDataAndResponse", "(", "err", ",", "data", ",", "response", ")", "{", "var", "apiError", ";", "if", "(", "err", ")", "{", "if", "(", "err", ".", "statusCode", "&&", "err", ".", "statusCode", ">=", "400", ")", "{", "if", "(", "typeof", "err", ".", "data", "===", "'string'", "&&", "/", "oauth", "/", "i", ".", "test", "(", "err", ".", "data", ")", ")", "{", "apiError", "=", "new", "OAuthError", "(", "err", ".", "data", ",", "err", ".", "data", "+", "': '", "+", "path", ")", ";", "}", "else", "{", "apiError", "=", "new", "ApiHttpError", "(", "response", ".", "statusCode", ",", "err", ".", "data", ",", "path", ")", ";", "}", "return", "callback", "(", "apiError", ")", ";", "}", "logger", ".", "error", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "return", "callback", "(", "null", ",", "data", ",", "response", ")", ";", "}", "if", "(", "httpMethod", "===", "'GET'", ")", "{", "return", "oauthClient", ".", "get", "(", "url", ",", "token", ",", "secret", ",", "cbWithDataAndResponse", ")", ";", "}", "if", "(", "oauthMethod", ")", "{", "logger", ".", "info", "(", "'DATA: '", "+", "qs", ".", "stringify", "(", "requestData", ")", ")", ";", "return", "oauthMethod", "(", "url", ",", "token", ",", "secret", ",", "requestData", ",", "'application/x-www-form-urlencoded'", ",", "cbWithDataAndResponse", ")", ";", "}", "return", "callback", "(", "new", "Error", "(", "'Unsupported HTTP verb: '", "+", "httpMethod", ")", ")", ";", "}" ]
Dispatches an oauth signed request to the API - @param {String} url - the path of the API url to request. - @param {String} httpMethod - @param {Object} requestData - hash of the parameters for the request. - @param {Object} headers - Headers for this request. - @param {String} authType - OAuth request type: '2-legged' or '3-legged' - @param {Object} hostInfo - API host information - @param {Function} callback - The callback to call with the response.
[ "Dispatches", "an", "oauth", "signed", "request", "to", "the", "API", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L131-L199
train
7digital/7digital-api
lib/request.js
dispatch
function dispatch(url, httpMethod, data, headers, hostInfo, credentials, logger, callback) { hostInfo.port = hostInfo.port || 80; var apiRequest, prop, hasErrored; var mergedHeaders = createHeaders(hostInfo.host, headers); var apiPath = url; data = prepare(data, credentials.consumerkey); // Special case for track previews: we explicitly request to be given // the XML response back instead of a redirect to the track download. if (url.indexOf('track/preview') >= 0) { data.redirect = 'false'; } if (httpMethod === 'GET') { url = url + '?' + qs.stringify(data); } logger.info(util.format('%s: http://%s:%s%s', httpMethod, hostInfo.host, hostInfo.port, url)); logHeaders(logger, mergedHeaders); // Make the request apiRequest = http.request({ method: httpMethod, hostname: hostInfo.host, // Force scheme to http for browserify otherwise it will pick up the // scheme from window.location.protocol which is app:// in firefoxos scheme: 'http', // Set this so browserify doesn't set it to true on the xhr, which // causes an http status of 0 and empty response text as it forces // the XHR to do a pre-flight access-control check and the API // currently does not set CORS headers. withCredentials: false, path: url, port: hostInfo.port, headers: mergedHeaders }, function handleResponse(response) { var responseBuffer = ''; if (typeof response.setEncoding === 'function') { response.setEncoding('utf8'); } response.on('data', function bufferData(chunk) { responseBuffer += chunk; }); response.on('end', function endResponse() { if (+response.statusCode >= 400) { return callback(new ApiHttpError( response.statusCode, responseBuffer, apiPath)); } if (!hasErrored) { return callback(null, responseBuffer, response); } }); }); apiRequest.on('error', function logErrorAndCallback(err) { // Flag that we've errored so we don't call the callback twice // if we get an end event on the response. hasErrored = true; logger.info('Error fetching [' + url + ']. Body:\n' + err); return callback(new RequestError(err, url)); }); if (httpMethod === 'GET') { apiRequest.end(); } else { apiRequest.end(data); } }
javascript
function dispatch(url, httpMethod, data, headers, hostInfo, credentials, logger, callback) { hostInfo.port = hostInfo.port || 80; var apiRequest, prop, hasErrored; var mergedHeaders = createHeaders(hostInfo.host, headers); var apiPath = url; data = prepare(data, credentials.consumerkey); // Special case for track previews: we explicitly request to be given // the XML response back instead of a redirect to the track download. if (url.indexOf('track/preview') >= 0) { data.redirect = 'false'; } if (httpMethod === 'GET') { url = url + '?' + qs.stringify(data); } logger.info(util.format('%s: http://%s:%s%s', httpMethod, hostInfo.host, hostInfo.port, url)); logHeaders(logger, mergedHeaders); // Make the request apiRequest = http.request({ method: httpMethod, hostname: hostInfo.host, // Force scheme to http for browserify otherwise it will pick up the // scheme from window.location.protocol which is app:// in firefoxos scheme: 'http', // Set this so browserify doesn't set it to true on the xhr, which // causes an http status of 0 and empty response text as it forces // the XHR to do a pre-flight access-control check and the API // currently does not set CORS headers. withCredentials: false, path: url, port: hostInfo.port, headers: mergedHeaders }, function handleResponse(response) { var responseBuffer = ''; if (typeof response.setEncoding === 'function') { response.setEncoding('utf8'); } response.on('data', function bufferData(chunk) { responseBuffer += chunk; }); response.on('end', function endResponse() { if (+response.statusCode >= 400) { return callback(new ApiHttpError( response.statusCode, responseBuffer, apiPath)); } if (!hasErrored) { return callback(null, responseBuffer, response); } }); }); apiRequest.on('error', function logErrorAndCallback(err) { // Flag that we've errored so we don't call the callback twice // if we get an end event on the response. hasErrored = true; logger.info('Error fetching [' + url + ']. Body:\n' + err); return callback(new RequestError(err, url)); }); if (httpMethod === 'GET') { apiRequest.end(); } else { apiRequest.end(data); } }
[ "function", "dispatch", "(", "url", ",", "httpMethod", ",", "data", ",", "headers", ",", "hostInfo", ",", "credentials", ",", "logger", ",", "callback", ")", "{", "hostInfo", ".", "port", "=", "hostInfo", ".", "port", "||", "80", ";", "var", "apiRequest", ",", "prop", ",", "hasErrored", ";", "var", "mergedHeaders", "=", "createHeaders", "(", "hostInfo", ".", "host", ",", "headers", ")", ";", "var", "apiPath", "=", "url", ";", "data", "=", "prepare", "(", "data", ",", "credentials", ".", "consumerkey", ")", ";", "if", "(", "url", ".", "indexOf", "(", "'track/preview'", ")", ">=", "0", ")", "{", "data", ".", "redirect", "=", "'false'", ";", "}", "if", "(", "httpMethod", "===", "'GET'", ")", "{", "url", "=", "url", "+", "'?'", "+", "qs", ".", "stringify", "(", "data", ")", ";", "}", "logger", ".", "info", "(", "util", ".", "format", "(", "'%s: http://%s:%s%s'", ",", "httpMethod", ",", "hostInfo", ".", "host", ",", "hostInfo", ".", "port", ",", "url", ")", ")", ";", "logHeaders", "(", "logger", ",", "mergedHeaders", ")", ";", "apiRequest", "=", "http", ".", "request", "(", "{", "method", ":", "httpMethod", ",", "hostname", ":", "hostInfo", ".", "host", ",", "scheme", ":", "'http'", ",", "withCredentials", ":", "false", ",", "path", ":", "url", ",", "port", ":", "hostInfo", ".", "port", ",", "headers", ":", "mergedHeaders", "}", ",", "function", "handleResponse", "(", "response", ")", "{", "var", "responseBuffer", "=", "''", ";", "if", "(", "typeof", "response", ".", "setEncoding", "===", "'function'", ")", "{", "response", ".", "setEncoding", "(", "'utf8'", ")", ";", "}", "response", ".", "on", "(", "'data'", ",", "function", "bufferData", "(", "chunk", ")", "{", "responseBuffer", "+=", "chunk", ";", "}", ")", ";", "response", ".", "on", "(", "'end'", ",", "function", "endResponse", "(", ")", "{", "if", "(", "+", "response", ".", "statusCode", ">=", "400", ")", "{", "return", "callback", "(", "new", "ApiHttpError", "(", "response", ".", "statusCode", ",", "responseBuffer", ",", "apiPath", ")", ")", ";", "}", "if", "(", "!", "hasErrored", ")", "{", "return", "callback", "(", "null", ",", "responseBuffer", ",", "response", ")", ";", "}", "}", ")", ";", "}", ")", ";", "apiRequest", ".", "on", "(", "'error'", ",", "function", "logErrorAndCallback", "(", "err", ")", "{", "hasErrored", "=", "true", ";", "logger", ".", "info", "(", "'Error fetching ['", "+", "url", "+", "']. Body:\\n'", "+", "\\n", ")", ";", "err", "}", ")", ";", "return", "callback", "(", "new", "RequestError", "(", "err", ",", "url", ")", ")", ";", "}" ]
Dispatches requests to the API. Serializes the data in keeping with the API specification and applies approriate HTTP headers. - @param {String} url - the URL on the API to make the request to. - @param {String} httpMethod - @param {Object} data - hash of the parameters for the request. - @param {Object} headers - Headers for this request. - @param {Object} hostInfo - hash of host, port and prefix - @param {Object} credentials - hash of oauth consumer key and secret - @param {Object} logger - an object implementing the npm log levels - @param {Function} callback
[ "Dispatches", "requests", "to", "the", "API", ".", "Serializes", "the", "data", "in", "keeping", "with", "the", "API", "specification", "and", "applies", "approriate", "HTTP", "headers", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/request.js#L212-L289
train
7digital/7digital-api
lib/logger.js
makeLogger
function makeLogger(level, method) { // The logger function to return takes a variable number of arguments // and formats like console.log function logger() { var args = [].slice.call(arguments); var format = level.toUpperCase() + ': (api-client) ' + args.shift(); var logArgs = [format].concat(args); return console[method].apply(console, logArgs); } return (level === 'warn' || level === 'error' || level === 'info') ? logger : function() {}; }
javascript
function makeLogger(level, method) { // The logger function to return takes a variable number of arguments // and formats like console.log function logger() { var args = [].slice.call(arguments); var format = level.toUpperCase() + ': (api-client) ' + args.shift(); var logArgs = [format].concat(args); return console[method].apply(console, logArgs); } return (level === 'warn' || level === 'error' || level === 'info') ? logger : function() {}; }
[ "function", "makeLogger", "(", "level", ",", "method", ")", "{", "function", "logger", "(", ")", "{", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "format", "=", "level", ".", "toUpperCase", "(", ")", "+", "': (api-client) '", "+", "args", ".", "shift", "(", ")", ";", "var", "logArgs", "=", "[", "format", "]", ".", "concat", "(", "args", ")", ";", "return", "console", "[", "method", "]", ".", "apply", "(", "console", ",", "logArgs", ")", ";", "}", "return", "(", "level", "===", "'warn'", "||", "level", "===", "'error'", "||", "level", "===", "'info'", ")", "?", "logger", ":", "function", "(", ")", "{", "}", ";", "}" ]
Makes a logger function that formats messages sensibly and logs to either stdout or stderr. - @param {String} level - the log level. - @param {String} method - the method on the console object to call. - @return {Function} - the logging function.
[ "Makes", "a", "logger", "function", "that", "formats", "messages", "sensibly", "and", "logs", "to", "either", "stdout", "or", "stderr", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/logger.js#L9-L23
train
7digital/7digital-api
lib/response-cleaners/ensure-collections.js
ensureCollections
function ensureCollections(collectionPaths, response) { var basket; _.each(collectionPaths, function checkLength(item) { var parts = item.split('.'); var allPartsButLast = _.initial(parts); var lastPart = _.last(parts); var parents = _.reduce(allPartsButLast, function (chain, part) { return chain.pluck(part).compact().flatten(); }, _([response])).value(); parents.map(function (parent) { if (parent[lastPart]) { parent[lastPart] = arrayify(parent[lastPart]); } else { parent[lastPart] = []; } }); }); basket = response.basket; if (basket) { if (basket.basketItems.basketItem) { basket.basketItems = basket.basketItems.basketItem; } else { basket.basketItems = []; } } return response; }
javascript
function ensureCollections(collectionPaths, response) { var basket; _.each(collectionPaths, function checkLength(item) { var parts = item.split('.'); var allPartsButLast = _.initial(parts); var lastPart = _.last(parts); var parents = _.reduce(allPartsButLast, function (chain, part) { return chain.pluck(part).compact().flatten(); }, _([response])).value(); parents.map(function (parent) { if (parent[lastPart]) { parent[lastPart] = arrayify(parent[lastPart]); } else { parent[lastPart] = []; } }); }); basket = response.basket; if (basket) { if (basket.basketItems.basketItem) { basket.basketItems = basket.basketItems.basketItem; } else { basket.basketItems = []; } } return response; }
[ "function", "ensureCollections", "(", "collectionPaths", ",", "response", ")", "{", "var", "basket", ";", "_", ".", "each", "(", "collectionPaths", ",", "function", "checkLength", "(", "item", ")", "{", "var", "parts", "=", "item", ".", "split", "(", "'.'", ")", ";", "var", "allPartsButLast", "=", "_", ".", "initial", "(", "parts", ")", ";", "var", "lastPart", "=", "_", ".", "last", "(", "parts", ")", ";", "var", "parents", "=", "_", ".", "reduce", "(", "allPartsButLast", ",", "function", "(", "chain", ",", "part", ")", "{", "return", "chain", ".", "pluck", "(", "part", ")", ".", "compact", "(", ")", ".", "flatten", "(", ")", ";", "}", ",", "_", "(", "[", "response", "]", ")", ")", ".", "value", "(", ")", ";", "parents", ".", "map", "(", "function", "(", "parent", ")", "{", "if", "(", "parent", "[", "lastPart", "]", ")", "{", "parent", "[", "lastPart", "]", "=", "arrayify", "(", "parent", "[", "lastPart", "]", ")", ";", "}", "else", "{", "parent", "[", "lastPart", "]", "=", "[", "]", ";", "}", "}", ")", ";", "}", ")", ";", "basket", "=", "response", ".", "basket", ";", "if", "(", "basket", ")", "{", "if", "(", "basket", ".", "basketItems", ".", "basketItem", ")", "{", "basket", ".", "basketItems", "=", "basket", ".", "basketItems", ".", "basketItem", ";", "}", "else", "{", "basket", ".", "basketItems", "=", "[", "]", ";", "}", "}", "return", "response", ";", "}" ]
The API returns resources as either a single object or an array. This makes responses fiddly to deal with for consumers as they manually check whether the resource has a length an access the property appropriately. This method checks the reponse for the existence of a property path and if it is an object wraps it in an array. - @param {String} collectionPaths - @param {Object} response - @return {Object} the modified response
[ "The", "API", "returns", "resources", "as", "either", "a", "single", "object", "or", "an", "array", ".", "This", "makes", "responses", "fiddly", "to", "deal", "with", "for", "consumers", "as", "they", "manually", "check", "whether", "the", "resource", "has", "a", "length", "an", "access", "the", "property", "appropriately", ".", "This", "method", "checks", "the", "reponse", "for", "the", "existence", "of", "a", "property", "path", "and", "if", "it", "is", "an", "object", "wraps", "it", "in", "an", "array", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/response-cleaners/ensure-collections.js#L18-L47
train
7digital/7digital-api
lib/api.js
Api
function Api(options, schema) { var prop, resourceOptions, resourceConstructor; var apiRoot = this; // Set default options for any unsupplied overrides _.defaults(options, config); this.options = options; this.schema = schema; configureSchemaFromEnv(this.schema); // Creates a constructor with the pre-built resource as its prototype // this is syntactic sugar to allow callers to new up the resources. function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; } for (prop in schema.resources) { if (schema.resources.hasOwnProperty(prop)) { resourceOptions = options; resourceOptions.api = this; resourceOptions.resourceDefinition = schema.resources[prop]; this[prop] = createResourceConstructor( new Resource(resourceOptions, schema)); } } this['OAuth'] = createResourceConstructor(new OAuth(options)); }
javascript
function Api(options, schema) { var prop, resourceOptions, resourceConstructor; var apiRoot = this; // Set default options for any unsupplied overrides _.defaults(options, config); this.options = options; this.schema = schema; configureSchemaFromEnv(this.schema); // Creates a constructor with the pre-built resource as its prototype // this is syntactic sugar to allow callers to new up the resources. function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; } for (prop in schema.resources) { if (schema.resources.hasOwnProperty(prop)) { resourceOptions = options; resourceOptions.api = this; resourceOptions.resourceDefinition = schema.resources[prop]; this[prop] = createResourceConstructor( new Resource(resourceOptions, schema)); } } this['OAuth'] = createResourceConstructor(new OAuth(options)); }
[ "function", "Api", "(", "options", ",", "schema", ")", "{", "var", "prop", ",", "resourceOptions", ",", "resourceConstructor", ";", "var", "apiRoot", "=", "this", ";", "_", ".", "defaults", "(", "options", ",", "config", ")", ";", "this", ".", "options", "=", "options", ";", "this", ".", "schema", "=", "schema", ";", "configureSchemaFromEnv", "(", "this", ".", "schema", ")", ";", "function", "createResourceConstructor", "(", "resourcePrototype", ")", "{", "function", "APIResource", "(", "resourceOptions", ")", "{", "if", "(", "!", "(", "this", "instanceof", "APIResource", ")", ")", "{", "return", "new", "APIResource", "(", "resourceOptions", ")", ";", "}", "resourceOptions", "=", "resourceOptions", "||", "{", "}", ";", "_", ".", "defaults", "(", "resourceOptions", ".", "defaultParams", ",", "apiRoot", ".", "options", ".", "defaultParams", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ".", "headers", ",", "apiRoot", ".", "options", ".", "headers", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ",", "apiRoot", ".", "options", ")", ";", "this", ".", "format", "=", "resourceOptions", ".", "format", ";", "this", ".", "logger", "=", "resourceOptions", ".", "logger", ";", "this", ".", "defaultParams", "=", "resourceOptions", ".", "defaultParams", ";", "this", ".", "headers", "=", "resourceOptions", ".", "headers", ";", "}", "APIResource", ".", "prototype", "=", "resourcePrototype", ";", "return", "APIResource", ";", "}", "for", "(", "prop", "in", "schema", ".", "resources", ")", "{", "if", "(", "schema", ".", "resources", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "resourceOptions", "=", "options", ";", "resourceOptions", ".", "api", "=", "this", ";", "resourceOptions", ".", "resourceDefinition", "=", "schema", ".", "resources", "[", "prop", "]", ";", "this", "[", "prop", "]", "=", "createResourceConstructor", "(", "new", "Resource", "(", "resourceOptions", ",", "schema", ")", ")", ";", "}", "}", "this", "[", "'OAuth'", "]", "=", "createResourceConstructor", "(", "new", "OAuth", "(", "options", ")", ")", ";", "}" ]
API Creates a new API wrapper from a schema definition - @param {Object} options - The API options, see below - @param {Object} schema - The definition of the api resources and actions see the assets/7digital-api-schema json file. - @constructor - @param {Object} options The options parameter should have the following properties: - `consumerkey` your application's oauth consumer key - `consumersecret` your application's oauth consumer secret - `format` the response format - `logger` a logger instance for output
[ "API", "Creates", "a", "new", "API", "wrapper", "from", "a", "schema", "definition", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/api.js#L56-L107
train
7digital/7digital-api
lib/api.js
createResourceConstructor
function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; }
javascript
function createResourceConstructor(resourcePrototype) { function APIResource(resourceOptions) { // Allow creating resources without `new` keyword if (!(this instanceof APIResource)) { return new APIResource(resourceOptions); } resourceOptions = resourceOptions || {}; // Override any default options for all requests on this resource _.defaults(resourceOptions.defaultParams, apiRoot.options.defaultParams); _.defaults(resourceOptions.headers, apiRoot.options.headers); _.defaults(resourceOptions, apiRoot.options); this.format = resourceOptions.format; this.logger = resourceOptions.logger; this.defaultParams = resourceOptions.defaultParams; this.headers = resourceOptions.headers; } APIResource.prototype = resourcePrototype; return APIResource; }
[ "function", "createResourceConstructor", "(", "resourcePrototype", ")", "{", "function", "APIResource", "(", "resourceOptions", ")", "{", "if", "(", "!", "(", "this", "instanceof", "APIResource", ")", ")", "{", "return", "new", "APIResource", "(", "resourceOptions", ")", ";", "}", "resourceOptions", "=", "resourceOptions", "||", "{", "}", ";", "_", ".", "defaults", "(", "resourceOptions", ".", "defaultParams", ",", "apiRoot", ".", "options", ".", "defaultParams", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ".", "headers", ",", "apiRoot", ".", "options", ".", "headers", ")", ";", "_", ".", "defaults", "(", "resourceOptions", ",", "apiRoot", ".", "options", ")", ";", "this", ".", "format", "=", "resourceOptions", ".", "format", ";", "this", ".", "logger", "=", "resourceOptions", ".", "logger", ";", "this", ".", "defaultParams", "=", "resourceOptions", ".", "defaultParams", ";", "this", ".", "headers", "=", "resourceOptions", ".", "headers", ";", "}", "APIResource", ".", "prototype", "=", "resourcePrototype", ";", "return", "APIResource", ";", "}" ]
Creates a constructor with the pre-built resource as its prototype this is syntactic sugar to allow callers to new up the resources.
[ "Creates", "a", "constructor", "with", "the", "pre", "-", "built", "resource", "as", "its", "prototype", "this", "is", "syntactic", "sugar", "to", "allow", "callers", "to", "new", "up", "the", "resources", "." ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/api.js#L69-L92
train
danillouz/devrant
src/index.js
_getIdByUsername
function _getIdByUsername(username) { const url = `${API}/get-user-id`; const params = { app: 3, username }; return http .GET(url, params) .then(data => data.user_id); }
javascript
function _getIdByUsername(username) { const url = `${API}/get-user-id`; const params = { app: 3, username }; return http .GET(url, params) .then(data => data.user_id); }
[ "function", "_getIdByUsername", "(", "username", ")", "{", "const", "url", "=", "`", "${", "API", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", ",", "username", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "user_id", ")", ";", "}" ]
Retrieve the user id associated with the devRant username. @private @param {String} username - the devRant username @return {Promise} Resolves with the user id
[ "Retrieve", "the", "user", "id", "associated", "with", "the", "devRant", "username", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L47-L57
train
danillouz/devrant
src/index.js
rant
function rant(id = _noRantIdError()) { const url = `${API}/devrant/rants/${id}`; const params = { app: 3 }; return http.GET(url, params); }
javascript
function rant(id = _noRantIdError()) { const url = `${API}/devrant/rants/${id}`; const params = { app: 3 }; return http.GET(url, params); }
[ "function", "rant", "(", "id", "=", "_noRantIdError", "(", ")", ")", "{", "const", "url", "=", "`", "${", "API", "}", "${", "id", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ";", "}" ]
Retrieve a single rant from devRant. Use this method to retrieve a rant with its full text and comments. @param {String} id - the rant id @return {Promise} Resolves with the fetched rant
[ "Retrieve", "a", "single", "rant", "from", "devRant", ".", "Use", "this", "method", "to", "retrieve", "a", "rant", "with", "its", "full", "text", "and", "comments", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L67-L72
train
danillouz/devrant
src/index.js
rants
function rants({ sort = 'algo', limit = 50, skip = 0 } = {}) { const url = `${API}/devrant/rants`; const params = { app: 3, sort, limit, skip }; return http .GET(url, params) .then(data => data.rants); }
javascript
function rants({ sort = 'algo', limit = 50, skip = 0 } = {}) { const url = `${API}/devrant/rants`; const params = { app: 3, sort, limit, skip }; return http .GET(url, params) .then(data => data.rants); }
[ "function", "rants", "(", "{", "sort", "=", "'algo'", ",", "limit", "=", "50", ",", "skip", "=", "0", "}", "=", "{", "}", ")", "{", "const", "url", "=", "`", "${", "API", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", ",", "sort", ",", "limit", ",", "skip", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "rants", ")", ";", "}" ]
Retrieve rants from devRant. @param {Object} options - sort (by `algo`, `recent` or `top`), limit and skip @return {Promise} Resolves with the fetched rants
[ "Retrieve", "rants", "from", "devRant", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L81-L95
train
danillouz/devrant
src/index.js
search
function search(term = _noSearchTermError()) { const url = `${API}/devrant/search`; const params = { app: 3, term }; return http .GET(url, params) .then(data => data.results); }
javascript
function search(term = _noSearchTermError()) { const url = `${API}/devrant/search`; const params = { app: 3, term }; return http .GET(url, params) .then(data => data.results); }
[ "function", "search", "(", "term", "=", "_noSearchTermError", "(", ")", ")", "{", "const", "url", "=", "`", "${", "API", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", ",", "term", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "results", ")", ";", "}" ]
Retrieve rants from devRant that match a specific search term. @param {String} term - the search term @return {Promise} Resolves with the fetched rants
[ "Retrieve", "rants", "from", "devRant", "that", "match", "a", "specific", "search", "term", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L105-L115
train
danillouz/devrant
src/index.js
profile
function profile(username = _noUsernameError()) { return co(function *resolveUsername() { const userId = yield _getIdByUsername(username); const url = `${API}/users/${userId}`; const params = { app: 3 }; return http .GET(url, params) .then(data => data.profile); }); }
javascript
function profile(username = _noUsernameError()) { return co(function *resolveUsername() { const userId = yield _getIdByUsername(username); const url = `${API}/users/${userId}`; const params = { app: 3 }; return http .GET(url, params) .then(data => data.profile); }); }
[ "function", "profile", "(", "username", "=", "_noUsernameError", "(", ")", ")", "{", "return", "co", "(", "function", "*", "resolveUsername", "(", ")", "{", "const", "userId", "=", "yield", "_getIdByUsername", "(", "username", ")", ";", "const", "url", "=", "`", "${", "API", "}", "${", "userId", "}", "`", ";", "const", "params", "=", "{", "app", ":", "3", "}", ";", "return", "http", ".", "GET", "(", "url", ",", "params", ")", ".", "then", "(", "data", "=>", "data", ".", "profile", ")", ";", "}", ")", ";", "}" ]
Retrieve the profile of a devRant user by username. @param {String} username - the devRant username @return {Promise} Resolves with the fetched user profile
[ "Retrieve", "the", "profile", "of", "a", "devRant", "user", "by", "username", "." ]
d9938d2d0cd94823c69e291a2229f6cd799feddc
https://github.com/danillouz/devrant/blob/d9938d2d0cd94823c69e291a2229f6cd799feddc/src/index.js#L124-L134
train
moimikey/iso3166-1
src/index.js
to2
function to2 (alpha3) { if (alpha3 && alpha3.length > 1) state = alpha3 if (state.length !== 3) return state return ISOCodes.filter(function (row) { return row.alpha3 === state })[0].alpha2 }
javascript
function to2 (alpha3) { if (alpha3 && alpha3.length > 1) state = alpha3 if (state.length !== 3) return state return ISOCodes.filter(function (row) { return row.alpha3 === state })[0].alpha2 }
[ "function", "to2", "(", "alpha3", ")", "{", "if", "(", "alpha3", "&&", "alpha3", ".", "length", ">", "1", ")", "state", "=", "alpha3", "if", "(", "state", ".", "length", "!==", "3", ")", "return", "state", "return", "ISOCodes", ".", "filter", "(", "function", "(", "row", ")", "{", "return", "row", ".", "alpha3", "===", "state", "}", ")", "[", "0", "]", ".", "alpha2", "}" ]
Convert an ISO 3166-1 alpha-3 code to alpha-2 @param {String} alpha3 USA @return {String}
[ "Convert", "an", "ISO", "3166", "-", "1", "alpha", "-", "3", "code", "to", "alpha", "-", "2" ]
f3596c1957e5c35d2a33f71567265f0a3bf571b7
https://github.com/moimikey/iso3166-1/blob/f3596c1957e5c35d2a33f71567265f0a3bf571b7/src/index.js#L14-L20
train
moimikey/iso3166-1
src/index.js
to3
function to3 (alpha2) { if (alpha2 && alpha2.length > 1) state = alpha2 if (state.length !== 2) return state return ISOCodes.filter(function (row) { return row.alpha2 === state })[0].alpha3 }
javascript
function to3 (alpha2) { if (alpha2 && alpha2.length > 1) state = alpha2 if (state.length !== 2) return state return ISOCodes.filter(function (row) { return row.alpha2 === state })[0].alpha3 }
[ "function", "to3", "(", "alpha2", ")", "{", "if", "(", "alpha2", "&&", "alpha2", ".", "length", ">", "1", ")", "state", "=", "alpha2", "if", "(", "state", ".", "length", "!==", "2", ")", "return", "state", "return", "ISOCodes", ".", "filter", "(", "function", "(", "row", ")", "{", "return", "row", ".", "alpha2", "===", "state", "}", ")", "[", "0", "]", ".", "alpha3", "}" ]
Convert an ISO 3166-1 alpha-2 code to alpha-3 @param {String} alpha2 US @return {String}
[ "Convert", "an", "ISO", "3166", "-", "1", "alpha", "-", "2", "code", "to", "alpha", "-", "3" ]
f3596c1957e5c35d2a33f71567265f0a3bf571b7
https://github.com/moimikey/iso3166-1/blob/f3596c1957e5c35d2a33f71567265f0a3bf571b7/src/index.js#L28-L34
train
7digital/7digital-api
lib/resource.js
Resource
function Resource(options, schema) { this.logger = options.logger; this.resourceName = options.resourceDefinition.resource; this.host = options.resourceDefinition.host || schema.host; this.sslHost = options.resourceDefinition.sslHost || schema.sslHost; this.port = options.resourceDefinition.port || schema.port; this.prefix = options.resourceDefinition.prefix || schema.prefix; this.consumerkey = options.consumerkey; this.consumersecret = options.consumersecret; if(this.logger.silly) { this.logger.silly('Creating constructor for resource: ' + this.resourceName); } _.each(options.resourceDefinition.actions, function processAction(action) { this.createAction(action, options.userManagement); }, this); }
javascript
function Resource(options, schema) { this.logger = options.logger; this.resourceName = options.resourceDefinition.resource; this.host = options.resourceDefinition.host || schema.host; this.sslHost = options.resourceDefinition.sslHost || schema.sslHost; this.port = options.resourceDefinition.port || schema.port; this.prefix = options.resourceDefinition.prefix || schema.prefix; this.consumerkey = options.consumerkey; this.consumersecret = options.consumersecret; if(this.logger.silly) { this.logger.silly('Creating constructor for resource: ' + this.resourceName); } _.each(options.resourceDefinition.actions, function processAction(action) { this.createAction(action, options.userManagement); }, this); }
[ "function", "Resource", "(", "options", ",", "schema", ")", "{", "this", ".", "logger", "=", "options", ".", "logger", ";", "this", ".", "resourceName", "=", "options", ".", "resourceDefinition", ".", "resource", ";", "this", ".", "host", "=", "options", ".", "resourceDefinition", ".", "host", "||", "schema", ".", "host", ";", "this", ".", "sslHost", "=", "options", ".", "resourceDefinition", ".", "sslHost", "||", "schema", ".", "sslHost", ";", "this", ".", "port", "=", "options", ".", "resourceDefinition", ".", "port", "||", "schema", ".", "port", ";", "this", ".", "prefix", "=", "options", ".", "resourceDefinition", ".", "prefix", "||", "schema", ".", "prefix", ";", "this", ".", "consumerkey", "=", "options", ".", "consumerkey", ";", "this", ".", "consumersecret", "=", "options", ".", "consumersecret", ";", "if", "(", "this", ".", "logger", ".", "silly", ")", "{", "this", ".", "logger", ".", "silly", "(", "'Creating constructor for resource: '", "+", "this", ".", "resourceName", ")", ";", "}", "_", ".", "each", "(", "options", ".", "resourceDefinition", ".", "actions", ",", "function", "processAction", "(", "action", ")", "{", "this", ".", "createAction", "(", "action", ",", "options", ".", "userManagement", ")", ";", "}", ",", "this", ")", ";", "}" ]
A resource on the API, instances of this are used as the prototype of instances of each API resource. This constructor will build up a method for each action that can be performed on the resource. - @param {Object} options - @param {Object} schema The `options` argument should have the following properties: - `resourceDefinition` - the definition of the resource and its actions from the schema definition. - `consumerkey` - the oauth consumerkey - `consumersecret` the oauth consumersecret - `schema` - the schema defintion - `format` - the desired response format - `logger` - for logging output
[ "A", "resource", "on", "the", "API", "instances", "of", "this", "are", "used", "as", "the", "prototype", "of", "instances", "of", "each", "API", "resource", ".", "This", "constructor", "will", "build", "up", "a", "method", "for", "each", "action", "that", "can", "be", "performed", "on", "the", "resource", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/resource.js#L24-L42
train
MarkHerhold/palin
palin.js
truncFilename
function truncFilename(path, rootFolderName) { // bail if a string wasn't provided if (typeof path !== 'string') { return path; } var index = path.indexOf(rootFolderName); if (index > 0) { return path.substring(index + rootFolderName.length + 1); } else { return path; } }
javascript
function truncFilename(path, rootFolderName) { // bail if a string wasn't provided if (typeof path !== 'string') { return path; } var index = path.indexOf(rootFolderName); if (index > 0) { return path.substring(index + rootFolderName.length + 1); } else { return path; } }
[ "function", "truncFilename", "(", "path", ",", "rootFolderName", ")", "{", "if", "(", "typeof", "path", "!==", "'string'", ")", "{", "return", "path", ";", "}", "var", "index", "=", "path", ".", "indexOf", "(", "rootFolderName", ")", ";", "if", "(", "index", ">", "0", ")", "{", "return", "path", ".", "substring", "(", "index", "+", "rootFolderName", ".", "length", "+", "1", ")", ";", "}", "else", "{", "return", "path", ";", "}", "}" ]
shortens the file name to exclude any path before the project folder name @param path: file path string. e.g. /home/mark/myproj/run.js @param rootFolderName: root folder for the project. e.g. "myproj" @return the shortened file path string
[ "shortens", "the", "file", "name", "to", "exclude", "any", "path", "before", "the", "project", "folder", "name" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L11-L23
train
MarkHerhold/palin
palin.js
getTimestampString
function getTimestampString(date) { // all this nasty code is faster (~30k ops/sec) than doing "moment(date).format('HH:mm:ss:SSS')" and means 0 dependencies var hour = '0' + date.getHours(); hour = hour.slice(hour.length - 2); var minute = '0' + date.getMinutes(); minute = minute.slice(minute.length - 2); var second = '0' + date.getSeconds(); second = second.slice(second.length - 2); var ms = '' + date.getMilliseconds(); // https://github.com/MarkHerhold/palin/issues/6 // this is faster than using an actual left-pad algorithm if (ms.length === 1) { ms = '00' + ms; } else if (ms.length === 2) { ms = '0' + ms; } // no modifications for 3 or more digits return chalk.dim(`${hour}:${minute}:${second}:${ms}`); }
javascript
function getTimestampString(date) { // all this nasty code is faster (~30k ops/sec) than doing "moment(date).format('HH:mm:ss:SSS')" and means 0 dependencies var hour = '0' + date.getHours(); hour = hour.slice(hour.length - 2); var minute = '0' + date.getMinutes(); minute = minute.slice(minute.length - 2); var second = '0' + date.getSeconds(); second = second.slice(second.length - 2); var ms = '' + date.getMilliseconds(); // https://github.com/MarkHerhold/palin/issues/6 // this is faster than using an actual left-pad algorithm if (ms.length === 1) { ms = '00' + ms; } else if (ms.length === 2) { ms = '0' + ms; } // no modifications for 3 or more digits return chalk.dim(`${hour}:${minute}:${second}:${ms}`); }
[ "function", "getTimestampString", "(", "date", ")", "{", "var", "hour", "=", "'0'", "+", "date", ".", "getHours", "(", ")", ";", "hour", "=", "hour", ".", "slice", "(", "hour", ".", "length", "-", "2", ")", ";", "var", "minute", "=", "'0'", "+", "date", ".", "getMinutes", "(", ")", ";", "minute", "=", "minute", ".", "slice", "(", "minute", ".", "length", "-", "2", ")", ";", "var", "second", "=", "'0'", "+", "date", ".", "getSeconds", "(", ")", ";", "second", "=", "second", ".", "slice", "(", "second", ".", "length", "-", "2", ")", ";", "var", "ms", "=", "''", "+", "date", ".", "getMilliseconds", "(", ")", ";", "if", "(", "ms", ".", "length", "===", "1", ")", "{", "ms", "=", "'00'", "+", "ms", ";", "}", "else", "if", "(", "ms", ".", "length", "===", "2", ")", "{", "ms", "=", "'0'", "+", "ms", ";", "}", "return", "chalk", ".", "dim", "(", "`", "${", "hour", "}", "${", "minute", "}", "${", "second", "}", "${", "ms", "}", "`", ")", ";", "}" ]
retruns the colorized timestamp string
[ "retruns", "the", "colorized", "timestamp", "string" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L26-L45
train
MarkHerhold/palin
palin.js
getColorSeverity
function getColorSeverity(severity) { // get the color associated with the severity level const color = severityMap[severity] || 'white'; return chalk[color].bold(severity.toUpperCase()); }
javascript
function getColorSeverity(severity) { // get the color associated with the severity level const color = severityMap[severity] || 'white'; return chalk[color].bold(severity.toUpperCase()); }
[ "function", "getColorSeverity", "(", "severity", ")", "{", "const", "color", "=", "severityMap", "[", "severity", "]", "||", "'white'", ";", "return", "chalk", "[", "color", "]", ".", "bold", "(", "severity", ".", "toUpperCase", "(", ")", ")", ";", "}" ]
returns the colorized text for the given severity level
[ "returns", "the", "colorized", "text", "for", "the", "given", "severity", "level" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L56-L60
train
MarkHerhold/palin
palin.js
formatter
function formatter(options, severity, date, elems) { /* OPTIONS */ const indent = options.indent || defaultIndent; const objectDepth = options.objectDepth; const timestamp = (function () { if (check.function(options.timestamp)) { return options.timestamp; // user-provided timestamp generating function } else if (options.timestamp === false) { return false; // no timestamp } else { return getTimestampString; // default timestamp generating function } })(); const rootFolderName = options.rootFolderName; /* LOGIC */ // the last element is an aggregate object of all of the additional passed in elements var aggObj = elems[elems.length - 1]; // initial log string var build = ' '; // add the date if (timestamp !== false) { // otherwise, use the default timestamp generator function build += ' ' + timestamp(date); } build += ' ' + getColorSeverity(severity) + ' '; // add the component if provided if (aggObj.scope) { build += getScopeString(aggObj.scope) + ' '; delete aggObj.scope; } // errors are a special case that we absolutely need to keep track of and log the entire stack var errors = []; for (let i = 0; i < elems.length - 1; i++) { // iterate through all elements in the array except the last (obj map of options) let element = elems[i]; // Attempt to determine an appropriate title given the first element if (i === 0) { let elementConsumed = false; if (check.string(element)) { // string is obviously the title build += chalk.blue(element); elementConsumed = true; } else if (check.instance(element, Error)) { // title is the error text representation build += chalk.blue(element.message || '[no message]'); // also store error stacktrace in the aggregate object errors.push(element); elementConsumed = true; } // add on the file and line number, which always go after the title, inline if (aggObj.file && aggObj.line) { aggObj.file = truncFilename(aggObj.file, rootFolderName); build += chalk.dim(` (${aggObj.file}:${aggObj.line})`); delete aggObj.file; delete aggObj.line; } // do not add element 0 to the 'extra' data section if (elementConsumed) { continue; } } // add the element to the errors array if it's an error if (check.instance(element, Error)) { errors.push(element); // the error will be concatinated later so continue to the next element continue; } let objString = '\n' + util.inspect(element, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } if (Object.keys(aggObj).length > 0) { let objString = '\n' + util.inspect(aggObj, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } // iterate through the top-level object keys looking for Errors as well for (let o of Object.keys(aggObj)) { if (check.instance(o, Error)) { errors.push(o); } } // iterate through all the Error objects and print the stacks for (let e of errors) { build += indent + e.stack.replace(/\n/g, indent); } return build; }
javascript
function formatter(options, severity, date, elems) { /* OPTIONS */ const indent = options.indent || defaultIndent; const objectDepth = options.objectDepth; const timestamp = (function () { if (check.function(options.timestamp)) { return options.timestamp; // user-provided timestamp generating function } else if (options.timestamp === false) { return false; // no timestamp } else { return getTimestampString; // default timestamp generating function } })(); const rootFolderName = options.rootFolderName; /* LOGIC */ // the last element is an aggregate object of all of the additional passed in elements var aggObj = elems[elems.length - 1]; // initial log string var build = ' '; // add the date if (timestamp !== false) { // otherwise, use the default timestamp generator function build += ' ' + timestamp(date); } build += ' ' + getColorSeverity(severity) + ' '; // add the component if provided if (aggObj.scope) { build += getScopeString(aggObj.scope) + ' '; delete aggObj.scope; } // errors are a special case that we absolutely need to keep track of and log the entire stack var errors = []; for (let i = 0; i < elems.length - 1; i++) { // iterate through all elements in the array except the last (obj map of options) let element = elems[i]; // Attempt to determine an appropriate title given the first element if (i === 0) { let elementConsumed = false; if (check.string(element)) { // string is obviously the title build += chalk.blue(element); elementConsumed = true; } else if (check.instance(element, Error)) { // title is the error text representation build += chalk.blue(element.message || '[no message]'); // also store error stacktrace in the aggregate object errors.push(element); elementConsumed = true; } // add on the file and line number, which always go after the title, inline if (aggObj.file && aggObj.line) { aggObj.file = truncFilename(aggObj.file, rootFolderName); build += chalk.dim(` (${aggObj.file}:${aggObj.line})`); delete aggObj.file; delete aggObj.line; } // do not add element 0 to the 'extra' data section if (elementConsumed) { continue; } } // add the element to the errors array if it's an error if (check.instance(element, Error)) { errors.push(element); // the error will be concatinated later so continue to the next element continue; } let objString = '\n' + util.inspect(element, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } if (Object.keys(aggObj).length > 0) { let objString = '\n' + util.inspect(aggObj, { colors: true, depth: objectDepth }); build += objString.replace(/\n/g, indent); } // iterate through the top-level object keys looking for Errors as well for (let o of Object.keys(aggObj)) { if (check.instance(o, Error)) { errors.push(o); } } // iterate through all the Error objects and print the stacks for (let e of errors) { build += indent + e.stack.replace(/\n/g, indent); } return build; }
[ "function", "formatter", "(", "options", ",", "severity", ",", "date", ",", "elems", ")", "{", "const", "indent", "=", "options", ".", "indent", "||", "defaultIndent", ";", "const", "objectDepth", "=", "options", ".", "objectDepth", ";", "const", "timestamp", "=", "(", "function", "(", ")", "{", "if", "(", "check", ".", "function", "(", "options", ".", "timestamp", ")", ")", "{", "return", "options", ".", "timestamp", ";", "}", "else", "if", "(", "options", ".", "timestamp", "===", "false", ")", "{", "return", "false", ";", "}", "else", "{", "return", "getTimestampString", ";", "}", "}", ")", "(", ")", ";", "const", "rootFolderName", "=", "options", ".", "rootFolderName", ";", "var", "aggObj", "=", "elems", "[", "elems", ".", "length", "-", "1", "]", ";", "var", "build", "=", "' '", ";", "if", "(", "timestamp", "!==", "false", ")", "{", "build", "+=", "' '", "+", "timestamp", "(", "date", ")", ";", "}", "build", "+=", "' '", "+", "getColorSeverity", "(", "severity", ")", "+", "' '", ";", "if", "(", "aggObj", ".", "scope", ")", "{", "build", "+=", "getScopeString", "(", "aggObj", ".", "scope", ")", "+", "' '", ";", "delete", "aggObj", ".", "scope", ";", "}", "var", "errors", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "elems", ".", "length", "-", "1", ";", "i", "++", ")", "{", "let", "element", "=", "elems", "[", "i", "]", ";", "if", "(", "i", "===", "0", ")", "{", "let", "elementConsumed", "=", "false", ";", "if", "(", "check", ".", "string", "(", "element", ")", ")", "{", "build", "+=", "chalk", ".", "blue", "(", "element", ")", ";", "elementConsumed", "=", "true", ";", "}", "else", "if", "(", "check", ".", "instance", "(", "element", ",", "Error", ")", ")", "{", "build", "+=", "chalk", ".", "blue", "(", "element", ".", "message", "||", "'[no message]'", ")", ";", "errors", ".", "push", "(", "element", ")", ";", "elementConsumed", "=", "true", ";", "}", "if", "(", "aggObj", ".", "file", "&&", "aggObj", ".", "line", ")", "{", "aggObj", ".", "file", "=", "truncFilename", "(", "aggObj", ".", "file", ",", "rootFolderName", ")", ";", "build", "+=", "chalk", ".", "dim", "(", "`", "${", "aggObj", ".", "file", "}", "${", "aggObj", ".", "line", "}", "`", ")", ";", "delete", "aggObj", ".", "file", ";", "delete", "aggObj", ".", "line", ";", "}", "if", "(", "elementConsumed", ")", "{", "continue", ";", "}", "}", "if", "(", "check", ".", "instance", "(", "element", ",", "Error", ")", ")", "{", "errors", ".", "push", "(", "element", ")", ";", "continue", ";", "}", "let", "objString", "=", "'\\n'", "+", "\\n", ";", "util", ".", "inspect", "(", "element", ",", "{", "colors", ":", "true", ",", "depth", ":", "objectDepth", "}", ")", "}", "build", "+=", "objString", ".", "replace", "(", "/", "\\n", "/", "g", ",", "indent", ")", ";", "if", "(", "Object", ".", "keys", "(", "aggObj", ")", ".", "length", ">", "0", ")", "{", "let", "objString", "=", "'\\n'", "+", "\\n", ";", "util", ".", "inspect", "(", "aggObj", ",", "{", "colors", ":", "true", ",", "depth", ":", "objectDepth", "}", ")", "}", "build", "+=", "objString", ".", "replace", "(", "/", "\\n", "/", "g", ",", "indent", ")", ";", "for", "(", "let", "o", "of", "Object", ".", "keys", "(", "aggObj", ")", ")", "{", "if", "(", "check", ".", "instance", "(", "o", ",", "Error", ")", ")", "{", "errors", ".", "push", "(", "o", ")", ";", "}", "}", "}" ]
the formatter to export
[ "the", "formatter", "to", "export" ]
857ccd222bc649ab9be1411a049f76d779251fd8
https://github.com/MarkHerhold/palin/blob/857ccd222bc649ab9be1411a049f76d779251fd8/palin.js#L83-L189
train
7digital/7digital-api
lib/responseparser.js
parse
function parse(response, opts, callback) { var parser, jsonParseError, result; if (opts.format.toUpperCase() === 'XML') { callback(null, response); return; } if (opts.contentType && opts.contentType.indexOf('json') >= 0) { try { result = JSON.parse(response); } catch (e) { jsonParseError = e; } return validateAndCleanResponse(jsonParseError, { response: result }); } parser = new xml2js.Parser({ mergeAttrs: true, explicitArray: false }); parser.parseString(response, validateAndCleanResponse); function validateAndCleanResponse(err, result) { var cleanedResult; var clean, error, apiError; function makeParseErr(msg) { return new ApiParseError(msg + ' from: ' + opts.url, response); } // Unparsable response text if (err) { return callback(makeParseErr('Unparsable api response')); } if (!result) { return callback(makeParseErr('Empty response')); } if (!result.response) { return callback(makeParseErr('Missing response node')); } // Reponse was a 7digital API error object if (result.response.status === 'error') { error = result.response.error; if (/oauth/i.test(error.errorMessage)) { return callback(new OAuthError(error, error.errorMessage + ': ' + opts.url)); } apiError = new ApiError(error, error.errorMessage + ': ' + opts.url); apiError.params = opts.params; return callback(apiError); } else if (result.response.status !== 'ok') { return callback(new ApiParseError( 'Unexpected response status from: ' + opts.url, response)); } clean = _.compose( cleaners.renameCardTypes, cleaners.ensureCollections.bind(null, cleaners.collectionPaths), cleaners.removeXmlNamespaceKeys, cleaners.nullifyNils); cleanedResult = clean(result.response); return callback(null, cleanedResult); } }
javascript
function parse(response, opts, callback) { var parser, jsonParseError, result; if (opts.format.toUpperCase() === 'XML') { callback(null, response); return; } if (opts.contentType && opts.contentType.indexOf('json') >= 0) { try { result = JSON.parse(response); } catch (e) { jsonParseError = e; } return validateAndCleanResponse(jsonParseError, { response: result }); } parser = new xml2js.Parser({ mergeAttrs: true, explicitArray: false }); parser.parseString(response, validateAndCleanResponse); function validateAndCleanResponse(err, result) { var cleanedResult; var clean, error, apiError; function makeParseErr(msg) { return new ApiParseError(msg + ' from: ' + opts.url, response); } // Unparsable response text if (err) { return callback(makeParseErr('Unparsable api response')); } if (!result) { return callback(makeParseErr('Empty response')); } if (!result.response) { return callback(makeParseErr('Missing response node')); } // Reponse was a 7digital API error object if (result.response.status === 'error') { error = result.response.error; if (/oauth/i.test(error.errorMessage)) { return callback(new OAuthError(error, error.errorMessage + ': ' + opts.url)); } apiError = new ApiError(error, error.errorMessage + ': ' + opts.url); apiError.params = opts.params; return callback(apiError); } else if (result.response.status !== 'ok') { return callback(new ApiParseError( 'Unexpected response status from: ' + opts.url, response)); } clean = _.compose( cleaners.renameCardTypes, cleaners.ensureCollections.bind(null, cleaners.collectionPaths), cleaners.removeXmlNamespaceKeys, cleaners.nullifyNils); cleanedResult = clean(result.response); return callback(null, cleanedResult); } }
[ "function", "parse", "(", "response", ",", "opts", ",", "callback", ")", "{", "var", "parser", ",", "jsonParseError", ",", "result", ";", "if", "(", "opts", ".", "format", ".", "toUpperCase", "(", ")", "===", "'XML'", ")", "{", "callback", "(", "null", ",", "response", ")", ";", "return", ";", "}", "if", "(", "opts", ".", "contentType", "&&", "opts", ".", "contentType", ".", "indexOf", "(", "'json'", ")", ">=", "0", ")", "{", "try", "{", "result", "=", "JSON", ".", "parse", "(", "response", ")", ";", "}", "catch", "(", "e", ")", "{", "jsonParseError", "=", "e", ";", "}", "return", "validateAndCleanResponse", "(", "jsonParseError", ",", "{", "response", ":", "result", "}", ")", ";", "}", "parser", "=", "new", "xml2js", ".", "Parser", "(", "{", "mergeAttrs", ":", "true", ",", "explicitArray", ":", "false", "}", ")", ";", "parser", ".", "parseString", "(", "response", ",", "validateAndCleanResponse", ")", ";", "function", "validateAndCleanResponse", "(", "err", ",", "result", ")", "{", "var", "cleanedResult", ";", "var", "clean", ",", "error", ",", "apiError", ";", "function", "makeParseErr", "(", "msg", ")", "{", "return", "new", "ApiParseError", "(", "msg", "+", "' from: '", "+", "opts", ".", "url", ",", "response", ")", ";", "}", "if", "(", "err", ")", "{", "return", "callback", "(", "makeParseErr", "(", "'Unparsable api response'", ")", ")", ";", "}", "if", "(", "!", "result", ")", "{", "return", "callback", "(", "makeParseErr", "(", "'Empty response'", ")", ")", ";", "}", "if", "(", "!", "result", ".", "response", ")", "{", "return", "callback", "(", "makeParseErr", "(", "'Missing response node'", ")", ")", ";", "}", "if", "(", "result", ".", "response", ".", "status", "===", "'error'", ")", "{", "error", "=", "result", ".", "response", ".", "error", ";", "if", "(", "/", "oauth", "/", "i", ".", "test", "(", "error", ".", "errorMessage", ")", ")", "{", "return", "callback", "(", "new", "OAuthError", "(", "error", ",", "error", ".", "errorMessage", "+", "': '", "+", "opts", ".", "url", ")", ")", ";", "}", "apiError", "=", "new", "ApiError", "(", "error", ",", "error", ".", "errorMessage", "+", "': '", "+", "opts", ".", "url", ")", ";", "apiError", ".", "params", "=", "opts", ".", "params", ";", "return", "callback", "(", "apiError", ")", ";", "}", "else", "if", "(", "result", ".", "response", ".", "status", "!==", "'ok'", ")", "{", "return", "callback", "(", "new", "ApiParseError", "(", "'Unexpected response status from: '", "+", "opts", ".", "url", ",", "response", ")", ")", ";", "}", "clean", "=", "_", ".", "compose", "(", "cleaners", ".", "renameCardTypes", ",", "cleaners", ".", "ensureCollections", ".", "bind", "(", "null", ",", "cleaners", ".", "collectionPaths", ")", ",", "cleaners", ".", "removeXmlNamespaceKeys", ",", "cleaners", ".", "nullifyNils", ")", ";", "cleanedResult", "=", "clean", "(", "result", ".", "response", ")", ";", "return", "callback", "(", "null", ",", "cleanedResult", ")", ";", "}", "}" ]
Callback for parsing the XML response return from the API and converting it to JSON and handing control back to the caller. - @param {Function} callback - the caller's callback - @param {String} response - the XML response from the API - @parma {Object} opts - an options hash with the desired format and logger
[ "Callback", "for", "parsing", "the", "XML", "response", "return", "from", "the", "API", "and", "converting", "it", "to", "JSON", "and", "handing", "control", "back", "to", "the", "caller", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/responseparser.js#L17-L86
train
7digital/7digital-api
lib/errors.js
ApiHttpError
function ApiHttpError(statusCode, response, message) { this.name = "ApiHttpError"; this.statusCode = statusCode; this.response = response; this.message = message || response || util.format('Unexpected %s status code', statusCode); if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiHttpError); } }
javascript
function ApiHttpError(statusCode, response, message) { this.name = "ApiHttpError"; this.statusCode = statusCode; this.response = response; this.message = message || response || util.format('Unexpected %s status code', statusCode); if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiHttpError); } }
[ "function", "ApiHttpError", "(", "statusCode", ",", "response", ",", "message", ")", "{", "this", ".", "name", "=", "\"ApiHttpError\"", ";", "this", ".", "statusCode", "=", "statusCode", ";", "this", ".", "response", "=", "response", ";", "this", ".", "message", "=", "message", "||", "response", "||", "util", ".", "format", "(", "'Unexpected %s status code'", ",", "statusCode", ")", ";", "if", "(", "Error", ".", "captureStackTrace", "&&", "typeof", "Error", ".", "captureStackTrace", "===", "'function'", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "ApiHttpError", ")", ";", "}", "}" ]
ApiHttpError Creates a new ApiHttpError supplied to callbacks when an error response is received at transport level. - @constructor - @param {Number} statusCode - The HTTP status code of the request. - @param {String} response - (Optional) The response body. - @param {String} message - (Optional) The message
[ "ApiHttpError", "Creates", "a", "new", "ApiHttpError", "supplied", "to", "callbacks", "when", "an", "error", "response", "is", "received", "at", "transport", "level", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L25-L36
train
7digital/7digital-api
lib/errors.js
ApiParseError
function ApiParseError(parseErrorMessage, response) { this.name = "ApiParseError"; this.response = response; this.message = parseErrorMessage; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiParseError); } }
javascript
function ApiParseError(parseErrorMessage, response) { this.name = "ApiParseError"; this.response = response; this.message = parseErrorMessage; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, ApiParseError); } }
[ "function", "ApiParseError", "(", "parseErrorMessage", ",", "response", ")", "{", "this", ".", "name", "=", "\"ApiParseError\"", ";", "this", ".", "response", "=", "response", ";", "this", ".", "message", "=", "parseErrorMessage", ";", "if", "(", "Error", ".", "captureStackTrace", "&&", "typeof", "Error", ".", "captureStackTrace", "===", "'function'", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "ApiParseError", ")", ";", "}", "}" ]
ApiParseError Creates a new ApiParseError supplied to callbacks when an invalid or unexpected response is received. - @constructor - @param {String} parseErrorMessage - Custom error message describing the nature of the parse error. - @param {String} response - The response body string.
[ "ApiParseError", "Creates", "a", "new", "ApiParseError", "supplied", "to", "callbacks", "when", "an", "invalid", "or", "unexpected", "response", "is", "received", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L49-L58
train
7digital/7digital-api
lib/errors.js
RequestError
function RequestError(err, url) { VError.call(this, err, 'for url %s', url); this.name = RequestError.name; }
javascript
function RequestError(err, url) { VError.call(this, err, 'for url %s', url); this.name = RequestError.name; }
[ "function", "RequestError", "(", "err", ",", "url", ")", "{", "VError", ".", "call", "(", "this", ",", "err", ",", "'for url %s'", ",", "url", ")", ";", "this", ".", "name", "=", "RequestError", ".", "name", ";", "}" ]
RequestError Creates a new RequestError supplied to callbacks when the request to the api fails.
[ "RequestError", "Creates", "a", "new", "RequestError", "supplied", "to", "callbacks", "when", "the", "request", "to", "the", "api", "fails", "." ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L67-L70
train
7digital/7digital-api
lib/errors.js
OAuthError
function OAuthError(errorResponse, message) { this.name = "OAuthError"; this.message = message || errorResponse.errorMessage; this.code = errorResponse.code; this.response = errorResponse; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, OAuthError); } }
javascript
function OAuthError(errorResponse, message) { this.name = "OAuthError"; this.message = message || errorResponse.errorMessage; this.code = errorResponse.code; this.response = errorResponse; if (Error.captureStackTrace && typeof Error.captureStackTrace === 'function') { Error.captureStackTrace(this, OAuthError); } }
[ "function", "OAuthError", "(", "errorResponse", ",", "message", ")", "{", "this", ".", "name", "=", "\"OAuthError\"", ";", "this", ".", "message", "=", "message", "||", "errorResponse", ".", "errorMessage", ";", "this", ".", "code", "=", "errorResponse", ".", "code", ";", "this", ".", "response", "=", "errorResponse", ";", "if", "(", "Error", ".", "captureStackTrace", "&&", "typeof", "Error", ".", "captureStackTrace", "===", "'function'", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "OAuthError", ")", ";", "}", "}" ]
OAuthError Creates a new ApiError supplied to callbacks when a valid error response is received. - @constructor - @param {Object} errorResponse - The parsed API error response - @param {Object} message - The message
[ "OAuthError", "Creates", "a", "new", "ApiError", "supplied", "to", "callbacks", "when", "a", "valid", "error", "response", "is", "received", ".", "-" ]
3ca5db83d95a0361d997e2de72a215fb725b279d
https://github.com/7digital/7digital-api/blob/3ca5db83d95a0361d997e2de72a215fb725b279d/lib/errors.js#L82-L92
train
haroldiedema/joii
src/PrototypeBuilder.js
function(args, data, msg) { if (typeof (args) !== 'object') { args = [args]; } for (var i in args) { if (args.hasOwnProperty(i) === false) continue; if (JOII.Compat.indexOf(data, args[i]) !== -1) { throw msg; } } }
javascript
function(args, data, msg) { if (typeof (args) !== 'object') { args = [args]; } for (var i in args) { if (args.hasOwnProperty(i) === false) continue; if (JOII.Compat.indexOf(data, args[i]) !== -1) { throw msg; } } }
[ "function", "(", "args", ",", "data", ",", "msg", ")", "{", "if", "(", "typeof", "(", "args", ")", "!==", "'object'", ")", "{", "args", "=", "[", "args", "]", ";", "}", "for", "(", "var", "i", "in", "args", ")", "{", "if", "(", "args", ".", "hasOwnProperty", "(", "i", ")", "===", "false", ")", "continue", ";", "if", "(", "JOII", ".", "Compat", ".", "indexOf", "(", "data", ",", "args", "[", "i", "]", ")", "!==", "-", "1", ")", "{", "throw", "msg", ";", "}", "}", "}" ]
Shorthand for validating other flags within the same declaration. If args exists in data, msg is thrown.
[ "Shorthand", "for", "validating", "other", "flags", "within", "the", "same", "declaration", ".", "If", "args", "exists", "in", "data", "msg", "is", "thrown", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/PrototypeBuilder.js#L604-L615
train
SamyPesse/octocat.js
src/page.js
parseLinkHeader
function parseLinkHeader(header) { if (!header) { return {}; } // Split parts by comma const parts = header.split(','); const links = {}; // Parse each part into a named link parts.forEach((p) => { const section = p.split(';'); if (section.length != 2) { throw new Error('section could not be split on ";"'); } const url = section[0].replace(/<(.*)>/, '$1').trim(); const name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = url; }); return links; }
javascript
function parseLinkHeader(header) { if (!header) { return {}; } // Split parts by comma const parts = header.split(','); const links = {}; // Parse each part into a named link parts.forEach((p) => { const section = p.split(';'); if (section.length != 2) { throw new Error('section could not be split on ";"'); } const url = section[0].replace(/<(.*)>/, '$1').trim(); const name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = url; }); return links; }
[ "function", "parseLinkHeader", "(", "header", ")", "{", "if", "(", "!", "header", ")", "{", "return", "{", "}", ";", "}", "const", "parts", "=", "header", ".", "split", "(", "','", ")", ";", "const", "links", "=", "{", "}", ";", "parts", ".", "forEach", "(", "(", "p", ")", "=>", "{", "const", "section", "=", "p", ".", "split", "(", "';'", ")", ";", "if", "(", "section", ".", "length", "!=", "2", ")", "{", "throw", "new", "Error", "(", "'section could not be split on \";\"'", ")", ";", "}", "const", "url", "=", "section", "[", "0", "]", ".", "replace", "(", "/", "<(.*)>", "/", ",", "'$1'", ")", ".", "trim", "(", ")", ";", "const", "name", "=", "section", "[", "1", "]", ".", "replace", "(", "/", "rel=\"(.*)\"", "/", ",", "'$1'", ")", ".", "trim", "(", ")", ";", "links", "[", "name", "]", "=", "url", ";", "}", ")", ";", "return", "links", ";", "}" ]
Extract next and prev from link header @param {String} header @return {Object}
[ "Extract", "next", "and", "prev", "from", "link", "header" ]
1cbc1c499d0f8595db34c4c0df498deba8e4099f
https://github.com/SamyPesse/octocat.js/blob/1cbc1c499d0f8595db34c4c0df498deba8e4099f/src/page.js#L113-L134
train
haroldiedema/joii
src/Config.js
function (name) { if (JOII.Config.constructors.indexOf(name) !== -1) { return; } JOII.Config.constructors.push(name); }
javascript
function (name) { if (JOII.Config.constructors.indexOf(name) !== -1) { return; } JOII.Config.constructors.push(name); }
[ "function", "(", "name", ")", "{", "if", "(", "JOII", ".", "Config", ".", "constructors", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "{", "return", ";", "}", "JOII", ".", "Config", ".", "constructors", ".", "push", "(", "name", ")", ";", "}" ]
Adds a constructor method name. The first occurance of a function named like one of these is executed. The rest is ignored to prevent ambiguous behavior. @param {string} name
[ "Adds", "a", "constructor", "method", "name", ".", "The", "first", "occurance", "of", "a", "function", "named", "like", "one", "of", "these", "is", "executed", ".", "The", "rest", "is", "ignored", "to", "prevent", "ambiguous", "behavior", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Config.js#L25-L31
train
haroldiedema/joii
src/Config.js
function(name) { if (JOII.Config.constructors.indexOf(name) === -1) { return; } JOII.Config.constructors.splice(JOII.Config.constructors.indexOf(name), 1); }
javascript
function(name) { if (JOII.Config.constructors.indexOf(name) === -1) { return; } JOII.Config.constructors.splice(JOII.Config.constructors.indexOf(name), 1); }
[ "function", "(", "name", ")", "{", "if", "(", "JOII", ".", "Config", ".", "constructors", ".", "indexOf", "(", "name", ")", "===", "-", "1", ")", "{", "return", ";", "}", "JOII", ".", "Config", ".", "constructors", ".", "splice", "(", "JOII", ".", "Config", ".", "constructors", ".", "indexOf", "(", "name", ")", ",", "1", ")", ";", "}" ]
Removes a constructor method name. The first occurance of a function named like one of these is executed. The rest is ignored to prevent ambiguous behavior. @param {string} name
[ "Removes", "a", "constructor", "method", "name", ".", "The", "first", "occurance", "of", "a", "function", "named", "like", "one", "of", "these", "is", "executed", ".", "The", "rest", "is", "ignored", "to", "prevent", "ambiguous", "behavior", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Config.js#L40-L46
train
dannymidnight/node-weather
yahoo.js
function(msg) { if (yahoo.logging) { console.log('ERROR: ' + msg); } if (module.exports.error) { module.exports.error(msg); } }
javascript
function(msg) { if (yahoo.logging) { console.log('ERROR: ' + msg); } if (module.exports.error) { module.exports.error(msg); } }
[ "function", "(", "msg", ")", "{", "if", "(", "yahoo", ".", "logging", ")", "{", "console", ".", "log", "(", "'ERROR: '", "+", "msg", ")", ";", "}", "if", "(", "module", ".", "exports", ".", "error", ")", "{", "module", ".", "exports", ".", "error", "(", "msg", ")", ";", "}", "}" ]
Report error.
[ "Report", "error", "." ]
6658662f8641ed272a93c280b327429f23c6d3d8
https://github.com/dannymidnight/node-weather/blob/6658662f8641ed272a93c280b327429f23c6d3d8/yahoo.js#L15-L23
train
telligro/opal-nodes
packages/opal-node-email/emailprocess.js
processNewMessage
function processNewMessage(msg, mailMessage) { // msg = JSON.parse(JSON.stringify(msg)); // Clone the message // Populate the msg fields from the content of the email message // that we have just parsed. msg.payload = mailMessage.text; msg.topic = mailMessage.subject; msg.date = mailMessage.date; msg.header = mailMessage.headers; if (mailMessage.html) { msg.html = mailMessage.html; } if (mailMessage.to && mailMessage.from.to > 0) { msg.to = mailMessage.to; } if (mailMessage.cc && mailMessage.from.cc > 0) { msg.cc = mailMessage.cc; } if (mailMessage.bcc && mailMessage.from.bcc > 0) { msg.bcc = mailMessage.bcc; } if (mailMessage.from && mailMessage.from.length > 0) { msg.from = mailMessage.from[0].address; } if (mailMessage.attachments) { msg.attachments = mailMessage.attachments; } else { msg.attachments = []; } n.send(msg); // Propagate the message down the flow }
javascript
function processNewMessage(msg, mailMessage) { // msg = JSON.parse(JSON.stringify(msg)); // Clone the message // Populate the msg fields from the content of the email message // that we have just parsed. msg.payload = mailMessage.text; msg.topic = mailMessage.subject; msg.date = mailMessage.date; msg.header = mailMessage.headers; if (mailMessage.html) { msg.html = mailMessage.html; } if (mailMessage.to && mailMessage.from.to > 0) { msg.to = mailMessage.to; } if (mailMessage.cc && mailMessage.from.cc > 0) { msg.cc = mailMessage.cc; } if (mailMessage.bcc && mailMessage.from.bcc > 0) { msg.bcc = mailMessage.bcc; } if (mailMessage.from && mailMessage.from.length > 0) { msg.from = mailMessage.from[0].address; } if (mailMessage.attachments) { msg.attachments = mailMessage.attachments; } else { msg.attachments = []; } n.send(msg); // Propagate the message down the flow }
[ "function", "processNewMessage", "(", "msg", ",", "mailMessage", ")", "{", "msg", ".", "payload", "=", "mailMessage", ".", "text", ";", "msg", ".", "topic", "=", "mailMessage", ".", "subject", ";", "msg", ".", "date", "=", "mailMessage", ".", "date", ";", "msg", ".", "header", "=", "mailMessage", ".", "headers", ";", "if", "(", "mailMessage", ".", "html", ")", "{", "msg", ".", "html", "=", "mailMessage", ".", "html", ";", "}", "if", "(", "mailMessage", ".", "to", "&&", "mailMessage", ".", "from", ".", "to", ">", "0", ")", "{", "msg", ".", "to", "=", "mailMessage", ".", "to", ";", "}", "if", "(", "mailMessage", ".", "cc", "&&", "mailMessage", ".", "from", ".", "cc", ">", "0", ")", "{", "msg", ".", "cc", "=", "mailMessage", ".", "cc", ";", "}", "if", "(", "mailMessage", ".", "bcc", "&&", "mailMessage", ".", "from", ".", "bcc", ">", "0", ")", "{", "msg", ".", "bcc", "=", "mailMessage", ".", "bcc", ";", "}", "if", "(", "mailMessage", ".", "from", "&&", "mailMessage", ".", "from", ".", "length", ">", "0", ")", "{", "msg", ".", "from", "=", "mailMessage", ".", "from", "[", "0", "]", ".", "address", ";", "}", "if", "(", "mailMessage", ".", "attachments", ")", "{", "msg", ".", "attachments", "=", "mailMessage", ".", "attachments", ";", "}", "else", "{", "msg", ".", "attachments", "=", "[", "]", ";", "}", "n", ".", "send", "(", "msg", ")", ";", "}" ]
Process a new email message by building a Node-RED message to be passed onwards in the message flow. The parameter called `msg` is the template message we start with while `mailMessage` is an object returned from `mailparser` that will be used to populate the email. Process a new email message by building a Node-RED message to be passed onwards in the message flow. The parameter called `msg` is the template message we start with while `mailMessage` is an object returned from `mailparser` that will be used to populate the email. @param {any} msg __DOCSPLACEHOLDER__ @param {any} mailMessage __DOCSPLACEHOLDER__
[ "Process", "a", "new", "email", "message", "by", "building", "a", "Node", "-", "RED", "message", "to", "be", "passed", "onwards", "in", "the", "message", "flow", ".", "The", "parameter", "called", "msg", "is", "the", "template", "message", "we", "start", "with", "while", "mailMessage", "is", "an", "object", "returned", "from", "mailparser", "that", "will", "be", "used", "to", "populate", "the", "email", ".", "Process", "a", "new", "email", "message", "by", "building", "a", "Node", "-", "RED", "message", "to", "be", "passed", "onwards", "in", "the", "message", "flow", ".", "The", "parameter", "called", "msg", "is", "the", "template", "message", "we", "start", "with", "while", "mailMessage", "is", "an", "object", "returned", "from", "mailparser", "that", "will", "be", "used", "to", "populate", "the", "email", "." ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-email/emailprocess.js#L352-L381
train
telligro/opal-nodes
packages/opal-node-email/emailprocess.js
checkPOP3
function checkPOP3(msg) { let currentMessage; let maxMessage; // Form a new connection to our email server using POP3. let pop3Client = new POP3Client( node.port, node.server, {enabletls: node.useSSL} // Should we use SSL to connect to our email server? ); // If we have a next message to retrieve, ask to retrieve it otherwise issue a /** * If we have a next message to retrieve, ask to retrieve it otherwise issue a */ function nextMessage() { if (currentMessage > maxMessage) { pop3Client.quit(); return; } pop3Client.retr(currentMessage); currentMessage++; } // End of nextMessage pop3Client.on('stat', function(status, data) { // Data contains: // { // count: <Number of messages to be read> // octect: <size of messages to be read> // } if (status) { currentMessage = 1; maxMessage = data.count; nextMessage(); } else { node.log(util.format('stat error: %s %j', status, data)); } }); pop3Client.on('error', function(err) { node.log('We caught an error: ' + JSON.stringify(err)); }); pop3Client.on('connect', function() { // node.log("We are now connected"); pop3Client.login(node.userid, node.password); }); pop3Client.on('login', function(status, rawData) { // node.log("login: " + status + ", " + rawData); if (status) { pop3Client.stat(); } else { node.log(util.format('login error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('retr', function(status, msgNumber, data, rawData) { // node.log(util.format("retr: status=%s, msgNumber=%d, data=%j", status, msgNumber, data)); if (status) { // We have now received a new email message. Create an instance of a mail parser // and pass in the email message. The parser will signal when it has parsed the message. let mailparser = new MailParser(); mailparser.on('end', function(mailObject) { // node.log(util.format("mailparser: on(end): %j", mailObject)); processNewMessage(msg, mailObject); }); mailparser.write(data); mailparser.end(); pop3Client.dele(msgNumber); } else { node.log(util.format('retr error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('invalid-state', function(cmd) { node.log('Invalid state: ' + cmd); }); pop3Client.on('locked', function(cmd) { node.log('We were locked: ' + cmd); }); // When we have deleted the last processed message, we can move on to // processing the next message. pop3Client.on('dele', function(status, msgNumber) { nextMessage(); }); }
javascript
function checkPOP3(msg) { let currentMessage; let maxMessage; // Form a new connection to our email server using POP3. let pop3Client = new POP3Client( node.port, node.server, {enabletls: node.useSSL} // Should we use SSL to connect to our email server? ); // If we have a next message to retrieve, ask to retrieve it otherwise issue a /** * If we have a next message to retrieve, ask to retrieve it otherwise issue a */ function nextMessage() { if (currentMessage > maxMessage) { pop3Client.quit(); return; } pop3Client.retr(currentMessage); currentMessage++; } // End of nextMessage pop3Client.on('stat', function(status, data) { // Data contains: // { // count: <Number of messages to be read> // octect: <size of messages to be read> // } if (status) { currentMessage = 1; maxMessage = data.count; nextMessage(); } else { node.log(util.format('stat error: %s %j', status, data)); } }); pop3Client.on('error', function(err) { node.log('We caught an error: ' + JSON.stringify(err)); }); pop3Client.on('connect', function() { // node.log("We are now connected"); pop3Client.login(node.userid, node.password); }); pop3Client.on('login', function(status, rawData) { // node.log("login: " + status + ", " + rawData); if (status) { pop3Client.stat(); } else { node.log(util.format('login error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('retr', function(status, msgNumber, data, rawData) { // node.log(util.format("retr: status=%s, msgNumber=%d, data=%j", status, msgNumber, data)); if (status) { // We have now received a new email message. Create an instance of a mail parser // and pass in the email message. The parser will signal when it has parsed the message. let mailparser = new MailParser(); mailparser.on('end', function(mailObject) { // node.log(util.format("mailparser: on(end): %j", mailObject)); processNewMessage(msg, mailObject); }); mailparser.write(data); mailparser.end(); pop3Client.dele(msgNumber); } else { node.log(util.format('retr error: %s %j', status, rawData)); pop3Client.quit(); } }); pop3Client.on('invalid-state', function(cmd) { node.log('Invalid state: ' + cmd); }); pop3Client.on('locked', function(cmd) { node.log('We were locked: ' + cmd); }); // When we have deleted the last processed message, we can move on to // processing the next message. pop3Client.on('dele', function(status, msgNumber) { nextMessage(); }); }
[ "function", "checkPOP3", "(", "msg", ")", "{", "let", "currentMessage", ";", "let", "maxMessage", ";", "let", "pop3Client", "=", "new", "POP3Client", "(", "node", ".", "port", ",", "node", ".", "server", ",", "{", "enabletls", ":", "node", ".", "useSSL", "}", ")", ";", "function", "nextMessage", "(", ")", "{", "if", "(", "currentMessage", ">", "maxMessage", ")", "{", "pop3Client", ".", "quit", "(", ")", ";", "return", ";", "}", "pop3Client", ".", "retr", "(", "currentMessage", ")", ";", "currentMessage", "++", ";", "}", "pop3Client", ".", "on", "(", "'stat'", ",", "function", "(", "status", ",", "data", ")", "{", "if", "(", "status", ")", "{", "currentMessage", "=", "1", ";", "maxMessage", "=", "data", ".", "count", ";", "nextMessage", "(", ")", ";", "}", "else", "{", "node", ".", "log", "(", "util", ".", "format", "(", "'stat error: %s %j'", ",", "status", ",", "data", ")", ")", ";", "}", "}", ")", ";", "pop3Client", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "node", ".", "log", "(", "'We caught an error: '", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "}", ")", ";", "pop3Client", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "pop3Client", ".", "login", "(", "node", ".", "userid", ",", "node", ".", "password", ")", ";", "}", ")", ";", "pop3Client", ".", "on", "(", "'login'", ",", "function", "(", "status", ",", "rawData", ")", "{", "if", "(", "status", ")", "{", "pop3Client", ".", "stat", "(", ")", ";", "}", "else", "{", "node", ".", "log", "(", "util", ".", "format", "(", "'login error: %s %j'", ",", "status", ",", "rawData", ")", ")", ";", "pop3Client", ".", "quit", "(", ")", ";", "}", "}", ")", ";", "pop3Client", ".", "on", "(", "'retr'", ",", "function", "(", "status", ",", "msgNumber", ",", "data", ",", "rawData", ")", "{", "if", "(", "status", ")", "{", "let", "mailparser", "=", "new", "MailParser", "(", ")", ";", "mailparser", ".", "on", "(", "'end'", ",", "function", "(", "mailObject", ")", "{", "processNewMessage", "(", "msg", ",", "mailObject", ")", ";", "}", ")", ";", "mailparser", ".", "write", "(", "data", ")", ";", "mailparser", ".", "end", "(", ")", ";", "pop3Client", ".", "dele", "(", "msgNumber", ")", ";", "}", "else", "{", "node", ".", "log", "(", "util", ".", "format", "(", "'retr error: %s %j'", ",", "status", ",", "rawData", ")", ")", ";", "pop3Client", ".", "quit", "(", ")", ";", "}", "}", ")", ";", "pop3Client", ".", "on", "(", "'invalid-state'", ",", "function", "(", "cmd", ")", "{", "node", ".", "log", "(", "'Invalid state: '", "+", "cmd", ")", ";", "}", ")", ";", "pop3Client", ".", "on", "(", "'locked'", ",", "function", "(", "cmd", ")", "{", "node", ".", "log", "(", "'We were locked: '", "+", "cmd", ")", ";", "}", ")", ";", "pop3Client", ".", "on", "(", "'dele'", ",", "function", "(", "status", ",", "msgNumber", ")", "{", "nextMessage", "(", ")", ";", "}", ")", ";", "}" ]
Check the POP3 email mailbox for any new messages. For any that are found, retrieve each message, call processNewMessage to process it and then delete Check the POP3 email mailbox for any new messages. For any that are found, retrieve each message, call processNewMessage to process it and then delete @param {any} msg __DOCSPLACEHOLDER__
[ "Check", "the", "POP3", "email", "mailbox", "for", "any", "new", "messages", ".", "For", "any", "that", "are", "found", "retrieve", "each", "message", "call", "processNewMessage", "to", "process", "it", "and", "then", "delete", "Check", "the", "POP3", "email", "mailbox", "for", "any", "new", "messages", ".", "For", "any", "that", "are", "found", "retrieve", "each", "message", "call", "processNewMessage", "to", "process", "it", "and", "then", "delete" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-email/emailprocess.js#L391-L480
train
telligro/opal-nodes
packages/opal-node-email/emailprocess.js
processValuesFromContext
function processValuesFromContext(node, params, msg, varList) { let pMsg = {}; Object.assign(pMsg, params); varList.forEach((varItem) => { if (varItem.type === undefined || params[varItem.type] === undefined) { pMsg[varItem.name] = params[varItem.name]; } else if (params[varItem.type] === 'flow' || params[varItem.type] === 'global') { pMsg[varItem.name] = RED.util.evaluateNodeProperty(params[varItem.name], params[varItem.type], node, msg); pMsg[varItem.type] = params[varItem.type]; console.log('Inside flow or global'); console.log(varItem.name + ' - - ' + pMsg[varItem.name]); } else { pMsg[varItem.name] = params[varItem.name]; pMsg[varItem.type] = params[varItem.type]; } }); return pMsg; }
javascript
function processValuesFromContext(node, params, msg, varList) { let pMsg = {}; Object.assign(pMsg, params); varList.forEach((varItem) => { if (varItem.type === undefined || params[varItem.type] === undefined) { pMsg[varItem.name] = params[varItem.name]; } else if (params[varItem.type] === 'flow' || params[varItem.type] === 'global') { pMsg[varItem.name] = RED.util.evaluateNodeProperty(params[varItem.name], params[varItem.type], node, msg); pMsg[varItem.type] = params[varItem.type]; console.log('Inside flow or global'); console.log(varItem.name + ' - - ' + pMsg[varItem.name]); } else { pMsg[varItem.name] = params[varItem.name]; pMsg[varItem.type] = params[varItem.type]; } }); return pMsg; }
[ "function", "processValuesFromContext", "(", "node", ",", "params", ",", "msg", ",", "varList", ")", "{", "let", "pMsg", "=", "{", "}", ";", "Object", ".", "assign", "(", "pMsg", ",", "params", ")", ";", "varList", ".", "forEach", "(", "(", "varItem", ")", "=>", "{", "if", "(", "varItem", ".", "type", "===", "undefined", "||", "params", "[", "varItem", ".", "type", "]", "===", "undefined", ")", "{", "pMsg", "[", "varItem", ".", "name", "]", "=", "params", "[", "varItem", ".", "name", "]", ";", "}", "else", "if", "(", "params", "[", "varItem", ".", "type", "]", "===", "'flow'", "||", "params", "[", "varItem", ".", "type", "]", "===", "'global'", ")", "{", "pMsg", "[", "varItem", ".", "name", "]", "=", "RED", ".", "util", ".", "evaluateNodeProperty", "(", "params", "[", "varItem", ".", "name", "]", ",", "params", "[", "varItem", ".", "type", "]", ",", "node", ",", "msg", ")", ";", "pMsg", "[", "varItem", ".", "type", "]", "=", "params", "[", "varItem", ".", "type", "]", ";", "console", ".", "log", "(", "'Inside flow or global'", ")", ";", "console", ".", "log", "(", "varItem", ".", "name", "+", "' - - '", "+", "pMsg", "[", "varItem", ".", "name", "]", ")", ";", "}", "else", "{", "pMsg", "[", "varItem", ".", "name", "]", "=", "params", "[", "varItem", ".", "name", "]", ";", "pMsg", "[", "varItem", ".", "type", "]", "=", "params", "[", "varItem", ".", "type", "]", ";", "}", "}", ")", ";", "return", "pMsg", ";", "}" ]
End of checkEmail proccess values from context @param {any} node __DOCSPLACEHOLDER__ @param {any} params __DOCSPLACEHOLDER__ @param {any} msg __DOCSPLACEHOLDER__ @param {any} varList __DOCSPLACEHOLDER__ @return {object} pMsg
[ "End", "of", "checkEmail", "proccess", "values", "from", "context" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-email/emailprocess.js#L650-L667
train
nodebox/g.js
src/g.js
splitRow
function splitRow(s, delimiter) { var row = [], c, col = '', i, inString = false; s = s.trim(); for (i = 0; i < s.length; i += 1) { c = s[i]; if (c === '"') { if (s[i+1] === '"') { col += '"'; i += 1; } else { inString = !inString; } } else if (c === delimiter) { if (!inString) { row.push(col); col = ''; } else { col += c; } } else { col += c; } } row.push(col); return row; }
javascript
function splitRow(s, delimiter) { var row = [], c, col = '', i, inString = false; s = s.trim(); for (i = 0; i < s.length; i += 1) { c = s[i]; if (c === '"') { if (s[i+1] === '"') { col += '"'; i += 1; } else { inString = !inString; } } else if (c === delimiter) { if (!inString) { row.push(col); col = ''; } else { col += c; } } else { col += c; } } row.push(col); return row; }
[ "function", "splitRow", "(", "s", ",", "delimiter", ")", "{", "var", "row", "=", "[", "]", ",", "c", ",", "col", "=", "''", ",", "i", ",", "inString", "=", "false", ";", "s", "=", "s", ".", "trim", "(", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "s", ".", "length", ";", "i", "+=", "1", ")", "{", "c", "=", "s", "[", "i", "]", ";", "if", "(", "c", "===", "'\"'", ")", "{", "if", "(", "s", "[", "i", "+", "1", "]", "===", "'\"'", ")", "{", "col", "+=", "'\"'", ";", "i", "+=", "1", ";", "}", "else", "{", "inString", "=", "!", "inString", ";", "}", "}", "else", "if", "(", "c", "===", "delimiter", ")", "{", "if", "(", "!", "inString", ")", "{", "row", ".", "push", "(", "col", ")", ";", "col", "=", "''", ";", "}", "else", "{", "col", "+=", "c", ";", "}", "}", "else", "{", "col", "+=", "c", ";", "}", "}", "row", ".", "push", "(", "col", ")", ";", "return", "row", ";", "}" ]
Split the row, taking quotes into account.
[ "Split", "the", "row", "taking", "quotes", "into", "account", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/g.js#L49-L74
train
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
javascript
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getProperties", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if a property by the given name exists. @return bool
[ "Returns", "true", "if", "a", "property", "by", "the", "given", "name", "exists", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L106-L114
train
haroldiedema/joii
src/Reflection.js
function(filter) { var result = []; for (var i in this.proto) { if (typeof (this.proto[i]) === 'function' && JOII.Compat.indexOf(JOII.InternalPropertyNames, i) === -1) { result.push(new JOII.Reflection.Method(this, i)); } } return result; }
javascript
function(filter) { var result = []; for (var i in this.proto) { if (typeof (this.proto[i]) === 'function' && JOII.Compat.indexOf(JOII.InternalPropertyNames, i) === -1) { result.push(new JOII.Reflection.Method(this, i)); } } return result; }
[ "function", "(", "filter", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "in", "this", ".", "proto", ")", "{", "if", "(", "typeof", "(", "this", ".", "proto", "[", "i", "]", ")", "===", "'function'", "&&", "JOII", ".", "Compat", ".", "indexOf", "(", "JOII", ".", "InternalPropertyNames", ",", "i", ")", "===", "-", "1", ")", "{", "result", ".", "push", "(", "new", "JOII", ".", "Reflection", ".", "Method", "(", "this", ",", "i", ")", ")", ";", "}", "}", "return", "result", ";", "}" ]
Returns an array of JOII.Reflection.Method based on the methods defined in this class. @param string filter Optional filter for 'private' or 'public'. @return JOII.Reflection.Method[]
[ "Returns", "an", "array", "of", "JOII", ".", "Reflection", ".", "Method", "based", "on", "the", "methods", "defined", "in", "this", "class", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L141-L149
train
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
javascript
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return true; } } return false; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getMethods", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if a method by the given name exists. @return bool
[ "Returns", "true", "if", "a", "method", "by", "the", "given", "name", "exists", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L156-L164
train
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Method "' + name + '" does not exist.'; }
javascript
function(name) { var list = this.getMethods(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Method "' + name + '" does not exist.'; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getMethods", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "list", "[", "i", "]", ";", "}", "}", "throw", "'Method \"'", "+", "name", "+", "'\" does not exist.'", ";", "}" ]
Returns an instance of JOII.Reflection.Method of a method by the given name. @param string name @return JOII.Reflection.Method
[ "Returns", "an", "instance", "of", "JOII", ".", "Reflection", ".", "Method", "of", "a", "method", "by", "the", "given", "name", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L173-L181
train
haroldiedema/joii
src/Reflection.js
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Property "' + name + '" does not exist.'; }
javascript
function(name) { var list = this.getProperties(); for (var i in list) { if (list[i].getName() === name) { return list[i]; } } throw 'Property "' + name + '" does not exist.'; }
[ "function", "(", "name", ")", "{", "var", "list", "=", "this", ".", "getProperties", "(", ")", ";", "for", "(", "var", "i", "in", "list", ")", "{", "if", "(", "list", "[", "i", "]", ".", "getName", "(", ")", "===", "name", ")", "{", "return", "list", "[", "i", "]", ";", "}", "}", "throw", "'Property \"'", "+", "name", "+", "'\" does not exist.'", ";", "}" ]
Returns an instance of JOII.Reflection.Property of a property by the given name. @param string name @return JOII.Reflection.Property
[ "Returns", "an", "instance", "of", "JOII", ".", "Reflection", ".", "Property", "of", "a", "property", "by", "the", "given", "name", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L207-L215
train
haroldiedema/joii
src/Reflection.js
function() { var name_parts = [], proto_ref = this.reflector.getProto()[this.name], name = '', body = ''; if (this.meta.is_abstract) { name_parts.push('abstract'); } if (this.meta.is_final) { name_parts.push('final'); } name_parts.push(this.meta.visibility); if (this.meta.is_static) { name_parts.push('static'); } if (this.meta.is_nullable) { name_parts.push('nullable'); } if (this.meta.is_read_only) { name_parts.push('read'); } // If type === null, attempt to detect it by the predefined value. if (this.meta.type === null) { if (proto_ref === null) { name_parts.push('mixed'); } else { name_parts.push(typeof (proto_ref)); } } else { name_parts.push(this.meta.type); } name_parts.push('"' + this.meta.name + '"'); name = name_parts.join(' '); if (typeof (proto_ref) === 'function') { body = '[Function]'; } else if (typeof (proto_ref) === 'object' && proto_ref !== null) { body = '[Object (' + proto_ref.length + ')]'; } else if (typeof (proto_ref) === 'string') { body = '"' + proto_ref + '"'; } else { body = proto_ref; } return name + ': ' + body; }
javascript
function() { var name_parts = [], proto_ref = this.reflector.getProto()[this.name], name = '', body = ''; if (this.meta.is_abstract) { name_parts.push('abstract'); } if (this.meta.is_final) { name_parts.push('final'); } name_parts.push(this.meta.visibility); if (this.meta.is_static) { name_parts.push('static'); } if (this.meta.is_nullable) { name_parts.push('nullable'); } if (this.meta.is_read_only) { name_parts.push('read'); } // If type === null, attempt to detect it by the predefined value. if (this.meta.type === null) { if (proto_ref === null) { name_parts.push('mixed'); } else { name_parts.push(typeof (proto_ref)); } } else { name_parts.push(this.meta.type); } name_parts.push('"' + this.meta.name + '"'); name = name_parts.join(' '); if (typeof (proto_ref) === 'function') { body = '[Function]'; } else if (typeof (proto_ref) === 'object' && proto_ref !== null) { body = '[Object (' + proto_ref.length + ')]'; } else if (typeof (proto_ref) === 'string') { body = '"' + proto_ref + '"'; } else { body = proto_ref; } return name + ': ' + body; }
[ "function", "(", ")", "{", "var", "name_parts", "=", "[", "]", ",", "proto_ref", "=", "this", ".", "reflector", ".", "getProto", "(", ")", "[", "this", ".", "name", "]", ",", "name", "=", "''", ",", "body", "=", "''", ";", "if", "(", "this", ".", "meta", ".", "is_abstract", ")", "{", "name_parts", ".", "push", "(", "'abstract'", ")", ";", "}", "if", "(", "this", ".", "meta", ".", "is_final", ")", "{", "name_parts", ".", "push", "(", "'final'", ")", ";", "}", "name_parts", ".", "push", "(", "this", ".", "meta", ".", "visibility", ")", ";", "if", "(", "this", ".", "meta", ".", "is_static", ")", "{", "name_parts", ".", "push", "(", "'static'", ")", ";", "}", "if", "(", "this", ".", "meta", ".", "is_nullable", ")", "{", "name_parts", ".", "push", "(", "'nullable'", ")", ";", "}", "if", "(", "this", ".", "meta", ".", "is_read_only", ")", "{", "name_parts", ".", "push", "(", "'read'", ")", ";", "}", "if", "(", "this", ".", "meta", ".", "type", "===", "null", ")", "{", "if", "(", "proto_ref", "===", "null", ")", "{", "name_parts", ".", "push", "(", "'mixed'", ")", ";", "}", "else", "{", "name_parts", ".", "push", "(", "typeof", "(", "proto_ref", ")", ")", ";", "}", "}", "else", "{", "name_parts", ".", "push", "(", "this", ".", "meta", ".", "type", ")", ";", "}", "name_parts", ".", "push", "(", "'\"'", "+", "this", ".", "meta", ".", "name", "+", "'\"'", ")", ";", "name", "=", "name_parts", ".", "join", "(", "' '", ")", ";", "if", "(", "typeof", "(", "proto_ref", ")", "===", "'function'", ")", "{", "body", "=", "'[Function]'", ";", "}", "else", "if", "(", "typeof", "(", "proto_ref", ")", "===", "'object'", "&&", "proto_ref", "!==", "null", ")", "{", "body", "=", "'[Object ('", "+", "proto_ref", ".", "length", "+", "')]'", ";", "}", "else", "if", "(", "typeof", "(", "proto_ref", ")", "===", "'string'", ")", "{", "body", "=", "'\"'", "+", "proto_ref", "+", "'\"'", ";", "}", "else", "{", "body", "=", "proto_ref", ";", "}", "return", "name", "+", "': '", "+", "body", ";", "}" ]
Returns a string representation of this object. @return string
[ "Returns", "a", "string", "representation", "of", "this", "object", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L392-L432
train
haroldiedema/joii
src/Reflection.js
function() { var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m, FN_ARG_SPLIT = /,/, FN_ARG = /^\s*(_?)(\S+?)\1\s*$/, STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, getParams = function(fn) { var fnText, argDecl; var args = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); var r = argDecl[1].split(FN_ARG_SPLIT), repl = function(all, underscore, name) { args.push(name); }; for (var a in r) { var arg = r[a]; arg.replace(FN_ARG, repl); } return args; }; var prototype = this.reflector.getProto(); var overloads = prototype.__joii__.metadata[this.name].overloads; if (!overloads || overloads.length === 0) { // old method for BC (wasn't recognized as a function when prototyping) return getParams(this.reflector.getProto()[this.name]); } else if (overloads.length === 1 && overloads[0].parameters.length === 0) { // old method for BC (was recognized when prototyping, but old style) return getParams(overloads[0].fn); } else { var ret = []; for (var idx = 0; idx < overloads.length; idx++) { var fn_meta = []; var function_parameters_meta = overloads[idx]; var parsed_params = getParams(function_parameters_meta.fn); for (var j = 0; j < function_parameters_meta.parameters.length; j++) { var param = { name: parsed_params.length > j ? parsed_params[j] : null, type: function_parameters_meta.parameters[j] }; fn_meta.push(param); } ret.push(fn_meta); } return ret; } }
javascript
function() { var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m, FN_ARG_SPLIT = /,/, FN_ARG = /^\s*(_?)(\S+?)\1\s*$/, STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, getParams = function(fn) { var fnText, argDecl; var args = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); var r = argDecl[1].split(FN_ARG_SPLIT), repl = function(all, underscore, name) { args.push(name); }; for (var a in r) { var arg = r[a]; arg.replace(FN_ARG, repl); } return args; }; var prototype = this.reflector.getProto(); var overloads = prototype.__joii__.metadata[this.name].overloads; if (!overloads || overloads.length === 0) { // old method for BC (wasn't recognized as a function when prototyping) return getParams(this.reflector.getProto()[this.name]); } else if (overloads.length === 1 && overloads[0].parameters.length === 0) { // old method for BC (was recognized when prototyping, but old style) return getParams(overloads[0].fn); } else { var ret = []; for (var idx = 0; idx < overloads.length; idx++) { var fn_meta = []; var function_parameters_meta = overloads[idx]; var parsed_params = getParams(function_parameters_meta.fn); for (var j = 0; j < function_parameters_meta.parameters.length; j++) { var param = { name: parsed_params.length > j ? parsed_params[j] : null, type: function_parameters_meta.parameters[j] }; fn_meta.push(param); } ret.push(fn_meta); } return ret; } }
[ "function", "(", ")", "{", "var", "FN_ARGS", "=", "/", "^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)", "/", "m", ",", "FN_ARG_SPLIT", "=", "/", ",", "/", ",", "FN_ARG", "=", "/", "^\\s*(_?)(\\S+?)\\1\\s*$", "/", ",", "STRIP_COMMENTS", "=", "/", "((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))", "/", "mg", ",", "getParams", "=", "function", "(", "fn", ")", "{", "var", "fnText", ",", "argDecl", ";", "var", "args", "=", "[", "]", ";", "fnText", "=", "fn", ".", "toString", "(", ")", ".", "replace", "(", "STRIP_COMMENTS", ",", "''", ")", ";", "argDecl", "=", "fnText", ".", "match", "(", "FN_ARGS", ")", ";", "var", "r", "=", "argDecl", "[", "1", "]", ".", "split", "(", "FN_ARG_SPLIT", ")", ",", "repl", "=", "function", "(", "all", ",", "underscore", ",", "name", ")", "{", "args", ".", "push", "(", "name", ")", ";", "}", ";", "for", "(", "var", "a", "in", "r", ")", "{", "var", "arg", "=", "r", "[", "a", "]", ";", "arg", ".", "replace", "(", "FN_ARG", ",", "repl", ")", ";", "}", "return", "args", ";", "}", ";", "var", "prototype", "=", "this", ".", "reflector", ".", "getProto", "(", ")", ";", "var", "overloads", "=", "prototype", ".", "__joii__", ".", "metadata", "[", "this", ".", "name", "]", ".", "overloads", ";", "if", "(", "!", "overloads", "||", "overloads", ".", "length", "===", "0", ")", "{", "return", "getParams", "(", "this", ".", "reflector", ".", "getProto", "(", ")", "[", "this", ".", "name", "]", ")", ";", "}", "else", "if", "(", "overloads", ".", "length", "===", "1", "&&", "overloads", "[", "0", "]", ".", "parameters", ".", "length", "===", "0", ")", "{", "return", "getParams", "(", "overloads", "[", "0", "]", ".", "fn", ")", ";", "}", "else", "{", "var", "ret", "=", "[", "]", ";", "for", "(", "var", "idx", "=", "0", ";", "idx", "<", "overloads", ".", "length", ";", "idx", "++", ")", "{", "var", "fn_meta", "=", "[", "]", ";", "var", "function_parameters_meta", "=", "overloads", "[", "idx", "]", ";", "var", "parsed_params", "=", "getParams", "(", "function_parameters_meta", ".", "fn", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "function_parameters_meta", ".", "parameters", ".", "length", ";", "j", "++", ")", "{", "var", "param", "=", "{", "name", ":", "parsed_params", ".", "length", ">", "j", "?", "parsed_params", "[", "j", "]", ":", "null", ",", "type", ":", "function_parameters_meta", ".", "parameters", "[", "j", "]", "}", ";", "fn_meta", ".", "push", "(", "param", ")", ";", "}", "ret", ".", "push", "(", "fn_meta", ")", ";", "}", "return", "ret", ";", "}", "}" ]
Returns an array of strings based on the parameters defined in the declared function. @return string[]
[ "Returns", "an", "array", "of", "strings", "based", "on", "the", "parameters", "defined", "in", "the", "declared", "function", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L443-L493
train
haroldiedema/joii
src/Reflection.js
function(f) { var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, fn_text = this.reflector.getProto()[this.name].toString().replace(STRIP_COMMENTS, ''); return fn_text.substr(fn_text.indexOf('{') + 1, fn_text.lastIndexOf('}') - 4).replace(/}([^}]*)$/, '$1'); }
javascript
function(f) { var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, fn_text = this.reflector.getProto()[this.name].toString().replace(STRIP_COMMENTS, ''); return fn_text.substr(fn_text.indexOf('{') + 1, fn_text.lastIndexOf('}') - 4).replace(/}([^}]*)$/, '$1'); }
[ "function", "(", "f", ")", "{", "var", "STRIP_COMMENTS", "=", "/", "((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))", "/", "mg", ",", "fn_text", "=", "this", ".", "reflector", ".", "getProto", "(", ")", "[", "this", ".", "name", "]", ".", "toString", "(", ")", ".", "replace", "(", "STRIP_COMMENTS", ",", "''", ")", ";", "return", "fn_text", ".", "substr", "(", "fn_text", ".", "indexOf", "(", "'{'", ")", "+", "1", ",", "fn_text", ".", "lastIndexOf", "(", "'}'", ")", "-", "4", ")", ".", "replace", "(", "/", "}([^}]*)$", "/", ",", "'$1'", ")", ";", "}" ]
Returns the body of this method as a string. @return string
[ "Returns", "the", "body", "of", "this", "method", "as", "a", "string", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L500-L505
train
haroldiedema/joii
src/Reflection.js
function() { // Get the "declaration" part of the method. var prefix = this['super']('toString').split(':')[0], body = '[Function', args = this.getParameters(), is_var = this.usesVariadicArguments(); if (args.length > 0 && typeof (args[0]) === 'object') { // right now, this is spitting out every overload's signature one after another, each on a new line. // should probably find a better way to do this for (var idx = 0; idx < args.length; idx++) { var function_parameters_meta = args[idx]; body += ' ('; var first_time = true; for (var i = 0; i < function_parameters_meta.length; i++) { if (!first_time) { body += ', '; } first_time = false; body += function_parameters_meta[i].type; if (function_parameters_meta[i].name !== null) { body += " " + function_parameters_meta[i].name; is_var = true; } } var data = this.reflector.getProto().__joii__.metadata[this.name].overloads[idx].fn.toString(); is_var = data.match(/[\(|\.|\ ](arguments)[\)|\.|\,|\ |]/g); if (is_var) { body += ', ...'; } body += ')\n'; } } else if (args.length > 0) { body += ' (' + args.join(', '); if (is_var) { body += ', ...'; } body += ')'; } else if (args.length === 0 && is_var) { body += ' (...)'; } body += ']'; return prefix + ': ' + body; }
javascript
function() { // Get the "declaration" part of the method. var prefix = this['super']('toString').split(':')[0], body = '[Function', args = this.getParameters(), is_var = this.usesVariadicArguments(); if (args.length > 0 && typeof (args[0]) === 'object') { // right now, this is spitting out every overload's signature one after another, each on a new line. // should probably find a better way to do this for (var idx = 0; idx < args.length; idx++) { var function_parameters_meta = args[idx]; body += ' ('; var first_time = true; for (var i = 0; i < function_parameters_meta.length; i++) { if (!first_time) { body += ', '; } first_time = false; body += function_parameters_meta[i].type; if (function_parameters_meta[i].name !== null) { body += " " + function_parameters_meta[i].name; is_var = true; } } var data = this.reflector.getProto().__joii__.metadata[this.name].overloads[idx].fn.toString(); is_var = data.match(/[\(|\.|\ ](arguments)[\)|\.|\,|\ |]/g); if (is_var) { body += ', ...'; } body += ')\n'; } } else if (args.length > 0) { body += ' (' + args.join(', '); if (is_var) { body += ', ...'; } body += ')'; } else if (args.length === 0 && is_var) { body += ' (...)'; } body += ']'; return prefix + ': ' + body; }
[ "function", "(", ")", "{", "var", "prefix", "=", "this", "[", "'super'", "]", "(", "'toString'", ")", ".", "split", "(", "':'", ")", "[", "0", "]", ",", "body", "=", "'[Function'", ",", "args", "=", "this", ".", "getParameters", "(", ")", ",", "is_var", "=", "this", ".", "usesVariadicArguments", "(", ")", ";", "if", "(", "args", ".", "length", ">", "0", "&&", "typeof", "(", "args", "[", "0", "]", ")", "===", "'object'", ")", "{", "for", "(", "var", "idx", "=", "0", ";", "idx", "<", "args", ".", "length", ";", "idx", "++", ")", "{", "var", "function_parameters_meta", "=", "args", "[", "idx", "]", ";", "body", "+=", "' ('", ";", "var", "first_time", "=", "true", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "function_parameters_meta", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "first_time", ")", "{", "body", "+=", "', '", ";", "}", "first_time", "=", "false", ";", "body", "+=", "function_parameters_meta", "[", "i", "]", ".", "type", ";", "if", "(", "function_parameters_meta", "[", "i", "]", ".", "name", "!==", "null", ")", "{", "body", "+=", "\" \"", "+", "function_parameters_meta", "[", "i", "]", ".", "name", ";", "is_var", "=", "true", ";", "}", "}", "var", "data", "=", "this", ".", "reflector", ".", "getProto", "(", ")", ".", "__joii__", ".", "metadata", "[", "this", ".", "name", "]", ".", "overloads", "[", "idx", "]", ".", "fn", ".", "toString", "(", ")", ";", "is_var", "=", "data", ".", "match", "(", "/", "[\\(|\\.|\\ ](arguments)[\\)|\\.|\\,|\\ |]", "/", "g", ")", ";", "if", "(", "is_var", ")", "{", "body", "+=", "', ...'", ";", "}", "body", "+=", "')\\n'", ";", "}", "}", "else", "\\n", "if", "(", "args", ".", "length", ">", "0", ")", "{", "body", "+=", "' ('", "+", "args", ".", "join", "(", "', '", ")", ";", "if", "(", "is_var", ")", "{", "body", "+=", "', ...'", ";", "}", "body", "+=", "')'", ";", "}", "else", "if", "(", "args", ".", "length", "===", "0", "&&", "is_var", ")", "{", "body", "+=", "' (...)'", ";", "}", "body", "+=", "']'", ";", "}" ]
Returns a string representation of the method. @return string
[ "Returns", "a", "string", "representation", "of", "the", "method", "." ]
08f9b795109f01c584b769959d573ef9a799f6ba
https://github.com/haroldiedema/joii/blob/08f9b795109f01c584b769959d573ef9a799f6ba/src/Reflection.js#L526-L576
train
telligro/opal-nodes
packages/opal-node-pdfreader/pdfreader.js
sendError
function sendError(node, msg, err, ...attrs) { if (check.string(err)) { msg.error = { node: node.name, message: util.format(err, ...attrs), }; } else if (check.instance(err, Error)) { msg.error = err; } node.error(node.name + ': ' + msg.error.message, msg); }
javascript
function sendError(node, msg, err, ...attrs) { if (check.string(err)) { msg.error = { node: node.name, message: util.format(err, ...attrs), }; } else if (check.instance(err, Error)) { msg.error = err; } node.error(node.name + ': ' + msg.error.message, msg); }
[ "function", "sendError", "(", "node", ",", "msg", ",", "err", ",", "...", "attrs", ")", "{", "if", "(", "check", ".", "string", "(", "err", ")", ")", "{", "msg", ".", "error", "=", "{", "node", ":", "node", ".", "name", ",", "message", ":", "util", ".", "format", "(", "err", ",", "...", "attrs", ")", ",", "}", ";", "}", "else", "if", "(", "check", ".", "instance", "(", "err", ",", "Error", ")", ")", "{", "msg", ".", "error", "=", "err", ";", "}", "node", ".", "error", "(", "node", ".", "name", "+", "': '", "+", "msg", ".", "error", ".", "message", ",", "msg", ")", ";", "}" ]
sends Error back to node-red @function @param {object} node - the node object returned by createNode @param {object} msg - msg object passed as input to this node. @param {object} err - error object. @param {object} attrs - attrs to be used to construct error message.
[ "sends", "Error", "back", "to", "node", "-", "red" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-pdfreader/pdfreader.js#L35-L45
train
node-modules/ndir
lib/ndir.js
Walk
function Walk(root, onDir, onEnd, onError) { if (!(this instanceof Walk)) { return new Walk(root, onDir, onEnd, onError); } this.dirs = [path.resolve(root)]; if (onDir) { this.on('dir', onDir); } if (onEnd) { this.on('end', onEnd); } onError && this.on('error', onError); var self = this; // let listen `files` Event first. process.nextTick(function () { self.next(); }); }
javascript
function Walk(root, onDir, onEnd, onError) { if (!(this instanceof Walk)) { return new Walk(root, onDir, onEnd, onError); } this.dirs = [path.resolve(root)]; if (onDir) { this.on('dir', onDir); } if (onEnd) { this.on('end', onEnd); } onError && this.on('error', onError); var self = this; // let listen `files` Event first. process.nextTick(function () { self.next(); }); }
[ "function", "Walk", "(", "root", ",", "onDir", ",", "onEnd", ",", "onError", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Walk", ")", ")", "{", "return", "new", "Walk", "(", "root", ",", "onDir", ",", "onEnd", ",", "onError", ")", ";", "}", "this", ".", "dirs", "=", "[", "path", ".", "resolve", "(", "root", ")", "]", ";", "if", "(", "onDir", ")", "{", "this", ".", "on", "(", "'dir'", ",", "onDir", ")", ";", "}", "if", "(", "onEnd", ")", "{", "this", ".", "on", "(", "'end'", ",", "onEnd", ")", ";", "}", "onError", "&&", "this", ".", "on", "(", "'error'", ",", "onError", ")", ";", "var", "self", "=", "this", ";", "process", ".", "nextTick", "(", "function", "(", ")", "{", "self", ".", "next", "(", ")", ";", "}", ")", ";", "}" ]
dir Walker Class. @constructor @param {String} root Root path. @param {Function(dirpath, files)} [onDir] The `dir` event callback. @param {Function} [onEnd] The `end` event callback. @param {Function(err)} [onError] The `error` event callback. @public
[ "dir", "Walker", "Class", "." ]
d8fe9dca7c103f4180624bfa86ed6bbeaad67847
https://github.com/node-modules/ndir/blob/d8fe9dca7c103f4180624bfa86ed6bbeaad67847/lib/ndir.js#L27-L44
train
node-modules/ndir
lib/ndir.js
LineReader
function LineReader(file) { if (typeof file === 'string') { this.readstream = fs.createReadStream(file); } else { this.readstream = file; } this.remainBuffers = []; var self = this; this.readstream.on('data', function (data) { self.ondata(data); }); this.readstream.on('error', function (err) { self.emit('error', err); }); this.readstream.on('end', function () { self.emit('end'); }); }
javascript
function LineReader(file) { if (typeof file === 'string') { this.readstream = fs.createReadStream(file); } else { this.readstream = file; } this.remainBuffers = []; var self = this; this.readstream.on('data', function (data) { self.ondata(data); }); this.readstream.on('error', function (err) { self.emit('error', err); }); this.readstream.on('end', function () { self.emit('end'); }); }
[ "function", "LineReader", "(", "file", ")", "{", "if", "(", "typeof", "file", "===", "'string'", ")", "{", "this", ".", "readstream", "=", "fs", ".", "createReadStream", "(", "file", ")", ";", "}", "else", "{", "this", ".", "readstream", "=", "file", ";", "}", "this", ".", "remainBuffers", "=", "[", "]", ";", "var", "self", "=", "this", ";", "this", ".", "readstream", ".", "on", "(", "'data'", ",", "function", "(", "data", ")", "{", "self", ".", "ondata", "(", "data", ")", ";", "}", ")", ";", "this", ".", "readstream", ".", "on", "(", "'error'", ",", "function", "(", "err", ")", "{", "self", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ")", ";", "this", ".", "readstream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'end'", ")", ";", "}", ")", ";", "}" ]
Read stream data line by line. @constructor @param {String|ReadStream} file File path or data stream object.
[ "Read", "stream", "data", "line", "by", "line", "." ]
d8fe9dca7c103f4180624bfa86ed6bbeaad67847
https://github.com/node-modules/ndir/blob/d8fe9dca7c103f4180624bfa86ed6bbeaad67847/lib/ndir.js#L197-L214
train
wavesjs/waves-lfo
benchmarks/wasm/src/index.js
loadWebAssembly
function loadWebAssembly(filename, imports) { // Fetch the file and compile it return fetch(filename) .then(response => response.arrayBuffer()) .then(buffer => WebAssembly.compile(buffer)) .then(module => { // create the imports for the module, including the // standard dynamic library imports imports = imports || {}; imports.env = imports.env || {}; imports.env.memoryBase = imports.env.memoryBase || 0; imports.env.tableBase = imports.env.tableBase || 0; // note: just take really memory for now... if (!imports.env.memory) imports.env.memory = new WebAssembly.Memory({ initial: 256 }); if (!imports.env.table) imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' }); // create the instance const instance = new WebAssembly.Instance(module, imports); return Promise.resolve({ instance, imports }); }); }
javascript
function loadWebAssembly(filename, imports) { // Fetch the file and compile it return fetch(filename) .then(response => response.arrayBuffer()) .then(buffer => WebAssembly.compile(buffer)) .then(module => { // create the imports for the module, including the // standard dynamic library imports imports = imports || {}; imports.env = imports.env || {}; imports.env.memoryBase = imports.env.memoryBase || 0; imports.env.tableBase = imports.env.tableBase || 0; // note: just take really memory for now... if (!imports.env.memory) imports.env.memory = new WebAssembly.Memory({ initial: 256 }); if (!imports.env.table) imports.env.table = new WebAssembly.Table({ initial: 0, element: 'anyfunc' }); // create the instance const instance = new WebAssembly.Instance(module, imports); return Promise.resolve({ instance, imports }); }); }
[ "function", "loadWebAssembly", "(", "filename", ",", "imports", ")", "{", "return", "fetch", "(", "filename", ")", ".", "then", "(", "response", "=>", "response", ".", "arrayBuffer", "(", ")", ")", ".", "then", "(", "buffer", "=>", "WebAssembly", ".", "compile", "(", "buffer", ")", ")", ".", "then", "(", "module", "=>", "{", "imports", "=", "imports", "||", "{", "}", ";", "imports", ".", "env", "=", "imports", ".", "env", "||", "{", "}", ";", "imports", ".", "env", ".", "memoryBase", "=", "imports", ".", "env", ".", "memoryBase", "||", "0", ";", "imports", ".", "env", ".", "tableBase", "=", "imports", ".", "env", ".", "tableBase", "||", "0", ";", "if", "(", "!", "imports", ".", "env", ".", "memory", ")", "imports", ".", "env", ".", "memory", "=", "new", "WebAssembly", ".", "Memory", "(", "{", "initial", ":", "256", "}", ")", ";", "if", "(", "!", "imports", ".", "env", ".", "table", ")", "imports", ".", "env", ".", "table", "=", "new", "WebAssembly", ".", "Table", "(", "{", "initial", ":", "0", ",", "element", ":", "'anyfunc'", "}", ")", ";", "const", "instance", "=", "new", "WebAssembly", ".", "Instance", "(", "module", ",", "imports", ")", ";", "return", "Promise", ".", "resolve", "(", "{", "instance", ",", "imports", "}", ")", ";", "}", ")", ";", "}" ]
loads a WebAssembly dynamic library, returns a promise. imports is an optional imports object
[ "loads", "a", "WebAssembly", "dynamic", "library", "returns", "a", "promise", ".", "imports", "is", "an", "optional", "imports", "object" ]
4353a8ef55b7921755fe182cb09b0df566696bc8
https://github.com/wavesjs/waves-lfo/blob/4353a8ef55b7921755fe182cb09b0df566696bc8/benchmarks/wasm/src/index.js#L21-L45
train
sipcapture/hep-js
index.js
function(message) { if (debug) console.log('Decoding HEP3 Packet...'); try { var HEP = hepHeader.parse(message); if(HEP.payload && HEP.payload.length>0){ var data = HEP.payload; var tot = 0; var decoded = {}; var PAYLOAD; while(true){ PAYLOAD = hepParse.parse( data.slice(tot) ); var tmp = hepDecode(PAYLOAD); decoded = mixinDeep(decoded, tmp); tot += PAYLOAD.length; if(tot>=HEP.payload.length) { break; } } if(debug) console.log(decoded); return decoded; } } catch(e) { return false; } }
javascript
function(message) { if (debug) console.log('Decoding HEP3 Packet...'); try { var HEP = hepHeader.parse(message); if(HEP.payload && HEP.payload.length>0){ var data = HEP.payload; var tot = 0; var decoded = {}; var PAYLOAD; while(true){ PAYLOAD = hepParse.parse( data.slice(tot) ); var tmp = hepDecode(PAYLOAD); decoded = mixinDeep(decoded, tmp); tot += PAYLOAD.length; if(tot>=HEP.payload.length) { break; } } if(debug) console.log(decoded); return decoded; } } catch(e) { return false; } }
[ "function", "(", "message", ")", "{", "if", "(", "debug", ")", "console", ".", "log", "(", "'Decoding HEP3 Packet...'", ")", ";", "try", "{", "var", "HEP", "=", "hepHeader", ".", "parse", "(", "message", ")", ";", "if", "(", "HEP", ".", "payload", "&&", "HEP", ".", "payload", ".", "length", ">", "0", ")", "{", "var", "data", "=", "HEP", ".", "payload", ";", "var", "tot", "=", "0", ";", "var", "decoded", "=", "{", "}", ";", "var", "PAYLOAD", ";", "while", "(", "true", ")", "{", "PAYLOAD", "=", "hepParse", ".", "parse", "(", "data", ".", "slice", "(", "tot", ")", ")", ";", "var", "tmp", "=", "hepDecode", "(", "PAYLOAD", ")", ";", "decoded", "=", "mixinDeep", "(", "decoded", ",", "tmp", ")", ";", "tot", "+=", "PAYLOAD", ".", "length", ";", "if", "(", "tot", ">=", "HEP", ".", "payload", ".", "length", ")", "{", "break", ";", "}", "}", "if", "(", "debug", ")", "console", ".", "log", "(", "decoded", ")", ";", "return", "decoded", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Decode HEP3 Packet to JSON Object. @param {Buffer} hep message @return {Object}
[ "Decode", "HEP3", "Packet", "to", "JSON", "Object", "." ]
03922c439e4cce39ff2a0a87743476dfcdc2f298
https://github.com/sipcapture/hep-js/blob/03922c439e4cce39ff2a0a87743476dfcdc2f298/index.js#L39-L62
train
nodebox/g.js
src/libraries/img/img.js
toGradientData
function toGradientData(v1, v2, v3, v4, v5) { var startColor, endColor, type, rotation, spread, d; var data = {}; if (arguments.length === 1) { // The argument is a dictionary or undefined. d = v1 || {}; startColor = d.startColor; endColor = d.endColor; type = d.type; rotation = d.rotation; spread = d.spread; } else if (arguments.length >= 2) { // The first two arguments are a start color and an end color. startColor = v1; endColor = v2; type = 'linear'; rotation = 0; spread = 0; if (arguments.length === 3) { if (typeof v3 === 'string') { // The type can be either linear or radial. type = v3; } else if (typeof v3 === 'number') { // The type is implicitly linear and the third argument is the rotation angle. rotation = v3; } } else if (arguments.length === 4) { if (typeof v3 === 'number') { // The type is implicitly linear and the third/forth arguments are the rotation angle and gradient spread. rotation = v3; spread = v4; } else if (v3 === 'linear') { // The type is explicitly linear and the forth argument is the rotation angle. rotation = v4; } else if (v3 === 'radial') { // The type is explicitly radial and the forth argument is the gradient spread. type = v3; spread = v4; } else { throw new Error('Wrong argument provided: ' + v3); } } else if (arguments.length === 5) { // Type, rotation (unused in case of radial type gradient), and gradient spread. type = v3; rotation = v4; spread = v5; } } if (!startColor && startColor !== 0) { throw new Error('No startColor was given.'); } if (!endColor && endColor !== 0) { throw new Error('No endColor was given.'); } try { data.startColor = toColor(startColor); } catch (e1) { throw new Error('startColor is not a valid color: ' + startColor); } try { data.endColor = toColor(endColor); } catch (e2) { throw new Error('endColor is not a valid color: ' + endColor); } if (type === undefined) { type = 'linear'; } if (type !== 'linear' && type !== 'radial') { throw new Error('Unknown gradient type: ' + type); } data.type = type; if (spread === undefined) { spread = 0; } if (typeof spread !== 'number') { throw new Error('Spread value is not a number: ' + spread); } if (type === 'linear') { if (rotation === undefined) { rotation = 0; } if (typeof rotation !== 'number') { throw new Error('Rotation value is not a number: ' + rotation); } data.rotation = rotation; } data.spread = clamp(spread, 0, 0.99); return data; }
javascript
function toGradientData(v1, v2, v3, v4, v5) { var startColor, endColor, type, rotation, spread, d; var data = {}; if (arguments.length === 1) { // The argument is a dictionary or undefined. d = v1 || {}; startColor = d.startColor; endColor = d.endColor; type = d.type; rotation = d.rotation; spread = d.spread; } else if (arguments.length >= 2) { // The first two arguments are a start color and an end color. startColor = v1; endColor = v2; type = 'linear'; rotation = 0; spread = 0; if (arguments.length === 3) { if (typeof v3 === 'string') { // The type can be either linear or radial. type = v3; } else if (typeof v3 === 'number') { // The type is implicitly linear and the third argument is the rotation angle. rotation = v3; } } else if (arguments.length === 4) { if (typeof v3 === 'number') { // The type is implicitly linear and the third/forth arguments are the rotation angle and gradient spread. rotation = v3; spread = v4; } else if (v3 === 'linear') { // The type is explicitly linear and the forth argument is the rotation angle. rotation = v4; } else if (v3 === 'radial') { // The type is explicitly radial and the forth argument is the gradient spread. type = v3; spread = v4; } else { throw new Error('Wrong argument provided: ' + v3); } } else if (arguments.length === 5) { // Type, rotation (unused in case of radial type gradient), and gradient spread. type = v3; rotation = v4; spread = v5; } } if (!startColor && startColor !== 0) { throw new Error('No startColor was given.'); } if (!endColor && endColor !== 0) { throw new Error('No endColor was given.'); } try { data.startColor = toColor(startColor); } catch (e1) { throw new Error('startColor is not a valid color: ' + startColor); } try { data.endColor = toColor(endColor); } catch (e2) { throw new Error('endColor is not a valid color: ' + endColor); } if (type === undefined) { type = 'linear'; } if (type !== 'linear' && type !== 'radial') { throw new Error('Unknown gradient type: ' + type); } data.type = type; if (spread === undefined) { spread = 0; } if (typeof spread !== 'number') { throw new Error('Spread value is not a number: ' + spread); } if (type === 'linear') { if (rotation === undefined) { rotation = 0; } if (typeof rotation !== 'number') { throw new Error('Rotation value is not a number: ' + rotation); } data.rotation = rotation; } data.spread = clamp(spread, 0, 0.99); return data; }
[ "function", "toGradientData", "(", "v1", ",", "v2", ",", "v3", ",", "v4", ",", "v5", ")", "{", "var", "startColor", ",", "endColor", ",", "type", ",", "rotation", ",", "spread", ",", "d", ";", "var", "data", "=", "{", "}", ";", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "d", "=", "v1", "||", "{", "}", ";", "startColor", "=", "d", ".", "startColor", ";", "endColor", "=", "d", ".", "endColor", ";", "type", "=", "d", ".", "type", ";", "rotation", "=", "d", ".", "rotation", ";", "spread", "=", "d", ".", "spread", ";", "}", "else", "if", "(", "arguments", ".", "length", ">=", "2", ")", "{", "startColor", "=", "v1", ";", "endColor", "=", "v2", ";", "type", "=", "'linear'", ";", "rotation", "=", "0", ";", "spread", "=", "0", ";", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "if", "(", "typeof", "v3", "===", "'string'", ")", "{", "type", "=", "v3", ";", "}", "else", "if", "(", "typeof", "v3", "===", "'number'", ")", "{", "rotation", "=", "v3", ";", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "4", ")", "{", "if", "(", "typeof", "v3", "===", "'number'", ")", "{", "rotation", "=", "v3", ";", "spread", "=", "v4", ";", "}", "else", "if", "(", "v3", "===", "'linear'", ")", "{", "rotation", "=", "v4", ";", "}", "else", "if", "(", "v3", "===", "'radial'", ")", "{", "type", "=", "v3", ";", "spread", "=", "v4", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Wrong argument provided: '", "+", "v3", ")", ";", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "5", ")", "{", "type", "=", "v3", ";", "rotation", "=", "v4", ";", "spread", "=", "v5", ";", "}", "}", "if", "(", "!", "startColor", "&&", "startColor", "!==", "0", ")", "{", "throw", "new", "Error", "(", "'No startColor was given.'", ")", ";", "}", "if", "(", "!", "endColor", "&&", "endColor", "!==", "0", ")", "{", "throw", "new", "Error", "(", "'No endColor was given.'", ")", ";", "}", "try", "{", "data", ".", "startColor", "=", "toColor", "(", "startColor", ")", ";", "}", "catch", "(", "e1", ")", "{", "throw", "new", "Error", "(", "'startColor is not a valid color: '", "+", "startColor", ")", ";", "}", "try", "{", "data", ".", "endColor", "=", "toColor", "(", "endColor", ")", ";", "}", "catch", "(", "e2", ")", "{", "throw", "new", "Error", "(", "'endColor is not a valid color: '", "+", "endColor", ")", ";", "}", "if", "(", "type", "===", "undefined", ")", "{", "type", "=", "'linear'", ";", "}", "if", "(", "type", "!==", "'linear'", "&&", "type", "!==", "'radial'", ")", "{", "throw", "new", "Error", "(", "'Unknown gradient type: '", "+", "type", ")", ";", "}", "data", ".", "type", "=", "type", ";", "if", "(", "spread", "===", "undefined", ")", "{", "spread", "=", "0", ";", "}", "if", "(", "typeof", "spread", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "'Spread value is not a number: '", "+", "spread", ")", ";", "}", "if", "(", "type", "===", "'linear'", ")", "{", "if", "(", "rotation", "===", "undefined", ")", "{", "rotation", "=", "0", ";", "}", "if", "(", "typeof", "rotation", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "'Rotation value is not a number: '", "+", "rotation", ")", ";", "}", "data", ".", "rotation", "=", "rotation", ";", "}", "data", ".", "spread", "=", "clamp", "(", "spread", ",", "0", ",", "0.99", ")", ";", "return", "data", ";", "}" ]
Converts a number of arguments into a dictionary of gradient information that is understood by the renderer.
[ "Converts", "a", "number", "of", "arguments", "into", "a", "dictionary", "of", "gradient", "information", "that", "is", "understood", "by", "the", "renderer", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/img.js#L124-L214
train
nodebox/g.js
src/libraries/img/img.js
function (canvas) { this.width = canvas.width; this.height = canvas.height; var ctx = canvas.getContext('2d'); this._data = ctx.getImageData(0, 0, this.width, this.height); this.array = this._data.data; }
javascript
function (canvas) { this.width = canvas.width; this.height = canvas.height; var ctx = canvas.getContext('2d'); this._data = ctx.getImageData(0, 0, this.width, this.height); this.array = this._data.data; }
[ "function", "(", "canvas", ")", "{", "this", ".", "width", "=", "canvas", ".", "width", ";", "this", ".", "height", "=", "canvas", ".", "height", ";", "var", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "this", ".", "_data", "=", "ctx", ".", "getImageData", "(", "0", ",", "0", ",", "this", ".", "width", ",", "this", ".", "height", ")", ";", "this", ".", "array", "=", "this", ".", "_data", ".", "data", ";", "}" ]
IMAGE PIXELS.
[ "IMAGE", "PIXELS", "." ]
4ef0c579a607a38337fbf9f36f176b35eb7092d2
https://github.com/nodebox/g.js/blob/4ef0c579a607a38337fbf9f36f176b35eb7092d2/src/libraries/img/img.js#L457-L463
train
arifsetiawan/flatten
lib/flatten.js
walkModules
function walkModules(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { file = dir + path.sep + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { if (file.indexOf('node_modules') > -1) { walkModules(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { if (!--pending) done(null, results); } } else { if (file.slice(-12) === 'package.json') { var parts = file.split(path.sep); if (parts[parts.length-3] === 'node_modules') { results.push(file); } } if (!--pending) done(null, results); } }); }); }); }
javascript
function walkModules(dir, done) { var results = []; fs.readdir(dir, function(err, list) { if (err) return done(err); var pending = list.length; if (!pending) return done(null, results); list.forEach(function(file) { file = dir + path.sep + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { if (file.indexOf('node_modules') > -1) { walkModules(file, function(err, res) { results = results.concat(res); if (!--pending) done(null, results); }); } else { if (!--pending) done(null, results); } } else { if (file.slice(-12) === 'package.json') { var parts = file.split(path.sep); if (parts[parts.length-3] === 'node_modules') { results.push(file); } } if (!--pending) done(null, results); } }); }); }); }
[ "function", "walkModules", "(", "dir", ",", "done", ")", "{", "var", "results", "=", "[", "]", ";", "fs", ".", "readdir", "(", "dir", ",", "function", "(", "err", ",", "list", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "var", "pending", "=", "list", ".", "length", ";", "if", "(", "!", "pending", ")", "return", "done", "(", "null", ",", "results", ")", ";", "list", ".", "forEach", "(", "function", "(", "file", ")", "{", "file", "=", "dir", "+", "path", ".", "sep", "+", "file", ";", "fs", ".", "stat", "(", "file", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "stat", "&&", "stat", ".", "isDirectory", "(", ")", ")", "{", "if", "(", "file", ".", "indexOf", "(", "'node_modules'", ")", ">", "-", "1", ")", "{", "walkModules", "(", "file", ",", "function", "(", "err", ",", "res", ")", "{", "results", "=", "results", ".", "concat", "(", "res", ")", ";", "if", "(", "!", "--", "pending", ")", "done", "(", "null", ",", "results", ")", ";", "}", ")", ";", "}", "else", "{", "if", "(", "!", "--", "pending", ")", "done", "(", "null", ",", "results", ")", ";", "}", "}", "else", "{", "if", "(", "file", ".", "slice", "(", "-", "12", ")", "===", "'package.json'", ")", "{", "var", "parts", "=", "file", ".", "split", "(", "path", ".", "sep", ")", ";", "if", "(", "parts", "[", "parts", ".", "length", "-", "3", "]", "===", "'node_modules'", ")", "{", "results", ".", "push", "(", "file", ")", ";", "}", "}", "if", "(", "!", "--", "pending", ")", "done", "(", "null", ",", "results", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Walk module folder Find folder node_modules, scan its folders, find package.json and store it, recursively @param {String} dir Directory name @param {Function} done this will contains array of package.json file
[ "Walk", "module", "folder" ]
d5dbbf3753270df5fc0890a794bf0f7b24e1d00b
https://github.com/arifsetiawan/flatten/blob/d5dbbf3753270df5fc0890a794bf0f7b24e1d00b/lib/flatten.js#L188-L227
train
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
readRows
function readRows(ws, rows, opts) { let contents = {}; if (typeof rows === 'string') { rows = rows.split(','); } opts = (opts === undefined) ? {} : opts; // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < rows.length; ++i) { // console.log('rows[%d]=%s', i, rows[i]); let dRow = xlsx.utils.decode_row(rows[i]); for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let encCell = xlsx.utils.encode_cell({c: C, r: dRow}); contents[encCell] = ws[encCell] || {}; } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
javascript
function readRows(ws, rows, opts) { let contents = {}; if (typeof rows === 'string') { rows = rows.split(','); } opts = (opts === undefined) ? {} : opts; // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < rows.length; ++i) { // console.log('rows[%d]=%s', i, rows[i]); let dRow = xlsx.utils.decode_row(rows[i]); for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let encCell = xlsx.utils.encode_cell({c: C, r: dRow}); contents[encCell] = ws[encCell] || {}; } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
[ "function", "readRows", "(", "ws", ",", "rows", ",", "opts", ")", "{", "let", "contents", "=", "{", "}", ";", "if", "(", "typeof", "rows", "===", "'string'", ")", "{", "rows", "=", "rows", ".", "split", "(", "','", ")", ";", "}", "opts", "=", "(", "opts", "===", "undefined", ")", "?", "{", "}", ":", "opts", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "ws", "[", "'!ref'", "]", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "++", "i", ")", "{", "let", "dRow", "=", "xlsx", ".", "utils", ".", "decode_row", "(", "rows", "[", "i", "]", ")", ";", "for", "(", "let", "C", "=", "dRange", ".", "s", ".", "c", ";", "C", "<=", "dRange", ".", "e", ".", "c", ";", "++", "C", ")", "{", "let", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "dRow", "}", ")", ";", "contents", "[", "encCell", "]", "=", "ws", "[", "encCell", "]", "||", "{", "}", ";", "}", "}", "contents", "[", "'!ref'", "]", "=", "ws", "[", "'!ref'", "]", ";", "if", "(", "opts", ".", "asis", ")", "{", "return", "contents", ";", "}", "Object", ".", "assign", "(", "opts", ",", "{", "header", ":", "1", ",", "raw", ":", "true", ",", "blankrows", ":", "true", ",", "}", ")", ";", "opts", ".", "header", "=", "opts", ".", "useLabel", "?", "'A'", ":", "opts", ".", "header", ";", "let", "contentsJson", "=", "xlsx", ".", "utils", ".", "sheet_to_json", "(", "contents", ",", "opts", ")", ";", "if", "(", "opts", ".", "removeEmpty", ")", "{", "contentsJson", "=", "contentsJson", ".", "filter", "(", "(", "row", ")", "=>", "{", "return", "check", ".", "object", "(", "row", ")", "?", "check", ".", "nonEmptyObject", "(", "row", ")", ":", "check", ".", "nonEmptyArray", "(", "row", ")", ";", "}", ")", ";", "}", "return", "contentsJson", ";", "}" ]
reads a specified rows from an opened workbook @function @param {object} ws - worksheet. @param {object} rows - rows to be fetched. @param {{asis: bool, useLabel: boolean, header: string, removeEmpty:boolean}} opts - options for processing the read request @return {object} contentsJson - returns the fetched content as a JSON
[ "reads", "a", "specified", "rows", "from", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L88-L131
train
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
readCols
function readCols(ws, cols, opts) { // console.log('Reading cols ' + cols.length); // console.log(cols); let contents = {}; if (typeof cols === 'string') { cols = cols.split(','); } opts = (opts === undefined) ? {} : opts; let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < cols.length; ++i) { // console.log('Reading col:' + cols[i]); let dCol = xlsx.utils.decode_col(cols[i]); for (let R = dRange.s.r; R <= dRange.e.r; ++R) { // console.log('Reading cell:' + cols[i] + ', ' + R); let encCell = xlsx.utils.encode_cell({c: dCol, r: R}); contents[encCell] = ws[encCell] || {}; // console.log('Done cell:' + cols[i] + ', ' + R + ', ' + JSON.stringify(contents[encCell])); } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((col) => { // console.log(typeof col); return check.object(col) ? check.nonEmptyObject(col) : check.nonEmptyArray(col); }); } return contentsJson; }
javascript
function readCols(ws, cols, opts) { // console.log('Reading cols ' + cols.length); // console.log(cols); let contents = {}; if (typeof cols === 'string') { cols = cols.split(','); } opts = (opts === undefined) ? {} : opts; let dRange = xlsx.utils.decode_range(ws['!ref']); for (let i = 0; i < cols.length; ++i) { // console.log('Reading col:' + cols[i]); let dCol = xlsx.utils.decode_col(cols[i]); for (let R = dRange.s.r; R <= dRange.e.r; ++R) { // console.log('Reading cell:' + cols[i] + ', ' + R); let encCell = xlsx.utils.encode_cell({c: dCol, r: R}); contents[encCell] = ws[encCell] || {}; // console.log('Done cell:' + cols[i] + ', ' + R + ', ' + JSON.stringify(contents[encCell])); } } contents['!ref'] = ws['!ref']; if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((col) => { // console.log(typeof col); return check.object(col) ? check.nonEmptyObject(col) : check.nonEmptyArray(col); }); } return contentsJson; }
[ "function", "readCols", "(", "ws", ",", "cols", ",", "opts", ")", "{", "let", "contents", "=", "{", "}", ";", "if", "(", "typeof", "cols", "===", "'string'", ")", "{", "cols", "=", "cols", ".", "split", "(", "','", ")", ";", "}", "opts", "=", "(", "opts", "===", "undefined", ")", "?", "{", "}", ":", "opts", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "ws", "[", "'!ref'", "]", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "cols", ".", "length", ";", "++", "i", ")", "{", "let", "dCol", "=", "xlsx", ".", "utils", ".", "decode_col", "(", "cols", "[", "i", "]", ")", ";", "for", "(", "let", "R", "=", "dRange", ".", "s", ".", "r", ";", "R", "<=", "dRange", ".", "e", ".", "r", ";", "++", "R", ")", "{", "let", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "dCol", ",", "r", ":", "R", "}", ")", ";", "contents", "[", "encCell", "]", "=", "ws", "[", "encCell", "]", "||", "{", "}", ";", "}", "}", "contents", "[", "'!ref'", "]", "=", "ws", "[", "'!ref'", "]", ";", "if", "(", "opts", ".", "asis", ")", "{", "return", "contents", ";", "}", "Object", ".", "assign", "(", "opts", ",", "{", "header", ":", "1", ",", "raw", ":", "true", ",", "blankrows", ":", "true", ",", "}", ")", ";", "opts", ".", "header", "=", "opts", ".", "useLabel", "?", "'A'", ":", "opts", ".", "header", ";", "let", "contentsJson", "=", "xlsx", ".", "utils", ".", "sheet_to_json", "(", "contents", ",", "opts", ")", ";", "if", "(", "opts", ".", "removeEmpty", ")", "{", "contentsJson", "=", "contentsJson", ".", "filter", "(", "(", "col", ")", "=>", "{", "return", "check", ".", "object", "(", "col", ")", "?", "check", ".", "nonEmptyObject", "(", "col", ")", ":", "check", ".", "nonEmptyArray", "(", "col", ")", ";", "}", ")", ";", "}", "return", "contentsJson", ";", "}" ]
reads a specified cols from an opened workbook @function @param {object} ws - worksheet. @param {object} cols - cols to be fetched. @param {{asis: bool, useLabel: boolean, header: string, removeEmpty:boolean}} opts - options for processing the read request @return {object} contentsJson - returns the fetched content as a JSON
[ "reads", "a", "specified", "cols", "from", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L144-L188
train
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
readRegion
function readRegion(ws, range, opts) { let contents = {}; opts = (opts === undefined) ? {} : opts; // console.log('Xref:%s', ws['!ref']); let dORange = xlsx.utils.decode_range(ws['!ref']); let dRange = xlsx.utils.decode_range(range); // Support for cols only ranges like !A:A,!A:C dRange.s.r = (isNaN(dRange.s.r)) ? dORange.s.r : dRange.s.r; dRange.e.r = (isNaN(dRange.e.r)) ? dORange.e.r : dRange.e.r; // Single for row only ranges like !1:1, !1:3 dRange.s.c = (dRange.s.c === -1) ? dORange.s.c : dRange.s.c; dRange.e.c = (dRange.e.c === -1) ? dORange.e.c : dRange.e.c; for (let R = dRange.s.r; R <= dRange.e.r; ++R) { for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let cellref = xlsx.utils.encode_cell({c: C, r: R}); contents[cellref] = ws[cellref] || {}; } } // console.log(JSON.stringify(dRange)); contents['!ref'] = xlsx.utils.encode_range(dRange); if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
javascript
function readRegion(ws, range, opts) { let contents = {}; opts = (opts === undefined) ? {} : opts; // console.log('Xref:%s', ws['!ref']); let dORange = xlsx.utils.decode_range(ws['!ref']); let dRange = xlsx.utils.decode_range(range); // Support for cols only ranges like !A:A,!A:C dRange.s.r = (isNaN(dRange.s.r)) ? dORange.s.r : dRange.s.r; dRange.e.r = (isNaN(dRange.e.r)) ? dORange.e.r : dRange.e.r; // Single for row only ranges like !1:1, !1:3 dRange.s.c = (dRange.s.c === -1) ? dORange.s.c : dRange.s.c; dRange.e.c = (dRange.e.c === -1) ? dORange.e.c : dRange.e.c; for (let R = dRange.s.r; R <= dRange.e.r; ++R) { for (let C = dRange.s.c; C <= dRange.e.c; ++C) { let cellref = xlsx.utils.encode_cell({c: C, r: R}); contents[cellref] = ws[cellref] || {}; } } // console.log(JSON.stringify(dRange)); contents['!ref'] = xlsx.utils.encode_range(dRange); if (opts.asis) { return contents; } Object.assign(opts, { header: 1, raw: true, blankrows: true, }); opts.header = opts.useLabel ? 'A' : opts.header; let contentsJson = xlsx.utils.sheet_to_json(contents, opts); if (opts.removeEmpty) { contentsJson = contentsJson.filter((row) => { // console.log(typeof row); return check.object(row) ? check.nonEmptyObject(row) : check.nonEmptyArray(row); }); } return contentsJson; }
[ "function", "readRegion", "(", "ws", ",", "range", ",", "opts", ")", "{", "let", "contents", "=", "{", "}", ";", "opts", "=", "(", "opts", "===", "undefined", ")", "?", "{", "}", ":", "opts", ";", "let", "dORange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "ws", "[", "'!ref'", "]", ")", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "dRange", ".", "s", ".", "r", "=", "(", "isNaN", "(", "dRange", ".", "s", ".", "r", ")", ")", "?", "dORange", ".", "s", ".", "r", ":", "dRange", ".", "s", ".", "r", ";", "dRange", ".", "e", ".", "r", "=", "(", "isNaN", "(", "dRange", ".", "e", ".", "r", ")", ")", "?", "dORange", ".", "e", ".", "r", ":", "dRange", ".", "e", ".", "r", ";", "dRange", ".", "s", ".", "c", "=", "(", "dRange", ".", "s", ".", "c", "===", "-", "1", ")", "?", "dORange", ".", "s", ".", "c", ":", "dRange", ".", "s", ".", "c", ";", "dRange", ".", "e", ".", "c", "=", "(", "dRange", ".", "e", ".", "c", "===", "-", "1", ")", "?", "dORange", ".", "e", ".", "c", ":", "dRange", ".", "e", ".", "c", ";", "for", "(", "let", "R", "=", "dRange", ".", "s", ".", "r", ";", "R", "<=", "dRange", ".", "e", ".", "r", ";", "++", "R", ")", "{", "for", "(", "let", "C", "=", "dRange", ".", "s", ".", "c", ";", "C", "<=", "dRange", ".", "e", ".", "c", ";", "++", "C", ")", "{", "let", "cellref", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "R", "}", ")", ";", "contents", "[", "cellref", "]", "=", "ws", "[", "cellref", "]", "||", "{", "}", ";", "}", "}", "contents", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "dRange", ")", ";", "if", "(", "opts", ".", "asis", ")", "{", "return", "contents", ";", "}", "Object", ".", "assign", "(", "opts", ",", "{", "header", ":", "1", ",", "raw", ":", "true", ",", "blankrows", ":", "true", ",", "}", ")", ";", "opts", ".", "header", "=", "opts", ".", "useLabel", "?", "'A'", ":", "opts", ".", "header", ";", "let", "contentsJson", "=", "xlsx", ".", "utils", ".", "sheet_to_json", "(", "contents", ",", "opts", ")", ";", "if", "(", "opts", ".", "removeEmpty", ")", "{", "contentsJson", "=", "contentsJson", ".", "filter", "(", "(", "row", ")", "=>", "{", "return", "check", ".", "object", "(", "row", ")", "?", "check", ".", "nonEmptyObject", "(", "row", ")", ":", "check", ".", "nonEmptyArray", "(", "row", ")", ";", "}", ")", ";", "}", "return", "contentsJson", ";", "}" ]
reads a specified region from an opened workbook @function @param {object} ws - worksheet. @param {object} range - rows to be fetched. @param {{asis: bool, useLabel: boolean, header: string, removeEmpty:boolean}} opts - options for processing the read request @return {object} contentsJson - returns the fetched content as a JSON
[ "reads", "a", "specified", "region", "from", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L201-L247
train
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
writeRegion
function writeRegion(ws, urange, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let dUrange = xlsx.utils.decode_range(urange); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; for (let R = dUrange.s.r, i = 0; R <= dUrange.e.r; ++R, ++i) { let cellVal = contents[i]; if (R > newRef.e.r) { newRef.e.r = R; } for (let C = dUrange.s.c, j = 0; C <= dUrange.e.c; ++C, ++j) { encCell = xlsx.utils.encode_cell({c: C, r: R}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[j]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
javascript
function writeRegion(ws, urange, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let dUrange = xlsx.utils.decode_range(urange); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; for (let R = dUrange.s.r, i = 0; R <= dUrange.e.r; ++R, ++i) { let cellVal = contents[i]; if (R > newRef.e.r) { newRef.e.r = R; } for (let C = dUrange.s.c, j = 0; C <= dUrange.e.c; ++C, ++j) { encCell = xlsx.utils.encode_cell({c: C, r: R}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[j]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
[ "function", "writeRegion", "(", "ws", ",", "urange", ",", "contents", ")", "{", "let", "range", "=", "ws", "[", "'!ref'", "]", ";", "range", "=", "check", ".", "undefined", "(", "range", ")", "?", "'A1:A1'", ":", "range", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "let", "dUrange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "urange", ")", ";", "let", "newRef", "=", "{", "s", ":", "{", "c", ":", "0", ",", "r", ":", "0", "}", ",", "e", ":", "{", "c", ":", "dRange", ".", "e", ".", "c", ",", "r", ":", "dRange", ".", "e", ".", "r", "}", "}", ";", "let", "encCell", ";", "for", "(", "let", "R", "=", "dUrange", ".", "s", ".", "r", ",", "i", "=", "0", ";", "R", "<=", "dUrange", ".", "e", ".", "r", ";", "++", "R", ",", "++", "i", ")", "{", "let", "cellVal", "=", "contents", "[", "i", "]", ";", "if", "(", "R", ">", "newRef", ".", "e", ".", "r", ")", "{", "newRef", ".", "e", ".", "r", "=", "R", ";", "}", "for", "(", "let", "C", "=", "dUrange", ".", "s", ".", "c", ",", "j", "=", "0", ";", "C", "<=", "dUrange", ".", "e", ".", "c", ";", "++", "C", ",", "++", "j", ")", "{", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "R", "}", ")", ";", "if", "(", "C", ">", "newRef", ".", "e", ".", "c", ")", "{", "newRef", ".", "e", ".", "c", "=", "C", ";", "}", "ws", "[", "encCell", "]", "=", "updateCellData", "(", "ws", "[", "encCell", "]", ",", "cellVal", "[", "j", "]", ")", ";", "}", "}", "ws", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "newRef", ")", ";", "return", "ws", ";", "}" ]
writes a specified region to an opened workbook @function @param {object} ws - worksheet. @param {object} urange - range where contents are written @param {boolean} contents - contents that are to written to specified range @return {object} ws - returns the modified worksheet
[ "writes", "a", "specified", "region", "to", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L257-L282
train
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
writeCols
function writeCols(ws, cols, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof cols === 'string') { cols = cols.split(','); } for (let i = 0; i < cols.length; ++i) { let dCol = xlsx.utils.decode_col(cols[i]); let cellVal = contents[i]; if (dCol > newRef.e.c) { newRef.e.c = dCol; } for (let R = dRange.s.r; R < cellVal.length; ++R) { encCell = xlsx.utils.encode_cell({c: dCol, r: R}); if (R > newRef.e.r) { newRef.e.r = R; } ws[encCell] = updateCellData(ws[encCell], cellVal[R]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
javascript
function writeCols(ws, cols, contents) { let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof cols === 'string') { cols = cols.split(','); } for (let i = 0; i < cols.length; ++i) { let dCol = xlsx.utils.decode_col(cols[i]); let cellVal = contents[i]; if (dCol > newRef.e.c) { newRef.e.c = dCol; } for (let R = dRange.s.r; R < cellVal.length; ++R) { encCell = xlsx.utils.encode_cell({c: dCol, r: R}); if (R > newRef.e.r) { newRef.e.r = R; } ws[encCell] = updateCellData(ws[encCell], cellVal[R]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
[ "function", "writeCols", "(", "ws", ",", "cols", ",", "contents", ")", "{", "let", "range", "=", "ws", "[", "'!ref'", "]", ";", "range", "=", "check", ".", "undefined", "(", "range", ")", "?", "'A1:A1'", ":", "range", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "let", "newRef", "=", "{", "s", ":", "{", "c", ":", "0", ",", "r", ":", "0", "}", ",", "e", ":", "{", "c", ":", "dRange", ".", "e", ".", "c", ",", "r", ":", "dRange", ".", "e", ".", "r", "}", "}", ";", "let", "encCell", ";", "if", "(", "typeof", "cols", "===", "'string'", ")", "{", "cols", "=", "cols", ".", "split", "(", "','", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "cols", ".", "length", ";", "++", "i", ")", "{", "let", "dCol", "=", "xlsx", ".", "utils", ".", "decode_col", "(", "cols", "[", "i", "]", ")", ";", "let", "cellVal", "=", "contents", "[", "i", "]", ";", "if", "(", "dCol", ">", "newRef", ".", "e", ".", "c", ")", "{", "newRef", ".", "e", ".", "c", "=", "dCol", ";", "}", "for", "(", "let", "R", "=", "dRange", ".", "s", ".", "r", ";", "R", "<", "cellVal", ".", "length", ";", "++", "R", ")", "{", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "dCol", ",", "r", ":", "R", "}", ")", ";", "if", "(", "R", ">", "newRef", ".", "e", ".", "r", ")", "{", "newRef", ".", "e", ".", "r", "=", "R", ";", "}", "ws", "[", "encCell", "]", "=", "updateCellData", "(", "ws", "[", "encCell", "]", ",", "cellVal", "[", "R", "]", ")", ";", "}", "}", "ws", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "newRef", ")", ";", "return", "ws", ";", "}" ]
writes specified cols to an opened workbook @function @param {object} ws - worksheet. @param {object} cols - cols where contents are written @param {boolean} contents - contents that are to written to specified cols @return {object} ws - returns the modified worksheet
[ "writes", "specified", "cols", "to", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L292-L320
train
telligro/opal-nodes
packages/opal-node-msexcel/msexcel.js
writeRows
function writeRows(ws, rows, contents) { // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof rows === 'string') { rows = rows.split(','); } for (let i = 0; i < rows.length; ++i) { let dRow = xlsx.utils.decode_row(rows[i]); let cellVal = contents[i]; // console.log('contents[%d]=%s', i, cellVal); if (dRow > newRef.e.r) { newRef.e.r = dRow; } for (let C = dRange.s.c; C < cellVal.length; ++C) { encCell = xlsx.utils.encode_cell({c: C, r: dRow}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[C]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
javascript
function writeRows(ws, rows, contents) { // console.log('Typeof Rows %s', typeof rows); // console.log('Typeof Rows %s', rows); // console.log('Length Rows %d', rows.length); let range = ws['!ref']; range = check.undefined(range) ? 'A1:A1' : range; let dRange = xlsx.utils.decode_range(range); let newRef = {s: {c: 0, r: 0}, e: {c: dRange.e.c, r: dRange.e.r}}; let encCell; if (typeof rows === 'string') { rows = rows.split(','); } for (let i = 0; i < rows.length; ++i) { let dRow = xlsx.utils.decode_row(rows[i]); let cellVal = contents[i]; // console.log('contents[%d]=%s', i, cellVal); if (dRow > newRef.e.r) { newRef.e.r = dRow; } for (let C = dRange.s.c; C < cellVal.length; ++C) { encCell = xlsx.utils.encode_cell({c: C, r: dRow}); if (C > newRef.e.c) { newRef.e.c = C; } ws[encCell] = updateCellData(ws[encCell], cellVal[C]); } } ws['!ref'] = xlsx.utils.encode_range(newRef); return ws; }
[ "function", "writeRows", "(", "ws", ",", "rows", ",", "contents", ")", "{", "let", "range", "=", "ws", "[", "'!ref'", "]", ";", "range", "=", "check", ".", "undefined", "(", "range", ")", "?", "'A1:A1'", ":", "range", ";", "let", "dRange", "=", "xlsx", ".", "utils", ".", "decode_range", "(", "range", ")", ";", "let", "newRef", "=", "{", "s", ":", "{", "c", ":", "0", ",", "r", ":", "0", "}", ",", "e", ":", "{", "c", ":", "dRange", ".", "e", ".", "c", ",", "r", ":", "dRange", ".", "e", ".", "r", "}", "}", ";", "let", "encCell", ";", "if", "(", "typeof", "rows", "===", "'string'", ")", "{", "rows", "=", "rows", ".", "split", "(", "','", ")", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "++", "i", ")", "{", "let", "dRow", "=", "xlsx", ".", "utils", ".", "decode_row", "(", "rows", "[", "i", "]", ")", ";", "let", "cellVal", "=", "contents", "[", "i", "]", ";", "if", "(", "dRow", ">", "newRef", ".", "e", ".", "r", ")", "{", "newRef", ".", "e", ".", "r", "=", "dRow", ";", "}", "for", "(", "let", "C", "=", "dRange", ".", "s", ".", "c", ";", "C", "<", "cellVal", ".", "length", ";", "++", "C", ")", "{", "encCell", "=", "xlsx", ".", "utils", ".", "encode_cell", "(", "{", "c", ":", "C", ",", "r", ":", "dRow", "}", ")", ";", "if", "(", "C", ">", "newRef", ".", "e", ".", "c", ")", "{", "newRef", ".", "e", ".", "c", "=", "C", ";", "}", "ws", "[", "encCell", "]", "=", "updateCellData", "(", "ws", "[", "encCell", "]", ",", "cellVal", "[", "C", "]", ")", ";", "}", "}", "ws", "[", "'!ref'", "]", "=", "xlsx", ".", "utils", ".", "encode_range", "(", "newRef", ")", ";", "return", "ws", ";", "}" ]
writes specified rows to an opened workbook @function @param {object} ws - worksheet. @param {object} rows - rows where contents are written @param {boolean} contents - contents that are to written to specified rows @return {object} ws - returns the modified worksheet
[ "writes", "specified", "rows", "to", "an", "opened", "workbook" ]
028e02b8ef9709ba548e153db446931c6d7a385d
https://github.com/telligro/opal-nodes/blob/028e02b8ef9709ba548e153db446931c6d7a385d/packages/opal-node-msexcel/msexcel.js#L330-L360
train
angular/gulp-clang-format
index.js
format
function format(opt_clangOptions, opt_clangFormat) { var actualClangFormat = opt_clangFormat || clangFormat; var optsStr = getOptsString(opt_clangOptions); function formatFilter(file, enc, done) { function onClangFormatFinished() { file.contents = Buffer.from(formatted, 'utf-8'); done(null, file); } var formatted = ''; actualClangFormat(file, enc, optsStr, onClangFormatFinished) .on('data', function(b) { formatted += b.toString(); }) .on('error', this.emit.bind(this, 'error')); } return through2.obj(formatFilter); }
javascript
function format(opt_clangOptions, opt_clangFormat) { var actualClangFormat = opt_clangFormat || clangFormat; var optsStr = getOptsString(opt_clangOptions); function formatFilter(file, enc, done) { function onClangFormatFinished() { file.contents = Buffer.from(formatted, 'utf-8'); done(null, file); } var formatted = ''; actualClangFormat(file, enc, optsStr, onClangFormatFinished) .on('data', function(b) { formatted += b.toString(); }) .on('error', this.emit.bind(this, 'error')); } return through2.obj(formatFilter); }
[ "function", "format", "(", "opt_clangOptions", ",", "opt_clangFormat", ")", "{", "var", "actualClangFormat", "=", "opt_clangFormat", "||", "clangFormat", ";", "var", "optsStr", "=", "getOptsString", "(", "opt_clangOptions", ")", ";", "function", "formatFilter", "(", "file", ",", "enc", ",", "done", ")", "{", "function", "onClangFormatFinished", "(", ")", "{", "file", ".", "contents", "=", "Buffer", ".", "from", "(", "formatted", ",", "'utf-8'", ")", ";", "done", "(", "null", ",", "file", ")", ";", "}", "var", "formatted", "=", "''", ";", "actualClangFormat", "(", "file", ",", "enc", ",", "optsStr", ",", "onClangFormatFinished", ")", ".", "on", "(", "'data'", ",", "function", "(", "b", ")", "{", "formatted", "+=", "b", ".", "toString", "(", ")", ";", "}", ")", ".", "on", "(", "'error'", ",", "this", ".", "emit", ".", "bind", "(", "this", ",", "'error'", ")", ")", ";", "}", "return", "through2", ".", "obj", "(", "formatFilter", ")", ";", "}" ]
Formats files using clang-format. @param {(string|Object)=} opt_clangOptions the string 'file' to search for a '.clang-format' file, or an object literal containing clang-format options http://clang.llvm.org/docs/ClangFormatStyleOptions.html#configurable-format-style-options @param {Object=} opt_clangFormat A clang-format module to optionally use.
[ "Formats", "files", "using", "clang", "-", "format", "." ]
585c281cdd7788e6dee8082d6c9e5f53830baa4a
https://github.com/angular/gulp-clang-format/blob/585c281cdd7788e6dee8082d6c9e5f53830baa4a/index.js#L19-L34
train