repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
mojaie/kiwiii
src/component/formRangeBox.js
rangeBox
function rangeBox(selection, label) { selection .classed('form-row', true) .classed('form-group', true) .classed('align-items-center', true) .append('div') .classed('col-form-label', true) .classed('col-form-label-sm', true) .text(label); const minBox = selection.append('div'); minBox.append('label').text('min'); minBox.append('input').classed('min', true); const maxBox = selection.append('div'); maxBox.append('label').text('max'); maxBox.append('input').classed('max', true); selection.selectAll('div') .classed('form-group', true) .classed('col-4', true) .classed('mb-0', true); selection.selectAll('label') .classed('col-form-label', true) .classed('col-form-label-sm', true) .classed('py-0', true); selection.selectAll('input') .classed('form-control', true) .classed('form-control-sm', true) .attr('type', 'number'); selection.append('div') .classed('col-4', true); selection.append('div') .call(badge.invalidFeedback) .classed('col-8', true); }
javascript
function rangeBox(selection, label) { selection .classed('form-row', true) .classed('form-group', true) .classed('align-items-center', true) .append('div') .classed('col-form-label', true) .classed('col-form-label-sm', true) .text(label); const minBox = selection.append('div'); minBox.append('label').text('min'); minBox.append('input').classed('min', true); const maxBox = selection.append('div'); maxBox.append('label').text('max'); maxBox.append('input').classed('max', true); selection.selectAll('div') .classed('form-group', true) .classed('col-4', true) .classed('mb-0', true); selection.selectAll('label') .classed('col-form-label', true) .classed('col-form-label-sm', true) .classed('py-0', true); selection.selectAll('input') .classed('form-control', true) .classed('form-control-sm', true) .attr('type', 'number'); selection.append('div') .classed('col-4', true); selection.append('div') .call(badge.invalidFeedback) .classed('col-8', true); }
[ "function", "rangeBox", "(", "selection", ",", "label", ")", "{", "selection", ".", "classed", "(", "'form-row'", ",", "true", ")", ".", "classed", "(", "'form-group'", ",", "true", ")", ".", "classed", "(", "'align-items-center'", ",", "true", ")", ".", "append", "(", "'div'", ")", ".", "classed", "(", "'col-form-label'", ",", "true", ")", ".", "classed", "(", "'col-form-label-sm'", ",", "true", ")", ".", "text", "(", "label", ")", ";", "const", "minBox", "=", "selection", ".", "append", "(", "'div'", ")", ";", "minBox", ".", "append", "(", "'label'", ")", ".", "text", "(", "'min'", ")", ";", "minBox", ".", "append", "(", "'input'", ")", ".", "classed", "(", "'min'", ",", "true", ")", ";", "const", "maxBox", "=", "selection", ".", "append", "(", "'div'", ")", ";", "maxBox", ".", "append", "(", "'label'", ")", ".", "text", "(", "'max'", ")", ";", "maxBox", ".", "append", "(", "'input'", ")", ".", "classed", "(", "'max'", ",", "true", ")", ";", "selection", ".", "selectAll", "(", "'div'", ")", ".", "classed", "(", "'form-group'", ",", "true", ")", ".", "classed", "(", "'col-4'", ",", "true", ")", ".", "classed", "(", "'mb-0'", ",", "true", ")", ";", "selection", ".", "selectAll", "(", "'label'", ")", ".", "classed", "(", "'col-form-label'", ",", "true", ")", ".", "classed", "(", "'col-form-label-sm'", ",", "true", ")", ".", "classed", "(", "'py-0'", ",", "true", ")", ";", "selection", ".", "selectAll", "(", "'input'", ")", ".", "classed", "(", "'form-control'", ",", "true", ")", ".", "classed", "(", "'form-control-sm'", ",", "true", ")", ".", "attr", "(", "'type'", ",", "'number'", ")", ";", "selection", ".", "append", "(", "'div'", ")", ".", "classed", "(", "'col-4'", ",", "true", ")", ";", "selection", ".", "append", "(", "'div'", ")", ".", "call", "(", "badge", ".", "invalidFeedback", ")", ".", "classed", "(", "'col-8'", ",", "true", ")", ";", "}" ]
Render range box components @param {d3.selection} selection - selection of box container (div element)
[ "Render", "range", "box", "components" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/component/formRangeBox.js#L13-L51
train
EricCrosson/coinmarketcap-api
index.js
getMarketCaps
function getMarketCaps() { return new Promise(function (resolve, reject) { scraper .get(urlMarketCap) .then(function(tableData) { const coinmarketcapTable = tableData[0]; resolve(getAllMarketCaps(coinmarketcapTable)); }); }); }
javascript
function getMarketCaps() { return new Promise(function (resolve, reject) { scraper .get(urlMarketCap) .then(function(tableData) { const coinmarketcapTable = tableData[0]; resolve(getAllMarketCaps(coinmarketcapTable)); }); }); }
[ "function", "getMarketCaps", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "scraper", ".", "get", "(", "urlMarketCap", ")", ".", "then", "(", "function", "(", "tableData", ")", "{", "const", "coinmarketcapTable", "=", "tableData", "[", "0", "]", ";", "resolve", "(", "getAllMarketCaps", "(", "coinmarketcapTable", ")", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Return array of market capitalizations, in order of size.
[ "Return", "array", "of", "market", "capitalizations", "in", "order", "of", "size", "." ]
ec6cf161a6e9219a85f049144b2b0d6c5462f3a0
https://github.com/EricCrosson/coinmarketcap-api/blob/ec6cf161a6e9219a85f049144b2b0d6c5462f3a0/index.js#L121-L132
train
etpinard/karma-benchmark-json-reporter
example/03-output-info/karma.conf.js
formatResults
function formatResults (results) { return results.map(function (r) { return { fullName: r.fullName, hz: r.hz, hzDeviation: r.hzDeviation } }) }
javascript
function formatResults (results) { return results.map(function (r) { return { fullName: r.fullName, hz: r.hz, hzDeviation: r.hzDeviation } }) }
[ "function", "formatResults", "(", "results", ")", "{", "return", "results", ".", "map", "(", "function", "(", "r", ")", "{", "return", "{", "fullName", ":", "r", ".", "fullName", ",", "hz", ":", "r", ".", "hz", ",", "hzDeviation", ":", "r", ".", "hzDeviation", "}", "}", ")", "}" ]
only keep full name and hz statistics
[ "only", "keep", "full", "name", "and", "hz", "statistics" ]
9e89e325dcf53bb7291e5ab2174dd7fd55cc572b
https://github.com/etpinard/karma-benchmark-json-reporter/blob/9e89e325dcf53bb7291e5ab2174dd7fd55cc572b/example/03-output-info/karma.conf.js#L28-L36
train
etpinard/karma-benchmark-json-reporter
example/03-output-info/karma.conf.js
formatOutput
function formatOutput (results) { var date = new Date() var commit try { commit = execSync('git rev-parse HEAD').toString().replace('\n', '') } catch (e) { commit = 'commit hash not found' } return { meta: { title: 'example benchmark', version: pkg.version, commit: commit, date: [ date.toLocaleDateString(), date.toLocaleTimeString(), date.toString().match(/\(([A-Za-z\s].*)\)/)[1] ].join(' ') }, results: results } }
javascript
function formatOutput (results) { var date = new Date() var commit try { commit = execSync('git rev-parse HEAD').toString().replace('\n', '') } catch (e) { commit = 'commit hash not found' } return { meta: { title: 'example benchmark', version: pkg.version, commit: commit, date: [ date.toLocaleDateString(), date.toLocaleTimeString(), date.toString().match(/\(([A-Za-z\s].*)\)/)[1] ].join(' ') }, results: results } }
[ "function", "formatOutput", "(", "results", ")", "{", "var", "date", "=", "new", "Date", "(", ")", "var", "commit", "try", "{", "commit", "=", "execSync", "(", "'git rev-parse HEAD'", ")", ".", "toString", "(", ")", ".", "replace", "(", "'\\n'", ",", "\\n", ")", "}", "''", "catch", "(", "e", ")", "{", "commit", "=", "'commit hash not found'", "}", "}" ]
add date, commit package version info to output JSON
[ "add", "date", "commit", "package", "version", "info", "to", "output", "JSON" ]
9e89e325dcf53bb7291e5ab2174dd7fd55cc572b
https://github.com/etpinard/karma-benchmark-json-reporter/blob/9e89e325dcf53bb7291e5ab2174dd7fd55cc572b/example/03-output-info/karma.conf.js#L39-L62
train
cgmartin/spa-express-static-server
src/middleware/request-logger.js
getConversationId
function getConversationId(req, res, options) { var cookieName = options.conversationIdCookieName; var headerName = options.conversationIdHeader; var conversationId = req.headers[headerName] || req.cookies && req.cookies[cookieName]; if (!conversationId) { conversationId = uuid.v1(); } req.conversationId = conversationId; res.cookie(cookieName, conversationId, { path: '/' }); return conversationId; }
javascript
function getConversationId(req, res, options) { var cookieName = options.conversationIdCookieName; var headerName = options.conversationIdHeader; var conversationId = req.headers[headerName] || req.cookies && req.cookies[cookieName]; if (!conversationId) { conversationId = uuid.v1(); } req.conversationId = conversationId; res.cookie(cookieName, conversationId, { path: '/' }); return conversationId; }
[ "function", "getConversationId", "(", "req", ",", "res", ",", "options", ")", "{", "var", "cookieName", "=", "options", ".", "conversationIdCookieName", ";", "var", "headerName", "=", "options", ".", "conversationIdHeader", ";", "var", "conversationId", "=", "req", ".", "headers", "[", "headerName", "]", "||", "req", ".", "cookies", "&&", "req", ".", "cookies", "[", "cookieName", "]", ";", "if", "(", "!", "conversationId", ")", "{", "conversationId", "=", "uuid", ".", "v1", "(", ")", ";", "}", "req", ".", "conversationId", "=", "conversationId", ";", "res", ".", "cookie", "(", "cookieName", ",", "conversationId", ",", "{", "path", ":", "'/'", "}", ")", ";", "return", "conversationId", ";", "}" ]
Create a "conversation" identifier to track requests per browser session
[ "Create", "a", "conversation", "identifier", "to", "track", "requests", "per", "browser", "session" ]
6f5d2e9cb394dcd634cc7e29f92c586ce5c61163
https://github.com/cgmartin/spa-express-static-server/blob/6f5d2e9cb394dcd634cc7e29f92c586ce5c61163/src/middleware/request-logger.js#L71-L81
train
artdecocode/erotic
build/callback.js
makeCallback
function makeCallback(entryCaller, entryStack, shadow = false) { /** * This callback should be called when an asynchronous error occurred. * @param {(string|Error)} messageOrError A message string or an _Error_ object at the point of actual error. * @returns {Error} An error with the updated stack which includes the callee. */ function cb(messageOrError) { const caller = getCallerFromArguments(arguments) const { stack: errorStack } = new Error() const calleeStackLine = getCalleeStackLine(errorStack) const isError = messageOrError instanceof Error const message = isError ? messageOrError.message : messageOrError const stackHeading = getStackHeading(message) const entryHasCallee = caller !== null && entryCaller === caller const stackMessage = [ stackHeading, ...(entryHasCallee || shadow ? [entryStack] : [ calleeStackLine, entryStack, ]), ].join('\n') const stack = cleanStack(stackMessage) const properties = { message, stack } const e = isError ? messageOrError : new Error() return /** @type {Error} */ (Object.assign(/** @type {!Object} */ (e), properties)) } return cb }
javascript
function makeCallback(entryCaller, entryStack, shadow = false) { /** * This callback should be called when an asynchronous error occurred. * @param {(string|Error)} messageOrError A message string or an _Error_ object at the point of actual error. * @returns {Error} An error with the updated stack which includes the callee. */ function cb(messageOrError) { const caller = getCallerFromArguments(arguments) const { stack: errorStack } = new Error() const calleeStackLine = getCalleeStackLine(errorStack) const isError = messageOrError instanceof Error const message = isError ? messageOrError.message : messageOrError const stackHeading = getStackHeading(message) const entryHasCallee = caller !== null && entryCaller === caller const stackMessage = [ stackHeading, ...(entryHasCallee || shadow ? [entryStack] : [ calleeStackLine, entryStack, ]), ].join('\n') const stack = cleanStack(stackMessage) const properties = { message, stack } const e = isError ? messageOrError : new Error() return /** @type {Error} */ (Object.assign(/** @type {!Object} */ (e), properties)) } return cb }
[ "function", "makeCallback", "(", "entryCaller", ",", "entryStack", ",", "shadow", "=", "false", ")", "{", "function", "cb", "(", "messageOrError", ")", "{", "const", "caller", "=", "getCallerFromArguments", "(", "arguments", ")", "const", "{", "stack", ":", "errorStack", "}", "=", "new", "Error", "(", ")", "const", "calleeStackLine", "=", "getCalleeStackLine", "(", "errorStack", ")", "const", "isError", "=", "messageOrError", "instanceof", "Error", "const", "message", "=", "isError", "?", "messageOrError", ".", "message", ":", "messageOrError", "const", "stackHeading", "=", "getStackHeading", "(", "message", ")", "const", "entryHasCallee", "=", "caller", "!==", "null", "&&", "entryCaller", "===", "caller", "const", "stackMessage", "=", "[", "stackHeading", ",", "...", "(", "entryHasCallee", "||", "shadow", "?", "[", "entryStack", "]", ":", "[", "calleeStackLine", ",", "entryStack", ",", "]", ")", ",", "]", ".", "join", "(", "'\\n'", ")", "\\n", "const", "stack", "=", "cleanStack", "(", "stackMessage", ")", "const", "properties", "=", "{", "message", ",", "stack", "}", "const", "e", "=", "isError", "?", "messageOrError", ":", "new", "Error", "(", ")", "}", "return", "(", "Object", ".", "assign", "(", "(", "e", ")", ",", "properties", ")", ")", "}" ]
Create a callback. @param {!Function} entryCaller The function which was called at entry. @param {string} entryStack The first line of the error stack to be returned @param {boolean} [shadow=false] Print only entry stack.
[ "Create", "a", "callback", "." ]
2d8cb268bd6ddc64a8bb90ac25d388e553866a0a
https://github.com/artdecocode/erotic/blob/2d8cb268bd6ddc64a8bb90ac25d388e553866a0a/build/callback.js#L12-L43
train
nwtjs/nwt
src/anim/js/anim.js
function(duration, easing) { var newStylesheet = localnwt.node.create('<style type="text/css"></style>'); easing = easing || 'ease-in'; duration = duration || 1; var trail = ' ' + duration + 's ' + easing, // Just support all browsers for now cssTransitionProperties = { '-webkit-transition': 'all' + trail, '-moz-transition': ' all' + trail, '-o-ransition': ' all' + trail, 'ms-transition': ' all' + trail, 'transition': ' all' + trail }, newContent = ''; for (i in cssTransitionProperties) { newContent += i + ': ' + cssTransitionProperties[i] + ';'; } newStylesheet.setHtml('.' + this.animClass + '{' + newContent + '}'); localnwt.one('head').append(newStylesheet); setTimeout(function(){ newStylesheet.remove() }, duration*1001) }
javascript
function(duration, easing) { var newStylesheet = localnwt.node.create('<style type="text/css"></style>'); easing = easing || 'ease-in'; duration = duration || 1; var trail = ' ' + duration + 's ' + easing, // Just support all browsers for now cssTransitionProperties = { '-webkit-transition': 'all' + trail, '-moz-transition': ' all' + trail, '-o-ransition': ' all' + trail, 'ms-transition': ' all' + trail, 'transition': ' all' + trail }, newContent = ''; for (i in cssTransitionProperties) { newContent += i + ': ' + cssTransitionProperties[i] + ';'; } newStylesheet.setHtml('.' + this.animClass + '{' + newContent + '}'); localnwt.one('head').append(newStylesheet); setTimeout(function(){ newStylesheet.remove() }, duration*1001) }
[ "function", "(", "duration", ",", "easing", ")", "{", "var", "newStylesheet", "=", "localnwt", ".", "node", ".", "create", "(", "'<style type=\"text/css\"></style>'", ")", ";", "easing", "=", "easing", "||", "'ease-in'", ";", "duration", "=", "duration", "||", "1", ";", "var", "trail", "=", "' '", "+", "duration", "+", "'s '", "+", "easing", ",", "cssTransitionProperties", "=", "{", "'-webkit-transition'", ":", "'all'", "+", "trail", ",", "'-moz-transition'", ":", "' all'", "+", "trail", ",", "'-o-ransition'", ":", "' all'", "+", "trail", ",", "'ms-transition'", ":", "' all'", "+", "trail", ",", "'transition'", ":", "' all'", "+", "trail", "}", ",", "newContent", "=", "''", ";", "for", "(", "i", "in", "cssTransitionProperties", ")", "{", "newContent", "+=", "i", "+", "': '", "+", "cssTransitionProperties", "[", "i", "]", "+", "';'", ";", "}", "newStylesheet", ".", "setHtml", "(", "'.'", "+", "this", ".", "animClass", "+", "'{'", "+", "newContent", "+", "'}'", ")", ";", "localnwt", ".", "one", "(", "'head'", ")", ".", "append", "(", "newStylesheet", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "newStylesheet", ".", "remove", "(", ")", "}", ",", "duration", "*", "1001", ")", "}" ]
Initializes CSS for transforms
[ "Initializes", "CSS", "for", "transforms" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/anim/js/anim.js#L14-L45
train
nwtjs/nwt
src/anim/js/anim.js
function(node, styles, duration, easing) { animation.init(duration, easing); node.fire('anim:start', [styles, duration, easing]) setTimeout(function(){ node.fire('anim:done', [styles, duration, easing]) }, duration*1000) // Need to be sure to implement the transition function first node.addClass(animation.animClass); node.setStyles(styles); return node; }
javascript
function(node, styles, duration, easing) { animation.init(duration, easing); node.fire('anim:start', [styles, duration, easing]) setTimeout(function(){ node.fire('anim:done', [styles, duration, easing]) }, duration*1000) // Need to be sure to implement the transition function first node.addClass(animation.animClass); node.setStyles(styles); return node; }
[ "function", "(", "node", ",", "styles", ",", "duration", ",", "easing", ")", "{", "animation", ".", "init", "(", "duration", ",", "easing", ")", ";", "node", ".", "fire", "(", "'anim:start'", ",", "[", "styles", ",", "duration", ",", "easing", "]", ")", "setTimeout", "(", "function", "(", ")", "{", "node", ".", "fire", "(", "'anim:done'", ",", "[", "styles", ",", "duration", ",", "easing", "]", ")", "}", ",", "duration", "*", "1000", ")", "node", ".", "addClass", "(", "animation", ".", "animClass", ")", ";", "node", ".", "setStyles", "(", "styles", ")", ";", "return", "node", ";", "}" ]
Method to animate a node @param object NWTNode instance @param object Object of styles to animate. E.g., {top: 10} @param integer Duration in seconds to animate @param string Easing type. One of: linear|ease|ease-in|ease-out|ease-in-out|cubic-bezier(n,n,n,n);
[ "Method", "to", "animate", "a", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/anim/js/anim.js#L55-L72
train
nwtjs/nwt
src/event/js/event.js
NWTEventInstance
function NWTEventInstance (e, attrs) { this._e = e; this.target = new NWTNodeInstance(e.target); for (var i in attrs) { this[i] = attrs[i]; } }
javascript
function NWTEventInstance (e, attrs) { this._e = e; this.target = new NWTNodeInstance(e.target); for (var i in attrs) { this[i] = attrs[i]; } }
[ "function", "NWTEventInstance", "(", "e", ",", "attrs", ")", "{", "this", ".", "_e", "=", "e", ";", "this", ".", "target", "=", "new", "NWTNodeInstance", "(", "e", ".", "target", ")", ";", "for", "(", "var", "i", "in", "attrs", ")", "{", "this", "[", "i", "]", "=", "attrs", "[", "i", "]", ";", "}", "}" ]
NWTEventInstance Class Event object wrapper @param event Event object @param object (Optional) attributes to populate the event object with @constructor
[ "NWTEventInstance", "Class", "Event", "object", "wrapper" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/event/js/event.js#L8-L15
train
nwtjs/nwt
src/event/js/event.js
function(attribute, pattern, callback, interaction, maxDepth) { var classPattern = new RegExp(pattern), interaction = interaction || 'click', maxSearch, dispatcher, body = localnwt.one('body'); // Currently only search one level for a mouse listener for performance reasons if (interaction == 'click') { maxSearch = 100; } else { maxSearch = maxDepth || 1; } dispatcher = function(e) { var originalTarget = e.target, target = originalTarget, // Did we find it? found = true, // Keep track of how many times we bubble up depthSearched = 0; while(target._node && target._node.parentNode) { if (target._node == localnwt.one('body')._node || depthSearched >= maxSearch) { break; } if (target.hasAttribute(attribute)) { var matches = target.getAttribute(attribute).match(pattern); if (matches) { callback(originalTarget, target, matches); // If we found a callback, we usually want to stop the event // Except for input elements (still want checkboxes to check and stuff) if( target.get('nodeName').toUpperCase() !== "INPUT") { e.stop(); } break; } } depthSearched++; target = target.parent(); }; return; }; var enableListener = function() { body.on(interaction, dispatcher); }; enableListener(); if (interaction !== 'click') { // Disable mouseover listeners on scroll var timer = false; localnwt.one(document).on('scroll', function() { body.off(interaction, dispatcher); if (timer) { clearTimeout(timer); timer = false; } timer = setTimeout(enableListener, 75); }); } }
javascript
function(attribute, pattern, callback, interaction, maxDepth) { var classPattern = new RegExp(pattern), interaction = interaction || 'click', maxSearch, dispatcher, body = localnwt.one('body'); // Currently only search one level for a mouse listener for performance reasons if (interaction == 'click') { maxSearch = 100; } else { maxSearch = maxDepth || 1; } dispatcher = function(e) { var originalTarget = e.target, target = originalTarget, // Did we find it? found = true, // Keep track of how many times we bubble up depthSearched = 0; while(target._node && target._node.parentNode) { if (target._node == localnwt.one('body')._node || depthSearched >= maxSearch) { break; } if (target.hasAttribute(attribute)) { var matches = target.getAttribute(attribute).match(pattern); if (matches) { callback(originalTarget, target, matches); // If we found a callback, we usually want to stop the event // Except for input elements (still want checkboxes to check and stuff) if( target.get('nodeName').toUpperCase() !== "INPUT") { e.stop(); } break; } } depthSearched++; target = target.parent(); }; return; }; var enableListener = function() { body.on(interaction, dispatcher); }; enableListener(); if (interaction !== 'click') { // Disable mouseover listeners on scroll var timer = false; localnwt.one(document).on('scroll', function() { body.off(interaction, dispatcher); if (timer) { clearTimeout(timer); timer = false; } timer = setTimeout(enableListener, 75); }); } }
[ "function", "(", "attribute", ",", "pattern", ",", "callback", ",", "interaction", ",", "maxDepth", ")", "{", "var", "classPattern", "=", "new", "RegExp", "(", "pattern", ")", ",", "interaction", "=", "interaction", "||", "'click'", ",", "maxSearch", ",", "dispatcher", ",", "body", "=", "localnwt", ".", "one", "(", "'body'", ")", ";", "if", "(", "interaction", "==", "'click'", ")", "{", "maxSearch", "=", "100", ";", "}", "else", "{", "maxSearch", "=", "maxDepth", "||", "1", ";", "}", "dispatcher", "=", "function", "(", "e", ")", "{", "var", "originalTarget", "=", "e", ".", "target", ",", "target", "=", "originalTarget", ",", "found", "=", "true", ",", "depthSearched", "=", "0", ";", "while", "(", "target", ".", "_node", "&&", "target", ".", "_node", ".", "parentNode", ")", "{", "if", "(", "target", ".", "_node", "==", "localnwt", ".", "one", "(", "'body'", ")", ".", "_node", "||", "depthSearched", ">=", "maxSearch", ")", "{", "break", ";", "}", "if", "(", "target", ".", "hasAttribute", "(", "attribute", ")", ")", "{", "var", "matches", "=", "target", ".", "getAttribute", "(", "attribute", ")", ".", "match", "(", "pattern", ")", ";", "if", "(", "matches", ")", "{", "callback", "(", "originalTarget", ",", "target", ",", "matches", ")", ";", "if", "(", "target", ".", "get", "(", "'nodeName'", ")", ".", "toUpperCase", "(", ")", "!==", "\"INPUT\"", ")", "{", "e", ".", "stop", "(", ")", ";", "}", "break", ";", "}", "}", "depthSearched", "++", ";", "target", "=", "target", ".", "parent", "(", ")", ";", "}", ";", "return", ";", "}", ";", "var", "enableListener", "=", "function", "(", ")", "{", "body", ".", "on", "(", "interaction", ",", "dispatcher", ")", ";", "}", ";", "enableListener", "(", ")", ";", "if", "(", "interaction", "!==", "'click'", ")", "{", "var", "timer", "=", "false", ";", "localnwt", ".", "one", "(", "document", ")", ".", "on", "(", "'scroll'", ",", "function", "(", ")", "{", "body", ".", "off", "(", "interaction", ",", "dispatcher", ")", ";", "if", "(", "timer", ")", "{", "clearTimeout", "(", "timer", ")", ";", "timer", "=", "false", ";", "}", "timer", "=", "setTimeout", "(", "enableListener", ",", "75", ")", ";", "}", ")", ";", "}", "}" ]
Adds a live listener to the page This allows us to update page components, and still have javascript function properly @param string Attribute to check on @param regex Pattern to match against the string @param function callback if matched @param string Type of listener to use, one of: click | mousemove | mouseout @param integer Max depth to search. Defaults to 1 for a mouseover action
[ "Adds", "a", "live", "listener", "to", "the", "page", "This", "allows", "us", "to", "update", "page", "components", "and", "still", "have", "javascript", "function", "properly" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/event/js/event.js#L99-L178
train
nwtjs/nwt
src/event/js/event.js
function (implementOn, event, callback) { var stringy = callback.toString(); if (this._cached[stringy]) { // Iteratre through the cached callbacks and remove the correct one based on reference for(var i=0,numCbs=this._cached[stringy].length; i < numCbs; i++) { if (this._cached[stringy][i].raw === callback) { implementOn.removeEventListener(event, this._cached[stringy][i].fn); } } } }
javascript
function (implementOn, event, callback) { var stringy = callback.toString(); if (this._cached[stringy]) { // Iteratre through the cached callbacks and remove the correct one based on reference for(var i=0,numCbs=this._cached[stringy].length; i < numCbs; i++) { if (this._cached[stringy][i].raw === callback) { implementOn.removeEventListener(event, this._cached[stringy][i].fn); } } } }
[ "function", "(", "implementOn", ",", "event", ",", "callback", ")", "{", "var", "stringy", "=", "callback", ".", "toString", "(", ")", ";", "if", "(", "this", ".", "_cached", "[", "stringy", "]", ")", "{", "for", "(", "var", "i", "=", "0", ",", "numCbs", "=", "this", ".", "_cached", "[", "stringy", "]", ".", "length", ";", "i", "<", "numCbs", ";", "i", "++", ")", "{", "if", "(", "this", ".", "_cached", "[", "stringy", "]", "[", "i", "]", ".", "raw", "===", "callback", ")", "{", "implementOn", ".", "removeEventListener", "(", "event", ",", "this", ".", "_cached", "[", "stringy", "]", "[", "i", "]", ".", "fn", ")", ";", "}", "}", "}", "}" ]
Removes an event listener from an eventable object @param string Name Event name @param function Callback Event callback
[ "Removes", "an", "event", "listener", "from", "an", "eventable", "object" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/event/js/event.js#L250-L262
train
XOP/sass-vars-to-js
src/_get-expression-value.js
getExpressionValue
function getExpressionValue (varName, scssExpression) { if (is.undef(scssExpression) || is.args.empty(arguments)) { message('Error: Missing arguments'); return undefined; } if (!is.string(varName) || !is.string(scssExpression)) { message('Error: Check arguments type'); return undefined; } if (!~scssExpression.indexOf('$')) { message('Warning: Check scssExpression to contain valid code') } // print the interpolated value in comment string // /*#{$varName}*/ --> /*varValue*/ const scssContent = `${scssExpression}/*#{$${varName}}*/`; const sassResult = sass.renderSync({ data: scssContent }); const cssResult = sassResult.css.toString(); return extractExpressionValue(cssResult); }
javascript
function getExpressionValue (varName, scssExpression) { if (is.undef(scssExpression) || is.args.empty(arguments)) { message('Error: Missing arguments'); return undefined; } if (!is.string(varName) || !is.string(scssExpression)) { message('Error: Check arguments type'); return undefined; } if (!~scssExpression.indexOf('$')) { message('Warning: Check scssExpression to contain valid code') } // print the interpolated value in comment string // /*#{$varName}*/ --> /*varValue*/ const scssContent = `${scssExpression}/*#{$${varName}}*/`; const sassResult = sass.renderSync({ data: scssContent }); const cssResult = sassResult.css.toString(); return extractExpressionValue(cssResult); }
[ "function", "getExpressionValue", "(", "varName", ",", "scssExpression", ")", "{", "if", "(", "is", ".", "undef", "(", "scssExpression", ")", "||", "is", ".", "args", ".", "empty", "(", "arguments", ")", ")", "{", "message", "(", "'Error: Missing arguments'", ")", ";", "return", "undefined", ";", "}", "if", "(", "!", "is", ".", "string", "(", "varName", ")", "||", "!", "is", ".", "string", "(", "scssExpression", ")", ")", "{", "message", "(", "'Error: Check arguments type'", ")", ";", "return", "undefined", ";", "}", "if", "(", "!", "~", "scssExpression", ".", "indexOf", "(", "'$'", ")", ")", "{", "message", "(", "'Warning: Check scssExpression to contain valid code'", ")", "}", "const", "scssContent", "=", "`", "${", "scssExpression", "}", "${", "varName", "}", "`", ";", "const", "sassResult", "=", "sass", ".", "renderSync", "(", "{", "data", ":", "scssContent", "}", ")", ";", "const", "cssResult", "=", "sassResult", ".", "css", ".", "toString", "(", ")", ";", "return", "extractExpressionValue", "(", "cssResult", ")", ";", "}" ]
Resolve variable value By variable name and previous code @param varName @param scssExpression
[ "Resolve", "variable", "value", "By", "variable", "name", "and", "previous", "code" ]
87ad8588701a9c2e69ace75931947d11698f25f0
https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/_get-expression-value.js#L14-L40
train
XOP/sass-vars-to-js
src/_get-expression-value.js
extractExpressionValue
function extractExpressionValue (css) { // parse the comment string: // /*varValue*/ --> varValue const valueRegExp = /(?:\/\*)(.+)(?:\*\/)/; const value = css.match(valueRegExp)[1]; if (!value) { message('Warning: empty value'); } return value; }
javascript
function extractExpressionValue (css) { // parse the comment string: // /*varValue*/ --> varValue const valueRegExp = /(?:\/\*)(.+)(?:\*\/)/; const value = css.match(valueRegExp)[1]; if (!value) { message('Warning: empty value'); } return value; }
[ "function", "extractExpressionValue", "(", "css", ")", "{", "const", "valueRegExp", "=", "/", "(?:\\/\\*)(.+)(?:\\*\\/)", "/", ";", "const", "value", "=", "css", ".", "match", "(", "valueRegExp", ")", "[", "1", "]", ";", "if", "(", "!", "value", ")", "{", "message", "(", "'Warning: empty value'", ")", ";", "}", "return", "value", ";", "}" ]
Parse calculated variable value From CSS comment @param css @returns {*}
[ "Parse", "calculated", "variable", "value", "From", "CSS", "comment" ]
87ad8588701a9c2e69ace75931947d11698f25f0
https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/_get-expression-value.js#L48-L60
train
byron-dupreez/aws-core-utils
regions.js
getRegion
function getRegion() { const awsRegion = trim(process.env.AWS_REGION); return awsRegion !== "undefined" && awsRegion !== "null" ? awsRegion : undefined; }
javascript
function getRegion() { const awsRegion = trim(process.env.AWS_REGION); return awsRegion !== "undefined" && awsRegion !== "null" ? awsRegion : undefined; }
[ "function", "getRegion", "(", ")", "{", "const", "awsRegion", "=", "trim", "(", "process", ".", "env", ".", "AWS_REGION", ")", ";", "return", "awsRegion", "!==", "\"undefined\"", "&&", "awsRegion", "!==", "\"null\"", "?", "awsRegion", ":", "undefined", ";", "}" ]
Gets the region in which this function is running from the `AWS_REGION` environment variable and returns it as is if it's neither "undefined" nor "null"; otherwise returns undefined. @returns {string|undefined} the AWS region (if it exists); otherwise undefined.
[ "Gets", "the", "region", "in", "which", "this", "function", "is", "running", "from", "the", "AWS_REGION", "environment", "variable", "and", "returns", "it", "as", "is", "if", "it", "s", "neither", "undefined", "nor", "null", ";", "otherwise", "returns", "undefined", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/regions.js#L41-L44
train
byron-dupreez/aws-core-utils
regions.js
configureRegion
function configureRegion(context) { // Resolve the AWS region, if it is not already defined on the context if (!context.region) { context.region = getRegion(); } const msg = `Using region (${process.env.AWS_REGION}) & context.region (${context.region})`; context.debug ? context.debug(msg) : console.log(msg); return context; }
javascript
function configureRegion(context) { // Resolve the AWS region, if it is not already defined on the context if (!context.region) { context.region = getRegion(); } const msg = `Using region (${process.env.AWS_REGION}) & context.region (${context.region})`; context.debug ? context.debug(msg) : console.log(msg); return context; }
[ "function", "configureRegion", "(", "context", ")", "{", "if", "(", "!", "context", ".", "region", ")", "{", "context", ".", "region", "=", "getRegion", "(", ")", ";", "}", "const", "msg", "=", "`", "${", "process", ".", "env", ".", "AWS_REGION", "}", "${", "context", ".", "region", "}", "`", ";", "context", ".", "debug", "?", "context", ".", "debug", "(", "msg", ")", ":", "console", ".", "log", "(", "msg", ")", ";", "return", "context", ";", "}" ]
Keeps context.region as is if it's already configured on the given context, otherwise gets the current region from process.env.AWS_REGION and sets it on the context as context.region. @param {Object|RegionAware} context - a context on which to set the region @returns {RegionAware} the context with its existing region or the current AWS_REGION env variable value.
[ "Keeps", "context", ".", "region", "as", "is", "if", "it", "s", "already", "configured", "on", "the", "given", "context", "otherwise", "gets", "the", "current", "region", "from", "process", ".", "env", ".", "AWS_REGION", "and", "sets", "it", "on", "the", "context", "as", "context", ".", "region", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/regions.js#L143-L151
train
byron-dupreez/aws-core-utils
regions.js
getOrSetRegionKey
function getOrSetRegionKey(region) { const regionName = region ? region : getRegion(); let regionKey = regionKeysByRegion.get(regionName); if (!regionKey) { regionKey = {region: regionName}; regionKeysByRegion.set(regionName, regionKey); } return regionKey; }
javascript
function getOrSetRegionKey(region) { const regionName = region ? region : getRegion(); let regionKey = regionKeysByRegion.get(regionName); if (!regionKey) { regionKey = {region: regionName}; regionKeysByRegion.set(regionName, regionKey); } return regionKey; }
[ "function", "getOrSetRegionKey", "(", "region", ")", "{", "const", "regionName", "=", "region", "?", "region", ":", "getRegion", "(", ")", ";", "let", "regionKey", "=", "regionKeysByRegion", ".", "get", "(", "regionName", ")", ";", "if", "(", "!", "regionKey", ")", "{", "regionKey", "=", "{", "region", ":", "regionName", "}", ";", "regionKeysByRegion", ".", "set", "(", "regionName", ",", "regionKey", ")", ";", "}", "return", "regionKey", ";", "}" ]
Returns the existing region key object or sets & returns a new region key object for the given region name. @param {string|undefined} [region] - the name of the region (defaults to current region if not defined) @returns {{region: string}} a region key object
[ "Returns", "the", "existing", "region", "key", "object", "or", "sets", "&", "returns", "a", "new", "region", "key", "object", "for", "the", "given", "region", "name", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/regions.js#L168-L176
train
dutchenkoOleg/happiness-scss
linter.js
transformConfig
function transformConfig (config) { if (config === null || typeof config !== 'object') { config = {}; } if (!Object.keys(config).length) { return { options: {}, files: { ignore: [ignoreNodeModules()] } }; } let runConfig = { options: { showMaxStack: 0 } }; if (config.noDisabling) { runConfig.options.noDisabling = true; } if (config.formatter) { runConfig.options.formatter = config.formatter; } if (config.showMaxStack >= 0) { runConfig.options.showMaxStack = config.showMaxStack; } if (config.outputFile) { runConfig.options['output-file'] = config.outputFile; } if (Array.isArray(config.ignore)) { runConfig.files = { ignore: config.ignore.concat(ignoreNodeModules()) }; } else { runConfig.files = { ignore: [ignoreNodeModules()] }; } return runConfig; }
javascript
function transformConfig (config) { if (config === null || typeof config !== 'object') { config = {}; } if (!Object.keys(config).length) { return { options: {}, files: { ignore: [ignoreNodeModules()] } }; } let runConfig = { options: { showMaxStack: 0 } }; if (config.noDisabling) { runConfig.options.noDisabling = true; } if (config.formatter) { runConfig.options.formatter = config.formatter; } if (config.showMaxStack >= 0) { runConfig.options.showMaxStack = config.showMaxStack; } if (config.outputFile) { runConfig.options['output-file'] = config.outputFile; } if (Array.isArray(config.ignore)) { runConfig.files = { ignore: config.ignore.concat(ignoreNodeModules()) }; } else { runConfig.files = { ignore: [ignoreNodeModules()] }; } return runConfig; }
[ "function", "transformConfig", "(", "config", ")", "{", "if", "(", "config", "===", "null", "||", "typeof", "config", "!==", "'object'", ")", "{", "config", "=", "{", "}", ";", "}", "if", "(", "!", "Object", ".", "keys", "(", "config", ")", ".", "length", ")", "{", "return", "{", "options", ":", "{", "}", ",", "files", ":", "{", "ignore", ":", "[", "ignoreNodeModules", "(", ")", "]", "}", "}", ";", "}", "let", "runConfig", "=", "{", "options", ":", "{", "showMaxStack", ":", "0", "}", "}", ";", "if", "(", "config", ".", "noDisabling", ")", "{", "runConfig", ".", "options", ".", "noDisabling", "=", "true", ";", "}", "if", "(", "config", ".", "formatter", ")", "{", "runConfig", ".", "options", ".", "formatter", "=", "config", ".", "formatter", ";", "}", "if", "(", "config", ".", "showMaxStack", ">=", "0", ")", "{", "runConfig", ".", "options", ".", "showMaxStack", "=", "config", ".", "showMaxStack", ";", "}", "if", "(", "config", ".", "outputFile", ")", "{", "runConfig", ".", "options", "[", "'output-file'", "]", "=", "config", ".", "outputFile", ";", "}", "if", "(", "Array", ".", "isArray", "(", "config", ".", "ignore", ")", ")", "{", "runConfig", ".", "files", "=", "{", "ignore", ":", "config", ".", "ignore", ".", "concat", "(", "ignoreNodeModules", "(", ")", ")", "}", ";", "}", "else", "{", "runConfig", ".", "files", "=", "{", "ignore", ":", "[", "ignoreNodeModules", "(", ")", "]", "}", ";", "}", "return", "runConfig", ";", "}" ]
Transform user config for linter config @private @param {Object} [config] @returns {Object}
[ "Transform", "user", "config", "for", "linter", "config" ]
03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c
https://github.com/dutchenkoOleg/happiness-scss/blob/03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c/linter.js#L40-L84
train
dutchenkoOleg/happiness-scss
linter.js
lintMethod
function lintMethod (mtd, file, config, cb, configPath) { let runConfig = transformConfig(config); if (typeof cb !== 'function') { cb = function () {}; } try { let results = sassLint[mtd](file, runConfig, configPath); if (mtd !== 'lintFiles') { if (!Array.isArray(results)) { results = [results]; } } let data = { results, errorCount: sassLint.errorCount(results), warningCount: sassLint.warningCount(results) }; cb(null, data); } catch (err) { cb(err); } }
javascript
function lintMethod (mtd, file, config, cb, configPath) { let runConfig = transformConfig(config); if (typeof cb !== 'function') { cb = function () {}; } try { let results = sassLint[mtd](file, runConfig, configPath); if (mtd !== 'lintFiles') { if (!Array.isArray(results)) { results = [results]; } } let data = { results, errorCount: sassLint.errorCount(results), warningCount: sassLint.warningCount(results) }; cb(null, data); } catch (err) { cb(err); } }
[ "function", "lintMethod", "(", "mtd", ",", "file", ",", "config", ",", "cb", ",", "configPath", ")", "{", "let", "runConfig", "=", "transformConfig", "(", "config", ")", ";", "if", "(", "typeof", "cb", "!==", "'function'", ")", "{", "cb", "=", "function", "(", ")", "{", "}", ";", "}", "try", "{", "let", "results", "=", "sassLint", "[", "mtd", "]", "(", "file", ",", "runConfig", ",", "configPath", ")", ";", "if", "(", "mtd", "!==", "'lintFiles'", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "results", ")", ")", "{", "results", "=", "[", "results", "]", ";", "}", "}", "let", "data", "=", "{", "results", ",", "errorCount", ":", "sassLint", ".", "errorCount", "(", "results", ")", ",", "warningCount", ":", "sassLint", ".", "warningCount", "(", "results", ")", "}", ";", "cb", "(", "null", ",", "data", ")", ";", "}", "catch", "(", "err", ")", "{", "cb", "(", "err", ")", ";", "}", "}" ]
Creating linting methods with happiness-scss configPath @param {string} mtd @param {string} file @param {Object} [config] @param {function} [cb] @param {string} configPath
[ "Creating", "linting", "methods", "with", "happiness", "-", "scss", "configPath" ]
03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c
https://github.com/dutchenkoOleg/happiness-scss/blob/03307cd4ee5f7b3fa2ee000f69d91f80ebbbd04c/linter.js#L94-L120
train
recidive/choko
lib/install.js
install
function install(destination, prg, callback) { prompt.start(); prompt.message = ':'.white.bold.bgBlack; prompt.delimiter = ': '.white.bold.bgBlack; var schema = { properties: { appName: { description: 'Application name'.white.bold.bgBlack, pattern: /^[a-zA-Z0-9\s\-]+$/, message: 'Application name must be only letters, spaces, or dashes', default: path.basename(destination), required: true }, appEmail: { description: 'Application email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, adminName: { description: 'Administrator username'.white.bold.bgBlack, conform: validator.isAlphanumeric, default: 'admin', message: 'Enter a valid username e.g. admin', required: true }, adminPass: { description: 'Administrator password (at least 6 characters)'.white.bold.bgBlack, hidden: true, conform: function (pass) { return validator.isLength(pass, 6); }, message: 'Password must have at least 6 characters.', required: true }, adminEmail: { description: 'Administrator email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, database: { description: 'Database URI'.white.bold.bgBlack, conform: function(uri) { return validator.isURL(uri, { protocols: ['mongodb'], require_protocol: true, allow_underscores: true }); }, default: 'mongodb://localhost/' + path.basename(destination), message: 'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp', required: true } } }; prompt.get(schema, function (error, result) { if (error) { return console.log('\nInstall aborted, no changes were made.'); } doInstall({ application: { name: result.appName, email: result.appEmail }, database: result.database, sessionSecret: crypto.randomBytes(32).toString('base64') }, destination); var app = new Application(destination); app.start(prg.port, function(error, app) { if (error) { throw error; } createAdminUser(app, result, function(error, newAccount, errors) { // @todo: handle errors. util.log('Navigate to http://localhost:' + prg.port + ' to start building your new application.'); }); }); }); }
javascript
function install(destination, prg, callback) { prompt.start(); prompt.message = ':'.white.bold.bgBlack; prompt.delimiter = ': '.white.bold.bgBlack; var schema = { properties: { appName: { description: 'Application name'.white.bold.bgBlack, pattern: /^[a-zA-Z0-9\s\-]+$/, message: 'Application name must be only letters, spaces, or dashes', default: path.basename(destination), required: true }, appEmail: { description: 'Application email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, adminName: { description: 'Administrator username'.white.bold.bgBlack, conform: validator.isAlphanumeric, default: 'admin', message: 'Enter a valid username e.g. admin', required: true }, adminPass: { description: 'Administrator password (at least 6 characters)'.white.bold.bgBlack, hidden: true, conform: function (pass) { return validator.isLength(pass, 6); }, message: 'Password must have at least 6 characters.', required: true }, adminEmail: { description: 'Administrator email address'.white.bold.bgBlack, conform: validator.isEmail, message: 'Enter a valid email', required: true }, database: { description: 'Database URI'.white.bold.bgBlack, conform: function(uri) { return validator.isURL(uri, { protocols: ['mongodb'], require_protocol: true, allow_underscores: true }); }, default: 'mongodb://localhost/' + path.basename(destination), message: 'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp', required: true } } }; prompt.get(schema, function (error, result) { if (error) { return console.log('\nInstall aborted, no changes were made.'); } doInstall({ application: { name: result.appName, email: result.appEmail }, database: result.database, sessionSecret: crypto.randomBytes(32).toString('base64') }, destination); var app = new Application(destination); app.start(prg.port, function(error, app) { if (error) { throw error; } createAdminUser(app, result, function(error, newAccount, errors) { // @todo: handle errors. util.log('Navigate to http://localhost:' + prg.port + ' to start building your new application.'); }); }); }); }
[ "function", "install", "(", "destination", ",", "prg", ",", "callback", ")", "{", "prompt", ".", "start", "(", ")", ";", "prompt", ".", "message", "=", "':'", ".", "white", ".", "bold", ".", "bgBlack", ";", "prompt", ".", "delimiter", "=", "': '", ".", "white", ".", "bold", ".", "bgBlack", ";", "var", "schema", "=", "{", "properties", ":", "{", "appName", ":", "{", "description", ":", "'Application name'", ".", "white", ".", "bold", ".", "bgBlack", ",", "pattern", ":", "/", "^[a-zA-Z0-9\\s\\-]+$", "/", ",", "message", ":", "'Application name must be only letters, spaces, or dashes'", ",", "default", ":", "path", ".", "basename", "(", "destination", ")", ",", "required", ":", "true", "}", ",", "appEmail", ":", "{", "description", ":", "'Application email address'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "validator", ".", "isEmail", ",", "message", ":", "'Enter a valid email'", ",", "required", ":", "true", "}", ",", "adminName", ":", "{", "description", ":", "'Administrator username'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "validator", ".", "isAlphanumeric", ",", "default", ":", "'admin'", ",", "message", ":", "'Enter a valid username e.g. admin'", ",", "required", ":", "true", "}", ",", "adminPass", ":", "{", "description", ":", "'Administrator password (at least 6 characters)'", ".", "white", ".", "bold", ".", "bgBlack", ",", "hidden", ":", "true", ",", "conform", ":", "function", "(", "pass", ")", "{", "return", "validator", ".", "isLength", "(", "pass", ",", "6", ")", ";", "}", ",", "message", ":", "'Password must have at least 6 characters.'", ",", "required", ":", "true", "}", ",", "adminEmail", ":", "{", "description", ":", "'Administrator email address'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "validator", ".", "isEmail", ",", "message", ":", "'Enter a valid email'", ",", "required", ":", "true", "}", ",", "database", ":", "{", "description", ":", "'Database URI'", ".", "white", ".", "bold", ".", "bgBlack", ",", "conform", ":", "function", "(", "uri", ")", "{", "return", "validator", ".", "isURL", "(", "uri", ",", "{", "protocols", ":", "[", "'mongodb'", "]", ",", "require_protocol", ":", "true", ",", "allow_underscores", ":", "true", "}", ")", ";", "}", ",", "default", ":", "'mongodb://localhost/'", "+", "path", ".", "basename", "(", "destination", ")", ",", "message", ":", "'Enter a valid URI for your database e.g. mongodb://localhost/chokoapp'", ",", "required", ":", "true", "}", "}", "}", ";", "prompt", ".", "get", "(", "schema", ",", "function", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "return", "console", ".", "log", "(", "'\\nInstall aborted, no changes were made.'", ")", ";", "}", "\\n", "doInstall", "(", "{", "application", ":", "{", "name", ":", "result", ".", "appName", ",", "email", ":", "result", ".", "appEmail", "}", ",", "database", ":", "result", ".", "database", ",", "sessionSecret", ":", "crypto", ".", "randomBytes", "(", "32", ")", ".", "toString", "(", "'base64'", ")", "}", ",", "destination", ")", ";", "var", "app", "=", "new", "Application", "(", "destination", ")", ";", "}", ")", ";", "}" ]
Run a questionnaire for interactively configuring the new application.
[ "Run", "a", "questionnaire", "for", "interactively", "configuring", "the", "new", "application", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/install.js#L17-L105
train
recidive/choko
lib/install.js
doInstall
function doInstall(settings, destination) { // Create application directories if they don't exist. var folders = [ destination, path.join(destination, '/public'), path.join(destination, '/extensions') ]; folders.forEach(function(folder) { if (!fs.existsSync(folder)) { fs.mkdirSync(folder); } }); // Create settings.json. fs.writeFileSync(path.join(destination, 'settings.json'), JSON.stringify(settings, null, ' '), {flag: 'w'}); }
javascript
function doInstall(settings, destination) { // Create application directories if they don't exist. var folders = [ destination, path.join(destination, '/public'), path.join(destination, '/extensions') ]; folders.forEach(function(folder) { if (!fs.existsSync(folder)) { fs.mkdirSync(folder); } }); // Create settings.json. fs.writeFileSync(path.join(destination, 'settings.json'), JSON.stringify(settings, null, ' '), {flag: 'w'}); }
[ "function", "doInstall", "(", "settings", ",", "destination", ")", "{", "var", "folders", "=", "[", "destination", ",", "path", ".", "join", "(", "destination", ",", "'/public'", ")", ",", "path", ".", "join", "(", "destination", ",", "'/extensions'", ")", "]", ";", "folders", ".", "forEach", "(", "function", "(", "folder", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "folder", ")", ")", "{", "fs", ".", "mkdirSync", "(", "folder", ")", ";", "}", "}", ")", ";", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "destination", ",", "'settings.json'", ")", ",", "JSON", ".", "stringify", "(", "settings", ",", "null", ",", "' '", ")", ",", "{", "flag", ":", "'w'", "}", ")", ";", "}" ]
Create application folder structure and initial settings.
[ "Create", "application", "folder", "structure", "and", "initial", "settings", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/install.js#L110-L125
train
recidive/choko
lib/install.js
createAdminUser
function createAdminUser(app, result, callback) { // Create the admin user. var User = app.type('user'); var userData = { username: result.adminName, password: result.adminPass, email: result.adminEmail, roles: ['administrator'] }; User.validateAndSave(userData, callback); }
javascript
function createAdminUser(app, result, callback) { // Create the admin user. var User = app.type('user'); var userData = { username: result.adminName, password: result.adminPass, email: result.adminEmail, roles: ['administrator'] }; User.validateAndSave(userData, callback); }
[ "function", "createAdminUser", "(", "app", ",", "result", ",", "callback", ")", "{", "var", "User", "=", "app", ".", "type", "(", "'user'", ")", ";", "var", "userData", "=", "{", "username", ":", "result", ".", "adminName", ",", "password", ":", "result", ".", "adminPass", ",", "email", ":", "result", ".", "adminEmail", ",", "roles", ":", "[", "'administrator'", "]", "}", ";", "User", ".", "validateAndSave", "(", "userData", ",", "callback", ")", ";", "}" ]
Create administrator user.
[ "Create", "administrator", "user", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/install.js#L130-L140
train
jgable/react-native-fluxbone
lib/dispatcherEvents.js
function () { // Allow using a function or an object var events = _.result(this, 'dispatcherEvents'); if (_.isUndefined(events) || _.isEmpty(events)) { // Bug out early if no dispatcherEvents return; } var registrations = {}; _.each(events, function (funcOrName, actionType) { // Quick sanity check for whether there is a problem with the function/name passed if (!(_.isFunction(funcOrName) || _.isFunction(this[funcOrName]))) { console.warn('dispatcherEvent: "' + funcOrName + '" is not a function'); return; } if (_.isFunction(funcOrName)) { registrations[actionType] = funcOrName; } else { registrations[actionType] = this[funcOrName]; } }.bind(this)); this.dispatcherToken = dispatcher.register(registrations, this); }
javascript
function () { // Allow using a function or an object var events = _.result(this, 'dispatcherEvents'); if (_.isUndefined(events) || _.isEmpty(events)) { // Bug out early if no dispatcherEvents return; } var registrations = {}; _.each(events, function (funcOrName, actionType) { // Quick sanity check for whether there is a problem with the function/name passed if (!(_.isFunction(funcOrName) || _.isFunction(this[funcOrName]))) { console.warn('dispatcherEvent: "' + funcOrName + '" is not a function'); return; } if (_.isFunction(funcOrName)) { registrations[actionType] = funcOrName; } else { registrations[actionType] = this[funcOrName]; } }.bind(this)); this.dispatcherToken = dispatcher.register(registrations, this); }
[ "function", "(", ")", "{", "var", "events", "=", "_", ".", "result", "(", "this", ",", "'dispatcherEvents'", ")", ";", "if", "(", "_", ".", "isUndefined", "(", "events", ")", "||", "_", ".", "isEmpty", "(", "events", ")", ")", "{", "return", ";", "}", "var", "registrations", "=", "{", "}", ";", "_", ".", "each", "(", "events", ",", "function", "(", "funcOrName", ",", "actionType", ")", "{", "if", "(", "!", "(", "_", ".", "isFunction", "(", "funcOrName", ")", "||", "_", ".", "isFunction", "(", "this", "[", "funcOrName", "]", ")", ")", ")", "{", "console", ".", "warn", "(", "'dispatcherEvent: \"'", "+", "funcOrName", "+", "'\" is not a function'", ")", ";", "return", ";", "}", "if", "(", "_", ".", "isFunction", "(", "funcOrName", ")", ")", "{", "registrations", "[", "actionType", "]", "=", "funcOrName", ";", "}", "else", "{", "registrations", "[", "actionType", "]", "=", "this", "[", "funcOrName", "]", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "dispatcherToken", "=", "dispatcher", ".", "register", "(", "registrations", ",", "this", ")", ";", "}" ]
Registers the dispatcherEvents hash
[ "Registers", "the", "dispatcherEvents", "hash" ]
9847a598da0cc72f056c6bd4d2e21909b146f530
https://github.com/jgable/react-native-fluxbone/blob/9847a598da0cc72f056c6bd4d2e21909b146f530/lib/dispatcherEvents.js#L16-L42
train
LeanKit-Labs/autohost
src/transport.js
getActions
function getActions( state, resource ) { var list = state.actionList[ resource.name ] = []; _.each( resource.actions, function( action, actionName ) { list.push( [ resource.name, actionName ].join( '.' ) ); } ); }
javascript
function getActions( state, resource ) { var list = state.actionList[ resource.name ] = []; _.each( resource.actions, function( action, actionName ) { list.push( [ resource.name, actionName ].join( '.' ) ); } ); }
[ "function", "getActions", "(", "state", ",", "resource", ")", "{", "var", "list", "=", "state", ".", "actionList", "[", "resource", ".", "name", "]", "=", "[", "]", ";", "_", ".", "each", "(", "resource", ".", "actions", ",", "function", "(", "action", ",", "actionName", ")", "{", "list", ".", "push", "(", "[", "resource", ".", "name", ",", "actionName", "]", ".", "join", "(", "'.'", ")", ")", ";", "}", ")", ";", "}" ]
store actions from the resource
[ "store", "actions", "from", "the", "resource" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L35-L40
train
LeanKit-Labs/autohost
src/transport.js
getArguments
function getArguments( fn ) { return _.isFunction( fn ) ? trim( /[(]([^)]*)[)]/.exec( fn.toString() )[ 1 ].split( ',' ) ) : []; }
javascript
function getArguments( fn ) { return _.isFunction( fn ) ? trim( /[(]([^)]*)[)]/.exec( fn.toString() )[ 1 ].split( ',' ) ) : []; }
[ "function", "getArguments", "(", "fn", ")", "{", "return", "_", ".", "isFunction", "(", "fn", ")", "?", "trim", "(", "/", "[(]([^)]*)[)]", "/", ".", "exec", "(", "fn", ".", "toString", "(", ")", ")", "[", "1", "]", ".", "split", "(", "','", ")", ")", ":", "[", "]", ";", "}" ]
reads argument names from a function
[ "reads", "argument", "names", "from", "a", "function" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L58-L60
train
LeanKit-Labs/autohost
src/transport.js
loadAll
function loadAll( state, resourcePath ) { var loadActions = [ loadResources( state, resourcePath ) ] || []; if ( state.config.modules ) { _.each( state.config.modules, function( mod ) { var modPath; if ( /[\/]/.test( mod ) ) { modPath = require.resolve( path.resolve( process.cwd(), mod ) ); } else { modPath = require.resolve( mod ); } loadActions.push( loadModule( state, modPath ) ); } ); } loadActions.push( loadModule( state, './ahResource' ) ); return when.all( loadActions ); }
javascript
function loadAll( state, resourcePath ) { var loadActions = [ loadResources( state, resourcePath ) ] || []; if ( state.config.modules ) { _.each( state.config.modules, function( mod ) { var modPath; if ( /[\/]/.test( mod ) ) { modPath = require.resolve( path.resolve( process.cwd(), mod ) ); } else { modPath = require.resolve( mod ); } loadActions.push( loadModule( state, modPath ) ); } ); } loadActions.push( loadModule( state, './ahResource' ) ); return when.all( loadActions ); }
[ "function", "loadAll", "(", "state", ",", "resourcePath", ")", "{", "var", "loadActions", "=", "[", "loadResources", "(", "state", ",", "resourcePath", ")", "]", "||", "[", "]", ";", "if", "(", "state", ".", "config", ".", "modules", ")", "{", "_", ".", "each", "(", "state", ".", "config", ".", "modules", ",", "function", "(", "mod", ")", "{", "var", "modPath", ";", "if", "(", "/", "[\\/]", "/", ".", "test", "(", "mod", ")", ")", "{", "modPath", "=", "require", ".", "resolve", "(", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "mod", ")", ")", ";", "}", "else", "{", "modPath", "=", "require", ".", "resolve", "(", "mod", ")", ";", "}", "loadActions", ".", "push", "(", "loadModule", "(", "state", ",", "modPath", ")", ")", ";", "}", ")", ";", "}", "loadActions", ".", "push", "(", "loadModule", "(", "state", ",", "'./ahResource'", ")", ")", ";", "return", "when", ".", "all", "(", "loadActions", ")", ";", "}" ]
loads internal resources, resources from config path and node module resources
[ "loads", "internal", "resources", "resources", "from", "config", "path", "and", "node", "module", "resources" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L80-L95
train
LeanKit-Labs/autohost
src/transport.js
loadModule
function loadModule( state, resourcePath ) { try { var key = path.resolve( resourcePath ); delete require.cache[ key ]; var modFn = require( resourcePath ); var args = getArguments( modFn ); args.shift(); if ( args.length ) { return state.fount.resolve( args ) .then( function( deps ) { var argList = _.map( args, function( arg ) { return deps[ arg ]; } ); argList.unshift( state.host ); var mod = modFn.apply( modFn, argList ); attachPath( state, mod, resourcePath ); return mod; } ); } else { var mod = modFn( state.host ); attachPath( state, mod, resourcePath ); return when( mod ); } } catch ( err ) { console.error( 'Error loading resource module at %s with: %s', resourcePath, err.stack ); return when( [] ); } }
javascript
function loadModule( state, resourcePath ) { try { var key = path.resolve( resourcePath ); delete require.cache[ key ]; var modFn = require( resourcePath ); var args = getArguments( modFn ); args.shift(); if ( args.length ) { return state.fount.resolve( args ) .then( function( deps ) { var argList = _.map( args, function( arg ) { return deps[ arg ]; } ); argList.unshift( state.host ); var mod = modFn.apply( modFn, argList ); attachPath( state, mod, resourcePath ); return mod; } ); } else { var mod = modFn( state.host ); attachPath( state, mod, resourcePath ); return when( mod ); } } catch ( err ) { console.error( 'Error loading resource module at %s with: %s', resourcePath, err.stack ); return when( [] ); } }
[ "function", "loadModule", "(", "state", ",", "resourcePath", ")", "{", "try", "{", "var", "key", "=", "path", ".", "resolve", "(", "resourcePath", ")", ";", "delete", "require", ".", "cache", "[", "key", "]", ";", "var", "modFn", "=", "require", "(", "resourcePath", ")", ";", "var", "args", "=", "getArguments", "(", "modFn", ")", ";", "args", ".", "shift", "(", ")", ";", "if", "(", "args", ".", "length", ")", "{", "return", "state", ".", "fount", ".", "resolve", "(", "args", ")", ".", "then", "(", "function", "(", "deps", ")", "{", "var", "argList", "=", "_", ".", "map", "(", "args", ",", "function", "(", "arg", ")", "{", "return", "deps", "[", "arg", "]", ";", "}", ")", ";", "argList", ".", "unshift", "(", "state", ".", "host", ")", ";", "var", "mod", "=", "modFn", ".", "apply", "(", "modFn", ",", "argList", ")", ";", "attachPath", "(", "state", ",", "mod", ",", "resourcePath", ")", ";", "return", "mod", ";", "}", ")", ";", "}", "else", "{", "var", "mod", "=", "modFn", "(", "state", ".", "host", ")", ";", "attachPath", "(", "state", ",", "mod", ",", "resourcePath", ")", ";", "return", "when", "(", "mod", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "'Error loading resource module at %s with: %s'", ",", "resourcePath", ",", "err", ".", "stack", ")", ";", "return", "when", "(", "[", "]", ")", ";", "}", "}" ]
loads a module based on the file path and resolves the function promises and all
[ "loads", "a", "module", "based", "on", "the", "file", "path", "and", "resolves", "the", "function", "promises", "and", "all" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L100-L127
train
LeanKit-Labs/autohost
src/transport.js
loadResources
function loadResources( state, filePath ) { var resourcePath = path.resolve( process.cwd(), filePath ); return getResources( resourcePath ) .then( function( list ) { return when.all( _.map( _.filter( list ), loadModule.bind( undefined, state ) ) ) .then( function( lists ) { return _.flatten( lists ); } ); } ); }
javascript
function loadResources( state, filePath ) { var resourcePath = path.resolve( process.cwd(), filePath ); return getResources( resourcePath ) .then( function( list ) { return when.all( _.map( _.filter( list ), loadModule.bind( undefined, state ) ) ) .then( function( lists ) { return _.flatten( lists ); } ); } ); }
[ "function", "loadResources", "(", "state", ",", "filePath", ")", "{", "var", "resourcePath", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "filePath", ")", ";", "return", "getResources", "(", "resourcePath", ")", ".", "then", "(", "function", "(", "list", ")", "{", "return", "when", ".", "all", "(", "_", ".", "map", "(", "_", ".", "filter", "(", "list", ")", ",", "loadModule", ".", "bind", "(", "undefined", ",", "state", ")", ")", ")", ".", "then", "(", "function", "(", "lists", ")", "{", "return", "_", ".", "flatten", "(", "lists", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
loadResources from path and returns the modules once they're loaded
[ "loadResources", "from", "path", "and", "returns", "the", "modules", "once", "they", "re", "loaded" ]
b143e99336cbecf5ac5712c2b0c77cc091081983
https://github.com/LeanKit-Labs/autohost/blob/b143e99336cbecf5ac5712c2b0c77cc091081983/src/transport.js#L130-L139
train
nwtjs/nwt
src/node/js/node.js
function(other) { var me = this.region(), you = other.region(); return !( me.left > you.right || me.right < you.left || me.top > you.bottom || me.bottom < you.top || you.left > me.right || you.right < me.left || you.top > me.bottom || you.bottom < me.top ); }
javascript
function(other) { var me = this.region(), you = other.region(); return !( me.left > you.right || me.right < you.left || me.top > you.bottom || me.bottom < you.top || you.left > me.right || you.right < me.left || you.top > me.bottom || you.bottom < me.top ); }
[ "function", "(", "other", ")", "{", "var", "me", "=", "this", ".", "region", "(", ")", ",", "you", "=", "other", ".", "region", "(", ")", ";", "return", "!", "(", "me", ".", "left", ">", "you", ".", "right", "||", "me", ".", "right", "<", "you", ".", "left", "||", "me", ".", "top", ">", "you", ".", "bottom", "||", "me", ".", "bottom", "<", "you", ".", "top", "||", "you", ".", "left", ">", "me", ".", "right", "||", "you", ".", "right", "<", "me", ".", "left", "||", "you", ".", "top", ">", "me", ".", "bottom", "||", "you", ".", "bottom", "<", "me", ".", "top", ")", ";", "}" ]
Checks if a given node intersects another @param object Node to check against
[ "Checks", "if", "a", "given", "node", "intersects", "another" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L53-L68
train
nwtjs/nwt
src/node/js/node.js
function(selector) { var allMatches = localnwt.all(selector), testNode = this._node, ancestor = null, maxDepth = 0; if( allMatches.size() == 0 ) { return null; } while( true ) { // Iterate through all matches for each parent, and exit as soon as we have a match // Pretty bad performance, but super small. TODO: Omtimize allMatches.each(function (el) { if (el._node == testNode) { ancestor = el; } }); var parentNode = testNode.parentNode; if( ancestor || !parentNode) { break; } testNode = parentNode; } if( ancestor ) { return ancestor; } else { return null; } }
javascript
function(selector) { var allMatches = localnwt.all(selector), testNode = this._node, ancestor = null, maxDepth = 0; if( allMatches.size() == 0 ) { return null; } while( true ) { // Iterate through all matches for each parent, and exit as soon as we have a match // Pretty bad performance, but super small. TODO: Omtimize allMatches.each(function (el) { if (el._node == testNode) { ancestor = el; } }); var parentNode = testNode.parentNode; if( ancestor || !parentNode) { break; } testNode = parentNode; } if( ancestor ) { return ancestor; } else { return null; } }
[ "function", "(", "selector", ")", "{", "var", "allMatches", "=", "localnwt", ".", "all", "(", "selector", ")", ",", "testNode", "=", "this", ".", "_node", ",", "ancestor", "=", "null", ",", "maxDepth", "=", "0", ";", "if", "(", "allMatches", ".", "size", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "while", "(", "true", ")", "{", "allMatches", ".", "each", "(", "function", "(", "el", ")", "{", "if", "(", "el", ".", "_node", "==", "testNode", ")", "{", "ancestor", "=", "el", ";", "}", "}", ")", ";", "var", "parentNode", "=", "testNode", ".", "parentNode", ";", "if", "(", "ancestor", "||", "!", "parentNode", ")", "{", "break", ";", "}", "testNode", "=", "parentNode", ";", "}", "if", "(", "ancestor", ")", "{", "return", "ancestor", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Returns the ancestor that matches the css selector @param string CSS Selector
[ "Returns", "the", "ancestor", "that", "matches", "the", "css", "selector" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L75-L107
train
nwtjs/nwt
src/node/js/node.js
function(property) { if( property === 'parentNode' ) { var node = this._node[property]; if( !node ) { return null; } return new NWTNodeInstance(node); } return this._node[property]; }
javascript
function(property) { if( property === 'parentNode' ) { var node = this._node[property]; if( !node ) { return null; } return new NWTNodeInstance(node); } return this._node[property]; }
[ "function", "(", "property", ")", "{", "if", "(", "property", "===", "'parentNode'", ")", "{", "var", "node", "=", "this", ".", "_node", "[", "property", "]", ";", "if", "(", "!", "node", ")", "{", "return", "null", ";", "}", "return", "new", "NWTNodeInstance", "(", "node", ")", ";", "}", "return", "this", ".", "_node", "[", "property", "]", ";", "}" ]
Gets a property from the node object @param string Attribute to get
[ "Gets", "a", "property", "from", "the", "node", "object" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L176-L185
train
nwtjs/nwt
src/node/js/node.js
function(property) { if( !this.getAttribute('style') ) { return ''; } property = this._jsStyle(property); var matchedStyle = this._node.style[property]; if( matchedStyle ) { return matchedStyle; } else { return null; } }
javascript
function(property) { if( !this.getAttribute('style') ) { return ''; } property = this._jsStyle(property); var matchedStyle = this._node.style[property]; if( matchedStyle ) { return matchedStyle; } else { return null; } }
[ "function", "(", "property", ")", "{", "if", "(", "!", "this", ".", "getAttribute", "(", "'style'", ")", ")", "{", "return", "''", ";", "}", "property", "=", "this", ".", "_jsStyle", "(", "property", ")", ";", "var", "matchedStyle", "=", "this", ".", "_node", ".", "style", "[", "property", "]", ";", "if", "(", "matchedStyle", ")", "{", "return", "matchedStyle", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets a style attribute set on the node @param string Style attribute to get
[ "Gets", "a", "style", "attribute", "set", "on", "the", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L241-L256
train
nwtjs/nwt
src/node/js/node.js
function(props) { // Default properties to an array if (typeof props == 'string') { props = [props]; } var i, propsLen = props.length; for (i = 0; i < propsLen; i += 1) { this._node.style[props[i]] = ''; } return this; }
javascript
function(props) { // Default properties to an array if (typeof props == 'string') { props = [props]; } var i, propsLen = props.length; for (i = 0; i < propsLen; i += 1) { this._node.style[props[i]] = ''; } return this; }
[ "function", "(", "props", ")", "{", "if", "(", "typeof", "props", "==", "'string'", ")", "{", "props", "=", "[", "props", "]", ";", "}", "var", "i", ",", "propsLen", "=", "props", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "propsLen", ";", "i", "+=", "1", ")", "{", "this", ".", "_node", ".", "style", "[", "props", "[", "i", "]", "]", "=", "''", ";", "}", "return", "this", ";", "}" ]
Removes an array of styles from a node @param array Array of styles to remove
[ "Removes", "an", "array", "of", "styles", "from", "a", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L272-L285
train
nwtjs/nwt
src/node/js/node.js
function(newStyles) { if( !this.getAttribute('style') ) { this.setAttribute('style', ''); } var newStyle = '', // If the style matches one of the following, and we pass in an integer, default the unit // E.g., 10 becomes 10px defaultToUnit = { top: 'px', left: 'px', width: 'px', height: 'px' }, i, eachStyleValue, // Keep track of an array of styles that we need to remove newStyleKeys = []; for( i in newStyles ) { var styleKey = this._jsStyle(i), eachStyleVal = newStyles[i]; // Default the unit if necessary if (defaultToUnit[styleKey] && !isNaN(eachStyleVal)) { eachStyleVal += defaultToUnit[styleKey]; } this._node.style[styleKey] = eachStyleVal; } return this; }
javascript
function(newStyles) { if( !this.getAttribute('style') ) { this.setAttribute('style', ''); } var newStyle = '', // If the style matches one of the following, and we pass in an integer, default the unit // E.g., 10 becomes 10px defaultToUnit = { top: 'px', left: 'px', width: 'px', height: 'px' }, i, eachStyleValue, // Keep track of an array of styles that we need to remove newStyleKeys = []; for( i in newStyles ) { var styleKey = this._jsStyle(i), eachStyleVal = newStyles[i]; // Default the unit if necessary if (defaultToUnit[styleKey] && !isNaN(eachStyleVal)) { eachStyleVal += defaultToUnit[styleKey]; } this._node.style[styleKey] = eachStyleVal; } return this; }
[ "function", "(", "newStyles", ")", "{", "if", "(", "!", "this", ".", "getAttribute", "(", "'style'", ")", ")", "{", "this", ".", "setAttribute", "(", "'style'", ",", "''", ")", ";", "}", "var", "newStyle", "=", "''", ",", "defaultToUnit", "=", "{", "top", ":", "'px'", ",", "left", ":", "'px'", ",", "width", ":", "'px'", ",", "height", ":", "'px'", "}", ",", "i", ",", "eachStyleValue", ",", "newStyleKeys", "=", "[", "]", ";", "for", "(", "i", "in", "newStyles", ")", "{", "var", "styleKey", "=", "this", ".", "_jsStyle", "(", "i", ")", ",", "eachStyleVal", "=", "newStyles", "[", "i", "]", ";", "if", "(", "defaultToUnit", "[", "styleKey", "]", "&&", "!", "isNaN", "(", "eachStyleVal", ")", ")", "{", "eachStyleVal", "+=", "defaultToUnit", "[", "styleKey", "]", ";", "}", "this", ".", "_node", ".", "style", "[", "styleKey", "]", "=", "eachStyleVal", ";", "}", "return", "this", ";", "}" ]
Sets multiple styles @param object Object map of styles to set
[ "Sets", "multiple", "styles" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L304-L341
train
nwtjs/nwt
src/node/js/node.js
function() { var retVal = '', // Getting ALL elements inside of form element els = this._node.getElementsByTagName('*'); // Looping through all elements inside of form and checking to see if they're "form elements" for( var i = 0, el; el = els[i]; i++ ) { if( !el.disabled && el.name && el.name.length > 0 ) { switch(el.tagName.toLowerCase()) { case 'input': switch( el.type ) { // Note we SKIP Buttons and Submits since there are no reasons as to why we // should submit those anyway case 'checkbox': case 'radio': if( el.checked ) { if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); } break; case 'hidden': case 'password': case 'text': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } break; case 'select': case 'textarea': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } } } return retVal; }
javascript
function() { var retVal = '', // Getting ALL elements inside of form element els = this._node.getElementsByTagName('*'); // Looping through all elements inside of form and checking to see if they're "form elements" for( var i = 0, el; el = els[i]; i++ ) { if( !el.disabled && el.name && el.name.length > 0 ) { switch(el.tagName.toLowerCase()) { case 'input': switch( el.type ) { // Note we SKIP Buttons and Submits since there are no reasons as to why we // should submit those anyway case 'checkbox': case 'radio': if( el.checked ) { if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); } break; case 'hidden': case 'password': case 'text': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } break; case 'select': case 'textarea': if( retVal.length > 0 ) { retVal += '&'; } retVal += el.name + '=' + encodeURIComponent(el.value); break; } } } return retVal; }
[ "function", "(", ")", "{", "var", "retVal", "=", "''", ",", "els", "=", "this", ".", "_node", ".", "getElementsByTagName", "(", "'*'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "el", ";", "el", "=", "els", "[", "i", "]", ";", "i", "++", ")", "{", "if", "(", "!", "el", ".", "disabled", "&&", "el", ".", "name", "&&", "el", ".", "name", ".", "length", ">", "0", ")", "{", "switch", "(", "el", ".", "tagName", ".", "toLowerCase", "(", ")", ")", "{", "case", "'input'", ":", "switch", "(", "el", ".", "type", ")", "{", "case", "'checkbox'", ":", "case", "'radio'", ":", "if", "(", "el", ".", "checked", ")", "{", "if", "(", "retVal", ".", "length", ">", "0", ")", "{", "retVal", "+=", "'&'", ";", "}", "retVal", "+=", "el", ".", "name", "+", "'='", "+", "encodeURIComponent", "(", "el", ".", "value", ")", ";", "}", "break", ";", "case", "'hidden'", ":", "case", "'password'", ":", "case", "'text'", ":", "if", "(", "retVal", ".", "length", ">", "0", ")", "{", "retVal", "+=", "'&'", ";", "}", "retVal", "+=", "el", ".", "name", "+", "'='", "+", "encodeURIComponent", "(", "el", ".", "value", ")", ";", "break", ";", "}", "break", ";", "case", "'select'", ":", "case", "'textarea'", ":", "if", "(", "retVal", ".", "length", ">", "0", ")", "{", "retVal", "+=", "'&'", ";", "}", "retVal", "+=", "el", ".", "name", "+", "'='", "+", "encodeURIComponent", "(", "el", ".", "value", ")", ";", "break", ";", "}", "}", "}", "return", "retVal", ";", "}" ]
Serializes sub children of the current node into post data
[ "Serializes", "sub", "children", "of", "the", "current", "node", "into", "post", "data" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L347-L392
train
nwtjs/nwt
src/node/js/node.js
function(method, criteria) { // Iterate on the raw node var node = this._node, // Method to iterate on siblingType = method + 'Sibling', // Filter to test the node filter, validItems; // CSS Selector case if (typeof criteria == "string") { validItems = n.all(criteria); filter = function(rawNode) { var found = false; validItems.each(function(el){ if (rawNode == el._node) { found = true; } }); return found; }; // Default the filter to return true } else if (!criteria) { filter = function(){ return true } } else { filter = function(rawEl) { return criteria(new NWTNodeInstance(rawEl)); } } while(node) { node = node[siblingType]; if (node && node.nodeType == 1 && filter(node)) { break; } } return node ? new NWTNodeInstance(node) : null; }
javascript
function(method, criteria) { // Iterate on the raw node var node = this._node, // Method to iterate on siblingType = method + 'Sibling', // Filter to test the node filter, validItems; // CSS Selector case if (typeof criteria == "string") { validItems = n.all(criteria); filter = function(rawNode) { var found = false; validItems.each(function(el){ if (rawNode == el._node) { found = true; } }); return found; }; // Default the filter to return true } else if (!criteria) { filter = function(){ return true } } else { filter = function(rawEl) { return criteria(new NWTNodeInstance(rawEl)); } } while(node) { node = node[siblingType]; if (node && node.nodeType == 1 && filter(node)) { break; } } return node ? new NWTNodeInstance(node) : null; }
[ "function", "(", "method", ",", "criteria", ")", "{", "var", "node", "=", "this", ".", "_node", ",", "siblingType", "=", "method", "+", "'Sibling'", ",", "filter", ",", "validItems", ";", "if", "(", "typeof", "criteria", "==", "\"string\"", ")", "{", "validItems", "=", "n", ".", "all", "(", "criteria", ")", ";", "filter", "=", "function", "(", "rawNode", ")", "{", "var", "found", "=", "false", ";", "validItems", ".", "each", "(", "function", "(", "el", ")", "{", "if", "(", "rawNode", "==", "el", ".", "_node", ")", "{", "found", "=", "true", ";", "}", "}", ")", ";", "return", "found", ";", "}", ";", "}", "else", "if", "(", "!", "criteria", ")", "{", "filter", "=", "function", "(", ")", "{", "return", "true", "}", "}", "else", "{", "filter", "=", "function", "(", "rawEl", ")", "{", "return", "criteria", "(", "new", "NWTNodeInstance", "(", "rawEl", ")", ")", ";", "}", "}", "while", "(", "node", ")", "{", "node", "=", "node", "[", "siblingType", "]", ";", "if", "(", "node", "&&", "node", ".", "nodeType", "==", "1", "&&", "filter", "(", "node", ")", ")", "{", "break", ";", "}", "}", "return", "node", "?", "new", "NWTNodeInstance", "(", "node", ")", ":", "null", ";", "}" ]
Finds a node based on direction @param string Native method to iterate nodes {previous | next} @param string criteria CSS selector or Filtering function
[ "Finds", "a", "node", "based", "on", "direction" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L469-L513
train
nwtjs/nwt
src/node/js/node.js
function(node) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.append(this); return this; }
javascript
function(node) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.append(this); return this; }
[ "function", "(", "node", ")", "{", "var", "newParent", "=", "(", "node", "instanceof", "NWTNodeInstance", ")", "?", "node", ":", "localnwt", ".", "one", "(", "node", ")", ";", "newParent", ".", "append", "(", "this", ")", ";", "return", "this", ";", "}" ]
Appends the current node to another node @param {string|object} Either a CSS selector, or node instance @return object The node that we appended the current node to
[ "Appends", "the", "current", "node", "to", "another", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L572-L579
train
nwtjs/nwt
src/node/js/node.js
function(node) { if( node instanceof NWTNodeInstance ) { node = node._node; } var child = this.one('*'); this._node.insertBefore(node, (child._node? child._node : null)); return this; }
javascript
function(node) { if( node instanceof NWTNodeInstance ) { node = node._node; } var child = this.one('*'); this._node.insertBefore(node, (child._node? child._node : null)); return this; }
[ "function", "(", "node", ")", "{", "if", "(", "node", "instanceof", "NWTNodeInstance", ")", "{", "node", "=", "node", ".", "_node", ";", "}", "var", "child", "=", "this", ".", "one", "(", "'*'", ")", ";", "this", ".", "_node", ".", "insertBefore", "(", "node", ",", "(", "child", ".", "_node", "?", "child", ".", "_node", ":", "null", ")", ")", ";", "return", "this", ";", "}" ]
Prepends a node to the beginning of the children of this node
[ "Prepends", "a", "node", "to", "the", "beginning", "of", "the", "children", "of", "this", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L585-L596
train
nwtjs/nwt
src/node/js/node.js
function(node, position) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.insert(this, position); return this; }
javascript
function(node, position) { var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node); newParent.insert(this, position); return this; }
[ "function", "(", "node", ",", "position", ")", "{", "var", "newParent", "=", "(", "node", "instanceof", "NWTNodeInstance", ")", "?", "node", ":", "localnwt", ".", "one", "(", "node", ")", ";", "newParent", ".", "insert", "(", "this", ",", "position", ")", ";", "return", "this", ";", "}" ]
Inserts the current node into another node @param {string|object} Either a CSS selector, or node instance @param string Position to insert at. Defaults to 'before' @return object The node that we inserted the current node into
[ "Inserts", "the", "current", "node", "into", "another", "node" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L605-L612
train
nwtjs/nwt
src/node/js/node.js
function(node, position) { position = position || 'before'; if( position == 'before' ) { this._node.parentNode.insertBefore(node._node, this._node); } else if ( position == 'after' ) { this._node.parentNode.insertBefore(node._node, this.next() ? this.next()._node : null); } }
javascript
function(node, position) { position = position || 'before'; if( position == 'before' ) { this._node.parentNode.insertBefore(node._node, this._node); } else if ( position == 'after' ) { this._node.parentNode.insertBefore(node._node, this.next() ? this.next()._node : null); } }
[ "function", "(", "node", ",", "position", ")", "{", "position", "=", "position", "||", "'before'", ";", "if", "(", "position", "==", "'before'", ")", "{", "this", ".", "_node", ".", "parentNode", ".", "insertBefore", "(", "node", ".", "_node", ",", "this", ".", "_node", ")", ";", "}", "else", "if", "(", "position", "==", "'after'", ")", "{", "this", ".", "_node", ".", "parentNode", ".", "insertBefore", "(", "node", ".", "_node", ",", "this", ".", "next", "(", ")", "?", "this", ".", "next", "(", ")", ".", "_node", ":", "null", ")", ";", "}", "}" ]
Inserts a given node into this node at the proper position
[ "Inserts", "a", "given", "node", "into", "this", "node", "at", "the", "proper", "position" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L626-L634
train
nwtjs/nwt
src/node/js/node.js
function(event, fn, selector, context) { return localnwt.event.on(this, event, fn, selector,context); }
javascript
function(event, fn, selector, context) { return localnwt.event.on(this, event, fn, selector,context); }
[ "function", "(", "event", ",", "fn", ",", "selector", ",", "context", ")", "{", "return", "localnwt", ".", "event", ".", "on", "(", "this", ",", "event", ",", "fn", ",", "selector", ",", "context", ")", ";", "}" ]
Implement a node API to for event listeners @see NWTEvent::on
[ "Implement", "a", "node", "API", "to", "for", "event", "listeners" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L665-L667
train
nwtjs/nwt
src/node/js/node.js
function(type, callback, recurse) { var evt = localnwt.event; for (var i in evt._cached) { for(var j=0,numCbs=evt._cached[i].length; j < numCbs; j++) { var thisEvt = evt._cached[i][j]; if (this._node == thisEvt.obj._node && (!type || type == thisEvt.type)) { evt.off(thisEvt.obj, thisEvt.type, thisEvt.raw) } } } if (recurse) { this.all('*').each(function(el){ el.purge(type, callback, recurse); }) } }
javascript
function(type, callback, recurse) { var evt = localnwt.event; for (var i in evt._cached) { for(var j=0,numCbs=evt._cached[i].length; j < numCbs; j++) { var thisEvt = evt._cached[i][j]; if (this._node == thisEvt.obj._node && (!type || type == thisEvt.type)) { evt.off(thisEvt.obj, thisEvt.type, thisEvt.raw) } } } if (recurse) { this.all('*').each(function(el){ el.purge(type, callback, recurse); }) } }
[ "function", "(", "type", ",", "callback", ",", "recurse", ")", "{", "var", "evt", "=", "localnwt", ".", "event", ";", "for", "(", "var", "i", "in", "evt", ".", "_cached", ")", "{", "for", "(", "var", "j", "=", "0", ",", "numCbs", "=", "evt", ".", "_cached", "[", "i", "]", ".", "length", ";", "j", "<", "numCbs", ";", "j", "++", ")", "{", "var", "thisEvt", "=", "evt", ".", "_cached", "[", "i", "]", "[", "j", "]", ";", "if", "(", "this", ".", "_node", "==", "thisEvt", ".", "obj", ".", "_node", "&&", "(", "!", "type", "||", "type", "==", "thisEvt", ".", "type", ")", ")", "{", "evt", ".", "off", "(", "thisEvt", ".", "obj", ",", "thisEvt", ".", "type", ",", "thisEvt", ".", "raw", ")", "}", "}", "}", "if", "(", "recurse", ")", "{", "this", ".", "all", "(", "'*'", ")", ".", "each", "(", "function", "(", "el", ")", "{", "el", ".", "purge", "(", "type", ",", "callback", ",", "recurse", ")", ";", "}", ")", "}", "}" ]
Purges a node of all listeners @param string If passed, only purges this type of listener @param function If passed, only purges the node of this listener @param bool If true, purges children
[ "Purges", "a", "node", "of", "all", "listeners" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L694-L711
train
nwtjs/nwt
src/node/js/node.js
function(styles, duration, easing, pushState) { if (!pushState) { var styleAttrs = [], defaultStyles, animHistory, i for (i in styles) { styleAttrs.push(i) } defaultStyles = this.computeCss(styleAttrs) animHistory = { from: [defaultStyles, duration, easing, true /* This makes it so we do not push this again */], to: [styles, duration, easing] } fxObj[this.uuid()] = animHistory this.fire('anim:push', animHistory) } return localnwt.anim(this, styles, duration, easing); }
javascript
function(styles, duration, easing, pushState) { if (!pushState) { var styleAttrs = [], defaultStyles, animHistory, i for (i in styles) { styleAttrs.push(i) } defaultStyles = this.computeCss(styleAttrs) animHistory = { from: [defaultStyles, duration, easing, true /* This makes it so we do not push this again */], to: [styles, duration, easing] } fxObj[this.uuid()] = animHistory this.fire('anim:push', animHistory) } return localnwt.anim(this, styles, duration, easing); }
[ "function", "(", "styles", ",", "duration", ",", "easing", ",", "pushState", ")", "{", "if", "(", "!", "pushState", ")", "{", "var", "styleAttrs", "=", "[", "]", ",", "defaultStyles", ",", "animHistory", ",", "i", "for", "(", "i", "in", "styles", ")", "{", "styleAttrs", ".", "push", "(", "i", ")", "}", "defaultStyles", "=", "this", ".", "computeCss", "(", "styleAttrs", ")", "animHistory", "=", "{", "from", ":", "[", "defaultStyles", ",", "duration", ",", "easing", ",", "true", "]", ",", "to", ":", "[", "styles", ",", "duration", ",", "easing", "]", "}", "fxObj", "[", "this", ".", "uuid", "(", ")", "]", "=", "animHistory", "this", ".", "fire", "(", "'anim:push'", ",", "animHistory", ")", "}", "return", "localnwt", ".", "anim", "(", "this", ",", "styles", ",", "duration", ",", "easing", ")", ";", "}" ]
Implement a node API to animate Takes an additional argument, pushState which signals whether or not to push this anim state onto fxStack @see NWTAnimate::anin
[ "Implement", "a", "node", "API", "to", "animate", "Takes", "an", "additional", "argument", "pushState", "which", "signals", "whether", "or", "not", "to", "push", "this", "anim", "state", "onto", "fxStack" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L761-L785
train
nwtjs/nwt
src/node/js/node.js
function(plugin, config) { config = config || {}; config.node = this; return localnwt.plugin(plugin, config); }
javascript
function(plugin, config) { config = config || {}; config.node = this; return localnwt.plugin(plugin, config); }
[ "function", "(", "plugin", ",", "config", ")", "{", "config", "=", "config", "||", "{", "}", ";", "config", ".", "node", "=", "this", ";", "return", "localnwt", ".", "plugin", "(", "plugin", ",", "config", ")", ";", "}" ]
Implement a node API for plugins @see localnwt.plugin
[ "Implement", "a", "node", "API", "for", "plugins" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/src/node/js/node.js#L809-L813
train
byron-dupreez/aws-core-utils
arns.js
getArnComponent
function getArnComponent(arn, index) { const components = isNotBlank(arn) ? trim(arn).split(':') : []; return components.length > index ? trimOrEmpty(components[index]) : ''; }
javascript
function getArnComponent(arn, index) { const components = isNotBlank(arn) ? trim(arn).split(':') : []; return components.length > index ? trimOrEmpty(components[index]) : ''; }
[ "function", "getArnComponent", "(", "arn", ",", "index", ")", "{", "const", "components", "=", "isNotBlank", "(", "arn", ")", "?", "trim", "(", "arn", ")", ".", "split", "(", "':'", ")", ":", "[", "]", ";", "return", "components", ".", "length", ">", "index", "?", "trimOrEmpty", "(", "components", "[", "index", "]", ")", ":", "''", ";", "}" ]
Extracts the component at the given index of the given ARN. @param {string} arn the ARN from which to extract the component @param {number} index the index of the ARN component to retrieve @returns {string} the component (if extracted) or empty string (if not)
[ "Extracts", "the", "component", "at", "the", "given", "index", "of", "the", "given", "ARN", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/arns.js#L41-L44
train
byron-dupreez/aws-core-utils
stream-events.js
getKinesisShardIdFromEventID
function getKinesisShardIdFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? eventID.substring(0, sepPos) : ''; } return ''; }
javascript
function getKinesisShardIdFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? eventID.substring(0, sepPos) : ''; } return ''; }
[ "function", "getKinesisShardIdFromEventID", "(", "eventID", ")", "{", "if", "(", "eventID", ")", "{", "const", "sepPos", "=", "eventID", ".", "indexOf", "(", "':'", ")", ";", "return", "sepPos", "!==", "-", "1", "?", "eventID", ".", "substring", "(", "0", ",", "sepPos", ")", ":", "''", ";", "}", "return", "''", ";", "}" ]
Extracts the shard id from the given Kinesis eventID. @param {string} eventID - an eventID from an AWS Kinesis stream event record. @return {string|undefined} the shard id (if any) or an empty string
[ "Extracts", "the", "shard", "id", "from", "the", "given", "Kinesis", "eventID", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L145-L151
train
byron-dupreez/aws-core-utils
stream-events.js
getKinesisShardIdAndEventNoFromEventID
function getKinesisShardIdAndEventNoFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? [eventID.substring(0, sepPos), eventID.substring(sepPos + 1),] : ['', '']; } return ['', '']; }
javascript
function getKinesisShardIdAndEventNoFromEventID(eventID) { if (eventID) { const sepPos = eventID.indexOf(':'); return sepPos !== -1 ? [eventID.substring(0, sepPos), eventID.substring(sepPos + 1),] : ['', '']; } return ['', '']; }
[ "function", "getKinesisShardIdAndEventNoFromEventID", "(", "eventID", ")", "{", "if", "(", "eventID", ")", "{", "const", "sepPos", "=", "eventID", ".", "indexOf", "(", "':'", ")", ";", "return", "sepPos", "!==", "-", "1", "?", "[", "eventID", ".", "substring", "(", "0", ",", "sepPos", ")", ",", "eventID", ".", "substring", "(", "sepPos", "+", "1", ")", ",", "]", ":", "[", "''", ",", "''", "]", ";", "}", "return", "[", "''", ",", "''", "]", ";", "}" ]
Extracts the shard id and event number from the given Kinesis eventID. @param {string} eventID - an eventID from an AWS Kinesis stream event record. @return {[string,string]} an array containing: the shard id (if any) or an empty string; and the event number (if any) or an empty string
[ "Extracts", "the", "shard", "id", "and", "event", "number", "from", "the", "given", "Kinesis", "eventID", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L159-L166
train
byron-dupreez/aws-core-utils
stream-events.js
getKinesisSequenceNumber
function getKinesisSequenceNumber(record) { return record && record.kinesis && record.kinesis.sequenceNumber ? record.kinesis.sequenceNumber : ''; }
javascript
function getKinesisSequenceNumber(record) { return record && record.kinesis && record.kinesis.sequenceNumber ? record.kinesis.sequenceNumber : ''; }
[ "function", "getKinesisSequenceNumber", "(", "record", ")", "{", "return", "record", "&&", "record", ".", "kinesis", "&&", "record", ".", "kinesis", ".", "sequenceNumber", "?", "record", ".", "kinesis", ".", "sequenceNumber", ":", "''", ";", "}" ]
Gets the sequence number from the given Kinesis stream event record. @param {KinesisEventRecord|*} record - a Kinesis stream event record @returns {string} the sequence number (if any) or an empty string
[ "Gets", "the", "sequence", "number", "from", "the", "given", "Kinesis", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L173-L175
train
byron-dupreez/aws-core-utils
stream-events.js
getDynamoDBSequenceNumber
function getDynamoDBSequenceNumber(record) { return record && record.dynamodb && record.dynamodb.SequenceNumber ? record.dynamodb.SequenceNumber : ''; }
javascript
function getDynamoDBSequenceNumber(record) { return record && record.dynamodb && record.dynamodb.SequenceNumber ? record.dynamodb.SequenceNumber : ''; }
[ "function", "getDynamoDBSequenceNumber", "(", "record", ")", "{", "return", "record", "&&", "record", ".", "dynamodb", "&&", "record", ".", "dynamodb", ".", "SequenceNumber", "?", "record", ".", "dynamodb", ".", "SequenceNumber", ":", "''", ";", "}" ]
Returns the sequence number from the given DynamoDB stream event record. @param {DynamoDBEventRecord|*} record - a DynamoDB stream event record @returns {string} the sequence number (if any) or an empty string
[ "Returns", "the", "sequence", "number", "from", "the", "given", "DynamoDB", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L222-L224
train
byron-dupreez/aws-core-utils
stream-events.js
_validateKinesisStreamEventRecord
function _validateKinesisStreamEventRecord(record) { if (!record.kinesis) { throw new Error(`Missing kinesis property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.data) { throw new Error(`Missing data property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.partitionKey) { throw new Error(`Missing partitionKey property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.sequenceNumber) { throw new Error(`Missing sequenceNumber property for Kinesis stream event record (${record.eventID})`); } }
javascript
function _validateKinesisStreamEventRecord(record) { if (!record.kinesis) { throw new Error(`Missing kinesis property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.data) { throw new Error(`Missing data property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.partitionKey) { throw new Error(`Missing partitionKey property for Kinesis stream event record (${record.eventID})`); } if (!record.kinesis.sequenceNumber) { throw new Error(`Missing sequenceNumber property for Kinesis stream event record (${record.eventID})`); } }
[ "function", "_validateKinesisStreamEventRecord", "(", "record", ")", "{", "if", "(", "!", "record", ".", "kinesis", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "kinesis", ".", "data", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "kinesis", ".", "partitionKey", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "kinesis", ".", "sequenceNumber", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "}" ]
Validates the given Kinesis stream event record. @param {KinesisEventRecord|*} record - a Kinesis stream event record @private
[ "Validates", "the", "given", "Kinesis", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L306-L319
train
byron-dupreez/aws-core-utils
stream-events.js
isDynamoDBEventNameValid
function isDynamoDBEventNameValid(recordOrEventName) { const eventName = recordOrEventName.eventName ? recordOrEventName.eventName : recordOrEventName; return eventName === DynamoDBEventName.INSERT || eventName === DynamoDBEventName.MODIFY || eventName === DynamoDBEventName.REMOVE; }
javascript
function isDynamoDBEventNameValid(recordOrEventName) { const eventName = recordOrEventName.eventName ? recordOrEventName.eventName : recordOrEventName; return eventName === DynamoDBEventName.INSERT || eventName === DynamoDBEventName.MODIFY || eventName === DynamoDBEventName.REMOVE; }
[ "function", "isDynamoDBEventNameValid", "(", "recordOrEventName", ")", "{", "const", "eventName", "=", "recordOrEventName", ".", "eventName", "?", "recordOrEventName", ".", "eventName", ":", "recordOrEventName", ";", "return", "eventName", "===", "DynamoDBEventName", ".", "INSERT", "||", "eventName", "===", "DynamoDBEventName", ".", "MODIFY", "||", "eventName", "===", "DynamoDBEventName", ".", "REMOVE", ";", "}" ]
Returns true if the given DynamoDB event name OR given DynamoDB stream event record's eventName is valid; false otherwise @param {string|DynamoDBEventRecord} recordOrEventName - a DynamoDB event name OR DynamoDB stream event record @returns {boolean} true if valid; false otherwise
[ "Returns", "true", "if", "the", "given", "DynamoDB", "event", "name", "OR", "given", "DynamoDB", "stream", "event", "record", "s", "eventName", "is", "valid", ";", "false", "otherwise" ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L345-L348
train
byron-dupreez/aws-core-utils
stream-events.js
_validateDynamoDBStreamEventRecord
function _validateDynamoDBStreamEventRecord(record) { if (!isDynamoDBEventNameValid(record)) { throw new Error(`Invalid eventName property (${record.eventName}) for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb) { throw new Error(`Missing dynamodb property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.Keys) { throw new Error(`Missing Keys property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.SequenceNumber) { throw new Error(`Missing SequenceNumber property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.StreamViewType) { throw new Error(`Missing StreamViewType property for DynamoDB stream event record (${record.eventID})`); } switch (record.dynamodb.StreamViewType) { case 'KEYS_ONLY': break; case 'NEW_IMAGE': if (!record.dynamodb.NewImage && record.eventName !== 'REMOVE') { throw new Error(`Missing NewImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'OLD_IMAGE': if (!record.dynamodb.OldImage && record.eventName !== 'INSERT') { throw new Error(`Missing OldImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'NEW_AND_OLD_IMAGES': if ((!record.dynamodb.NewImage && record.eventName !== 'REMOVE') || (!record.dynamodb.OldImage && record.eventName !== 'INSERT')) { throw new Error(`Missing both NewImage and OldImage properties for DynamoDB stream event record (${record.eventID})`); } break; default: throw new Error(`Unexpected StreamViewType (${record.dynamodb.StreamViewType}) on DynamoDB stream event record (${record.eventID})`); } }
javascript
function _validateDynamoDBStreamEventRecord(record) { if (!isDynamoDBEventNameValid(record)) { throw new Error(`Invalid eventName property (${record.eventName}) for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb) { throw new Error(`Missing dynamodb property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.Keys) { throw new Error(`Missing Keys property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.SequenceNumber) { throw new Error(`Missing SequenceNumber property for DynamoDB stream event record (${record.eventID})`); } if (!record.dynamodb.StreamViewType) { throw new Error(`Missing StreamViewType property for DynamoDB stream event record (${record.eventID})`); } switch (record.dynamodb.StreamViewType) { case 'KEYS_ONLY': break; case 'NEW_IMAGE': if (!record.dynamodb.NewImage && record.eventName !== 'REMOVE') { throw new Error(`Missing NewImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'OLD_IMAGE': if (!record.dynamodb.OldImage && record.eventName !== 'INSERT') { throw new Error(`Missing OldImage property for DynamoDB stream event record (${record.eventID})`); } break; case 'NEW_AND_OLD_IMAGES': if ((!record.dynamodb.NewImage && record.eventName !== 'REMOVE') || (!record.dynamodb.OldImage && record.eventName !== 'INSERT')) { throw new Error(`Missing both NewImage and OldImage properties for DynamoDB stream event record (${record.eventID})`); } break; default: throw new Error(`Unexpected StreamViewType (${record.dynamodb.StreamViewType}) on DynamoDB stream event record (${record.eventID})`); } }
[ "function", "_validateDynamoDBStreamEventRecord", "(", "record", ")", "{", "if", "(", "!", "isDynamoDBEventNameValid", "(", "record", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventName", "}", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ".", "Keys", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ".", "SequenceNumber", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "if", "(", "!", "record", ".", "dynamodb", ".", "StreamViewType", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "switch", "(", "record", ".", "dynamodb", ".", "StreamViewType", ")", "{", "case", "'KEYS_ONLY'", ":", "break", ";", "case", "'NEW_IMAGE'", ":", "if", "(", "!", "record", ".", "dynamodb", ".", "NewImage", "&&", "record", ".", "eventName", "!==", "'REMOVE'", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "break", ";", "case", "'OLD_IMAGE'", ":", "if", "(", "!", "record", ".", "dynamodb", ".", "OldImage", "&&", "record", ".", "eventName", "!==", "'INSERT'", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "break", ";", "case", "'NEW_AND_OLD_IMAGES'", ":", "if", "(", "(", "!", "record", ".", "dynamodb", ".", "NewImage", "&&", "record", ".", "eventName", "!==", "'REMOVE'", ")", "||", "(", "!", "record", ".", "dynamodb", ".", "OldImage", "&&", "record", ".", "eventName", "!==", "'INSERT'", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "break", ";", "default", ":", "throw", "new", "Error", "(", "`", "${", "record", ".", "dynamodb", ".", "StreamViewType", "}", "${", "record", ".", "eventID", "}", "`", ")", ";", "}", "}" ]
Validates the given DynamoDB stream event record. @param {DynamoDBEventRecord|*} record - a DynamoDB stream event record @private
[ "Validates", "the", "given", "DynamoDB", "stream", "event", "record", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/stream-events.js#L355-L396
train
Streampunk/sevruga
index.js
createRenderStream
function createRenderStream(params) { return new Transform({ decodeStrings: params.decodeStrings || false, highWaterMark: params.highwaterMark || 16384, transform(svgStr, encoding, cb) { const renderBuf = Buffer.alloc(params.width * params.height * 4); // ARGB 8-bit per component addon.renderSVG(svgStr, renderBuf, params) .then(t => { renderBuf.timings = t; cb(null, renderBuf); }) .catch(cb); } }); }
javascript
function createRenderStream(params) { return new Transform({ decodeStrings: params.decodeStrings || false, highWaterMark: params.highwaterMark || 16384, transform(svgStr, encoding, cb) { const renderBuf = Buffer.alloc(params.width * params.height * 4); // ARGB 8-bit per component addon.renderSVG(svgStr, renderBuf, params) .then(t => { renderBuf.timings = t; cb(null, renderBuf); }) .catch(cb); } }); }
[ "function", "createRenderStream", "(", "params", ")", "{", "return", "new", "Transform", "(", "{", "decodeStrings", ":", "params", ".", "decodeStrings", "||", "false", ",", "highWaterMark", ":", "params", ".", "highwaterMark", "||", "16384", ",", "transform", "(", "svgStr", ",", "encoding", ",", "cb", ")", "{", "const", "renderBuf", "=", "Buffer", ".", "alloc", "(", "params", ".", "width", "*", "params", ".", "height", "*", "4", ")", ";", "addon", ".", "renderSVG", "(", "svgStr", ",", "renderBuf", ",", "params", ")", ".", "then", "(", "t", "=>", "{", "renderBuf", ".", "timings", "=", "t", ";", "cb", "(", "null", ",", "renderBuf", ")", ";", "}", ")", ".", "catch", "(", "cb", ")", ";", "}", "}", ")", ";", "}" ]
With no argument, SegfaultHandler will generate a generic log file name
[ "With", "no", "argument", "SegfaultHandler", "will", "generate", "a", "generic", "log", "file", "name" ]
f1bac605763f8025e836f5388cb8d034a78cc65d
https://github.com/Streampunk/sevruga/blob/f1bac605763f8025e836f5388cb8d034a78cc65d/index.js#L22-L36
train
ReedD/node-assetmanager
index.js
function (patterns) { // External restources have to be 1:1 dest to src, both strings // Check for external first, otherwise expand the pattern if (!_.isArray(patterns)) { if (isExternal(patterns)) { return [patterns]; } patterns = [patterns]; } return grunt.file.expand({filter: 'isFile'}, patterns); }
javascript
function (patterns) { // External restources have to be 1:1 dest to src, both strings // Check for external first, otherwise expand the pattern if (!_.isArray(patterns)) { if (isExternal(patterns)) { return [patterns]; } patterns = [patterns]; } return grunt.file.expand({filter: 'isFile'}, patterns); }
[ "function", "(", "patterns", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "patterns", ")", ")", "{", "if", "(", "isExternal", "(", "patterns", ")", ")", "{", "return", "[", "patterns", "]", ";", "}", "patterns", "=", "[", "patterns", "]", ";", "}", "return", "grunt", ".", "file", ".", "expand", "(", "{", "filter", ":", "'isFile'", "}", ",", "patterns", ")", ";", "}" ]
Get assets from pattern. Pattern could be - an array - a string - external resource @param patterns
[ "Get", "assets", "from", "pattern", ".", "Pattern", "could", "be", "-", "an", "array", "-", "a", "string", "-", "external", "resource" ]
f25aab34554a98abe0d0eb0f1262444aaef8e056
https://github.com/ReedD/node-assetmanager/blob/f25aab34554a98abe0d0eb0f1262444aaef8e056/index.js#L45-L57
train
ReedD/node-assetmanager
index.js
function(files) { var regex; if (options.webroot instanceof RegExp) { regex = options.webroot; } else { regex = new RegExp('^' + options.webroot); } _.each(files, function (value, key) { files[key] = value.replace(regex, ''); }); return files; }
javascript
function(files) { var regex; if (options.webroot instanceof RegExp) { regex = options.webroot; } else { regex = new RegExp('^' + options.webroot); } _.each(files, function (value, key) { files[key] = value.replace(regex, ''); }); return files; }
[ "function", "(", "files", ")", "{", "var", "regex", ";", "if", "(", "options", ".", "webroot", "instanceof", "RegExp", ")", "{", "regex", "=", "options", ".", "webroot", ";", "}", "else", "{", "regex", "=", "new", "RegExp", "(", "'^'", "+", "options", ".", "webroot", ")", ";", "}", "_", ".", "each", "(", "files", ",", "function", "(", "value", ",", "key", ")", "{", "files", "[", "key", "]", "=", "value", ".", "replace", "(", "regex", ",", "''", ")", ";", "}", ")", ";", "return", "files", ";", "}" ]
Strip server path from from file path so that the file path is relative to the webroot @param array files @return array files clean filenames
[ "Strip", "server", "path", "from", "from", "file", "path", "so", "that", "the", "file", "path", "is", "relative", "to", "the", "webroot" ]
f25aab34554a98abe0d0eb0f1262444aaef8e056
https://github.com/ReedD/node-assetmanager/blob/f25aab34554a98abe0d0eb0f1262444aaef8e056/index.js#L66-L77
train
ReedD/node-assetmanager
index.js
md5
function md5(files) { var hash = crypto.createHash('md5'); _.each(files, function(file) { if (!isExternal(file)) hash.update(grunt.file.read(file), 'utf-8'); }); return hash.digest('hex'); }
javascript
function md5(files) { var hash = crypto.createHash('md5'); _.each(files, function(file) { if (!isExternal(file)) hash.update(grunt.file.read(file), 'utf-8'); }); return hash.digest('hex'); }
[ "function", "md5", "(", "files", ")", "{", "var", "hash", "=", "crypto", ".", "createHash", "(", "'md5'", ")", ";", "_", ".", "each", "(", "files", ",", "function", "(", "file", ")", "{", "if", "(", "!", "isExternal", "(", "file", ")", ")", "hash", ".", "update", "(", "grunt", ".", "file", ".", "read", "(", "file", ")", ",", "'utf-8'", ")", ";", "}", ")", ";", "return", "hash", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Computes an MD5 digest of given files. @param array files @return MD5 hash (hex-encoded)
[ "Computes", "an", "MD5", "digest", "of", "given", "files", "." ]
f25aab34554a98abe0d0eb0f1262444aaef8e056
https://github.com/ReedD/node-assetmanager/blob/f25aab34554a98abe0d0eb0f1262444aaef8e056/index.js#L85-L92
train
KevinGrandon/sparky
index.js
function(command, callback) { command = 'curl https://api.spark.io/v1/devices/' + this.config.deviceId + '/' + command + '?access_token=' + this.config.token; this.debug('Running command: ', command); child = exec(command, function (error, stdout, stderr) { this.debug('stdout: ' + stdout); this.debug('stderr: ' + stderr); if (error !== null) { this.debug('exec error: ' + error); } if (callback) { try { callback(JSON.parse(stdout)); } catch (err) { callback(undefined); } } }.bind(this)); }
javascript
function(command, callback) { command = 'curl https://api.spark.io/v1/devices/' + this.config.deviceId + '/' + command + '?access_token=' + this.config.token; this.debug('Running command: ', command); child = exec(command, function (error, stdout, stderr) { this.debug('stdout: ' + stdout); this.debug('stderr: ' + stderr); if (error !== null) { this.debug('exec error: ' + error); } if (callback) { try { callback(JSON.parse(stdout)); } catch (err) { callback(undefined); } } }.bind(this)); }
[ "function", "(", "command", ",", "callback", ")", "{", "command", "=", "'curl https://api.spark.io/v1/devices/'", "+", "this", ".", "config", ".", "deviceId", "+", "'/'", "+", "command", "+", "'?access_token='", "+", "this", ".", "config", ".", "token", ";", "this", ".", "debug", "(", "'Running command: '", ",", "command", ")", ";", "child", "=", "exec", "(", "command", ",", "function", "(", "error", ",", "stdout", ",", "stderr", ")", "{", "this", ".", "debug", "(", "'stdout: '", "+", "stdout", ")", ";", "this", ".", "debug", "(", "'stderr: '", "+", "stderr", ")", ";", "if", "(", "error", "!==", "null", ")", "{", "this", ".", "debug", "(", "'exec error: '", "+", "error", ")", ";", "}", "if", "(", "callback", ")", "{", "try", "{", "callback", "(", "JSON", ".", "parse", "(", "stdout", ")", ")", ";", "}", "catch", "(", "err", ")", "{", "callback", "(", "undefined", ")", ";", "}", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "}" ]
Gets a variable from the spark core
[ "Gets", "a", "variable", "from", "the", "spark", "core" ]
b91cbcc0946daf0fe7d39ff14741cfc950b204ac
https://github.com/KevinGrandon/sparky/blob/b91cbcc0946daf0fe7d39ff14741cfc950b204ac/index.js#L119-L138
train
segmentio/isodate-traverse
lib/index.js
traverse
function traverse(input, strict) { if (strict === undefined) strict = true; if (type(input) === 'object') { return traverseObject(input, strict); } else if (type(input) === 'array') { return traverseArray(input, strict); } else if (isodate.is(input, strict)) { return isodate.parse(input); } return input; }
javascript
function traverse(input, strict) { if (strict === undefined) strict = true; if (type(input) === 'object') { return traverseObject(input, strict); } else if (type(input) === 'array') { return traverseArray(input, strict); } else if (isodate.is(input, strict)) { return isodate.parse(input); } return input; }
[ "function", "traverse", "(", "input", ",", "strict", ")", "{", "if", "(", "strict", "===", "undefined", ")", "strict", "=", "true", ";", "if", "(", "type", "(", "input", ")", "===", "'object'", ")", "{", "return", "traverseObject", "(", "input", ",", "strict", ")", ";", "}", "else", "if", "(", "type", "(", "input", ")", "===", "'array'", ")", "{", "return", "traverseArray", "(", "input", ",", "strict", ")", ";", "}", "else", "if", "(", "isodate", ".", "is", "(", "input", ",", "strict", ")", ")", "{", "return", "isodate", ".", "parse", "(", "input", ")", ";", "}", "return", "input", ";", "}" ]
Recursively traverse an object or array, and convert all ISO date strings parse into Date objects. @param {Object} input - object, array, or string to convert @param {Boolean} strict - only convert strings with year, month, and date @return {Object}
[ "Recursively", "traverse", "an", "object", "or", "array", "and", "convert", "all", "ISO", "date", "strings", "parse", "into", "Date", "objects", "." ]
ae4025aaae6b0acdb957ca31aeda9518767dc8b0
https://github.com/segmentio/isodate-traverse/blob/ae4025aaae6b0acdb957ca31aeda9518767dc8b0/lib/index.js#L19-L29
train
segmentio/isodate-traverse
lib/index.js
traverseObject
function traverseObject(obj, strict) { Object.keys(obj).forEach(function(key) { obj[key] = traverse(obj[key], strict); }); return obj; }
javascript
function traverseObject(obj, strict) { Object.keys(obj).forEach(function(key) { obj[key] = traverse(obj[key], strict); }); return obj; }
[ "function", "traverseObject", "(", "obj", ",", "strict", ")", "{", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "obj", "[", "key", "]", "=", "traverse", "(", "obj", "[", "key", "]", ",", "strict", ")", ";", "}", ")", ";", "return", "obj", ";", "}" ]
Object traverser helper function. @param {Object} obj - object to traverse @param {Boolean} strict - only convert strings with year, month, and date @return {Object}
[ "Object", "traverser", "helper", "function", "." ]
ae4025aaae6b0acdb957ca31aeda9518767dc8b0
https://github.com/segmentio/isodate-traverse/blob/ae4025aaae6b0acdb957ca31aeda9518767dc8b0/lib/index.js#L38-L43
train
segmentio/isodate-traverse
lib/index.js
traverseArray
function traverseArray(arr, strict) { arr.forEach(function(value, index) { arr[index] = traverse(value, strict); }); return arr; }
javascript
function traverseArray(arr, strict) { arr.forEach(function(value, index) { arr[index] = traverse(value, strict); }); return arr; }
[ "function", "traverseArray", "(", "arr", ",", "strict", ")", "{", "arr", ".", "forEach", "(", "function", "(", "value", ",", "index", ")", "{", "arr", "[", "index", "]", "=", "traverse", "(", "value", ",", "strict", ")", ";", "}", ")", ";", "return", "arr", ";", "}" ]
Array traverser helper function @param {Array} arr - array to traverse @param {Boolean} strict - only convert strings with year, month, and date @return {Array}
[ "Array", "traverser", "helper", "function" ]
ae4025aaae6b0acdb957ca31aeda9518767dc8b0
https://github.com/segmentio/isodate-traverse/blob/ae4025aaae6b0acdb957ca31aeda9518767dc8b0/lib/index.js#L52-L57
train
nwtjs/nwt
plugins/bootstrap/datatable.js
standardizeCols
function standardizeCols(columns) { /** * Gets the default column name */ function getDefaultFormatter(colName) { return function(o) { return o[colName]; }; } /** * Gets the default column sorter */ function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; } for (var i in columns) { var column = columns[i]; if (typeof column == "string") { column = {name: column}; } column.dir = column.sortDir || 'asc'; column.formatter = column.formatter || getDefaultFormatter(column.key || column.name); column.sorter = column.sorter || getDefaultSorter(column.key || column.name); columns[i] = column; } return columns; }
javascript
function standardizeCols(columns) { /** * Gets the default column name */ function getDefaultFormatter(colName) { return function(o) { return o[colName]; }; } /** * Gets the default column sorter */ function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; } for (var i in columns) { var column = columns[i]; if (typeof column == "string") { column = {name: column}; } column.dir = column.sortDir || 'asc'; column.formatter = column.formatter || getDefaultFormatter(column.key || column.name); column.sorter = column.sorter || getDefaultSorter(column.key || column.name); columns[i] = column; } return columns; }
[ "function", "standardizeCols", "(", "columns", ")", "{", "function", "getDefaultFormatter", "(", "colName", ")", "{", "return", "function", "(", "o", ")", "{", "return", "o", "[", "colName", "]", ";", "}", ";", "}", "function", "getDefaultSorter", "(", "colName", ")", "{", "return", "function", "(", "a", ",", "b", ",", "dir", ")", "{", "var", "firstRec", "=", "dir", "==", "'asc'", "?", "a", ":", "b", ",", "secondRec", "=", "dir", "==", "'asc'", "?", "b", ":", "a", ",", "fA", "=", "firstRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ",", "fB", "=", "secondRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "fA", "<", "fB", ")", "return", "-", "1", "if", "(", "fA", ">", "fB", ")", "return", "+", "1", "return", "0", "}", ";", "}", "for", "(", "var", "i", "in", "columns", ")", "{", "var", "column", "=", "columns", "[", "i", "]", ";", "if", "(", "typeof", "column", "==", "\"string\"", ")", "{", "column", "=", "{", "name", ":", "column", "}", ";", "}", "column", ".", "dir", "=", "column", ".", "sortDir", "||", "'asc'", ";", "column", ".", "formatter", "=", "column", ".", "formatter", "||", "getDefaultFormatter", "(", "column", ".", "key", "||", "column", ".", "name", ")", ";", "column", ".", "sorter", "=", "column", ".", "sorter", "||", "getDefaultSorter", "(", "column", ".", "key", "||", "column", ".", "name", ")", ";", "columns", "[", "i", "]", "=", "column", ";", "}", "return", "columns", ";", "}" ]
Standardizes the column definitions E.g., if the user passes a string for a column def, fill out the defaults
[ "Standardizes", "the", "column", "definitions", "E", ".", "g", ".", "if", "the", "user", "passes", "a", "string", "for", "a", "column", "def", "fill", "out", "the", "defaults" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L18-L64
train
nwtjs/nwt
plugins/bootstrap/datatable.js
getDefaultSorter
function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; }
javascript
function getDefaultSorter(colName) { return function(a, b, dir){ var firstRec = dir == 'asc' ? a : b, secondRec = dir == 'asc' ? b : a, fA = firstRec[colName].toLowerCase(), fB = secondRec[colName].toLowerCase(); // Handle numbers if (fA<fB) return -1 if (fA>fB) return +1 return 0 }; }
[ "function", "getDefaultSorter", "(", "colName", ")", "{", "return", "function", "(", "a", ",", "b", ",", "dir", ")", "{", "var", "firstRec", "=", "dir", "==", "'asc'", "?", "a", ":", "b", ",", "secondRec", "=", "dir", "==", "'asc'", "?", "b", ":", "a", ",", "fA", "=", "firstRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ",", "fB", "=", "secondRec", "[", "colName", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "fA", "<", "fB", ")", "return", "-", "1", "if", "(", "fA", ">", "fB", ")", "return", "+", "1", "return", "0", "}", ";", "}" ]
Gets the default column sorter
[ "Gets", "the", "default", "column", "sorter" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L32-L47
train
nwtjs/nwt
plugins/bootstrap/datatable.js
JSONDataSource
function JSONDataSource(config) { // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 this.data = config.data; this.columns = standardizeCols(config.columns); }
javascript
function JSONDataSource(config) { // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 this.data = config.data; this.columns = standardizeCols(config.columns); }
[ "function", "JSONDataSource", "(", "config", ")", "{", "this", ".", "colSortIdx", "=", "config", ".", "defaultSortCol", "||", "-", "1", "this", ".", "data", "=", "config", ".", "data", ";", "this", ".", "columns", "=", "standardizeCols", "(", "config", ".", "columns", ")", ";", "}" ]
Datasource from a local JSON object
[ "Datasource", "from", "a", "local", "JSON", "object" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L70-L76
train
nwtjs/nwt
plugins/bootstrap/datatable.js
IODataSource
function IODataSource(config) { this.columns = standardizeCols(config.columns); this.io = config.data; this.node = config.node; this.fetch = config.fetch || function(io, sort, dir) { io.post('sort=' + sort + '&dir=' + dir); } // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 }
javascript
function IODataSource(config) { this.columns = standardizeCols(config.columns); this.io = config.data; this.node = config.node; this.fetch = config.fetch || function(io, sort, dir) { io.post('sort=' + sort + '&dir=' + dir); } // Default to the first col ASC for sorting this.colSortIdx = config.defaultSortCol || -1 }
[ "function", "IODataSource", "(", "config", ")", "{", "this", ".", "columns", "=", "standardizeCols", "(", "config", ".", "columns", ")", ";", "this", ".", "io", "=", "config", ".", "data", ";", "this", ".", "node", "=", "config", ".", "node", ";", "this", ".", "fetch", "=", "config", ".", "fetch", "||", "function", "(", "io", ",", "sort", ",", "dir", ")", "{", "io", ".", "post", "(", "'sort='", "+", "sort", "+", "'&dir='", "+", "dir", ")", ";", "}", "this", ".", "colSortIdx", "=", "config", ".", "defaultSortCol", "||", "-", "1", "}" ]
Datasource from a remote IO source
[ "Datasource", "from", "a", "remote", "IO", "source" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L97-L108
train
nwtjs/nwt
plugins/bootstrap/datatable.js
ElementDataSource
function ElementDataSource(config) { var newData = [], newColumns = []; var headings = config.data.all('tr th'); headings.each(function(th){ newColumns.push(th.getHtml()); }); config.data.all('tr').each(function(tr){ var newRow = {}, populated = false; for (var i = 0, numCols = headings.size(); i < numCols; i++) { if (!tr.all('td').item(i)) { continue; } newRow[headings.item(i).getHtml()] = tr.all('td').item(i).getHtml(); populated = true; } if (populated) { newData.push(newRow); } }); config.columns = newColumns; config.data = newData; return new JSONDataSource(config); }
javascript
function ElementDataSource(config) { var newData = [], newColumns = []; var headings = config.data.all('tr th'); headings.each(function(th){ newColumns.push(th.getHtml()); }); config.data.all('tr').each(function(tr){ var newRow = {}, populated = false; for (var i = 0, numCols = headings.size(); i < numCols; i++) { if (!tr.all('td').item(i)) { continue; } newRow[headings.item(i).getHtml()] = tr.all('td').item(i).getHtml(); populated = true; } if (populated) { newData.push(newRow); } }); config.columns = newColumns; config.data = newData; return new JSONDataSource(config); }
[ "function", "ElementDataSource", "(", "config", ")", "{", "var", "newData", "=", "[", "]", ",", "newColumns", "=", "[", "]", ";", "var", "headings", "=", "config", ".", "data", ".", "all", "(", "'tr th'", ")", ";", "headings", ".", "each", "(", "function", "(", "th", ")", "{", "newColumns", ".", "push", "(", "th", ".", "getHtml", "(", ")", ")", ";", "}", ")", ";", "config", ".", "data", ".", "all", "(", "'tr'", ")", ".", "each", "(", "function", "(", "tr", ")", "{", "var", "newRow", "=", "{", "}", ",", "populated", "=", "false", ";", "for", "(", "var", "i", "=", "0", ",", "numCols", "=", "headings", ".", "size", "(", ")", ";", "i", "<", "numCols", ";", "i", "++", ")", "{", "if", "(", "!", "tr", ".", "all", "(", "'td'", ")", ".", "item", "(", "i", ")", ")", "{", "continue", ";", "}", "newRow", "[", "headings", ".", "item", "(", "i", ")", ".", "getHtml", "(", ")", "]", "=", "tr", ".", "all", "(", "'td'", ")", ".", "item", "(", "i", ")", ".", "getHtml", "(", ")", ";", "populated", "=", "true", ";", "}", "if", "(", "populated", ")", "{", "newData", ".", "push", "(", "newRow", ")", ";", "}", "}", ")", ";", "config", ".", "columns", "=", "newColumns", ";", "config", ".", "data", "=", "newData", ";", "return", "new", "JSONDataSource", "(", "config", ")", ";", "}" ]
All we do is transform the table into json and reutrn a JSONDataSource
[ "All", "we", "do", "is", "transform", "the", "table", "into", "json", "and", "reutrn", "a", "JSONDataSource" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L129-L160
train
nwtjs/nwt
plugins/bootstrap/datatable.js
function(el) { var mythis = this; this.source.colSortIdx = el.data('col-idx'); this.source.columns[el.data('col-idx')].dir = this.source.columns[el.data('col-idx')].dir == 'asc' ? 'desc' : 'asc'; this.source.update(function() { mythis.render(); }); }
javascript
function(el) { var mythis = this; this.source.colSortIdx = el.data('col-idx'); this.source.columns[el.data('col-idx')].dir = this.source.columns[el.data('col-idx')].dir == 'asc' ? 'desc' : 'asc'; this.source.update(function() { mythis.render(); }); }
[ "function", "(", "el", ")", "{", "var", "mythis", "=", "this", ";", "this", ".", "source", ".", "colSortIdx", "=", "el", ".", "data", "(", "'col-idx'", ")", ";", "this", ".", "source", ".", "columns", "[", "el", ".", "data", "(", "'col-idx'", ")", "]", ".", "dir", "=", "this", ".", "source", ".", "columns", "[", "el", ".", "data", "(", "'col-idx'", ")", "]", ".", "dir", "==", "'asc'", "?", "'desc'", ":", "'asc'", ";", "this", ".", "source", ".", "update", "(", "function", "(", ")", "{", "mythis", ".", "render", "(", ")", ";", "}", ")", ";", "}" ]
Sorts the datatable
[ "Sorts", "the", "datatable" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L236-L245
train
nwtjs/nwt
plugins/bootstrap/datatable.js
function() { var self = this; // Populate table html var content = ['<table class="' + this.tableClass + '" data-instance="' + this.instanceCount + '"><thead>', '<tr>']; for (var i in this.source.columns) { var sortContent = this.source.columns[i].name, colDir = self.source.columns[i].dir; if (self.source.colSortIdx == i) { sortContent = self.formatSortHeader(this.source.columns[i].name, colDir) } content.push('<th class="col-' + i + '"><a data-col-idx="' + i + '" data-sort="sort" href="#" title="' + this.source.columns[i].name +'">' + sortContent + '</a></th>'); } content.push('</tr></thead><tbody>'); for (var i = 0, rows = this.source.data.length; i < rows; i++) { var datum = this.source.data[i]; // Add in a reference to the data dataLookup[this.instanceCount][i] = datum content.push('<tr class="row-' + i + '"">'); for (var j in this.source.columns) { content.push('<td class="col-' + j +'">' + this.source.columns[j].formatter(datum) + '</td>'); } content.push('</tr>'); } content.push('</tbody></table>'); this.node.setHtml(content.join('')); this.node.one('table thead').on('click', function(e) { if (e.target.data('sort')) { self.sort(e.target); self.node.all('th a').item(e.target.data('col-idx'))._node.focus() e.stop(); } }); this.node.fire('render') }
javascript
function() { var self = this; // Populate table html var content = ['<table class="' + this.tableClass + '" data-instance="' + this.instanceCount + '"><thead>', '<tr>']; for (var i in this.source.columns) { var sortContent = this.source.columns[i].name, colDir = self.source.columns[i].dir; if (self.source.colSortIdx == i) { sortContent = self.formatSortHeader(this.source.columns[i].name, colDir) } content.push('<th class="col-' + i + '"><a data-col-idx="' + i + '" data-sort="sort" href="#" title="' + this.source.columns[i].name +'">' + sortContent + '</a></th>'); } content.push('</tr></thead><tbody>'); for (var i = 0, rows = this.source.data.length; i < rows; i++) { var datum = this.source.data[i]; // Add in a reference to the data dataLookup[this.instanceCount][i] = datum content.push('<tr class="row-' + i + '"">'); for (var j in this.source.columns) { content.push('<td class="col-' + j +'">' + this.source.columns[j].formatter(datum) + '</td>'); } content.push('</tr>'); } content.push('</tbody></table>'); this.node.setHtml(content.join('')); this.node.one('table thead').on('click', function(e) { if (e.target.data('sort')) { self.sort(e.target); self.node.all('th a').item(e.target.data('col-idx'))._node.focus() e.stop(); } }); this.node.fire('render') }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "content", "=", "[", "'<table class=\"'", "+", "this", ".", "tableClass", "+", "'\" data-instance=\"'", "+", "this", ".", "instanceCount", "+", "'\"><thead>'", ",", "'<tr>'", "]", ";", "for", "(", "var", "i", "in", "this", ".", "source", ".", "columns", ")", "{", "var", "sortContent", "=", "this", ".", "source", ".", "columns", "[", "i", "]", ".", "name", ",", "colDir", "=", "self", ".", "source", ".", "columns", "[", "i", "]", ".", "dir", ";", "if", "(", "self", ".", "source", ".", "colSortIdx", "==", "i", ")", "{", "sortContent", "=", "self", ".", "formatSortHeader", "(", "this", ".", "source", ".", "columns", "[", "i", "]", ".", "name", ",", "colDir", ")", "}", "content", ".", "push", "(", "'<th class=\"col-'", "+", "i", "+", "'\"><a data-col-idx=\"'", "+", "i", "+", "'\" data-sort=\"sort\" href=\"#\" title=\"'", "+", "this", ".", "source", ".", "columns", "[", "i", "]", ".", "name", "+", "'\">'", "+", "sortContent", "+", "'</a></th>'", ")", ";", "}", "content", ".", "push", "(", "'</tr></thead><tbody>'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "rows", "=", "this", ".", "source", ".", "data", ".", "length", ";", "i", "<", "rows", ";", "i", "++", ")", "{", "var", "datum", "=", "this", ".", "source", ".", "data", "[", "i", "]", ";", "dataLookup", "[", "this", ".", "instanceCount", "]", "[", "i", "]", "=", "datum", "content", ".", "push", "(", "'<tr class=\"row-'", "+", "i", "+", "'\"\">'", ")", ";", "for", "(", "var", "j", "in", "this", ".", "source", ".", "columns", ")", "{", "content", ".", "push", "(", "'<td class=\"col-'", "+", "j", "+", "'\">'", "+", "this", ".", "source", ".", "columns", "[", "j", "]", ".", "formatter", "(", "datum", ")", "+", "'</td>'", ")", ";", "}", "content", ".", "push", "(", "'</tr>'", ")", ";", "}", "content", ".", "push", "(", "'</tbody></table>'", ")", ";", "this", ".", "node", ".", "setHtml", "(", "content", ".", "join", "(", "''", ")", ")", ";", "this", ".", "node", ".", "one", "(", "'table thead'", ")", ".", "on", "(", "'click'", ",", "function", "(", "e", ")", "{", "if", "(", "e", ".", "target", ".", "data", "(", "'sort'", ")", ")", "{", "self", ".", "sort", "(", "e", ".", "target", ")", ";", "self", ".", "node", ".", "all", "(", "'th a'", ")", ".", "item", "(", "e", ".", "target", ".", "data", "(", "'col-idx'", ")", ")", ".", "_node", ".", "focus", "(", ")", "e", ".", "stop", "(", ")", ";", "}", "}", ")", ";", "this", ".", "node", ".", "fire", "(", "'render'", ")", "}" ]
When we render, the datasource should be updated
[ "When", "we", "render", "the", "datasource", "should", "be", "updated" ]
49991293e621846e435992b764265abb13a7346b
https://github.com/nwtjs/nwt/blob/49991293e621846e435992b764265abb13a7346b/plugins/bootstrap/datatable.js#L250-L300
train
brandonheyer/mazejs
js/foundation/foundation.js
function (el) { var opts = {}, ii, p, opts_arr = (el.attr('data-options') || ':').split(';'), opts_len = opts_arr.length; function isNumber (o) { return ! isNaN (o-0) && o !== null && o !== "" && o !== false && o !== true; } function trim(str) { if (typeof str === 'string') return $.trim(str); return str; } // parse options for (ii = opts_len - 1; ii >= 0; ii--) { p = opts_arr[ii].split(':'); if (/true/i.test(p[1])) p[1] = true; if (/false/i.test(p[1])) p[1] = false; if (isNumber(p[1])) p[1] = parseInt(p[1], 10); if (p.length === 2 && p[0].length > 0) { opts[trim(p[0])] = trim(p[1]); } } return opts; }
javascript
function (el) { var opts = {}, ii, p, opts_arr = (el.attr('data-options') || ':').split(';'), opts_len = opts_arr.length; function isNumber (o) { return ! isNaN (o-0) && o !== null && o !== "" && o !== false && o !== true; } function trim(str) { if (typeof str === 'string') return $.trim(str); return str; } // parse options for (ii = opts_len - 1; ii >= 0; ii--) { p = opts_arr[ii].split(':'); if (/true/i.test(p[1])) p[1] = true; if (/false/i.test(p[1])) p[1] = false; if (isNumber(p[1])) p[1] = parseInt(p[1], 10); if (p.length === 2 && p[0].length > 0) { opts[trim(p[0])] = trim(p[1]); } } return opts; }
[ "function", "(", "el", ")", "{", "var", "opts", "=", "{", "}", ",", "ii", ",", "p", ",", "opts_arr", "=", "(", "el", ".", "attr", "(", "'data-options'", ")", "||", "':'", ")", ".", "split", "(", "';'", ")", ",", "opts_len", "=", "opts_arr", ".", "length", ";", "function", "isNumber", "(", "o", ")", "{", "return", "!", "isNaN", "(", "o", "-", "0", ")", "&&", "o", "!==", "null", "&&", "o", "!==", "\"\"", "&&", "o", "!==", "false", "&&", "o", "!==", "true", ";", "}", "function", "trim", "(", "str", ")", "{", "if", "(", "typeof", "str", "===", "'string'", ")", "return", "$", ".", "trim", "(", "str", ")", ";", "return", "str", ";", "}", "for", "(", "ii", "=", "opts_len", "-", "1", ";", "ii", ">=", "0", ";", "ii", "--", ")", "{", "p", "=", "opts_arr", "[", "ii", "]", ".", "split", "(", "':'", ")", ";", "if", "(", "/", "true", "/", "i", ".", "test", "(", "p", "[", "1", "]", ")", ")", "p", "[", "1", "]", "=", "true", ";", "if", "(", "/", "false", "/", "i", ".", "test", "(", "p", "[", "1", "]", ")", ")", "p", "[", "1", "]", "=", "false", ";", "if", "(", "isNumber", "(", "p", "[", "1", "]", ")", ")", "p", "[", "1", "]", "=", "parseInt", "(", "p", "[", "1", "]", ",", "10", ")", ";", "if", "(", "p", ".", "length", "===", "2", "&&", "p", "[", "0", "]", ".", "length", ">", "0", ")", "{", "opts", "[", "trim", "(", "p", "[", "0", "]", ")", "]", "=", "trim", "(", "p", "[", "1", "]", ")", ";", "}", "}", "return", "opts", ";", "}" ]
parses data-options attribute on nodes and turns them into an object
[ "parses", "data", "-", "options", "attribute", "on", "nodes", "and", "turns", "them", "into", "an", "object" ]
5efffc0279eeb061a71ba243313d165c16300fe6
https://github.com/brandonheyer/mazejs/blob/5efffc0279eeb061a71ba243313d165c16300fe6/js/foundation/foundation.js#L254-L282
train
mojaie/kiwiii
src/common/idb.js
getAllItems
function getAllItems() { return new Promise(resolve => { const res = []; return instance.pkgs.then(db => { db.transaction(db.name) .objectStore(db.name).openCursor() .onsuccess = event => { const cursor = event.target.result; if (cursor) { res.push(cursor.value); cursor.continue(); } else { resolve(res); } }; }); }); }
javascript
function getAllItems() { return new Promise(resolve => { const res = []; return instance.pkgs.then(db => { db.transaction(db.name) .objectStore(db.name).openCursor() .onsuccess = event => { const cursor = event.target.result; if (cursor) { res.push(cursor.value); cursor.continue(); } else { resolve(res); } }; }); }); }
[ "function", "getAllItems", "(", ")", "{", "return", "new", "Promise", "(", "resolve", "=>", "{", "const", "res", "=", "[", "]", ";", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "db", ".", "transaction", "(", "db", ".", "name", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "openCursor", "(", ")", ".", "onsuccess", "=", "event", "=>", "{", "const", "cursor", "=", "event", ".", "target", ".", "result", ";", "if", "(", "cursor", ")", "{", "res", ".", "push", "(", "cursor", ".", "value", ")", ";", "cursor", ".", "continue", "(", ")", ";", "}", "else", "{", "resolve", "(", "res", ")", ";", "}", "}", ";", "}", ")", ";", "}", ")", ";", "}" ]
Returns all packages @return {Promise} Promise of list of packages
[ "Returns", "all", "packages" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L67-L84
train
mojaie/kiwiii
src/common/idb.js
getItem
function getItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(id); req.onsuccess = event => resolve(event.target.result); req.onerror = event => reject(event); }); }); }
javascript
function getItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(id); req.onsuccess = event => resolve(event.target.result); req.onerror = event => reject(event); }); }); }
[ "function", "getItem", "(", "id", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "req", "=", "db", ".", "transaction", "(", "db", ".", "name", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "get", "(", "id", ")", ";", "req", ".", "onsuccess", "=", "event", "=>", "resolve", "(", "event", ".", "target", ".", "result", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get packages by instance ID @param {string} id - Package instance ID @return {array} data store object
[ "Get", "packages", "by", "instance", "ID" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L92-L101
train
mojaie/kiwiii
src/common/idb.js
putItem
function putItem(value) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put(value); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
javascript
function putItem(value) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put(value); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
[ "function", "putItem", "(", "value", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "obj", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ";", "const", "req", "=", "obj", ".", "put", "(", "value", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Put data object in the store @param {string} value - value to store
[ "Put", "data", "object", "in", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L108-L118
train
mojaie/kiwiii
src/common/idb.js
updateItem
function updateItem(id, updater) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.get(id); req.onerror = event => reject(event); req.onsuccess = event => { const res = event.target.result; updater(res); const upd = obj.put(res); upd.onsuccess = () => resolve(); upd.onerror = event => reject(event); }; }); }); }
javascript
function updateItem(id, updater) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.get(id); req.onerror = event => reject(event); req.onsuccess = event => { const res = event.target.result; updater(res); const upd = obj.put(res); upd.onsuccess = () => resolve(); upd.onerror = event => reject(event); }; }); }); }
[ "function", "updateItem", "(", "id", ",", "updater", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "obj", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ";", "const", "req", "=", "obj", ".", "get", "(", "id", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "event", "=>", "{", "const", "res", "=", "event", ".", "target", ".", "result", ";", "updater", "(", "res", ")", ";", "const", "upd", "=", "obj", ".", "put", "(", "res", ")", ";", "upd", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "upd", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "}", ";", "}", ")", ";", "}", ")", ";", "}" ]
Update package in the store @param {string} id - Package instance ID @param {function} updater - update function
[ "Update", "package", "in", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L126-L142
train
mojaie/kiwiii
src/common/idb.js
deleteItem
function deleteItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name, 'readwrite') .objectStore(db.name).delete(id); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
javascript
function deleteItem(id) { return new Promise((resolve, reject) => { return instance.pkgs.then(db => { const req = db.transaction(db.name, 'readwrite') .objectStore(db.name).delete(id); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
[ "function", "deleteItem", "(", "id", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "pkgs", ".", "then", "(", "db", "=>", "{", "const", "req", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "delete", "(", "id", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delete a package @param {string} id - Package instance ID
[ "Delete", "a", "package" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L149-L158
train
mojaie/kiwiii
src/common/idb.js
getView
function getView(id, viewID) { return getItem(id) .then(pkg => pkg.views.find(e => e.viewID === viewID)); }
javascript
function getView(id, viewID) { return getItem(id) .then(pkg => pkg.views.find(e => e.viewID === viewID)); }
[ "function", "getView", "(", "id", ",", "viewID", ")", "{", "return", "getItem", "(", "id", ")", ".", "then", "(", "pkg", "=>", "pkg", ".", "views", ".", "find", "(", "e", "=>", "e", ".", "viewID", "===", "viewID", ")", ")", ";", "}" ]
Returns a view @param {string} id - Package instance ID @param {string} viewID - view ID @return {array} view objects
[ "Returns", "a", "view" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L167-L170
train
mojaie/kiwiii
src/common/idb.js
appendView
function appendView(id, viewID, viewObj) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos + 1, 0, viewObj); }); }
javascript
function appendView(id, viewID, viewObj) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos + 1, 0, viewObj); }); }
[ "function", "appendView", "(", "id", ",", "viewID", ",", "viewObj", ")", "{", "return", "updateItem", "(", "id", ",", "item", "=>", "{", "const", "pos", "=", "item", ".", "views", ".", "findIndex", "(", "e", "=>", "e", ".", "viewID", "===", "viewID", ")", ";", "item", ".", "views", ".", "splice", "(", "pos", "+", "1", ",", "0", ",", "viewObj", ")", ";", "}", ")", ";", "}" ]
Append a view next to a specific view @param {string} id - Package instance ID @param {string} viewID - view ID @param {object} viewObj - view object
[ "Append", "a", "view", "next", "to", "a", "specific", "view" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L179-L184
train
mojaie/kiwiii
src/common/idb.js
deleteView
function deleteView(id, viewID) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos, 1); // prune orphaned collections const bin = {}; item.dataset.forEach(e => { bin[e.collectionID] = 0; }); item.views.forEach(view => { ['rows', 'items', 'nodes', 'edges'] .filter(e => view.hasOwnProperty(e)) .forEach(e => { bin[view[e]] += 1; }); }); Object.entries(bin).forEach(entry => { if (!entry[1]) { const i = item.dataset.findIndex(e => e.collectionID === entry[0]); item.dataset.splice(i, 1); } }); }); }
javascript
function deleteView(id, viewID) { return updateItem(id, item => { const pos = item.views.findIndex(e => e.viewID === viewID); item.views.splice(pos, 1); // prune orphaned collections const bin = {}; item.dataset.forEach(e => { bin[e.collectionID] = 0; }); item.views.forEach(view => { ['rows', 'items', 'nodes', 'edges'] .filter(e => view.hasOwnProperty(e)) .forEach(e => { bin[view[e]] += 1; }); }); Object.entries(bin).forEach(entry => { if (!entry[1]) { const i = item.dataset.findIndex(e => e.collectionID === entry[0]); item.dataset.splice(i, 1); } }); }); }
[ "function", "deleteView", "(", "id", ",", "viewID", ")", "{", "return", "updateItem", "(", "id", ",", "item", "=>", "{", "const", "pos", "=", "item", ".", "views", ".", "findIndex", "(", "e", "=>", "e", ".", "viewID", "===", "viewID", ")", ";", "item", ".", "views", ".", "splice", "(", "pos", ",", "1", ")", ";", "const", "bin", "=", "{", "}", ";", "item", ".", "dataset", ".", "forEach", "(", "e", "=>", "{", "bin", "[", "e", ".", "collectionID", "]", "=", "0", ";", "}", ")", ";", "item", ".", "views", ".", "forEach", "(", "view", "=>", "{", "[", "'rows'", ",", "'items'", ",", "'nodes'", ",", "'edges'", "]", ".", "filter", "(", "e", "=>", "view", ".", "hasOwnProperty", "(", "e", ")", ")", ".", "forEach", "(", "e", "=>", "{", "bin", "[", "view", "[", "e", "]", "]", "+=", "1", ";", "}", ")", ";", "}", ")", ";", "Object", ".", "entries", "(", "bin", ")", ".", "forEach", "(", "entry", "=>", "{", "if", "(", "!", "entry", "[", "1", "]", ")", "{", "const", "i", "=", "item", ".", "dataset", ".", "findIndex", "(", "e", "=>", "e", ".", "collectionID", "===", "entry", "[", "0", "]", ")", ";", "item", ".", "dataset", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Delete a data object from the store @param {string} id - Package instance ID @return {integer} - number of deleted items
[ "Delete", "a", "data", "object", "from", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L210-L229
train
mojaie/kiwiii
src/common/idb.js
getAllCollections
function getAllCollections() { return getAllItems() .then(items => _.flatten( items.map(item => { return item.dataset.map(coll => { coll.instance = item.id; return coll; }); }) )); }
javascript
function getAllCollections() { return getAllItems() .then(items => _.flatten( items.map(item => { return item.dataset.map(coll => { coll.instance = item.id; return coll; }); }) )); }
[ "function", "getAllCollections", "(", ")", "{", "return", "getAllItems", "(", ")", ".", "then", "(", "items", "=>", "_", ".", "flatten", "(", "items", ".", "map", "(", "item", "=>", "{", "return", "item", ".", "dataset", ".", "map", "(", "coll", "=>", "{", "coll", ".", "instance", "=", "item", ".", "id", ";", "return", "coll", ";", "}", ")", ";", "}", ")", ")", ")", ";", "}" ]
Returns all collections in the store @return {array} Collection objects
[ "Returns", "all", "collections", "in", "the", "store" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L236-L246
train
mojaie/kiwiii
src/common/idb.js
getCollection
function getCollection(id, collID) { return getItem(id) .then(pkg => pkg.dataset.find(e => e.collectionID === collID)); }
javascript
function getCollection(id, collID) { return getItem(id) .then(pkg => pkg.dataset.find(e => e.collectionID === collID)); }
[ "function", "getCollection", "(", "id", ",", "collID", ")", "{", "return", "getItem", "(", "id", ")", ".", "then", "(", "pkg", "=>", "pkg", ".", "dataset", ".", "find", "(", "e", "=>", "e", ".", "collectionID", "===", "collID", ")", ")", ";", "}" ]
Returns a collection @param {string} id - Package instance ID @param {string} collID - Collection ID @return {array} Collection objects
[ "Returns", "a", "collection" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L255-L258
train
mojaie/kiwiii
src/common/idb.js
newNetwork
function newNetwork(instance, nodesID, nodesName, response) { const viewID = misc.uuidv4().slice(0, 8); const edgesID = response.workflowID.slice(0, 8); return updateItem(instance, item => { item.views.push({ $schema: "https://mojaie.github.io/kiwiii/specs/network_v1.0.json", viewID: viewID, name: `${nodesName}_${response.name}`, viewType: 'network', nodes: nodesID, edges: edgesID, minConnThld: response.query.params.threshold }); item.dataset.push({ $schema: "https://mojaie.github.io/kiwiii/specs/collection_v1.0.json", collectionID: edgesID, name: response.name, contents: [response] }); }).then(() => viewID); }
javascript
function newNetwork(instance, nodesID, nodesName, response) { const viewID = misc.uuidv4().slice(0, 8); const edgesID = response.workflowID.slice(0, 8); return updateItem(instance, item => { item.views.push({ $schema: "https://mojaie.github.io/kiwiii/specs/network_v1.0.json", viewID: viewID, name: `${nodesName}_${response.name}`, viewType: 'network', nodes: nodesID, edges: edgesID, minConnThld: response.query.params.threshold }); item.dataset.push({ $schema: "https://mojaie.github.io/kiwiii/specs/collection_v1.0.json", collectionID: edgesID, name: response.name, contents: [response] }); }).then(() => viewID); }
[ "function", "newNetwork", "(", "instance", ",", "nodesID", ",", "nodesName", ",", "response", ")", "{", "const", "viewID", "=", "misc", ".", "uuidv4", "(", ")", ".", "slice", "(", "0", ",", "8", ")", ";", "const", "edgesID", "=", "response", ".", "workflowID", ".", "slice", "(", "0", ",", "8", ")", ";", "return", "updateItem", "(", "instance", ",", "item", "=>", "{", "item", ".", "views", ".", "push", "(", "{", "$schema", ":", "\"https://mojaie.github.io/kiwiii/specs/network_v1.0.json\"", ",", "viewID", ":", "viewID", ",", "name", ":", "`", "${", "nodesName", "}", "${", "response", ".", "name", "}", "`", ",", "viewType", ":", "'network'", ",", "nodes", ":", "nodesID", ",", "edges", ":", "edgesID", ",", "minConnThld", ":", "response", ".", "query", ".", "params", ".", "threshold", "}", ")", ";", "item", ".", "dataset", ".", "push", "(", "{", "$schema", ":", "\"https://mojaie.github.io/kiwiii/specs/collection_v1.0.json\"", ",", "collectionID", ":", "edgesID", ",", "name", ":", "response", ".", "name", ",", "contents", ":", "[", "response", "]", "}", ")", ";", "}", ")", ".", "then", "(", "(", ")", "=>", "viewID", ")", ";", "}" ]
Store new network view @param {string} instance - Package instance ID @param {string} nodesID - ID of nodes collection @param {string} nodesName - Name of nodes collection @param {object} response - Response object
[ "Store", "new", "network", "view" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L431-L451
train
mojaie/kiwiii
src/common/idb.js
getAsset
function getAsset(key) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(key); req.onsuccess = event => { const undef = event.target.result === undefined; const value = undef ? undefined : event.target.result.value; resolve(value); }; req.onerror = event => reject(event); }); }); }
javascript
function getAsset(key) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const req = db.transaction(db.name) .objectStore(db.name).get(key); req.onsuccess = event => { const undef = event.target.result === undefined; const value = undef ? undefined : event.target.result.value; resolve(value); }; req.onerror = event => reject(event); }); }); }
[ "function", "getAsset", "(", "key", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "assets", ".", "then", "(", "db", "=>", "{", "const", "req", "=", "db", ".", "transaction", "(", "db", ".", "name", ")", ".", "objectStore", "(", "db", ".", "name", ")", ".", "get", "(", "key", ")", ";", "req", ".", "onsuccess", "=", "event", "=>", "{", "const", "undef", "=", "event", ".", "target", ".", "result", "===", "undefined", ";", "const", "value", "=", "undef", "?", "undefined", ":", "event", ".", "target", ".", "result", ".", "value", ";", "resolve", "(", "value", ")", ";", "}", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Get asset by a key @param {string} key - key @return {array} asset object (if not found, resolve with undefined)
[ "Get", "asset", "by", "a", "key" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L459-L472
train
mojaie/kiwiii
src/common/idb.js
putAsset
function putAsset(key, content) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put({key: key, value: content}); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
javascript
function putAsset(key, content) { return new Promise((resolve, reject) => { return instance.assets.then(db => { const obj = db.transaction(db.name, 'readwrite') .objectStore(db.name); const req = obj.put({key: key, value: content}); req.onerror = event => reject(event); req.onsuccess = () => resolve(); }); }); }
[ "function", "putAsset", "(", "key", ",", "content", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "return", "instance", ".", "assets", ".", "then", "(", "db", "=>", "{", "const", "obj", "=", "db", ".", "transaction", "(", "db", ".", "name", ",", "'readwrite'", ")", ".", "objectStore", "(", "db", ".", "name", ")", ";", "const", "req", "=", "obj", ".", "put", "(", "{", "key", ":", "key", ",", "value", ":", "content", "}", ")", ";", "req", ".", "onerror", "=", "event", "=>", "reject", "(", "event", ")", ";", "req", ".", "onsuccess", "=", "(", ")", "=>", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Put asset object with a key @param {string} key - key @param {string} content - asset to store
[ "Put", "asset", "object", "with", "a", "key" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/common/idb.js#L479-L489
train
mojaie/kiwiii
src/component/legend.js
updateLegendGroup
function updateLegendGroup(selection, viewBox, orient) { const widthFactor = 0.2; const scaleF = viewBox.right * widthFactor / 120; const o = orient.split('-'); const viewW = viewBox.right; const viewH = viewBox.bottom; const legW = viewW * widthFactor; const legH = legW * 50 / 120; const posX = {left: legW / 10, right: viewW - legW - (legW / 10)}[o[1]]; const posY = {top: legH / 10, bottom: viewH - legH - (legH / 10)}[o[0]]; selection.attr('transform', `translate(${posX}, ${posY}) scale(${scaleF})`); }
javascript
function updateLegendGroup(selection, viewBox, orient) { const widthFactor = 0.2; const scaleF = viewBox.right * widthFactor / 120; const o = orient.split('-'); const viewW = viewBox.right; const viewH = viewBox.bottom; const legW = viewW * widthFactor; const legH = legW * 50 / 120; const posX = {left: legW / 10, right: viewW - legW - (legW / 10)}[o[1]]; const posY = {top: legH / 10, bottom: viewH - legH - (legH / 10)}[o[0]]; selection.attr('transform', `translate(${posX}, ${posY}) scale(${scaleF})`); }
[ "function", "updateLegendGroup", "(", "selection", ",", "viewBox", ",", "orient", ")", "{", "const", "widthFactor", "=", "0.2", ";", "const", "scaleF", "=", "viewBox", ".", "right", "*", "widthFactor", "/", "120", ";", "const", "o", "=", "orient", ".", "split", "(", "'-'", ")", ";", "const", "viewW", "=", "viewBox", ".", "right", ";", "const", "viewH", "=", "viewBox", ".", "bottom", ";", "const", "legW", "=", "viewW", "*", "widthFactor", ";", "const", "legH", "=", "legW", "*", "50", "/", "120", ";", "const", "posX", "=", "{", "left", ":", "legW", "/", "10", ",", "right", ":", "viewW", "-", "legW", "-", "(", "legW", "/", "10", ")", "}", "[", "o", "[", "1", "]", "]", ";", "const", "posY", "=", "{", "top", ":", "legH", "/", "10", ",", "bottom", ":", "viewH", "-", "legH", "-", "(", "legH", "/", "10", ")", "}", "[", "o", "[", "0", "]", "]", ";", "selection", ".", "attr", "(", "'transform'", ",", "`", "${", "posX", "}", "${", "posY", "}", "${", "scaleF", "}", "`", ")", ";", "}" ]
Legend group component @param {d3.selection} selection - selection of group container (svg:g)
[ "Legend", "group", "component" ]
30d75685b1ab388b5f1467c753cacd090971ceba
https://github.com/mojaie/kiwiii/blob/30d75685b1ab388b5f1467c753cacd090971ceba/src/component/legend.js#L61-L73
train
fnogatz/node-swtparser
build-structure.js
loadKeyValueCSV
function loadKeyValueCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .on('record', function (data, index) { if (data[0].match(/^[\w\d]/)) { out[data[0]] = data[1] } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
javascript
function loadKeyValueCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .on('record', function (data, index) { if (data[0].match(/^[\w\d]/)) { out[data[0]] = data[1] } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
[ "function", "loadKeyValueCSV", "(", "filename", ",", "callback", ")", "{", "var", "out", "=", "{", "}", "csv", "(", ")", ".", "from", ".", "path", "(", "filename", ",", "{", "delimiter", ":", "'\\t'", "}", ")", ".", "\\t", "on", ".", "(", "'record'", ",", "function", "(", "data", ",", "index", ")", "{", "if", "(", "data", "[", "0", "]", ".", "match", "(", "/", "^[\\w\\d]", "/", ")", ")", "{", "out", "[", "data", "[", "0", "]", "]", "=", "data", "[", "1", "]", "}", "}", ")", "on", ".", "(", "'end'", ",", "function", "(", "count", ")", "{", "callback", "(", "null", ",", "out", ")", "}", ")", "on", "}" ]
Loads key-value-pairs saved in a CSV file into an object. @param {String} filename to read from @param {Function} callback that takes the object
[ "Loads", "key", "-", "value", "-", "pairs", "saved", "in", "a", "CSV", "file", "into", "an", "object", "." ]
4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3
https://github.com/fnogatz/node-swtparser/blob/4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3/build-structure.js#L16-L34
train
fnogatz/node-swtparser
build-structure.js
loadStructureCSV
function loadStructureCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .transform(function (data) { // hex values to decimal if (!data[0].match(/^[0-9A-Fa-f]/)) { return false } // comment var ret = { field: parseInt(data[3]), type: data[2].substr(0, 3) } if (ret.type === 'sel') { if (data[2].length === 3) { ret.selection = ret.field } else { ret.selection = parseInt(data[2].replace(/^sel:/, '')) } } if (data[1].length > 0) { ret.from = parseInt(data[0], 16) ret.to = parseInt(data[1], 16) } else { ret.where = parseInt(data[0], 16) } return ret }) .on('record', function (data, index) { if (data) { var field = data.field delete data.field out[field] = data } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
javascript
function loadStructureCSV (filename, callback) { var out = {} csv() .from.path(filename, { delimiter: '\t' }) .transform(function (data) { // hex values to decimal if (!data[0].match(/^[0-9A-Fa-f]/)) { return false } // comment var ret = { field: parseInt(data[3]), type: data[2].substr(0, 3) } if (ret.type === 'sel') { if (data[2].length === 3) { ret.selection = ret.field } else { ret.selection = parseInt(data[2].replace(/^sel:/, '')) } } if (data[1].length > 0) { ret.from = parseInt(data[0], 16) ret.to = parseInt(data[1], 16) } else { ret.where = parseInt(data[0], 16) } return ret }) .on('record', function (data, index) { if (data) { var field = data.field delete data.field out[field] = data } }) .on('end', function (count) { callback(null, out) }) .on('error', function (err) { callback(err) }) }
[ "function", "loadStructureCSV", "(", "filename", ",", "callback", ")", "{", "var", "out", "=", "{", "}", "csv", "(", ")", ".", "from", ".", "path", "(", "filename", ",", "{", "delimiter", ":", "'\\t'", "}", ")", ".", "\\t", "transform", ".", "(", "function", "(", "data", ")", "{", "if", "(", "!", "data", "[", "0", "]", ".", "match", "(", "/", "^[0-9A-Fa-f]", "/", ")", ")", "{", "return", "false", "}", "var", "ret", "=", "{", "field", ":", "parseInt", "(", "data", "[", "3", "]", ")", ",", "type", ":", "data", "[", "2", "]", ".", "substr", "(", "0", ",", "3", ")", "}", "if", "(", "ret", ".", "type", "===", "'sel'", ")", "{", "if", "(", "data", "[", "2", "]", ".", "length", "===", "3", ")", "{", "ret", ".", "selection", "=", "ret", ".", "field", "}", "else", "{", "ret", ".", "selection", "=", "parseInt", "(", "data", "[", "2", "]", ".", "replace", "(", "/", "^sel:", "/", ",", "''", ")", ")", "}", "}", "if", "(", "data", "[", "1", "]", ".", "length", ">", "0", ")", "{", "ret", ".", "from", "=", "parseInt", "(", "data", "[", "0", "]", ",", "16", ")", "ret", ".", "to", "=", "parseInt", "(", "data", "[", "1", "]", ",", "16", ")", "}", "else", "{", "ret", ".", "where", "=", "parseInt", "(", "data", "[", "0", "]", ",", "16", ")", "}", "return", "ret", "}", ")", "on", ".", "(", "'record'", ",", "function", "(", "data", ",", "index", ")", "{", "if", "(", "data", ")", "{", "var", "field", "=", "data", ".", "field", "delete", "data", ".", "field", "out", "[", "field", "]", "=", "data", "}", "}", ")", "on", ".", "(", "'end'", ",", "function", "(", "count", ")", "{", "callback", "(", "null", ",", "out", ")", "}", ")", "on", "}" ]
Loads a CSV structure file into an object with specified field keys as object keys. @param {String} filename to read from @param {Function} callback that takes the object
[ "Loads", "a", "CSV", "structure", "file", "into", "an", "object", "with", "specified", "field", "keys", "as", "object", "keys", "." ]
4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3
https://github.com/fnogatz/node-swtparser/blob/4a109dcfef19ca5ca01fa7b4256ee57a2a3c1dd3/build-structure.js#L43-L89
train
elb-min-uhh/markdown-elearnjs
assets/elearnjs/extensions/clickimage/assets/js/clickimage.js
initializeClickimages
function initializeClickimages() { var elements = document.querySelectorAll('[data-pins]'); for(var i = 0; i < elements.length; i++) { /* try/catch so it continues with the next element without breaking out of the loop, when any syntax error occurs. */ try { clickimagePins(elements[i]); } catch(err) { console.error(err); } } }
javascript
function initializeClickimages() { var elements = document.querySelectorAll('[data-pins]'); for(var i = 0; i < elements.length; i++) { /* try/catch so it continues with the next element without breaking out of the loop, when any syntax error occurs. */ try { clickimagePins(elements[i]); } catch(err) { console.error(err); } } }
[ "function", "initializeClickimages", "(", ")", "{", "var", "elements", "=", "document", ".", "querySelectorAll", "(", "'[data-pins]'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "try", "{", "clickimagePins", "(", "elements", "[", "i", "]", ")", ";", "}", "catch", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "}", "}", "}" ]
Initializes all Clickimages. Clickimages are declared by the attribute `pins`.
[ "Initializes", "all", "Clickimages", ".", "Clickimages", "are", "declared", "by", "the", "attribute", "pins", "." ]
a09bcc497c3c50dd565b7f440fa1f7b62074d679
https://github.com/elb-min-uhh/markdown-elearnjs/blob/a09bcc497c3c50dd565b7f440fa1f7b62074d679/assets/elearnjs/extensions/clickimage/assets/js/clickimage.js#L233-L247
train
jgable/react-native-fluxbone
lib/dispatcher.js
function (events, context) { if (!_.isObject(events)) { console.warn('Only registration objects can be passed to dispatcher.register()'); return; } return this.dispatcher.register(function (payload) { // Switch statements be damned... if (events[payload.type]) { events[payload.type].apply(context || null, [payload.data]); } }); }
javascript
function (events, context) { if (!_.isObject(events)) { console.warn('Only registration objects can be passed to dispatcher.register()'); return; } return this.dispatcher.register(function (payload) { // Switch statements be damned... if (events[payload.type]) { events[payload.type].apply(context || null, [payload.data]); } }); }
[ "function", "(", "events", ",", "context", ")", "{", "if", "(", "!", "_", ".", "isObject", "(", "events", ")", ")", "{", "console", ".", "warn", "(", "'Only registration objects can be passed to dispatcher.register()'", ")", ";", "return", ";", "}", "return", "this", ".", "dispatcher", ".", "register", "(", "function", "(", "payload", ")", "{", "if", "(", "events", "[", "payload", ".", "type", "]", ")", "{", "events", "[", "payload", ".", "type", "]", ".", "apply", "(", "context", "||", "null", ",", "[", "payload", ".", "data", "]", ")", ";", "}", "}", ")", ";", "}" ]
Register a collection of callbacks to action types @param {Object} events - A mapping of action types to callbacks @param {Object} [context=null] - The context applied to the callback @returns {string} The dispatcher token to use for unregister or waitFor
[ "Register", "a", "collection", "of", "callbacks", "to", "action", "types" ]
9847a598da0cc72f056c6bd4d2e21909b146f530
https://github.com/jgable/react-native-fluxbone/blob/9847a598da0cc72f056c6bd4d2e21909b146f530/lib/dispatcher.js#L25-L37
train
jgable/react-native-fluxbone
lib/dispatcher.js
function (type, data) { if (!_.isString(type)) { console.warn('Action types are required when calling dispatcher.dispatch()'); return; } this.dispatcher.dispatch({ type: type, data: data }); }
javascript
function (type, data) { if (!_.isString(type)) { console.warn('Action types are required when calling dispatcher.dispatch()'); return; } this.dispatcher.dispatch({ type: type, data: data }); }
[ "function", "(", "type", ",", "data", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "type", ")", ")", "{", "console", ".", "warn", "(", "'Action types are required when calling dispatcher.dispatch()'", ")", ";", "return", ";", "}", "this", ".", "dispatcher", ".", "dispatch", "(", "{", "type", ":", "type", ",", "data", ":", "data", "}", ")", ";", "}" ]
Dispatch an action by name @param {string} type - Name of the action @param {Object|string|number|boolean} data - The payload of the action
[ "Dispatch", "an", "action", "by", "name" ]
9847a598da0cc72f056c6bd4d2e21909b146f530
https://github.com/jgable/react-native-fluxbone/blob/9847a598da0cc72f056c6bd4d2e21909b146f530/lib/dispatcher.js#L62-L72
train
jgable/react-native-fluxbone
lib/dispatcher.js
function (token) { var tokens = token; if (!_.isArray(tokens)) { tokens = [tokens]; } tokens = tokens.map(function (token) { // Allow passing stores straight and we grab the dispatcherToken return token.dispatcherToken || token; }); return this.dispatcher.waitFor(tokens); }
javascript
function (token) { var tokens = token; if (!_.isArray(tokens)) { tokens = [tokens]; } tokens = tokens.map(function (token) { // Allow passing stores straight and we grab the dispatcherToken return token.dispatcherToken || token; }); return this.dispatcher.waitFor(tokens); }
[ "function", "(", "token", ")", "{", "var", "tokens", "=", "token", ";", "if", "(", "!", "_", ".", "isArray", "(", "tokens", ")", ")", "{", "tokens", "=", "[", "tokens", "]", ";", "}", "tokens", "=", "tokens", ".", "map", "(", "function", "(", "token", ")", "{", "return", "token", ".", "dispatcherToken", "||", "token", ";", "}", ")", ";", "return", "this", ".", "dispatcher", ".", "waitFor", "(", "tokens", ")", ";", "}" ]
Wait for another callback to occur before continuing @param {string|string[]|Store} token - The collection of dispatch tokens to wait on
[ "Wait", "for", "another", "callback", "to", "occur", "before", "continuing" ]
9847a598da0cc72f056c6bd4d2e21909b146f530
https://github.com/jgable/react-native-fluxbone/blob/9847a598da0cc72f056c6bd4d2e21909b146f530/lib/dispatcher.js#L79-L91
train
fashion-js/fashion-model
Model.js
_ensureArray
function _ensureArray (model, property) { const propertyKey = property.getKey(); let array = model.data[propertyKey]; if (!array) { model.data[propertyKey] = array = []; ArrayType.flagAsArrayType(array); } return array; }
javascript
function _ensureArray (model, property) { const propertyKey = property.getKey(); let array = model.data[propertyKey]; if (!array) { model.data[propertyKey] = array = []; ArrayType.flagAsArrayType(array); } return array; }
[ "function", "_ensureArray", "(", "model", ",", "property", ")", "{", "const", "propertyKey", "=", "property", ".", "getKey", "(", ")", ";", "let", "array", "=", "model", ".", "data", "[", "propertyKey", "]", ";", "if", "(", "!", "array", ")", "{", "model", ".", "data", "[", "propertyKey", "]", "=", "array", "=", "[", "]", ";", "ArrayType", ".", "flagAsArrayType", "(", "array", ")", ";", "}", "return", "array", ";", "}" ]
This function will be used to make sure an array value exists for the given property
[ "This", "function", "will", "be", "used", "to", "make", "sure", "an", "array", "value", "exists", "for", "the", "given", "property" ]
75a4090527ecf8b5075837a18f3d4216ccb561de
https://github.com/fashion-js/fashion-model/blob/75a4090527ecf8b5075837a18f3d4216ccb561de/Model.js#L112-L121
train
danShumway/serverboy.js
examples/streaming/video/index.js
function() { //io = socket(process.env.PORT || process.env.NODE_PORT || 3333); io = socket(http); io.on('connection', function(socket){ console.log('connection happened'); //Logic for handeling a new connection here. //ie. registering a user or something similar. //The new connection can send commands. socket.on('keydown', function(data) { var index = keysToPress.indexOf(data.key); if(index === -1) { keysToPress.push(data.key); } }); socket.on('keyup', function(data) { var index = keysToPress.indexOf(data.key); if(index !== -1) { keysToPress.splice(index, 1); } }); socket.on('restart', function(data) { gameboy_instance.loadROM(rom); }); }); }
javascript
function() { //io = socket(process.env.PORT || process.env.NODE_PORT || 3333); io = socket(http); io.on('connection', function(socket){ console.log('connection happened'); //Logic for handeling a new connection here. //ie. registering a user or something similar. //The new connection can send commands. socket.on('keydown', function(data) { var index = keysToPress.indexOf(data.key); if(index === -1) { keysToPress.push(data.key); } }); socket.on('keyup', function(data) { var index = keysToPress.indexOf(data.key); if(index !== -1) { keysToPress.splice(index, 1); } }); socket.on('restart', function(data) { gameboy_instance.loadROM(rom); }); }); }
[ "function", "(", ")", "{", "io", "=", "socket", "(", "http", ")", ";", "io", ".", "on", "(", "'connection'", ",", "function", "(", "socket", ")", "{", "console", ".", "log", "(", "'connection happened'", ")", ";", "socket", ".", "on", "(", "'keydown'", ",", "function", "(", "data", ")", "{", "var", "index", "=", "keysToPress", ".", "indexOf", "(", "data", ".", "key", ")", ";", "if", "(", "index", "===", "-", "1", ")", "{", "keysToPress", ".", "push", "(", "data", ".", "key", ")", ";", "}", "}", ")", ";", "socket", ".", "on", "(", "'keyup'", ",", "function", "(", "data", ")", "{", "var", "index", "=", "keysToPress", ".", "indexOf", "(", "data", ".", "key", ")", ";", "if", "(", "index", "!==", "-", "1", ")", "{", "keysToPress", ".", "splice", "(", "index", ",", "1", ")", ";", "}", "}", ")", ";", "socket", ".", "on", "(", "'restart'", ",", "function", "(", "data", ")", "{", "gameboy_instance", ".", "loadROM", "(", "rom", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
What keys we want pressed.
[ "What", "keys", "we", "want", "pressed", "." ]
68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628
https://github.com/danShumway/serverboy.js/blob/68f0ac88b5b280f64de2c8ae6d57d8a84cbe3628/examples/streaming/video/index.js#L17-L46
train
byron-dupreez/aws-core-utils
api-lambdas.js
configureHandlerContext
function configureHandlerContext(createContext, createSettings, createOptions, event, awsContext) { // Configure the context as a standard context let context = typeof createContext === 'function' ? createContext() : createContext && typeof createContext === 'object' ? copy(createContext, deep) : {}; if (!context) context = {}; const settings = typeof createSettings === 'function' ? copy(createSettings(), deep) : createSettings && typeof createSettings === 'object' ? copy(createSettings, deep) : undefined; const options = typeof createOptions === 'function' ? copy(createOptions(), deep) : createOptions && typeof createOptions === 'object' ? copy(createOptions, deep) : undefined; // Configure the context as a standard context contexts.configureStandardContext(context, settings, options, event, awsContext, false); // Merge the handler options into the handler settings and finally merge their result into context.handler const handlerOptions = (options && options.handler) || {}; const handlerSettings = settings && settings.handler ? mergeHandlerOpts(handlerOptions, settings.handler) : handlerOptions; context.handler = context.handler ? mergeHandlerOpts(handlerSettings, context.handler) : handlerSettings; return context; }
javascript
function configureHandlerContext(createContext, createSettings, createOptions, event, awsContext) { // Configure the context as a standard context let context = typeof createContext === 'function' ? createContext() : createContext && typeof createContext === 'object' ? copy(createContext, deep) : {}; if (!context) context = {}; const settings = typeof createSettings === 'function' ? copy(createSettings(), deep) : createSettings && typeof createSettings === 'object' ? copy(createSettings, deep) : undefined; const options = typeof createOptions === 'function' ? copy(createOptions(), deep) : createOptions && typeof createOptions === 'object' ? copy(createOptions, deep) : undefined; // Configure the context as a standard context contexts.configureStandardContext(context, settings, options, event, awsContext, false); // Merge the handler options into the handler settings and finally merge their result into context.handler const handlerOptions = (options && options.handler) || {}; const handlerSettings = settings && settings.handler ? mergeHandlerOpts(handlerOptions, settings.handler) : handlerOptions; context.handler = context.handler ? mergeHandlerOpts(handlerSettings, context.handler) : handlerSettings; return context; }
[ "function", "configureHandlerContext", "(", "createContext", ",", "createSettings", ",", "createOptions", ",", "event", ",", "awsContext", ")", "{", "let", "context", "=", "typeof", "createContext", "===", "'function'", "?", "createContext", "(", ")", ":", "createContext", "&&", "typeof", "createContext", "===", "'object'", "?", "copy", "(", "createContext", ",", "deep", ")", ":", "{", "}", ";", "if", "(", "!", "context", ")", "context", "=", "{", "}", ";", "const", "settings", "=", "typeof", "createSettings", "===", "'function'", "?", "copy", "(", "createSettings", "(", ")", ",", "deep", ")", ":", "createSettings", "&&", "typeof", "createSettings", "===", "'object'", "?", "copy", "(", "createSettings", ",", "deep", ")", ":", "undefined", ";", "const", "options", "=", "typeof", "createOptions", "===", "'function'", "?", "copy", "(", "createOptions", "(", ")", ",", "deep", ")", ":", "createOptions", "&&", "typeof", "createOptions", "===", "'object'", "?", "copy", "(", "createOptions", ",", "deep", ")", ":", "undefined", ";", "contexts", ".", "configureStandardContext", "(", "context", ",", "settings", ",", "options", ",", "event", ",", "awsContext", ",", "false", ")", ";", "const", "handlerOptions", "=", "(", "options", "&&", "options", ".", "handler", ")", "||", "{", "}", ";", "const", "handlerSettings", "=", "settings", "&&", "settings", ".", "handler", "?", "mergeHandlerOpts", "(", "handlerOptions", ",", "settings", ".", "handler", ")", ":", "handlerOptions", ";", "context", ".", "handler", "=", "context", ".", "handler", "?", "mergeHandlerOpts", "(", "handlerSettings", ",", "context", ".", "handler", ")", ":", "handlerSettings", ";", "return", "context", ";", "}" ]
Configures a standard handler context to use. @param {(function(): (Object|HandlerContext))|undefined|Object|HandlerContext} [createContext] - an optional function that will be used to create the initial context to be configured & used (OR or an optional LEGACY module-scope context from which to copy an initial standard context) @param {(function(): (Object|HandlerSettings))|undefined|Object|HandlerSettings} [createSettings] - an optional function that will be used to create the initial standard settings to use (OR optional LEGACY module-scoped settings from which to copy initial settings to use) @param {(function(): (Object|HandlerOptions))|undefined|Object|HandlerOptions} [createOptions] - an optional function that will be used to create the initial standard options to use (OR optional LEGACY module-scoped options from which to copy initial options to use) @param {Object} event - the AWS event passed to your handler @param {Object} awsContext - the AWS context passed to your handler @return {StandardHandlerContext} the handler context to use
[ "Configures", "a", "standard", "handler", "context", "to", "use", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/api-lambdas.js#L166-L188
train
byron-dupreez/aws-core-utils
api-lambdas.js
succeedLambdaCallback
function succeedLambdaCallback(callback, response, event, context) { return Promises.try(() => { const handler = context && context.handler; if (handler && handler.useLambdaProxy) { const statusCode = response && isNotBlank(response.statusCode) ? response.statusCode : 200; const body = (response && response.body) || response || {}; const proxyResponse = toLambdaProxyResponse(statusCode, response && response.headers, body, handler.defaultHeaders); return executePreSuccessCallback(proxyResponse, event, context) .then(() => callback(null, proxyResponse)) .catch(err => { console.error(`Unexpected failure after executePreSuccessCallback`, err); return callback(null, proxyResponse); }); } else { return executePreSuccessCallback(response, event, context) .then(() => callback(null, response)) .catch(err => { console.error(`Unexpected failure after executePreSuccessCallback`, err); return callback(null, response); }); } }).catch(err => { console.error(`Unexpected failure during succeedLambdaCallback`, err); return callback(null, response); }); }
javascript
function succeedLambdaCallback(callback, response, event, context) { return Promises.try(() => { const handler = context && context.handler; if (handler && handler.useLambdaProxy) { const statusCode = response && isNotBlank(response.statusCode) ? response.statusCode : 200; const body = (response && response.body) || response || {}; const proxyResponse = toLambdaProxyResponse(statusCode, response && response.headers, body, handler.defaultHeaders); return executePreSuccessCallback(proxyResponse, event, context) .then(() => callback(null, proxyResponse)) .catch(err => { console.error(`Unexpected failure after executePreSuccessCallback`, err); return callback(null, proxyResponse); }); } else { return executePreSuccessCallback(response, event, context) .then(() => callback(null, response)) .catch(err => { console.error(`Unexpected failure after executePreSuccessCallback`, err); return callback(null, response); }); } }).catch(err => { console.error(`Unexpected failure during succeedLambdaCallback`, err); return callback(null, response); }); }
[ "function", "succeedLambdaCallback", "(", "callback", ",", "response", ",", "event", ",", "context", ")", "{", "return", "Promises", ".", "try", "(", "(", ")", "=>", "{", "const", "handler", "=", "context", "&&", "context", ".", "handler", ";", "if", "(", "handler", "&&", "handler", ".", "useLambdaProxy", ")", "{", "const", "statusCode", "=", "response", "&&", "isNotBlank", "(", "response", ".", "statusCode", ")", "?", "response", ".", "statusCode", ":", "200", ";", "const", "body", "=", "(", "response", "&&", "response", ".", "body", ")", "||", "response", "||", "{", "}", ";", "const", "proxyResponse", "=", "toLambdaProxyResponse", "(", "statusCode", ",", "response", "&&", "response", ".", "headers", ",", "body", ",", "handler", ".", "defaultHeaders", ")", ";", "return", "executePreSuccessCallback", "(", "proxyResponse", ",", "event", ",", "context", ")", ".", "then", "(", "(", ")", "=>", "callback", "(", "null", ",", "proxyResponse", ")", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "error", "(", "`", "`", ",", "err", ")", ";", "return", "callback", "(", "null", ",", "proxyResponse", ")", ";", "}", ")", ";", "}", "else", "{", "return", "executePreSuccessCallback", "(", "response", ",", "event", ",", "context", ")", ".", "then", "(", "(", ")", "=>", "callback", "(", "null", ",", "response", ")", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "error", "(", "`", "`", ",", "err", ")", ";", "return", "callback", "(", "null", ",", "response", ")", ";", "}", ")", ";", "}", "}", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "error", "(", "`", "`", ",", "err", ")", ";", "return", "callback", "(", "null", ",", "response", ")", ";", "}", ")", ";", "}" ]
Succeeds the given callback of an API Gateway exposed AWS Lambda, by invoking the given callback with the given response. @param {Function} callback - the callback function passed as the last argument to your Lambda function on invocation. @param {Object} response - a normal or Lambda Proxy integration response to be returned @param {AWSEvent} event - the AWS event passed to your handler @param {StandardHandlerContext} context - the context to use
[ "Succeeds", "the", "given", "callback", "of", "an", "API", "Gateway", "exposed", "AWS", "Lambda", "by", "invoking", "the", "given", "callback", "with", "the", "given", "response", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/api-lambdas.js#L293-L318
train
byron-dupreez/aws-core-utils
api-lambdas.js
toLambdaProxyResponse
function toLambdaProxyResponse(statusCode, headers, body, defaultHeaders) { const proxyResponse = {statusCode: statusCode}; const headersWithDefaults = headers && defaultHeaders ? merge(defaultHeaders, copy(headers)) : headers || (defaultHeaders && copy(defaultHeaders)); if (headersWithDefaults) { proxyResponse.headers = headersWithDefaults; } proxyResponse.body = isString(body) ? body : stringify(body); return proxyResponse; }
javascript
function toLambdaProxyResponse(statusCode, headers, body, defaultHeaders) { const proxyResponse = {statusCode: statusCode}; const headersWithDefaults = headers && defaultHeaders ? merge(defaultHeaders, copy(headers)) : headers || (defaultHeaders && copy(defaultHeaders)); if (headersWithDefaults) { proxyResponse.headers = headersWithDefaults; } proxyResponse.body = isString(body) ? body : stringify(body); return proxyResponse; }
[ "function", "toLambdaProxyResponse", "(", "statusCode", ",", "headers", ",", "body", ",", "defaultHeaders", ")", "{", "const", "proxyResponse", "=", "{", "statusCode", ":", "statusCode", "}", ";", "const", "headersWithDefaults", "=", "headers", "&&", "defaultHeaders", "?", "merge", "(", "defaultHeaders", ",", "copy", "(", "headers", ")", ")", ":", "headers", "||", "(", "defaultHeaders", "&&", "copy", "(", "defaultHeaders", ")", ")", ";", "if", "(", "headersWithDefaults", ")", "{", "proxyResponse", ".", "headers", "=", "headersWithDefaults", ";", "}", "proxyResponse", ".", "body", "=", "isString", "(", "body", ")", "?", "body", ":", "stringify", "(", "body", ")", ";", "return", "proxyResponse", ";", "}" ]
Builds & returns a Lambda Proxy integration compatible response. @param {number|string} statusCode - the HTTP status code to return @param {Object|undefined} [headers] - optional response headers to use @param {Object|string|undefined} [body] - an optional response body to use @param {Object|undefined} [defaultHeaders] - optional default custom headers to be included in the Lambda Proxy response @return {{statusCode: (number|string), headers: (Object|undefined), body: (string|undefined)}} a Lambda Proxy response
[ "Builds", "&", "returns", "a", "Lambda", "Proxy", "integration", "compatible", "response", "." ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/api-lambdas.js#L385-L397
train
byron-dupreez/aws-core-utils
api-lambdas.js
toDefaultErrorResponseBody
function toDefaultErrorResponseBody(error) { const json = error && error.toJSON(); if (json) { if (json.httpStatus) { delete json.httpStatus; // don't really need `httpStatus` inside `body` too, since have it in response as `statusCode` } if (json.headers) { delete json.headers; // don't want error's `headers` inside `body`, since have more comprehensive `headers` in response } } return json; }
javascript
function toDefaultErrorResponseBody(error) { const json = error && error.toJSON(); if (json) { if (json.httpStatus) { delete json.httpStatus; // don't really need `httpStatus` inside `body` too, since have it in response as `statusCode` } if (json.headers) { delete json.headers; // don't want error's `headers` inside `body`, since have more comprehensive `headers` in response } } return json; }
[ "function", "toDefaultErrorResponseBody", "(", "error", ")", "{", "const", "json", "=", "error", "&&", "error", ".", "toJSON", "(", ")", ";", "if", "(", "json", ")", "{", "if", "(", "json", ".", "httpStatus", ")", "{", "delete", "json", ".", "httpStatus", ";", "}", "if", "(", "json", ".", "headers", ")", "{", "delete", "json", ".", "headers", ";", "}", "}", "return", "json", ";", "}" ]
A default conversion from an error to an error response body for a Lambda Proxy error response @param {AppError} error - an error to convert @return {Object} an error response body
[ "A", "default", "conversion", "from", "an", "error", "to", "an", "error", "response", "body", "for", "a", "Lambda", "Proxy", "error", "response" ]
2530155b5afc102f61658b28183a16027ecae86a
https://github.com/byron-dupreez/aws-core-utils/blob/2530155b5afc102f61658b28183a16027ecae86a/api-lambdas.js#L452-L463
train
ninejs/ninejs
ui/logic/FilterBuilder/DefaultClipboardStrategy.js
function(expression) { if (this.hasClipboard()) { var key = this._getKey(); localStorage[key] = json.stringify(expression.toJson()); } }
javascript
function(expression) { if (this.hasClipboard()) { var key = this._getKey(); localStorage[key] = json.stringify(expression.toJson()); } }
[ "function", "(", "expression", ")", "{", "if", "(", "this", ".", "hasClipboard", "(", ")", ")", "{", "var", "key", "=", "this", ".", "_getKey", "(", ")", ";", "localStorage", "[", "key", "]", "=", "json", ".", "stringify", "(", "expression", ".", "toJson", "(", ")", ")", ";", "}", "}" ]
Copies the expression parameter
[ "Copies", "the", "expression", "parameter" ]
5da252baff42c13f92fa8f45932439993e9f7dd3
https://github.com/ninejs/ninejs/blob/5da252baff42c13f92fa8f45932439993e9f7dd3/ui/logic/FilterBuilder/DefaultClipboardStrategy.js#L45-L50
train
ninejs/ninejs
ui/logic/FilterBuilder/DefaultClipboardStrategy.js
function(expression) { var pastedExpression = new Expression(); var key = this._getKey(); pastedExpression.fromJson(json.parse(localStorage[key])); var newExpression; if (expression) { var expressionClone = new Expression({ operator : 'and', expressionList : [expression, pastedExpression] }).toJson(); //converting the same instance expression.fromJson(expressionClone); newExpression = expression; } else { newExpression = pastedExpression; } var parentBuilder = this.get('filterBuilder'); parentBuilder.set('expression', newExpression, true /* preventChange Undo State * */); }
javascript
function(expression) { var pastedExpression = new Expression(); var key = this._getKey(); pastedExpression.fromJson(json.parse(localStorage[key])); var newExpression; if (expression) { var expressionClone = new Expression({ operator : 'and', expressionList : [expression, pastedExpression] }).toJson(); //converting the same instance expression.fromJson(expressionClone); newExpression = expression; } else { newExpression = pastedExpression; } var parentBuilder = this.get('filterBuilder'); parentBuilder.set('expression', newExpression, true /* preventChange Undo State * */); }
[ "function", "(", "expression", ")", "{", "var", "pastedExpression", "=", "new", "Expression", "(", ")", ";", "var", "key", "=", "this", ".", "_getKey", "(", ")", ";", "pastedExpression", ".", "fromJson", "(", "json", ".", "parse", "(", "localStorage", "[", "key", "]", ")", ")", ";", "var", "newExpression", ";", "if", "(", "expression", ")", "{", "var", "expressionClone", "=", "new", "Expression", "(", "{", "operator", ":", "'and'", ",", "expressionList", ":", "[", "expression", ",", "pastedExpression", "]", "}", ")", ".", "toJson", "(", ")", ";", "expression", ".", "fromJson", "(", "expressionClone", ")", ";", "newExpression", "=", "expression", ";", "}", "else", "{", "newExpression", "=", "pastedExpression", ";", "}", "var", "parentBuilder", "=", "this", ".", "get", "(", "'filterBuilder'", ")", ";", "parentBuilder", ".", "set", "(", "'expression'", ",", "newExpression", ",", "true", ")", ";", "}" ]
Pastes the copied expression in the same level as the one provided and returns the new Expression If null is provided then it just returns the pasted expression.
[ "Pastes", "the", "copied", "expression", "in", "the", "same", "level", "as", "the", "one", "provided", "and", "returns", "the", "new", "Expression", "If", "null", "is", "provided", "then", "it", "just", "returns", "the", "pasted", "expression", "." ]
5da252baff42c13f92fa8f45932439993e9f7dd3
https://github.com/ninejs/ninejs/blob/5da252baff42c13f92fa8f45932439993e9f7dd3/ui/logic/FilterBuilder/DefaultClipboardStrategy.js#L54-L76
train
recidive/choko
server.js
getArguments
function getArguments() { var port = 3000; var path = '.'; var args = process.argv.slice(2); while (args.length) { var arg = args.shift(); switch (arg) { case '-p': port = args.shift(); break; default: path = arg || path; } } return { port: port, path: path }; }
javascript
function getArguments() { var port = 3000; var path = '.'; var args = process.argv.slice(2); while (args.length) { var arg = args.shift(); switch (arg) { case '-p': port = args.shift(); break; default: path = arg || path; } } return { port: port, path: path }; }
[ "function", "getArguments", "(", ")", "{", "var", "port", "=", "3000", ";", "var", "path", "=", "'.'", ";", "var", "args", "=", "process", ".", "argv", ".", "slice", "(", "2", ")", ";", "while", "(", "args", ".", "length", ")", "{", "var", "arg", "=", "args", ".", "shift", "(", ")", ";", "switch", "(", "arg", ")", "{", "case", "'-p'", ":", "port", "=", "args", ".", "shift", "(", ")", ";", "break", ";", "default", ":", "path", "=", "arg", "||", "path", ";", "}", "}", "return", "{", "port", ":", "port", ",", "path", ":", "path", "}", ";", "}" ]
Get port and application folder path from command line arguments. Use port from "-p" or fallback to 3000. Default folder is the current folder.
[ "Get", "port", "and", "application", "folder", "path", "from", "command", "line", "arguments", ".", "Use", "port", "from", "-", "p", "or", "fallback", "to", "3000", ".", "Default", "folder", "is", "the", "current", "folder", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/server.js#L13-L33
train
scott-wyatt/sails-stripe
templates/Discount.template.js
function (discount, cb) { Discount.destroy(discount.id) .exec(function (err, destroyedDiscounts){ if (err) return cb(err); if (!destroyedDiscounts) return cb(null, null); Discount.afterStripeCustomerDiscountDeleted(destroyedDiscounts[0], function(err, discount){ cb(err, discount); }); }); }
javascript
function (discount, cb) { Discount.destroy(discount.id) .exec(function (err, destroyedDiscounts){ if (err) return cb(err); if (!destroyedDiscounts) return cb(null, null); Discount.afterStripeCustomerDiscountDeleted(destroyedDiscounts[0], function(err, discount){ cb(err, discount); }); }); }
[ "function", "(", "discount", ",", "cb", ")", "{", "Discount", ".", "destroy", "(", "discount", ".", "id", ")", ".", "exec", "(", "function", "(", "err", ",", "destroyedDiscounts", ")", "{", "if", "(", "err", ")", "return", "cb", "(", "err", ")", ";", "if", "(", "!", "destroyedDiscounts", ")", "return", "cb", "(", "null", ",", "null", ")", ";", "Discount", ".", "afterStripeCustomerDiscountDeleted", "(", "destroyedDiscounts", "[", "0", "]", ",", "function", "(", "err", ",", "discount", ")", "{", "cb", "(", "err", ",", "discount", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Stripe Webhook customer.discount.deleted
[ "Stripe", "Webhook", "customer", ".", "discount", ".", "deleted" ]
0766bc04a6893a07c842170f37b37200d6771425
https://github.com/scott-wyatt/sails-stripe/blob/0766bc04a6893a07c842170f37b37200d6771425/templates/Discount.template.js#L103-L113
train
impromptu/impromptu
lib/cache/ShimCache.js
ShimCache
function ShimCache(state, name, options) { this._callbacks = [] AbstractCache.call(this, state, name, options) }
javascript
function ShimCache(state, name, options) { this._callbacks = [] AbstractCache.call(this, state, name, options) }
[ "function", "ShimCache", "(", "state", ",", "name", ",", "options", ")", "{", "this", ".", "_callbacks", "=", "[", "]", "AbstractCache", ".", "call", "(", "this", ",", "state", ",", "name", ",", "options", ")", "}" ]
A shim that runs a function in the context of Impromptu's caching interface. Does NOT cache the result! @constructor @extends {AbstractCache} @param {State} state @param {string} name The name of the cache key. @param {Object} options The options for this instance of the cache.
[ "A", "shim", "that", "runs", "a", "function", "in", "the", "context", "of", "Impromptu", "s", "caching", "interface", ".", "Does", "NOT", "cache", "the", "result!" ]
829798eda62771d6a6ed971d87eef7a461932704
https://github.com/impromptu/impromptu/blob/829798eda62771d6a6ed971d87eef7a461932704/lib/cache/ShimCache.js#L16-L19
train
recidive/choko
lib/storage.js
function(when, operation) { return function(values, callback) { var callbackName = when + operation; // Call type callback. if (callbackName in settings) { return settings[callbackName](settings, values, function() { // Invoke hook on all extensions. application.invoke(callbackName, name, values, callback); }); } // Invoke hook on all extensions. application.invoke(callbackName, name, values, callback); }; }
javascript
function(when, operation) { return function(values, callback) { var callbackName = when + operation; // Call type callback. if (callbackName in settings) { return settings[callbackName](settings, values, function() { // Invoke hook on all extensions. application.invoke(callbackName, name, values, callback); }); } // Invoke hook on all extensions. application.invoke(callbackName, name, values, callback); }; }
[ "function", "(", "when", ",", "operation", ")", "{", "return", "function", "(", "values", ",", "callback", ")", "{", "var", "callbackName", "=", "when", "+", "operation", ";", "if", "(", "callbackName", "in", "settings", ")", "{", "return", "settings", "[", "callbackName", "]", "(", "settings", ",", "values", ",", "function", "(", ")", "{", "application", ".", "invoke", "(", "callbackName", ",", "name", ",", "values", ",", "callback", ")", ";", "}", ")", ";", "}", "application", ".", "invoke", "(", "callbackName", ",", "name", ",", "values", ",", "callback", ")", ";", "}", ";", "}" ]
Generate callbacks for all Waterline lifecycle callbacks.
[ "Generate", "callbacks", "for", "all", "Waterline", "lifecycle", "callbacks", "." ]
7c0576c8c55543ec99d04ea609700765f178f73a
https://github.com/recidive/choko/blob/7c0576c8c55543ec99d04ea609700765f178f73a/lib/storage.js#L115-L130
train
XOP/sass-vars-to-js
src/_collect-declarations.js
collectDeclarations
function collectDeclarations (filePath) { const declarationRegexp = /(?:\$)([\w-]+)(?:[\s\n\r\t])*(?::)(?:[\s\n\r\t])*(.+)(?:[\s\n\r\t])*(?:;)/gm; const fileSource = fs.readFileSync(filePath, 'utf8'); return fileSource.match(declarationRegexp); }
javascript
function collectDeclarations (filePath) { const declarationRegexp = /(?:\$)([\w-]+)(?:[\s\n\r\t])*(?::)(?:[\s\n\r\t])*(.+)(?:[\s\n\r\t])*(?:;)/gm; const fileSource = fs.readFileSync(filePath, 'utf8'); return fileSource.match(declarationRegexp); }
[ "function", "collectDeclarations", "(", "filePath", ")", "{", "const", "declarationRegexp", "=", "/", "(?:\\$)([\\w-]+)(?:[\\s\\n\\r\\t])*(?::)(?:[\\s\\n\\r\\t])*(.+)(?:[\\s\\n\\r\\t])*(?:;)", "/", "gm", ";", "const", "fileSource", "=", "fs", ".", "readFileSync", "(", "filePath", ",", "'utf8'", ")", ";", "return", "fileSource", ".", "match", "(", "declarationRegexp", ")", ";", "}" ]
Parses file Returns declarations array @param filePath @returns {Array|{index: number, input: string}|*|Array}
[ "Parses", "file", "Returns", "declarations", "array" ]
87ad8588701a9c2e69ace75931947d11698f25f0
https://github.com/XOP/sass-vars-to-js/blob/87ad8588701a9c2e69ace75931947d11698f25f0/src/_collect-declarations.js#L9-L14
train