repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
BrandwatchLtd/nudge
index.js
nudge
function nudge(emitter, eventSpecs) { 'use strict'; checkValidity(eventSpecs); var proxy = makeProxyEmitter(emitter, eventSpecs); return function middleware(req, res) { function write(string) { res.write(string); } proxy.on('data', write); req.once('close', function removeListener() { proxy.removeListener('data', write); }); // Necessary headers for SSE. res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' // Tell Nginx not to buffer this response. }); // SSE required newline. write('\n'); }; }
javascript
function nudge(emitter, eventSpecs) { 'use strict'; checkValidity(eventSpecs); var proxy = makeProxyEmitter(emitter, eventSpecs); return function middleware(req, res) { function write(string) { res.write(string); } proxy.on('data', write); req.once('close', function removeListener() { proxy.removeListener('data', write); }); // Necessary headers for SSE. res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' // Tell Nginx not to buffer this response. }); // SSE required newline. write('\n'); }; }
[ "function", "nudge", "(", "emitter", ",", "eventSpecs", ")", "{", "'use strict'", ";", "checkValidity", "(", "eventSpecs", ")", ";", "var", "proxy", "=", "makeProxyEmitter", "(", "emitter", ",", "eventSpecs", ")", ";", "return", "function", "middleware", "(", "req", ",", "res", ")", "{", "function", "write", "(", "string", ")", "{", "res", ".", "write", "(", "string", ")", ";", "}", "proxy", ".", "on", "(", "'data'", ",", "write", ")", ";", "req", ".", "once", "(", "'close'", ",", "function", "removeListener", "(", ")", "{", "proxy", ".", "removeListener", "(", "'data'", ",", "write", ")", ";", "}", ")", ";", "res", ".", "writeHead", "(", "200", ",", "{", "'Content-Type'", ":", "'text/event-stream'", ",", "'Cache-Control'", ":", "'no-cache'", ",", "'Connection'", ":", "'keep-alive'", ",", "'X-Accel-Buffering'", ":", "'no'", "}", ")", ";", "write", "(", "'\\n'", ")", ";", "}", ";", "}" ]
eventSpecs is an object. Each field must contain true, or a sub object with a name, or a function, or both.
[ "eventSpecs", "is", "an", "object", ".", "Each", "field", "must", "contain", "true", "or", "a", "sub", "object", "with", "a", "name", "or", "a", "function", "or", "both", "." ]
77d52b654791ccc8e4fc67860efa6706212bde7e
https://github.com/BrandwatchLtd/nudge/blob/77d52b654791ccc8e4fc67860efa6706212bde7e/index.js#L7-L36
train
applitools/Eyes.Protractor
src/Eyes.js
function (point, size, isRelative) { return {left: Math.ceil(point.x), top: Math.ceil(point.y), width: Math.ceil(size.width), height: Math.ceil(size.height), relative: isRelative}; }
javascript
function (point, size, isRelative) { return {left: Math.ceil(point.x), top: Math.ceil(point.y), width: Math.ceil(size.width), height: Math.ceil(size.height), relative: isRelative}; }
[ "function", "(", "point", ",", "size", ",", "isRelative", ")", "{", "return", "{", "left", ":", "Math", ".", "ceil", "(", "point", ".", "x", ")", ",", "top", ":", "Math", ".", "ceil", "(", "point", ".", "y", ")", ",", "width", ":", "Math", ".", "ceil", "(", "size", ".", "width", ")", ",", "height", ":", "Math", ".", "ceil", "(", "size", ".", "height", ")", ",", "relative", ":", "isRelative", "}", ";", "}" ]
A helper function for creating region objects to be used in checkWindow @param {Object} point A point which represents the location of the region (x,y). @param {Object} size The size of the region (width, height). @param {boolean} isRelative Whether or not the region coordinates are relative to the image coordinates. @return {Object} A region object.
[ "A", "helper", "function", "for", "creating", "region", "objects", "to", "be", "used", "in", "checkWindow" ]
bccd29c27029c2344e732ea120a6b544b859004d
https://github.com/applitools/Eyes.Protractor/blob/bccd29c27029c2344e732ea120a6b544b859004d/src/Eyes.js#L169-L172
train
helpers/handlebars-helper-md
index.js
function(grunt, context) { grunt.config.data = _.defaults(context || {}, _.cloneDeep(grunt.config.data)); return grunt.config.process(grunt.config.data); }
javascript
function(grunt, context) { grunt.config.data = _.defaults(context || {}, _.cloneDeep(grunt.config.data)); return grunt.config.process(grunt.config.data); }
[ "function", "(", "grunt", ",", "context", ")", "{", "grunt", ".", "config", ".", "data", "=", "_", ".", "defaults", "(", "context", "||", "{", "}", ",", "_", ".", "cloneDeep", "(", "grunt", ".", "config", ".", "data", ")", ")", ";", "return", "grunt", ".", "config", ".", "process", "(", "grunt", ".", "config", ".", "data", ")", ";", "}" ]
Process templates using grunt.config.data and context
[ "Process", "templates", "using", "grunt", ".", "config", ".", "data", "and", "context" ]
18e4b2f937473f88cbfce59122cb084ac18465ca
https://github.com/helpers/handlebars-helper-md/blob/18e4b2f937473f88cbfce59122cb084ac18465ca/index.js#L153-L156
train
aurelia-contrib/aurelia-typed-observable-plugin
dist/es2015/index.js
mapCoerceFunction
function mapCoerceFunction(type, strType, coerceFunction) { coerceFunction = coerceFunction || type.coerce; if (typeof strType !== 'string' || typeof coerceFunction !== 'function') { getLogger('map-coerce-function') .warn(`Bad attempt at mapping coerce function for type: ${type.name} to: ${strType}`); return; } coerceFunctions[strType] = coerceFunction; coerceFunctionMap.set(type, strType); }
javascript
function mapCoerceFunction(type, strType, coerceFunction) { coerceFunction = coerceFunction || type.coerce; if (typeof strType !== 'string' || typeof coerceFunction !== 'function') { getLogger('map-coerce-function') .warn(`Bad attempt at mapping coerce function for type: ${type.name} to: ${strType}`); return; } coerceFunctions[strType] = coerceFunction; coerceFunctionMap.set(type, strType); }
[ "function", "mapCoerceFunction", "(", "type", ",", "strType", ",", "coerceFunction", ")", "{", "coerceFunction", "=", "coerceFunction", "||", "type", ".", "coerce", ";", "if", "(", "typeof", "strType", "!==", "'string'", "||", "typeof", "coerceFunction", "!==", "'function'", ")", "{", "getLogger", "(", "'map-coerce-function'", ")", ".", "warn", "(", "`", "${", "type", ".", "name", "}", "${", "strType", "}", "`", ")", ";", "return", ";", "}", "coerceFunctions", "[", "strType", "]", "=", "coerceFunction", ";", "coerceFunctionMap", ".", "set", "(", "type", ",", "strType", ")", ";", "}" ]
Map a class to a string for typescript property coerce @param type the property class to register @param strType the string that represents class in the lookup @param coerceFunction coerce function to register with param strType
[ "Map", "a", "class", "to", "a", "string", "for", "typescript", "property", "coerce" ]
e041e96366b1179472f3e742a4dc40a03159e025
https://github.com/aurelia-contrib/aurelia-typed-observable-plugin/blob/e041e96366b1179472f3e742a4dc40a03159e025/dist/es2015/index.js#L43-L52
train
inadarei/connect-thumbs
lib/connect-thumbs.js
parseOptions
function parseOptions(options) { ttl = options.ttl || (3600 * 24); // cache for 1 day by default. tmpCacheTTL = options.tmpCacheTTL || 5; // small by default decodeFn = options.decodeFn || exports.decodeURL; presets = options.presets || defaultPresets(); tmpDir = options.tmpDir || '/tmp/nodethumbnails'; var rootPath = options.rootPath || '/thumbs'; if (rootPath[0] === '/') { rootPath = rootPath.substring(1); } // be forgiving to user errors! var allowedExtensions = options.allowedExtensions || ['gif', 'png', 'jpg', 'jpeg']; for (var i=0; i < allowedExtensions.length; i++) { // be forgiving to user errors! if (allowedExtensions[i][0] === '.') { allowedExtensions[i] = allowedExtensions[i].substring(1); } } var szExtensions = allowedExtensions.join('|'); // Example: http://example.com/thumbs/small/images/AB23DC16Hash.jpg regexp = new RegExp('^\/' + rootPath.replace(/\//ig, '\\/') + '\/([A-Za-z0-9_]+)\/images\/([%\.\-A-Za-z0-9_=\+]+)\.(?:' + szExtensions + ')$', 'i'); }
javascript
function parseOptions(options) { ttl = options.ttl || (3600 * 24); // cache for 1 day by default. tmpCacheTTL = options.tmpCacheTTL || 5; // small by default decodeFn = options.decodeFn || exports.decodeURL; presets = options.presets || defaultPresets(); tmpDir = options.tmpDir || '/tmp/nodethumbnails'; var rootPath = options.rootPath || '/thumbs'; if (rootPath[0] === '/') { rootPath = rootPath.substring(1); } // be forgiving to user errors! var allowedExtensions = options.allowedExtensions || ['gif', 'png', 'jpg', 'jpeg']; for (var i=0; i < allowedExtensions.length; i++) { // be forgiving to user errors! if (allowedExtensions[i][0] === '.') { allowedExtensions[i] = allowedExtensions[i].substring(1); } } var szExtensions = allowedExtensions.join('|'); // Example: http://example.com/thumbs/small/images/AB23DC16Hash.jpg regexp = new RegExp('^\/' + rootPath.replace(/\//ig, '\\/') + '\/([A-Za-z0-9_]+)\/images\/([%\.\-A-Za-z0-9_=\+]+)\.(?:' + szExtensions + ')$', 'i'); }
[ "function", "parseOptions", "(", "options", ")", "{", "ttl", "=", "options", ".", "ttl", "||", "(", "3600", "*", "24", ")", ";", "tmpCacheTTL", "=", "options", ".", "tmpCacheTTL", "||", "5", ";", "decodeFn", "=", "options", ".", "decodeFn", "||", "exports", ".", "decodeURL", ";", "presets", "=", "options", ".", "presets", "||", "defaultPresets", "(", ")", ";", "tmpDir", "=", "options", ".", "tmpDir", "||", "'/tmp/nodethumbnails'", ";", "var", "rootPath", "=", "options", ".", "rootPath", "||", "'/thumbs'", ";", "if", "(", "rootPath", "[", "0", "]", "===", "'/'", ")", "{", "rootPath", "=", "rootPath", ".", "substring", "(", "1", ")", ";", "}", "var", "allowedExtensions", "=", "options", ".", "allowedExtensions", "||", "[", "'gif'", ",", "'png'", ",", "'jpg'", ",", "'jpeg'", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "allowedExtensions", ".", "length", ";", "i", "++", ")", "{", "if", "(", "allowedExtensions", "[", "i", "]", "[", "0", "]", "===", "'.'", ")", "{", "allowedExtensions", "[", "i", "]", "=", "allowedExtensions", "[", "i", "]", ".", "substring", "(", "1", ")", ";", "}", "}", "var", "szExtensions", "=", "allowedExtensions", ".", "join", "(", "'|'", ")", ";", "regexp", "=", "new", "RegExp", "(", "'^\\/'", "+", "\\/", "+", "rootPath", ".", "replace", "(", "/", "\\/", "/", "ig", ",", "'\\\\/'", ")", "+", "\\\\", "+", "'\\/([A-Za-z0-9_]+)\\/images\\/([%\\.\\-A-Za-z0-9_=\\+]+)\\.(?:'", ",", "\\/", ")", ";", "}" ]
Merge user-provided options with the sensible defaults. @param options
[ "Merge", "user", "-", "provided", "options", "with", "the", "sensible", "defaults", "." ]
ccd6495cdb9718d674ce09eb35f1eb2ce077d340
https://github.com/inadarei/connect-thumbs/blob/ccd6495cdb9718d674ce09eb35f1eb2ce077d340/lib/connect-thumbs.js#L183-L207
train
sbolel/image-uploader
src/image-uploader.js
function () { var text = '' var regx = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for (var idx = 0; idx < 8; idx++) { text = text + regx.charAt(Math.floor(Math.random() * regx.length)) } return text }
javascript
function () { var text = '' var regx = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' for (var idx = 0; idx < 8; idx++) { text = text + regx.charAt(Math.floor(Math.random() * regx.length)) } return text }
[ "function", "(", ")", "{", "var", "text", "=", "''", "var", "regx", "=", "'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'", "for", "(", "var", "idx", "=", "0", ";", "idx", "<", "8", ";", "idx", "++", ")", "{", "text", "=", "text", "+", "regx", ".", "charAt", "(", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "regx", ".", "length", ")", ")", "}", "return", "text", "}" ]
Generate a unique string
[ "Generate", "a", "unique", "string" ]
7ddb9ef0029e577b81d88d6e4379687895cf64f3
https://github.com/sbolel/image-uploader/blob/7ddb9ef0029e577b81d88d6e4379687895cf64f3/src/image-uploader.js#L7-L14
train
calvium/react-native-device-screen-switcher
src/ScreenSwitcher.js
performResize
function performResize(deviceInfo) { const {windowPhysicalPixels} = deviceInfo; const {width, height} = windowPhysicalPixels; // Force RN to re-set the Dimensions sizes Dimensions.set({windowPhysicalPixels}); console.log(`Resizing window to physical pixels ${width}x${height}`); // TODO: Android uses screenPhysicalPixels - see https://github.com/facebook/react-native/blob/master/Libraries/Utilities/Dimensions.js }
javascript
function performResize(deviceInfo) { const {windowPhysicalPixels} = deviceInfo; const {width, height} = windowPhysicalPixels; // Force RN to re-set the Dimensions sizes Dimensions.set({windowPhysicalPixels}); console.log(`Resizing window to physical pixels ${width}x${height}`); // TODO: Android uses screenPhysicalPixels - see https://github.com/facebook/react-native/blob/master/Libraries/Utilities/Dimensions.js }
[ "function", "performResize", "(", "deviceInfo", ")", "{", "const", "{", "windowPhysicalPixels", "}", "=", "deviceInfo", ";", "const", "{", "width", ",", "height", "}", "=", "windowPhysicalPixels", ";", "Dimensions", ".", "set", "(", "{", "windowPhysicalPixels", "}", ")", ";", "console", ".", "log", "(", "`", "${", "width", "}", "${", "height", "}", "`", ")", ";", "}" ]
Force resize of Dimensions.get by using the setter.
[ "Force", "resize", "of", "Dimensions", ".", "get", "by", "using", "the", "setter", "." ]
b1ae5c9b90b9d99a5b972437498995dfdde1baff
https://github.com/calvium/react-native-device-screen-switcher/blob/b1ae5c9b90b9d99a5b972437498995dfdde1baff/src/ScreenSwitcher.js#L19-L27
train
jonschlinkert/write-json
index.js
writeJson
function writeJson(filepath, value, cb) { var args = [].slice.call(arguments, 1); if (typeof args[args.length - 1] === 'function') { cb = args.pop(); } return writeFile(filepath, stringify.apply(null, args), cb); }
javascript
function writeJson(filepath, value, cb) { var args = [].slice.call(arguments, 1); if (typeof args[args.length - 1] === 'function') { cb = args.pop(); } return writeFile(filepath, stringify.apply(null, args), cb); }
[ "function", "writeJson", "(", "filepath", ",", "value", ",", "cb", ")", "{", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "if", "(", "typeof", "args", "[", "args", ".", "length", "-", "1", "]", "===", "'function'", ")", "{", "cb", "=", "args", ".", "pop", "(", ")", ";", "}", "return", "writeFile", "(", "filepath", ",", "stringify", ".", "apply", "(", "null", ",", "args", ")", ",", "cb", ")", ";", "}" ]
Calls `JSON.stringify` on the given `value` then asynchronously writes the result to a file, replacing the file if it already exists and creating any intermediate directories if they don't already exist. Returns a promise if a callback function is not passed. ```js var writeJson = require('write'); var pkg = {name: 'write-json'}; writeJson('foo.json', pkg, function(err) { if (err) console.log(err); }); // pass options to JSON.stringify explicitly writeJson('foo.json', pkg, null, 2, function(err) { if (err) console.log(err); }); // pass options to JSON.stringify as an object // (since this method returns a promise if no callback is passed, // if you want to pass a replacer function to JSON.stringify, it // must be passed on an options object) writeJson('foo.json', pkg, { indent: 2, replacer: function(value) { // filter out properties if (typeof value === 'string') { return undefined; } return value; } }, function(err) { if (err) console.log(err); }); ``` @name writeJson @param {string} `filepath` Destination file path @param {object} `value` Value to stringify. @param {object} `options` Options to pass to [JSON.stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) @param {Function} `callback` (optional) If no callback is provided, a promise is returned. @return {undefined} @api public
[ "Calls", "JSON", ".", "stringify", "on", "the", "given", "value", "then", "asynchronously", "writes", "the", "result", "to", "a", "file", "replacing", "the", "file", "if", "it", "already", "exists", "and", "creating", "any", "intermediate", "directories", "if", "they", "don", "t", "already", "exist", ".", "Returns", "a", "promise", "if", "a", "callback", "function", "is", "not", "passed", "." ]
1159465425ab04f3a8748663fdb5dead306c2c2e
https://github.com/jonschlinkert/write-json/blob/1159465425ab04f3a8748663fdb5dead306c2c2e/index.js#L58-L64
train
jonschlinkert/write-json
index.js
stringify
function stringify(value, replacer, indent) { if (isObject(replacer)) { var opts = replacer; replacer = opts.replacer; indent = opts.indent; } if (indent == null) { indent = 2; } return JSON.stringify(value, replacer, indent); }
javascript
function stringify(value, replacer, indent) { if (isObject(replacer)) { var opts = replacer; replacer = opts.replacer; indent = opts.indent; } if (indent == null) { indent = 2; } return JSON.stringify(value, replacer, indent); }
[ "function", "stringify", "(", "value", ",", "replacer", ",", "indent", ")", "{", "if", "(", "isObject", "(", "replacer", ")", ")", "{", "var", "opts", "=", "replacer", ";", "replacer", "=", "opts", ".", "replacer", ";", "indent", "=", "opts", ".", "indent", ";", "}", "if", "(", "indent", "==", "null", ")", "{", "indent", "=", "2", ";", "}", "return", "JSON", ".", "stringify", "(", "value", ",", "replacer", ",", "indent", ")", ";", "}" ]
Utility function for stringifying the given value, ensuring that options are correctly passed to `JSON.stringify`. @param {any} `value` @param {Function|Object} `replacer` Function or options object @param {String|Number} `indent` The actual value to use for spacing, or the number of spaces to use. @return {String}
[ "Utility", "function", "for", "stringifying", "the", "given", "value", "ensuring", "that", "options", "are", "correctly", "passed", "to", "JSON", ".", "stringify", "." ]
1159465425ab04f3a8748663fdb5dead306c2c2e
https://github.com/jonschlinkert/write-json/blob/1159465425ab04f3a8748663fdb5dead306c2c2e/index.js#L144-L154
train
personality-insights/text-summary
src/utilities/comparators.js
compareByRelevance
function compareByRelevance(o1, o2) { var result = 0; if (Math.abs(0.5 - o1.percentage) > Math.abs(0.5 - o2.percentage)) { result = -1; // A trait with 1% is more interesting than one with 60%. } if (Math.abs(0.5 - o1.percentage) < Math.abs(0.5 - o2.percentage)) { result = 1; } return result; }
javascript
function compareByRelevance(o1, o2) { var result = 0; if (Math.abs(0.5 - o1.percentage) > Math.abs(0.5 - o2.percentage)) { result = -1; // A trait with 1% is more interesting than one with 60%. } if (Math.abs(0.5 - o1.percentage) < Math.abs(0.5 - o2.percentage)) { result = 1; } return result; }
[ "function", "compareByRelevance", "(", "o1", ",", "o2", ")", "{", "var", "result", "=", "0", ";", "if", "(", "Math", ".", "abs", "(", "0.5", "-", "o1", ".", "percentage", ")", ">", "Math", ".", "abs", "(", "0.5", "-", "o2", ".", "percentage", ")", ")", "{", "result", "=", "-", "1", ";", "}", "if", "(", "Math", ".", "abs", "(", "0.5", "-", "o1", ".", "percentage", ")", "<", "Math", ".", "abs", "(", "0.5", "-", "o2", ".", "percentage", ")", ")", "{", "result", "=", "1", ";", "}", "return", "result", ";", "}" ]
Copyright 2015 IBM Corp. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
[ "Copyright", "2015", "IBM", "Corp", ".", "All", "Rights", "Reserved", "." ]
3d6585e2ee65528b256857f9fa2be34bf1c2de0c
https://github.com/personality-insights/text-summary/blob/3d6585e2ee65528b256857f9fa2be34bf1c2de0c/src/utilities/comparators.js#L18-L30
train
scottinet/espresso-logic-minimizer
index.js
minimize
function minimize(data) { if (!Array.isArray(data)) { throw new Error('EspressoLogicMinimizer: expected an array, got a ' + typeof data); } const badContent = data.filter((element) => typeof element != 'string'); if (badContent.length > 0) { throw new Error('EspressoLogicMinimizer: incorrect data content. Only strings are supported: ' + badContent); } return EspressoLogicMinimizer.minimize_from_data(data); }
javascript
function minimize(data) { if (!Array.isArray(data)) { throw new Error('EspressoLogicMinimizer: expected an array, got a ' + typeof data); } const badContent = data.filter((element) => typeof element != 'string'); if (badContent.length > 0) { throw new Error('EspressoLogicMinimizer: incorrect data content. Only strings are supported: ' + badContent); } return EspressoLogicMinimizer.minimize_from_data(data); }
[ "function", "minimize", "(", "data", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "data", ")", ")", "{", "throw", "new", "Error", "(", "'EspressoLogicMinimizer: expected an array, got a '", "+", "typeof", "data", ")", ";", "}", "const", "badContent", "=", "data", ".", "filter", "(", "(", "element", ")", "=>", "typeof", "element", "!=", "'string'", ")", ";", "if", "(", "badContent", ".", "length", ">", "0", ")", "{", "throw", "new", "Error", "(", "'EspressoLogicMinimizer: incorrect data content. Only strings are supported: '", "+", "badContent", ")", ";", "}", "return", "EspressoLogicMinimizer", ".", "minimize_from_data", "(", "data", ")", ";", "}" ]
Applies the Espresso Heuristic Logic Minimizer algorithm to the provided data in PLA format @param {Array} data @returns {Array}
[ "Applies", "the", "Espresso", "Heuristic", "Logic", "Minimizer", "algorithm", "to", "the", "provided", "data", "in", "PLA", "format" ]
034ff2d466336ee49db64f8f3f975ed2b57f2364
https://github.com/scottinet/espresso-logic-minimizer/blob/034ff2d466336ee49db64f8f3f975ed2b57f2364/index.js#L15-L27
train
VideoSpike/nativescript-screen-orientation
screen-orientation.ios.js
findPrototypeForProperty
function findPrototypeForProperty(object,property){ while(false==object.hasOwnProperty(property)){ object = Object.getPrototypeOf(object); } return object; }
javascript
function findPrototypeForProperty(object,property){ while(false==object.hasOwnProperty(property)){ object = Object.getPrototypeOf(object); } return object; }
[ "function", "findPrototypeForProperty", "(", "object", ",", "property", ")", "{", "while", "(", "false", "==", "object", ".", "hasOwnProperty", "(", "property", ")", ")", "{", "object", "=", "Object", ".", "getPrototypeOf", "(", "object", ")", ";", "}", "return", "object", ";", "}" ]
find the exact object by which the property is owned in the prototype chain @param object @param property @returns {*}
[ "find", "the", "exact", "object", "by", "which", "the", "property", "is", "owned", "in", "the", "prototype", "chain" ]
95b526434b9f077cf1e295bba6bb67c739512a17
https://github.com/VideoSpike/nativescript-screen-orientation/blob/95b526434b9f077cf1e295bba6bb67c739512a17/screen-orientation.ios.js#L16-L21
train
VideoSpike/nativescript-screen-orientation
screen-orientation.ios.js
setShouldAutoRotate
function setShouldAutoRotate(bool){ var prototypeForNavController = findPrototypeForProperty(frameModule.topmost().ios.controller,"shouldAutorotate"); Object.defineProperty(prototypeForNavController,"shouldAutorotate",{ configurable:true, enumerable:false, get:function(){ return bool; } }) }
javascript
function setShouldAutoRotate(bool){ var prototypeForNavController = findPrototypeForProperty(frameModule.topmost().ios.controller,"shouldAutorotate"); Object.defineProperty(prototypeForNavController,"shouldAutorotate",{ configurable:true, enumerable:false, get:function(){ return bool; } }) }
[ "function", "setShouldAutoRotate", "(", "bool", ")", "{", "var", "prototypeForNavController", "=", "findPrototypeForProperty", "(", "frameModule", ".", "topmost", "(", ")", ".", "ios", ".", "controller", ",", "\"shouldAutorotate\"", ")", ";", "Object", ".", "defineProperty", "(", "prototypeForNavController", ",", "\"shouldAutorotate\"", ",", "{", "configurable", ":", "true", ",", "enumerable", ":", "false", ",", "get", ":", "function", "(", ")", "{", "return", "bool", ";", "}", "}", ")", "}" ]
set should auto rotate @param bool
[ "set", "should", "auto", "rotate" ]
95b526434b9f077cf1e295bba6bb67c739512a17
https://github.com/VideoSpike/nativescript-screen-orientation/blob/95b526434b9f077cf1e295bba6bb67c739512a17/screen-orientation.ios.js#L27-L37
train
VideoSpike/nativescript-screen-orientation
screen-orientation.ios.js
setCurrentOrientation
function setCurrentOrientation(orientationType,callback){ if("landscape"==orientationType.toLowerCase()){ UIDevice.currentDevice.setValueForKey(UIInterfaceOrientationLandscapeLeft,"orientation"); setShouldAutoRotate(false); } else if("portrait"==orientationType.toLowerCase()){ UIDevice.currentDevice.setValueForKey(UIInterfaceOrientationPortrait,"orientation"); setShouldAutoRotate(false); }else if("all" == orientationType.toLowerCase()){ setShouldAutoRotate(true); } if(undefined!==callback){ callback(); } }
javascript
function setCurrentOrientation(orientationType,callback){ if("landscape"==orientationType.toLowerCase()){ UIDevice.currentDevice.setValueForKey(UIInterfaceOrientationLandscapeLeft,"orientation"); setShouldAutoRotate(false); } else if("portrait"==orientationType.toLowerCase()){ UIDevice.currentDevice.setValueForKey(UIInterfaceOrientationPortrait,"orientation"); setShouldAutoRotate(false); }else if("all" == orientationType.toLowerCase()){ setShouldAutoRotate(true); } if(undefined!==callback){ callback(); } }
[ "function", "setCurrentOrientation", "(", "orientationType", ",", "callback", ")", "{", "if", "(", "\"landscape\"", "==", "orientationType", ".", "toLowerCase", "(", ")", ")", "{", "UIDevice", ".", "currentDevice", ".", "setValueForKey", "(", "UIInterfaceOrientationLandscapeLeft", ",", "\"orientation\"", ")", ";", "setShouldAutoRotate", "(", "false", ")", ";", "}", "else", "if", "(", "\"portrait\"", "==", "orientationType", ".", "toLowerCase", "(", ")", ")", "{", "UIDevice", ".", "currentDevice", ".", "setValueForKey", "(", "UIInterfaceOrientationPortrait", ",", "\"orientation\"", ")", ";", "setShouldAutoRotate", "(", "false", ")", ";", "}", "else", "if", "(", "\"all\"", "==", "orientationType", ".", "toLowerCase", "(", ")", ")", "{", "setShouldAutoRotate", "(", "true", ")", ";", "}", "if", "(", "undefined", "!==", "callback", ")", "{", "callback", "(", ")", ";", "}", "}" ]
set current orientation and call the callback once the orientation is set @param orientationType @param callback
[ "set", "current", "orientation", "and", "call", "the", "callback", "once", "the", "orientation", "is", "set" ]
95b526434b9f077cf1e295bba6bb67c739512a17
https://github.com/VideoSpike/nativescript-screen-orientation/blob/95b526434b9f077cf1e295bba6bb67c739512a17/screen-orientation.ios.js#L44-L61
train
textlint/textlint-plugin-html
src/html-to-ast.js
removeUnusedProperties
function removeUnusedProperties(node) { if (typeof node !== "object") { return; } ["position"].forEach(function (key) { if (node.hasOwnProperty(key)) { delete node[key]; } }); }
javascript
function removeUnusedProperties(node) { if (typeof node !== "object") { return; } ["position"].forEach(function (key) { if (node.hasOwnProperty(key)) { delete node[key]; } }); }
[ "function", "removeUnusedProperties", "(", "node", ")", "{", "if", "(", "typeof", "node", "!==", "\"object\"", ")", "{", "return", ";", "}", "[", "\"position\"", "]", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "node", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "delete", "node", "[", "key", "]", ";", "}", "}", ")", ";", "}" ]
Remove undocumented properties on TxtNode from node @param {TxtNode} node already has loc,range
[ "Remove", "undocumented", "properties", "on", "TxtNode", "from", "node" ]
13d1f3a7619dd3d1bdcd7e1a5bd80726b2bdd816
https://github.com/textlint/textlint-plugin-html/blob/13d1f3a7619dd3d1bdcd7e1a5bd80726b2bdd816/src/html-to-ast.js#L11-L20
train
dfahlander/just-build
src/execute.js
executeAll
function executeAll (cfg) { console.log(`${clr.DIM+clr.LIGHT_MAGENTA}Package: ${cfg.packageRoot}${clr.RESET}`); return new Promise((resolve, reject) => { createObservable(cfg).subscribe({ next ({command, exitCode}) { if (exitCode == 0) cfg.log(`${EMIT_COLOR}just-build ${cfg.tasksToRun.join(' ')}`+ ` done.${clr.RESET}${cfg.watchMode ? NOW_WATCHING_COLOR+' Still watching...'+clr.RESET : ''}`); else cfg.log(`just-build ${cfg.tasksToRun.join(' ')} failed. ${command} returned ${exitCode}`); }, error (err) { reject(err); }, complete () { resolve(); } }); }); }
javascript
function executeAll (cfg) { console.log(`${clr.DIM+clr.LIGHT_MAGENTA}Package: ${cfg.packageRoot}${clr.RESET}`); return new Promise((resolve, reject) => { createObservable(cfg).subscribe({ next ({command, exitCode}) { if (exitCode == 0) cfg.log(`${EMIT_COLOR}just-build ${cfg.tasksToRun.join(' ')}`+ ` done.${clr.RESET}${cfg.watchMode ? NOW_WATCHING_COLOR+' Still watching...'+clr.RESET : ''}`); else cfg.log(`just-build ${cfg.tasksToRun.join(' ')} failed. ${command} returned ${exitCode}`); }, error (err) { reject(err); }, complete () { resolve(); } }); }); }
[ "function", "executeAll", "(", "cfg", ")", "{", "console", ".", "log", "(", "`", "${", "clr", ".", "DIM", "+", "clr", ".", "LIGHT_MAGENTA", "}", "${", "cfg", ".", "packageRoot", "}", "${", "clr", ".", "RESET", "}", "`", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "createObservable", "(", "cfg", ")", ".", "subscribe", "(", "{", "next", "(", "{", "command", ",", "exitCode", "}", ")", "{", "if", "(", "exitCode", "==", "0", ")", "cfg", ".", "log", "(", "`", "${", "EMIT_COLOR", "}", "${", "cfg", ".", "tasksToRun", ".", "join", "(", "' '", ")", "}", "`", "+", "`", "${", "clr", ".", "RESET", "}", "${", "cfg", ".", "watchMode", "?", "NOW_WATCHING_COLOR", "+", "' Still watching...'", "+", "clr", ".", "RESET", ":", "''", "}", "`", ")", ";", "else", "cfg", ".", "log", "(", "`", "${", "cfg", ".", "tasksToRun", ".", "join", "(", "' '", ")", "}", "${", "command", "}", "${", "exitCode", "}", "`", ")", ";", "}", ",", "error", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", ",", "complete", "(", ")", "{", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Execute the build tasks. @param cfg {{ dir: string, taskSet: Object.<string, string[]>, tasksToRun: string[], watchMode: boolean, spawn: Function, env: Object, log: Function, packageRoot: string }} Configuration to execute @return Promise
[ "Execute", "the", "build", "tasks", "." ]
52919bab419bbda36a02524b6897333e52ec2a94
https://github.com/dfahlander/just-build/blob/52919bab419bbda36a02524b6897333e52ec2a94/src/execute.js#L31-L50
train
dfahlander/just-build
src/execute.js
createObservable
function createObservable (cfg) { const {dir, taskSet, tasksToRun, watchMode, spawn, env, log} = cfg; const tasks = tasksToRun.map(taskName => { const commandList = taskSet[taskName]; if (!commandList) throw new Error (`No such task name: ${taskName} was configured`); return commandList; }); return createParallellCommandsExecutor ( tasks, dir, env, watchMode, {spawn, log}); }
javascript
function createObservable (cfg) { const {dir, taskSet, tasksToRun, watchMode, spawn, env, log} = cfg; const tasks = tasksToRun.map(taskName => { const commandList = taskSet[taskName]; if (!commandList) throw new Error (`No such task name: ${taskName} was configured`); return commandList; }); return createParallellCommandsExecutor ( tasks, dir, env, watchMode, {spawn, log}); }
[ "function", "createObservable", "(", "cfg", ")", "{", "const", "{", "dir", ",", "taskSet", ",", "tasksToRun", ",", "watchMode", ",", "spawn", ",", "env", ",", "log", "}", "=", "cfg", ";", "const", "tasks", "=", "tasksToRun", ".", "map", "(", "taskName", "=>", "{", "const", "commandList", "=", "taskSet", "[", "taskName", "]", ";", "if", "(", "!", "commandList", ")", "throw", "new", "Error", "(", "`", "${", "taskName", "}", "`", ")", ";", "return", "commandList", ";", "}", ")", ";", "return", "createParallellCommandsExecutor", "(", "tasks", ",", "dir", ",", "env", ",", "watchMode", ",", "{", "spawn", ",", "log", "}", ")", ";", "}" ]
Create a build-task executer as an Observable @param cfg {{ dir: string, taskSet: Object.<string, string[]>, tasksToRun: string[], watchMode: boolean, spawn: Function, env: Object, log: Function }} Configuration to execute @return Observable
[ "Create", "a", "build", "-", "task", "executer", "as", "an", "Observable" ]
52919bab419bbda36a02524b6897333e52ec2a94
https://github.com/dfahlander/just-build/blob/52919bab419bbda36a02524b6897333e52ec2a94/src/execute.js#L66-L82
train
dfahlander/just-build
src/execute.js
createSequencialCommandExecutor
function createSequencialCommandExecutor (commands, workingDir, envVars, watchMode, host) { const source = Observable.from([{ cwd: workingDir, env: envVars, exitCode: 0 }]); return commands.reduce((prev, command) => createCommandExecutor(command, prev, watchMode, host), source); }
javascript
function createSequencialCommandExecutor (commands, workingDir, envVars, watchMode, host) { const source = Observable.from([{ cwd: workingDir, env: envVars, exitCode: 0 }]); return commands.reduce((prev, command) => createCommandExecutor(command, prev, watchMode, host), source); }
[ "function", "createSequencialCommandExecutor", "(", "commands", ",", "workingDir", ",", "envVars", ",", "watchMode", ",", "host", ")", "{", "const", "source", "=", "Observable", ".", "from", "(", "[", "{", "cwd", ":", "workingDir", ",", "env", ":", "envVars", ",", "exitCode", ":", "0", "}", "]", ")", ";", "return", "commands", ".", "reduce", "(", "(", "prev", ",", "command", ")", "=>", "createCommandExecutor", "(", "command", ",", "prev", ",", "watchMode", ",", "host", ")", ",", "source", ")", ";", "}" ]
Create an Observable that would execute a sequence of commands. @param commands {string[]} A sequence of commands to execute @param workingDir {string} Initial Working Directory @param envVars {Object} Initial environment variables @param watchMode {boolean} Whether to execute watchers or not @param host {{spawn: Function, log: Function}} Mockable host environment (mimicking child_process.spawn() and console.log()) @returns Observable
[ "Create", "an", "Observable", "that", "would", "execute", "a", "sequence", "of", "commands", "." ]
52919bab419bbda36a02524b6897333e52ec2a94
https://github.com/dfahlander/just-build/blob/52919bab419bbda36a02524b6897333e52ec2a94/src/execute.js#L144-L153
train
dfahlander/just-build
src/dirutils.js
getPackageRoot
function getPackageRoot (dir) { let lastDir = null; while (lastDir !== dir && !fs.existsSync(path.resolve(dir, "./package.json"))) { lastDir = dir; dir = path.dirname(dir); } return (lastDir === dir ? null : dir); }
javascript
function getPackageRoot (dir) { let lastDir = null; while (lastDir !== dir && !fs.existsSync(path.resolve(dir, "./package.json"))) { lastDir = dir; dir = path.dirname(dir); } return (lastDir === dir ? null : dir); }
[ "function", "getPackageRoot", "(", "dir", ")", "{", "let", "lastDir", "=", "null", ";", "while", "(", "lastDir", "!==", "dir", "&&", "!", "fs", ".", "existsSync", "(", "path", ".", "resolve", "(", "dir", ",", "\"./package.json\"", ")", ")", ")", "{", "lastDir", "=", "dir", ";", "dir", "=", "path", ".", "dirname", "(", "dir", ")", ";", "}", "return", "(", "lastDir", "===", "dir", "?", "null", ":", "dir", ")", ";", "}" ]
Navigates upwards to the closest dir that contains a 'package.json'. @param dir {string} Directory to start from.
[ "Navigates", "upwards", "to", "the", "closest", "dir", "that", "contains", "a", "package", ".", "json", "." ]
52919bab419bbda36a02524b6897333e52ec2a94
https://github.com/dfahlander/just-build/blob/52919bab419bbda36a02524b6897333e52ec2a94/src/dirutils.js#L7-L14
train
liferay/liferay-module-config-generator
lib/config-generator.js
function() { var self = this; self._modules = []; return new Promise(function(resolve, reject) { var base; var processors = []; if (self._options.base) { base = fs.readFileSync(path.resolve(self._options.base), 'utf8'); } // For every file or folder, create a promise, // parse the file, extract the config and store it // to the global modules array. // Once all files are being processed, store the generated config. for (var i = 0; i < self._options.args.length; i++) { var file = self._options.args[i]; var fileStats = fs.statSync(file); if (fileStats.isDirectory(file)) { var walker = walk.walk(file, { followLinks: false }); walker.on('file', self._onWalkerFile.bind(self)); processors.push(self._onWalkerEnd(walker)); } else if (fileStats.isFile()) { processors.push(self._processFile(file)); } } Promise.all(processors) .then(function(uselessPromises) { return self._generateConfig(); }) .then(function(config) { var content; if (self._options.config) { if (base) { content = base + self._options.config + '.modules = ' + JSON.stringify(config) + ';'; } else { content = 'var ' + self._options.config + ' = {modules: ' + JSON.stringify(config) + '};'; } } else { content = JSON.stringify(config); } return self._saveConfig(beautify(content)); }) .then(function(config) { resolve(config); }) .catch(function(error) { reject(error); }); }); }
javascript
function() { var self = this; self._modules = []; return new Promise(function(resolve, reject) { var base; var processors = []; if (self._options.base) { base = fs.readFileSync(path.resolve(self._options.base), 'utf8'); } // For every file or folder, create a promise, // parse the file, extract the config and store it // to the global modules array. // Once all files are being processed, store the generated config. for (var i = 0; i < self._options.args.length; i++) { var file = self._options.args[i]; var fileStats = fs.statSync(file); if (fileStats.isDirectory(file)) { var walker = walk.walk(file, { followLinks: false }); walker.on('file', self._onWalkerFile.bind(self)); processors.push(self._onWalkerEnd(walker)); } else if (fileStats.isFile()) { processors.push(self._processFile(file)); } } Promise.all(processors) .then(function(uselessPromises) { return self._generateConfig(); }) .then(function(config) { var content; if (self._options.config) { if (base) { content = base + self._options.config + '.modules = ' + JSON.stringify(config) + ';'; } else { content = 'var ' + self._options.config + ' = {modules: ' + JSON.stringify(config) + '};'; } } else { content = JSON.stringify(config); } return self._saveConfig(beautify(content)); }) .then(function(config) { resolve(config); }) .catch(function(error) { reject(error); }); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "self", ".", "_modules", "=", "[", "]", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "base", ";", "var", "processors", "=", "[", "]", ";", "if", "(", "self", ".", "_options", ".", "base", ")", "{", "base", "=", "fs", ".", "readFileSync", "(", "path", ".", "resolve", "(", "self", ".", "_options", ".", "base", ")", ",", "'utf8'", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "_options", ".", "args", ".", "length", ";", "i", "++", ")", "{", "var", "file", "=", "self", ".", "_options", ".", "args", "[", "i", "]", ";", "var", "fileStats", "=", "fs", ".", "statSync", "(", "file", ")", ";", "if", "(", "fileStats", ".", "isDirectory", "(", "file", ")", ")", "{", "var", "walker", "=", "walk", ".", "walk", "(", "file", ",", "{", "followLinks", ":", "false", "}", ")", ";", "walker", ".", "on", "(", "'file'", ",", "self", ".", "_onWalkerFile", ".", "bind", "(", "self", ")", ")", ";", "processors", ".", "push", "(", "self", ".", "_onWalkerEnd", "(", "walker", ")", ")", ";", "}", "else", "if", "(", "fileStats", ".", "isFile", "(", ")", ")", "{", "processors", ".", "push", "(", "self", ".", "_processFile", "(", "file", ")", ")", ";", "}", "}", "Promise", ".", "all", "(", "processors", ")", ".", "then", "(", "function", "(", "uselessPromises", ")", "{", "return", "self", ".", "_generateConfig", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "config", ")", "{", "var", "content", ";", "if", "(", "self", ".", "_options", ".", "config", ")", "{", "if", "(", "base", ")", "{", "content", "=", "base", "+", "self", ".", "_options", ".", "config", "+", "'.modules = '", "+", "JSON", ".", "stringify", "(", "config", ")", "+", "';'", ";", "}", "else", "{", "content", "=", "'var '", "+", "self", ".", "_options", ".", "config", "+", "' = {modules: '", "+", "JSON", ".", "stringify", "(", "config", ")", "+", "'};'", ";", "}", "}", "else", "{", "content", "=", "JSON", ".", "stringify", "(", "config", ")", ";", "}", "return", "self", ".", "_saveConfig", "(", "beautify", "(", "content", ")", ")", ";", "}", ")", ".", "then", "(", "function", "(", "config", ")", "{", "resolve", "(", "config", ")", ";", "}", ")", ".", "catch", "(", "function", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Processes the passed files or folders and generates config file. @method process @return {Promise} Returns a Promise which will be resolved with the generated config file
[ "Processes", "the", "passed", "files", "or", "folders", "and", "generates", "config", "file", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L37-L98
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(ast) { var self = this; var found; var meta = ast; var values = {}; jsstana.traverse(ast, function(node) { if (!found) { var match = jsstana.match('(ident META)', node); if (match) { jsstana.traverse(meta, function(node) { if (!found) { match = jsstana.match('(return)', node) || jsstana.match('(object)', node); if (match) { values = self._extractObjectValues(['path', 'fullPath', 'condition', 'group'], node); found = true; } } }); } else { meta = node; } } }); return values; }
javascript
function(ast) { var self = this; var found; var meta = ast; var values = {}; jsstana.traverse(ast, function(node) { if (!found) { var match = jsstana.match('(ident META)', node); if (match) { jsstana.traverse(meta, function(node) { if (!found) { match = jsstana.match('(return)', node) || jsstana.match('(object)', node); if (match) { values = self._extractObjectValues(['path', 'fullPath', 'condition', 'group'], node); found = true; } } }); } else { meta = node; } } }); return values; }
[ "function", "(", "ast", ")", "{", "var", "self", "=", "this", ";", "var", "found", ";", "var", "meta", "=", "ast", ";", "var", "values", "=", "{", "}", ";", "jsstana", ".", "traverse", "(", "ast", ",", "function", "(", "node", ")", "{", "if", "(", "!", "found", ")", "{", "var", "match", "=", "jsstana", ".", "match", "(", "'(ident META)'", ",", "node", ")", ";", "if", "(", "match", ")", "{", "jsstana", ".", "traverse", "(", "meta", ",", "function", "(", "node", ")", "{", "if", "(", "!", "found", ")", "{", "match", "=", "jsstana", ".", "match", "(", "'(return)'", ",", "node", ")", "||", "jsstana", ".", "match", "(", "'(object)'", ",", "node", ")", ";", "if", "(", "match", ")", "{", "values", "=", "self", ".", "_extractObjectValues", "(", "[", "'path'", ",", "'fullPath'", ",", "'condition'", ",", "'group'", "]", ",", "node", ")", ";", "found", "=", "true", ";", "}", "}", "}", ")", ";", "}", "else", "{", "meta", "=", "node", ";", "}", "}", "}", ")", ";", "return", "values", ";", "}" ]
Extracts conditions from a module configuration. @method _extractCondition @protected @param {Object} ast AST to be processed @return {Object} The extracted values for the conditional options
[ "Extracts", "conditions", "from", "a", "module", "configuration", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L108-L139
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(idents, ast) { var self = this; var result = Object.create(null); var found; var ident; if (ast) { jsstana.traverse(ast, function(node) { if (found) { found = false; result[ident] = self._extractValue(node); } for (var i = 0; i < idents.length; i++) { ident = idents[i]; if (jsstana.match('(ident ' + ident + ')', node)) { found = true; break; } } }); } return result; }
javascript
function(idents, ast) { var self = this; var result = Object.create(null); var found; var ident; if (ast) { jsstana.traverse(ast, function(node) { if (found) { found = false; result[ident] = self._extractValue(node); } for (var i = 0; i < idents.length; i++) { ident = idents[i]; if (jsstana.match('(ident ' + ident + ')', node)) { found = true; break; } } }); } return result; }
[ "function", "(", "idents", ",", "ast", ")", "{", "var", "self", "=", "this", ";", "var", "result", "=", "Object", ".", "create", "(", "null", ")", ";", "var", "found", ";", "var", "ident", ";", "if", "(", "ast", ")", "{", "jsstana", ".", "traverse", "(", "ast", ",", "function", "(", "node", ")", "{", "if", "(", "found", ")", "{", "found", "=", "false", ";", "result", "[", "ident", "]", "=", "self", ".", "_extractValue", "(", "node", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "idents", ".", "length", ";", "i", "++", ")", "{", "ident", "=", "idents", "[", "i", "]", ";", "if", "(", "jsstana", ".", "match", "(", "'(ident '", "+", "ident", "+", "')'", ",", "node", ")", ")", "{", "found", "=", "true", ";", "break", ";", "}", "}", "}", ")", ";", "}", "return", "result", ";", "}" ]
Extract values for some idents from an AST. @method _extractObjectValues @param {Array} idents The idents which values should be looked up in the AST @param {AST} ast The AST to be processed @return {Object} An object with the extracted values for all found idents
[ "Extract", "values", "for", "some", "idents", "from", "an", "AST", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L149-L177
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(node) { var self = this; var i; if (node.type === 'Literal') { return node.value; } else if (node.type === 'ObjectExpression') { var obj = {}; for (i = 0; i < node.properties.length; i++) { var property = node.properties[i]; obj[property.key.name] = self._extractValue(property.value); } return obj; } else if (node.type === 'ArrayExpression') { var arr = []; for (i = 0; i < node.elements.length; i++) { arr.push(self._extractValue(node.elements[i])); } return arr; } else if (node.type === 'FunctionExpression') { return recast.print(node, { wrapColumn: Number.Infinity }).code; } }
javascript
function(node) { var self = this; var i; if (node.type === 'Literal') { return node.value; } else if (node.type === 'ObjectExpression') { var obj = {}; for (i = 0; i < node.properties.length; i++) { var property = node.properties[i]; obj[property.key.name] = self._extractValue(property.value); } return obj; } else if (node.type === 'ArrayExpression') { var arr = []; for (i = 0; i < node.elements.length; i++) { arr.push(self._extractValue(node.elements[i])); } return arr; } else if (node.type === 'FunctionExpression') { return recast.print(node, { wrapColumn: Number.Infinity }).code; } }
[ "function", "(", "node", ")", "{", "var", "self", "=", "this", ";", "var", "i", ";", "if", "(", "node", ".", "type", "===", "'Literal'", ")", "{", "return", "node", ".", "value", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'ObjectExpression'", ")", "{", "var", "obj", "=", "{", "}", ";", "for", "(", "i", "=", "0", ";", "i", "<", "node", ".", "properties", ".", "length", ";", "i", "++", ")", "{", "var", "property", "=", "node", ".", "properties", "[", "i", "]", ";", "obj", "[", "property", ".", "key", ".", "name", "]", "=", "self", ".", "_extractValue", "(", "property", ".", "value", ")", ";", "}", "return", "obj", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'ArrayExpression'", ")", "{", "var", "arr", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "node", ".", "elements", ".", "length", ";", "i", "++", ")", "{", "arr", ".", "push", "(", "self", ".", "_extractValue", "(", "node", ".", "elements", "[", "i", "]", ")", ")", ";", "}", "return", "arr", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'FunctionExpression'", ")", "{", "return", "recast", ".", "print", "(", "node", ",", "{", "wrapColumn", ":", "Number", ".", "Infinity", "}", ")", ".", "code", ";", "}", "}" ]
Extracts the value from a jsstana node. The value may be Literal, ObjectExpression, ArrayExpression or FunctionExpression. @method _extractValue @protected @param {Object} node jsstana node which should be processed @return {String} The extracted value from the node
[ "Extracts", "the", "value", "from", "a", "jsstana", "node", ".", "The", "value", "may", "be", "Literal", "ObjectExpression", "ArrayExpression", "or", "FunctionExpression", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L188-L219
train
liferay/liferay-module-config-generator
lib/config-generator.js
function() { var self = this; return new Promise(function(resolve, reject) { var config = {}; for (var i = 0; i < self._modules.length; i++) { var module = self._modules[i]; var storedModule = config[module.name] = { dependencies: module.dependencies }; if (module.condition) { storedModule.condition = module.condition; } if (!self._options.ignorePath) { if (module.fullPath) { storedModule.fullPath = upath.toUnix(module.fullPath); } else { var dirname = path.dirname(module.name); var modulePath = module.path || (dirname !== '.' ? dirname + '/' + module.file : module.file); storedModule.path = upath.toUnix(modulePath); } } } resolve(config); }); }
javascript
function() { var self = this; return new Promise(function(resolve, reject) { var config = {}; for (var i = 0; i < self._modules.length; i++) { var module = self._modules[i]; var storedModule = config[module.name] = { dependencies: module.dependencies }; if (module.condition) { storedModule.condition = module.condition; } if (!self._options.ignorePath) { if (module.fullPath) { storedModule.fullPath = upath.toUnix(module.fullPath); } else { var dirname = path.dirname(module.name); var modulePath = module.path || (dirname !== '.' ? dirname + '/' + module.file : module.file); storedModule.path = upath.toUnix(modulePath); } } } resolve(config); }); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "config", "=", "{", "}", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "self", ".", "_modules", ".", "length", ";", "i", "++", ")", "{", "var", "module", "=", "self", ".", "_modules", "[", "i", "]", ";", "var", "storedModule", "=", "config", "[", "module", ".", "name", "]", "=", "{", "dependencies", ":", "module", ".", "dependencies", "}", ";", "if", "(", "module", ".", "condition", ")", "{", "storedModule", ".", "condition", "=", "module", ".", "condition", ";", "}", "if", "(", "!", "self", ".", "_options", ".", "ignorePath", ")", "{", "if", "(", "module", ".", "fullPath", ")", "{", "storedModule", ".", "fullPath", "=", "upath", ".", "toUnix", "(", "module", ".", "fullPath", ")", ";", "}", "else", "{", "var", "dirname", "=", "path", ".", "dirname", "(", "module", ".", "name", ")", ";", "var", "modulePath", "=", "module", ".", "path", "||", "(", "dirname", "!==", "'.'", "?", "dirname", "+", "'/'", "+", "module", ".", "file", ":", "module", ".", "file", ")", ";", "storedModule", ".", "path", "=", "upath", ".", "toUnix", "(", "modulePath", ")", ";", "}", "}", "}", "resolve", "(", "config", ")", ";", "}", ")", ";", "}" ]
Generates a config object from all found modules. @method _generateConfig @protected @return {Promise} Returns a Promise which will be resolved with the generated configuration
[ "Generates", "a", "config", "object", "from", "all", "found", "modules", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L228-L260
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(file) { var self = this; var ext; if (!self._options.keepExtension) { ext = self._options.extension || path.extname(file); } var fileName = path.basename(file, ext); if (self._options.format) { var formatRegex = self._options.format[0].split('/'); formatRegex = new RegExp(formatRegex[1], formatRegex[2]); var replaceValue = self._options.format[1]; fileName = fileName.replace(formatRegex, replaceValue); } var moduleConfig = { name: '', version: '1.0.0' }; if (self._options.moduleConfig) { if (typeof self._options.moduleConfig === 'string') { var fileModuleConfig = path.resolve(self._options.moduleConfig); if (fs.existsSync(fileModuleConfig)) { moduleConfig = require(fileModuleConfig); } } else { moduleConfig = self._options.moduleConfig; } } fileName = path.join(path.dirname(file), fileName); var moduleName = ''; if (moduleConfig.name) { moduleName = moduleConfig.name + '@' + moduleConfig.version; } moduleName = path.join(moduleName, fileName.substring(self._options.moduleRoot.length)); if (self._options.lowerCase) { moduleName = moduleName.toLowerCase(); } return upath.toUnix(moduleName); }
javascript
function(file) { var self = this; var ext; if (!self._options.keepExtension) { ext = self._options.extension || path.extname(file); } var fileName = path.basename(file, ext); if (self._options.format) { var formatRegex = self._options.format[0].split('/'); formatRegex = new RegExp(formatRegex[1], formatRegex[2]); var replaceValue = self._options.format[1]; fileName = fileName.replace(formatRegex, replaceValue); } var moduleConfig = { name: '', version: '1.0.0' }; if (self._options.moduleConfig) { if (typeof self._options.moduleConfig === 'string') { var fileModuleConfig = path.resolve(self._options.moduleConfig); if (fs.existsSync(fileModuleConfig)) { moduleConfig = require(fileModuleConfig); } } else { moduleConfig = self._options.moduleConfig; } } fileName = path.join(path.dirname(file), fileName); var moduleName = ''; if (moduleConfig.name) { moduleName = moduleConfig.name + '@' + moduleConfig.version; } moduleName = path.join(moduleName, fileName.substring(self._options.moduleRoot.length)); if (self._options.lowerCase) { moduleName = moduleName.toLowerCase(); } return upath.toUnix(moduleName); }
[ "function", "(", "file", ")", "{", "var", "self", "=", "this", ";", "var", "ext", ";", "if", "(", "!", "self", ".", "_options", ".", "keepExtension", ")", "{", "ext", "=", "self", ".", "_options", ".", "extension", "||", "path", ".", "extname", "(", "file", ")", ";", "}", "var", "fileName", "=", "path", ".", "basename", "(", "file", ",", "ext", ")", ";", "if", "(", "self", ".", "_options", ".", "format", ")", "{", "var", "formatRegex", "=", "self", ".", "_options", ".", "format", "[", "0", "]", ".", "split", "(", "'/'", ")", ";", "formatRegex", "=", "new", "RegExp", "(", "formatRegex", "[", "1", "]", ",", "formatRegex", "[", "2", "]", ")", ";", "var", "replaceValue", "=", "self", ".", "_options", ".", "format", "[", "1", "]", ";", "fileName", "=", "fileName", ".", "replace", "(", "formatRegex", ",", "replaceValue", ")", ";", "}", "var", "moduleConfig", "=", "{", "name", ":", "''", ",", "version", ":", "'1.0.0'", "}", ";", "if", "(", "self", ".", "_options", ".", "moduleConfig", ")", "{", "if", "(", "typeof", "self", ".", "_options", ".", "moduleConfig", "===", "'string'", ")", "{", "var", "fileModuleConfig", "=", "path", ".", "resolve", "(", "self", ".", "_options", ".", "moduleConfig", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "fileModuleConfig", ")", ")", "{", "moduleConfig", "=", "require", "(", "fileModuleConfig", ")", ";", "}", "}", "else", "{", "moduleConfig", "=", "self", ".", "_options", ".", "moduleConfig", ";", "}", "}", "fileName", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "file", ")", ",", "fileName", ")", ";", "var", "moduleName", "=", "''", ";", "if", "(", "moduleConfig", ".", "name", ")", "{", "moduleName", "=", "moduleConfig", ".", "name", "+", "'@'", "+", "moduleConfig", ".", "version", ";", "}", "moduleName", "=", "path", ".", "join", "(", "moduleName", ",", "fileName", ".", "substring", "(", "self", ".", "_options", ".", "moduleRoot", ".", "length", ")", ")", ";", "if", "(", "self", ".", "_options", ".", "lowerCase", ")", "{", "moduleName", "=", "moduleName", ".", "toLowerCase", "(", ")", ";", "}", "return", "upath", ".", "toUnix", "(", "moduleName", ")", ";", "}" ]
Generates a module name in case it is not present in the AMD definition. @method _generateModuleName @protected @param {String} file The file path to be processed and module name to be generated @return {String} The generated module name
[ "Generates", "a", "module", "name", "in", "case", "it", "is", "not", "present", "in", "the", "AMD", "definition", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L270-L322
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(root, fileStats, next) { var self = this; var file = path.join(root, fileStats.name); if (minimatch(file, self._options.filePattern, { dot: true })) { self._processFile(file) .then(function(config) { next(); }); } else { next(); } }
javascript
function(root, fileStats, next) { var self = this; var file = path.join(root, fileStats.name); if (minimatch(file, self._options.filePattern, { dot: true })) { self._processFile(file) .then(function(config) { next(); }); } else { next(); } }
[ "function", "(", "root", ",", "fileStats", ",", "next", ")", "{", "var", "self", "=", "this", ";", "var", "file", "=", "path", ".", "join", "(", "root", ",", "fileStats", ".", "name", ")", ";", "if", "(", "minimatch", "(", "file", ",", "self", ".", "_options", ".", "filePattern", ",", "{", "dot", ":", "true", "}", ")", ")", "{", "self", ".", "_processFile", "(", "file", ")", ".", "then", "(", "function", "(", "config", ")", "{", "next", "(", ")", ";", "}", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
Listener which will be invoked when a file whiting the provided folder is found @method _onWalkerFile @protected @param {String} root The root directory of the file @param {Object} fileStats Object with data about the file @param {Function} next A callback function to be called once the file is processed
[ "Listener", "which", "will", "be", "invoked", "when", "a", "file", "whiting", "the", "provided", "folder", "is", "found" ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L436-L451
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(file, content) { return new Promise(function(resolve, reject) { var ast = recast.parse(content); resolve(ast); }); }
javascript
function(file, content) { return new Promise(function(resolve, reject) { var ast = recast.parse(content); resolve(ast); }); }
[ "function", "(", "file", ",", "content", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "ast", "=", "recast", ".", "parse", "(", "content", ")", ";", "resolve", "(", "ast", ")", ";", "}", ")", ";", "}" ]
Parses the content of a file @method _parseFile @protected @param {String} file The file which should be parsed @param {String} content The content of the file which should be parsed @return {Promise} Returns a Promise which will be resolved with file's AST
[ "Parses", "the", "content", "of", "a", "file" ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L475-L481
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(file) { var self = this; return new Promise(function(resolve) { fs.readFileAsync(file, 'utf-8') .then(function(content) { return self._parseFile(file, content); }) .then(function(ast) { return self._getConfig(file, ast); }) .then(function(config) { self._modules = self._modules.concat(config); resolve(config); }); }); }
javascript
function(file) { var self = this; return new Promise(function(resolve) { fs.readFileAsync(file, 'utf-8') .then(function(content) { return self._parseFile(file, content); }) .then(function(ast) { return self._getConfig(file, ast); }) .then(function(config) { self._modules = self._modules.concat(config); resolve(config); }); }); }
[ "function", "(", "file", ")", "{", "var", "self", "=", "this", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "fs", ".", "readFileAsync", "(", "file", ",", "'utf-8'", ")", ".", "then", "(", "function", "(", "content", ")", "{", "return", "self", ".", "_parseFile", "(", "file", ",", "content", ")", ";", "}", ")", ".", "then", "(", "function", "(", "ast", ")", "{", "return", "self", ".", "_getConfig", "(", "file", ",", "ast", ")", ";", "}", ")", ".", "then", "(", "function", "(", "config", ")", "{", "self", ".", "_modules", "=", "self", ".", "_modules", ".", "concat", "(", "config", ")", ";", "resolve", "(", "config", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Processes a file and generates configuration object for all modules found inside. @method _processFile @protected @param {String} file The file which should be processed @return {Promise} Returns a Promise which will be resolved with the generated config
[ "Processes", "a", "file", "and", "generates", "configuration", "object", "for", "all", "modules", "found", "inside", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L491-L508
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(file, ast) { var content = recast.print(ast, { wrapColumn: Number.Infinity }).code; content = this._updateSourceMap(file, content); fs.writeFileSync(file, content); }
javascript
function(file, ast) { var content = recast.print(ast, { wrapColumn: Number.Infinity }).code; content = this._updateSourceMap(file, content); fs.writeFileSync(file, content); }
[ "function", "(", "file", ",", "ast", ")", "{", "var", "content", "=", "recast", ".", "print", "(", "ast", ",", "{", "wrapColumn", ":", "Number", ".", "Infinity", "}", ")", ".", "code", ";", "content", "=", "this", ".", "_updateSourceMap", "(", "file", ",", "content", ")", ";", "fs", ".", "writeFileSync", "(", "file", ",", "content", ")", ";", "}" ]
Saves file with the reprinted AST and updated source map, if any. @method _saveFile @protected @param {String} file The file to save @param {Object} ast The AST of the file
[ "Saves", "file", "with", "the", "reprinted", "AST", "and", "updated", "source", "map", "if", "any", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L518-L526
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(config) { var self = this; return new Promise(function(resolve, reject) { if (self._options.output) { fs.writeFileAsync(self._options.output, config) .then(function() { resolve(config); }); } else { resolve(config); } }); }
javascript
function(config) { var self = this; return new Promise(function(resolve, reject) { if (self._options.output) { fs.writeFileAsync(self._options.output, config) .then(function() { resolve(config); }); } else { resolve(config); } }); }
[ "function", "(", "config", ")", "{", "var", "self", "=", "this", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "self", ".", "_options", ".", "output", ")", "{", "fs", ".", "writeFileAsync", "(", "self", ".", "_options", ".", "output", ",", "config", ")", ".", "then", "(", "function", "(", ")", "{", "resolve", "(", "config", ")", ";", "}", ")", ";", "}", "else", "{", "resolve", "(", "config", ")", ";", "}", "}", ")", ";", "}" ]
Saves the generated configuration file on the hard drive. @method _saveConfig @protected @param {Object} config The configuration object to be saved @return {Promise} Returns a Promise which will be resolved with the generated config file
[ "Saves", "the", "generated", "configuration", "file", "on", "the", "hard", "drive", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L536-L549
train
liferay/liferay-module-config-generator
lib/config-generator.js
function(file, content) { var sourceMapURLMatch = REGEX_SOURCEMAP.exec(content); if (sourceMapURLMatch) { var sourceMapURL = sourceMapURLMatch[1]; if (sourceMapURL) { var sourceMapContent = fs.readFileSync(path.resolve(path.dirname(file), sourceMapURL), 'utf-8'); var consumer = new sourceMap.SourceMapConsumer(sourceMapContent); var node = sourceMap.SourceNode.fromStringWithSourceMap(content, consumer); var result = node.toStringWithSourceMap(); content = result.code; var map = result.map; fs.writeFileSync(path.resolve(path.dirname(file), sourceMapURL), JSON.stringify(map)); } } return content; }
javascript
function(file, content) { var sourceMapURLMatch = REGEX_SOURCEMAP.exec(content); if (sourceMapURLMatch) { var sourceMapURL = sourceMapURLMatch[1]; if (sourceMapURL) { var sourceMapContent = fs.readFileSync(path.resolve(path.dirname(file), sourceMapURL), 'utf-8'); var consumer = new sourceMap.SourceMapConsumer(sourceMapContent); var node = sourceMap.SourceNode.fromStringWithSourceMap(content, consumer); var result = node.toStringWithSourceMap(); content = result.code; var map = result.map; fs.writeFileSync(path.resolve(path.dirname(file), sourceMapURL), JSON.stringify(map)); } } return content; }
[ "function", "(", "file", ",", "content", ")", "{", "var", "sourceMapURLMatch", "=", "REGEX_SOURCEMAP", ".", "exec", "(", "content", ")", ";", "if", "(", "sourceMapURLMatch", ")", "{", "var", "sourceMapURL", "=", "sourceMapURLMatch", "[", "1", "]", ";", "if", "(", "sourceMapURL", ")", "{", "var", "sourceMapContent", "=", "fs", ".", "readFileSync", "(", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "file", ")", ",", "sourceMapURL", ")", ",", "'utf-8'", ")", ";", "var", "consumer", "=", "new", "sourceMap", ".", "SourceMapConsumer", "(", "sourceMapContent", ")", ";", "var", "node", "=", "sourceMap", ".", "SourceNode", ".", "fromStringWithSourceMap", "(", "content", ",", "consumer", ")", ";", "var", "result", "=", "node", ".", "toStringWithSourceMap", "(", ")", ";", "content", "=", "result", ".", "code", ";", "var", "map", "=", "result", ".", "map", ";", "fs", ".", "writeFileSync", "(", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "file", ")", ",", "sourceMapURL", ")", ",", "JSON", ".", "stringify", "(", "map", ")", ")", ";", "}", "}", "return", "content", ";", "}" ]
Updates the source and source map of the processed file. @method _updateSourceMap @protected @param {String} file The name of the processed file @param {String} content The content of the processed file @return {String} The modified content after updating the source map
[ "Updates", "the", "source", "and", "source", "map", "of", "the", "processed", "file", "." ]
c8b549dd0058cb39f242bc33ebee59a1a9474734
https://github.com/liferay/liferay-module-config-generator/blob/c8b549dd0058cb39f242bc33ebee59a1a9474734/lib/config-generator.js#L560-L582
train
dasuchin/grunt-ssh-deploy
tasks/ssh_deploy.js
function(cmd, showLog, next){ connection.exec(cmd, function(err, stream) { if (err) { grunt.log.errorlns(err); grunt.log.subhead('ERROR DEPLOYING. CLOSING CONNECTION AND DELETING RELEASE.'); deleteRelease(closeConnection); } stream.on('data', function(data, extended) { grunt.log.debug((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ') + data); }); stream.on('end', function() { grunt.log.debug('REMOTE: ' + cmd); if(!err) { next(); } }); }); }
javascript
function(cmd, showLog, next){ connection.exec(cmd, function(err, stream) { if (err) { grunt.log.errorlns(err); grunt.log.subhead('ERROR DEPLOYING. CLOSING CONNECTION AND DELETING RELEASE.'); deleteRelease(closeConnection); } stream.on('data', function(data, extended) { grunt.log.debug((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ') + data); }); stream.on('end', function() { grunt.log.debug('REMOTE: ' + cmd); if(!err) { next(); } }); }); }
[ "function", "(", "cmd", ",", "showLog", ",", "next", ")", "{", "connection", ".", "exec", "(", "cmd", ",", "function", "(", "err", ",", "stream", ")", "{", "if", "(", "err", ")", "{", "grunt", ".", "log", ".", "errorlns", "(", "err", ")", ";", "grunt", ".", "log", ".", "subhead", "(", "'ERROR DEPLOYING. CLOSING CONNECTION AND DELETING RELEASE.'", ")", ";", "deleteRelease", "(", "closeConnection", ")", ";", "}", "stream", ".", "on", "(", "'data'", ",", "function", "(", "data", ",", "extended", ")", "{", "grunt", ".", "log", ".", "debug", "(", "(", "extended", "===", "'stderr'", "?", "'STDERR: '", ":", "'STDOUT: '", ")", "+", "data", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "grunt", ".", "log", ".", "debug", "(", "'REMOTE: '", "+", "cmd", ")", ";", "if", "(", "!", "err", ")", "{", "next", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
executes a remote command via ssh
[ "executes", "a", "remote", "command", "via", "ssh" ]
b58d1caa5a79e4204f93caa9c8de2d3e6a6ec6a8
https://github.com/dasuchin/grunt-ssh-deploy/blob/b58d1caa5a79e4204f93caa9c8de2d3e6a6ec6a8/tasks/ssh_deploy.js#L120-L138
train
dasuchin/grunt-ssh-deploy
tasks/ssh_deploy.js
function(callback) { connection.end(); client.close(); client.__sftp = null; client.__ssh = null; callback(); }
javascript
function(callback) { connection.end(); client.close(); client.__sftp = null; client.__ssh = null; callback(); }
[ "function", "(", "callback", ")", "{", "connection", ".", "end", "(", ")", ";", "client", ".", "close", "(", ")", ";", "client", ".", "__sftp", "=", "null", ";", "client", ".", "__ssh", "=", "null", ";", "callback", "(", ")", ";", "}" ]
closing connection to remote server
[ "closing", "connection", "to", "remote", "server" ]
b58d1caa5a79e4204f93caa9c8de2d3e6a6ec6a8
https://github.com/dasuchin/grunt-ssh-deploy/blob/b58d1caa5a79e4204f93caa9c8de2d3e6a6ec6a8/tasks/ssh_deploy.js#L268-L276
train
Dreamscapes/semantic-merge
lib/merger.js
doMerge
function doMerge(source, target, opts) { return target instanceof Array ? mergeArrays(source, target) : mergeObjects(source, target, opts) }
javascript
function doMerge(source, target, opts) { return target instanceof Array ? mergeArrays(source, target) : mergeObjects(source, target, opts) }
[ "function", "doMerge", "(", "source", ",", "target", ",", "opts", ")", "{", "return", "target", "instanceof", "Array", "?", "mergeArrays", "(", "source", ",", "target", ")", ":", "mergeObjects", "(", "source", ",", "target", ",", "opts", ")", "}" ]
Determine whether we should do an array or object merge @private @param {Object} source Source to merge @param {Object} target Target to merge into @param {Object} opts Options for the merge @return {Object}
[ "Determine", "whether", "we", "should", "do", "an", "array", "or", "object", "merge" ]
212a17034f1bea3eedb15e5a30220a27d55c9366
https://github.com/Dreamscapes/semantic-merge/blob/212a17034f1bea3eedb15e5a30220a27d55c9366/lib/merger.js#L140-L144
train
phproberto/joomla-gulp
src/packages.js
getPackages
function getPackages() { var results = []; if (extensions && extensions.hasOwnProperty('packages')) { var sourceArray = extensions.packages; for (index = 0; index < sourceArray.length; ++index) { results.push(sourceArray[index]); } } return results; }
javascript
function getPackages() { var results = []; if (extensions && extensions.hasOwnProperty('packages')) { var sourceArray = extensions.packages; for (index = 0; index < sourceArray.length; ++index) { results.push(sourceArray[index]); } } return results; }
[ "function", "getPackages", "(", ")", "{", "var", "results", "=", "[", "]", ";", "if", "(", "extensions", "&&", "extensions", ".", "hasOwnProperty", "(", "'packages'", ")", ")", "{", "var", "sourceArray", "=", "extensions", ".", "packages", ";", "for", "(", "index", "=", "0", ";", "index", "<", "sourceArray", ".", "length", ";", "++", "index", ")", "{", "results", ".", "push", "(", "sourceArray", "[", "index", "]", ")", ";", "}", "}", "return", "results", ";", "}" ]
Get the list of the active packages @return array
[ "Get", "the", "list", "of", "the", "active", "packages" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/packages.js#L17-L29
train
phproberto/joomla-gulp
src/packages.js
getPackagesTasks
function getPackagesTasks(baseTask) { var packages = getPackages(); var tasks = []; for (index = 0; index < packages.length; ++index) { tasks.push(baseTask + '.' + packages[index]); } return tasks; }
javascript
function getPackagesTasks(baseTask) { var packages = getPackages(); var tasks = []; for (index = 0; index < packages.length; ++index) { tasks.push(baseTask + '.' + packages[index]); } return tasks; }
[ "function", "getPackagesTasks", "(", "baseTask", ")", "{", "var", "packages", "=", "getPackages", "(", ")", ";", "var", "tasks", "=", "[", "]", ";", "for", "(", "index", "=", "0", ";", "index", "<", "packages", ".", "length", ";", "++", "index", ")", "{", "tasks", ".", "push", "(", "baseTask", "+", "'.'", "+", "packages", "[", "index", "]", ")", ";", "}", "return", "tasks", ";", "}" ]
Get packages tasks @param string baseTask Task to use as root. Example: 'clean:modules.frontend' @return array
[ "Get", "packages", "tasks" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/packages.js#L38-L47
train
jasonreece/css-burrito
js/lib/utils/read-module-directory.js
readModuleDirectory
function readModuleDirectory() { return _fsExtra2.default.existsSync((0, _config2.default)().moduleDirectoryPath()) ? _fsExtra2.default.readdirSync((0, _config2.default)().moduleDirectoryPath(), function (err, files) { return files; }).filter(_isNotModulesImportFile) : []; }
javascript
function readModuleDirectory() { return _fsExtra2.default.existsSync((0, _config2.default)().moduleDirectoryPath()) ? _fsExtra2.default.readdirSync((0, _config2.default)().moduleDirectoryPath(), function (err, files) { return files; }).filter(_isNotModulesImportFile) : []; }
[ "function", "readModuleDirectory", "(", ")", "{", "return", "_fsExtra2", ".", "default", ".", "existsSync", "(", "(", "0", ",", "_config2", ".", "default", ")", "(", ")", ".", "moduleDirectoryPath", "(", ")", ")", "?", "_fsExtra2", ".", "default", ".", "readdirSync", "(", "(", "0", ",", "_config2", ".", "default", ")", "(", ")", ".", "moduleDirectoryPath", "(", ")", ",", "function", "(", "err", ",", "files", ")", "{", "return", "files", ";", "}", ")", ".", "filter", "(", "_isNotModulesImportFile", ")", ":", "[", "]", ";", "}" ]
if module file exists, return a list of everything in the directory, otherwise return an empty array
[ "if", "module", "file", "exists", "return", "a", "list", "of", "everything", "in", "the", "directory", "otherwise", "return", "an", "empty", "array" ]
f0b98a51f10f4bccc656f4ebf37ff9e0290968ac
https://github.com/jasonreece/css-burrito/blob/f0b98a51f10f4bccc656f4ebf37ff9e0290968ac/js/lib/utils/read-module-directory.js#L24-L28
train
ivpusic/sequelize-import
index.js
load
function load(PATH, sequelize, opts) { var files = fs.readdirSync(PATH), models = {}; opts = opts || {}; if (opts.exclude) { removeAll(opts.exclude, files); } files.forEach(function (file) { if (fs.statSync(path.join(PATH, file)).isDirectory()) { models[file] = load(path.join(PATH, file), sequelize, opts); } else { file = file.split('.')[0]; var model = sequelize.import(path.join(PATH, file)) models[model.name] = model; } }); return models; }
javascript
function load(PATH, sequelize, opts) { var files = fs.readdirSync(PATH), models = {}; opts = opts || {}; if (opts.exclude) { removeAll(opts.exclude, files); } files.forEach(function (file) { if (fs.statSync(path.join(PATH, file)).isDirectory()) { models[file] = load(path.join(PATH, file), sequelize, opts); } else { file = file.split('.')[0]; var model = sequelize.import(path.join(PATH, file)) models[model.name] = model; } }); return models; }
[ "function", "load", "(", "PATH", ",", "sequelize", ",", "opts", ")", "{", "var", "files", "=", "fs", ".", "readdirSync", "(", "PATH", ")", ",", "models", "=", "{", "}", ";", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "opts", ".", "exclude", ")", "{", "removeAll", "(", "opts", ".", "exclude", ",", "files", ")", ";", "}", "files", ".", "forEach", "(", "function", "(", "file", ")", "{", "if", "(", "fs", ".", "statSync", "(", "path", ".", "join", "(", "PATH", ",", "file", ")", ")", ".", "isDirectory", "(", ")", ")", "{", "models", "[", "file", "]", "=", "load", "(", "path", ".", "join", "(", "PATH", ",", "file", ")", ",", "sequelize", ",", "opts", ")", ";", "}", "else", "{", "file", "=", "file", ".", "split", "(", "'.'", ")", "[", "0", "]", ";", "var", "model", "=", "sequelize", ".", "import", "(", "path", ".", "join", "(", "PATH", ",", "file", ")", ")", "models", "[", "model", ".", "name", "]", "=", "model", ";", "}", "}", ")", ";", "return", "models", ";", "}" ]
Function for searching and loading sequelize models @param {Object} PATH root location to search @param {Object} sequelize sequelize connection @return {Object} @api public
[ "Function", "for", "searching", "and", "loading", "sequelize", "models" ]
1c7135168a14b2dcc3f33afa20a71702f9a46d71
https://github.com/ivpusic/sequelize-import/blob/1c7135168a14b2dcc3f33afa20a71702f9a46d71/index.js#L32-L51
train
fex-team/yog2-kernel
plugins/dispatcher/dispatcher.js
wrapAsyncFunction
function wrapAsyncFunction(fn, isSubAction) { if (!fn || fn.__asyncWrapped__) { return fn; } var wrapedFn = fn; if (typeof fn === 'function') { wrapedFn = function asyncWrap(req, res, next) { var maybePromise = fn(req, res, next); if (maybePromise && maybePromise.catch && typeof maybePromise.catch === 'function') { maybePromise.catch(next); } }; } for (var key in fn) { if (fn.hasOwnProperty(key)) { if (!isSubAction && VERB[key.toLowerCase()]) { // 仅在顶级Action中自动寻找VERB Action进行异步包裹 wrapedFn[key] = wrapAsyncFunction(fn[key], true); } else { // 其余对象仅复制 wrapedFn[key] = fn[key]; } } } wrapedFn.__asyncWrapped__ = true; return wrapedFn; }
javascript
function wrapAsyncFunction(fn, isSubAction) { if (!fn || fn.__asyncWrapped__) { return fn; } var wrapedFn = fn; if (typeof fn === 'function') { wrapedFn = function asyncWrap(req, res, next) { var maybePromise = fn(req, res, next); if (maybePromise && maybePromise.catch && typeof maybePromise.catch === 'function') { maybePromise.catch(next); } }; } for (var key in fn) { if (fn.hasOwnProperty(key)) { if (!isSubAction && VERB[key.toLowerCase()]) { // 仅在顶级Action中自动寻找VERB Action进行异步包裹 wrapedFn[key] = wrapAsyncFunction(fn[key], true); } else { // 其余对象仅复制 wrapedFn[key] = fn[key]; } } } wrapedFn.__asyncWrapped__ = true; return wrapedFn; }
[ "function", "wrapAsyncFunction", "(", "fn", ",", "isSubAction", ")", "{", "if", "(", "!", "fn", "||", "fn", ".", "__asyncWrapped__", ")", "{", "return", "fn", ";", "}", "var", "wrapedFn", "=", "fn", ";", "if", "(", "typeof", "fn", "===", "'function'", ")", "{", "wrapedFn", "=", "function", "asyncWrap", "(", "req", ",", "res", ",", "next", ")", "{", "var", "maybePromise", "=", "fn", "(", "req", ",", "res", ",", "next", ")", ";", "if", "(", "maybePromise", "&&", "maybePromise", ".", "catch", "&&", "typeof", "maybePromise", ".", "catch", "===", "'function'", ")", "{", "maybePromise", ".", "catch", "(", "next", ")", ";", "}", "}", ";", "}", "for", "(", "var", "key", "in", "fn", ")", "{", "if", "(", "fn", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "if", "(", "!", "isSubAction", "&&", "VERB", "[", "key", ".", "toLowerCase", "(", ")", "]", ")", "{", "wrapedFn", "[", "key", "]", "=", "wrapAsyncFunction", "(", "fn", "[", "key", "]", ",", "true", ")", ";", "}", "else", "{", "wrapedFn", "[", "key", "]", "=", "fn", "[", "key", "]", ";", "}", "}", "}", "wrapedFn", ".", "__asyncWrapped__", "=", "true", ";", "return", "wrapedFn", ";", "}" ]
warp a action method to catch async error @param {Function} fn [description] @return {[type]} [description]
[ "warp", "a", "action", "method", "to", "catch", "async", "error" ]
8446ec4822706d7b112000f64453655c20f9be77
https://github.com/fex-team/yog2-kernel/blob/8446ec4822706d7b112000f64453655c20f9be77/plugins/dispatcher/dispatcher.js#L186-L212
train
phproberto/joomla-gulp
src/templates.js
getTemplates
function getTemplates(app) { var results = []; if (extensions && extensions.hasOwnProperty('templates') && extensions.templates.hasOwnProperty(app) ) { var sourceArray = extensions.templates[app]; for (index = 0; index < sourceArray.length; ++index) { results.push(app + '.' + sourceArray[index]); } } return results; }
javascript
function getTemplates(app) { var results = []; if (extensions && extensions.hasOwnProperty('templates') && extensions.templates.hasOwnProperty(app) ) { var sourceArray = extensions.templates[app]; for (index = 0; index < sourceArray.length; ++index) { results.push(app + '.' + sourceArray[index]); } } return results; }
[ "function", "getTemplates", "(", "app", ")", "{", "var", "results", "=", "[", "]", ";", "if", "(", "extensions", "&&", "extensions", ".", "hasOwnProperty", "(", "'templates'", ")", "&&", "extensions", ".", "templates", ".", "hasOwnProperty", "(", "app", ")", ")", "{", "var", "sourceArray", "=", "extensions", ".", "templates", "[", "app", "]", ";", "for", "(", "index", "=", "0", ";", "index", "<", "sourceArray", ".", "length", ";", "++", "index", ")", "{", "results", ".", "push", "(", "app", "+", "'.'", "+", "sourceArray", "[", "index", "]", ")", ";", "}", "}", "return", "results", ";", "}" ]
Get the available templates @param string app 'frontend' | 'backend' @return array
[ "Get", "the", "available", "templates" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/templates.js#L19-L33
train
Microsoft/Essex-PowerBI-visuals-base
packages/oss-report-builder/index.js
parseNPMLL
function parseNPMLL(cb) { /* read the original package.json file and parse it */ const packagePath = path.join(process.cwd(), 'package.json') const packageJsonContent = fs.readFileSync(packagePath, 'utf8') const packageJson = JSON.parse(packageJsonContent) /* save a version of package.json with the privateSubmodules added to the dependencies object */ const privateSubmodules = packageJson.privateSubmodules const dependencies = packageJson.dependencies Object.keys(privateSubmodules || {}).forEach(key => { if (!dependencies.hasOwnProperty(key)) { dependencies[key] = privateSubmodules[key] } }) fs.writeFile(packagePath, JSON.stringify(packageJson), err => { if (err) throw err /* process the output of `npm ll` */ let output try { output = cp.execSync('npm ll --json', { env: process.env }) } catch (e) { output = e.stdout } /* restore the previous package.json */ fs.writeFile(packagePath, packageJsonContent, err => { if (err) throw err /* parse the output and call the callback */ let parsed try { parsed = JSON.parse(output) } catch (e) { console.warn('Cannot parse `npm ll` output:', e) parsed = null } cb(parsed) }) }) }
javascript
function parseNPMLL(cb) { /* read the original package.json file and parse it */ const packagePath = path.join(process.cwd(), 'package.json') const packageJsonContent = fs.readFileSync(packagePath, 'utf8') const packageJson = JSON.parse(packageJsonContent) /* save a version of package.json with the privateSubmodules added to the dependencies object */ const privateSubmodules = packageJson.privateSubmodules const dependencies = packageJson.dependencies Object.keys(privateSubmodules || {}).forEach(key => { if (!dependencies.hasOwnProperty(key)) { dependencies[key] = privateSubmodules[key] } }) fs.writeFile(packagePath, JSON.stringify(packageJson), err => { if (err) throw err /* process the output of `npm ll` */ let output try { output = cp.execSync('npm ll --json', { env: process.env }) } catch (e) { output = e.stdout } /* restore the previous package.json */ fs.writeFile(packagePath, packageJsonContent, err => { if (err) throw err /* parse the output and call the callback */ let parsed try { parsed = JSON.parse(output) } catch (e) { console.warn('Cannot parse `npm ll` output:', e) parsed = null } cb(parsed) }) }) }
[ "function", "parseNPMLL", "(", "cb", ")", "{", "const", "packagePath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "'package.json'", ")", "const", "packageJsonContent", "=", "fs", ".", "readFileSync", "(", "packagePath", ",", "'utf8'", ")", "const", "packageJson", "=", "JSON", ".", "parse", "(", "packageJsonContent", ")", "const", "privateSubmodules", "=", "packageJson", ".", "privateSubmodules", "const", "dependencies", "=", "packageJson", ".", "dependencies", "Object", ".", "keys", "(", "privateSubmodules", "||", "{", "}", ")", ".", "forEach", "(", "key", "=>", "{", "if", "(", "!", "dependencies", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "dependencies", "[", "key", "]", "=", "privateSubmodules", "[", "key", "]", "}", "}", ")", "fs", ".", "writeFile", "(", "packagePath", ",", "JSON", ".", "stringify", "(", "packageJson", ")", ",", "err", "=>", "{", "if", "(", "err", ")", "throw", "err", "let", "output", "try", "{", "output", "=", "cp", ".", "execSync", "(", "'npm ll --json'", ",", "{", "env", ":", "process", ".", "env", "}", ")", "}", "catch", "(", "e", ")", "{", "output", "=", "e", ".", "stdout", "}", "fs", ".", "writeFile", "(", "packagePath", ",", "packageJsonContent", ",", "err", "=>", "{", "if", "(", "err", ")", "throw", "err", "let", "parsed", "try", "{", "parsed", "=", "JSON", ".", "parse", "(", "output", ")", "}", "catch", "(", "e", ")", "{", "console", ".", "warn", "(", "'Cannot parse `npm ll` output:'", ",", "e", ")", "parsed", "=", "null", "}", "cb", "(", "parsed", ")", "}", ")", "}", ")", "}" ]
Parses the output of `npm ll` making sure that the private sub-modules are included in the report. @method parseNPMLL @param {Function} cb - Callback to be invoked when the operation is complete.
[ "Parses", "the", "output", "of", "npm", "ll", "making", "sure", "that", "the", "private", "sub", "-", "modules", "are", "included", "in", "the", "report", "." ]
effd9357d32860624ee1f8a0e825641697be95e1
https://github.com/Microsoft/Essex-PowerBI-visuals-base/blob/effd9357d32860624ee1f8a0e825641697be95e1/packages/oss-report-builder/index.js#L43-L83
train
Microsoft/Essex-PowerBI-visuals-base
packages/oss-report-builder/index.js
readObjectValue
function readObjectValue(object) { let result = '' if (typeof object === 'string' || object instanceof String) { result = object } else if (typeof object === 'number' || object instanceof Number) { result = object.toString() } else if (object) { Object.keys(object).forEach(key => { result += key + ': ' + object[key] + '\t' }) } if (!result.length) { result = 'Not Specified' } return result.replace(new RegExp('"', 'g'), '""') }
javascript
function readObjectValue(object) { let result = '' if (typeof object === 'string' || object instanceof String) { result = object } else if (typeof object === 'number' || object instanceof Number) { result = object.toString() } else if (object) { Object.keys(object).forEach(key => { result += key + ': ' + object[key] + '\t' }) } if (!result.length) { result = 'Not Specified' } return result.replace(new RegExp('"', 'g'), '""') }
[ "function", "readObjectValue", "(", "object", ")", "{", "let", "result", "=", "''", "if", "(", "typeof", "object", "===", "'string'", "||", "object", "instanceof", "String", ")", "{", "result", "=", "object", "}", "else", "if", "(", "typeof", "object", "===", "'number'", "||", "object", "instanceof", "Number", ")", "{", "result", "=", "object", ".", "toString", "(", ")", "}", "else", "if", "(", "object", ")", "{", "Object", ".", "keys", "(", "object", ")", ".", "forEach", "(", "key", "=>", "{", "result", "+=", "key", "+", "': '", "+", "object", "[", "key", "]", "+", "'\\t'", "}", ")", "}", "\\t", "if", "(", "!", "result", ".", "length", ")", "{", "result", "=", "'Not Specified'", "}", "}" ]
Converts an object representing a JSON property to a CSV compatible string. @method readObjectValue @param {Object} object - The object to read as a string. @returns {String}
[ "Converts", "an", "object", "representing", "a", "JSON", "property", "to", "a", "CSV", "compatible", "string", "." ]
effd9357d32860624ee1f8a0e825641697be95e1
https://github.com/Microsoft/Essex-PowerBI-visuals-base/blob/effd9357d32860624ee1f8a0e825641697be95e1/packages/oss-report-builder/index.js#L92-L110
train
Microsoft/Essex-PowerBI-visuals-base
packages/oss-report-builder/index.js
parseDependencies
function parseDependencies(info, runtimeDependencies, isParentRoot) { const dependencies = info.dependencies const devDependencies = info.devDependencies const nodeModulesPath = path.join(path.resolve('./'), 'node_modules/') let csv = '' /* licence */ /* URL */ /* description */ /* version */ /* type */ /* usage */ /* included in product */ /* in git repository */ /* dependency */ Object.keys(dependencies).forEach(key => { const dependency = dependencies[key] const name = readObjectValue(dependency.name) const version = readObjectValue(dependency.version) if (dependency.name && dependency.version) { const type = isParentRoot ? 'dependency' : 'sub-dependency' const usage = devDependencies.hasOwnProperty(key) ? 'development' : 'runtime' const included = !runtimeDependencies.hasOwnProperty(key) || !runtimeDependencies[key] ? 'No' : 'Yes' /* TODO: This could be done using `git check-ignore` for better results */ const inRepo = dependency.link && !dependency.link.startsWith(nodeModulesPath) ? 'Yes' : 'No' const license = readObjectValue(dependency.license) const url = readObjectValue( dependency.homepage || dependency.repository || null ) const description = readObjectValue(dependency.description) csv += '"' + name + '","' + version + '","' + type + '","' + usage + '","' + included + '","' + inRepo + '","' + license + '","' + url + '","' + description + '"\n' } if (dependency.dependencies) { csv += parseDependencies(dependency, runtimeDependencies, false) } }) return csv }
javascript
function parseDependencies(info, runtimeDependencies, isParentRoot) { const dependencies = info.dependencies const devDependencies = info.devDependencies const nodeModulesPath = path.join(path.resolve('./'), 'node_modules/') let csv = '' /* licence */ /* URL */ /* description */ /* version */ /* type */ /* usage */ /* included in product */ /* in git repository */ /* dependency */ Object.keys(dependencies).forEach(key => { const dependency = dependencies[key] const name = readObjectValue(dependency.name) const version = readObjectValue(dependency.version) if (dependency.name && dependency.version) { const type = isParentRoot ? 'dependency' : 'sub-dependency' const usage = devDependencies.hasOwnProperty(key) ? 'development' : 'runtime' const included = !runtimeDependencies.hasOwnProperty(key) || !runtimeDependencies[key] ? 'No' : 'Yes' /* TODO: This could be done using `git check-ignore` for better results */ const inRepo = dependency.link && !dependency.link.startsWith(nodeModulesPath) ? 'Yes' : 'No' const license = readObjectValue(dependency.license) const url = readObjectValue( dependency.homepage || dependency.repository || null ) const description = readObjectValue(dependency.description) csv += '"' + name + '","' + version + '","' + type + '","' + usage + '","' + included + '","' + inRepo + '","' + license + '","' + url + '","' + description + '"\n' } if (dependency.dependencies) { csv += parseDependencies(dependency, runtimeDependencies, false) } }) return csv }
[ "function", "parseDependencies", "(", "info", ",", "runtimeDependencies", ",", "isParentRoot", ")", "{", "const", "dependencies", "=", "info", ".", "dependencies", "const", "devDependencies", "=", "info", ".", "devDependencies", "const", "nodeModulesPath", "=", "path", ".", "join", "(", "path", ".", "resolve", "(", "'./'", ")", ",", "'node_modules/'", ")", "let", "csv", "=", "''", "Object", ".", "keys", "(", "dependencies", ")", ".", "forEach", "(", "key", "=>", "{", "const", "dependency", "=", "dependencies", "[", "key", "]", "const", "name", "=", "readObjectValue", "(", "dependency", ".", "name", ")", "const", "version", "=", "readObjectValue", "(", "dependency", ".", "version", ")", "if", "(", "dependency", ".", "name", "&&", "dependency", ".", "version", ")", "{", "const", "type", "=", "isParentRoot", "?", "'dependency'", ":", "'sub-dependency'", "const", "usage", "=", "devDependencies", ".", "hasOwnProperty", "(", "key", ")", "?", "'development'", ":", "'runtime'", "const", "included", "=", "!", "runtimeDependencies", ".", "hasOwnProperty", "(", "key", ")", "||", "!", "runtimeDependencies", "[", "key", "]", "?", "'No'", ":", "'Yes'", "const", "inRepo", "=", "dependency", ".", "link", "&&", "!", "dependency", ".", "link", ".", "startsWith", "(", "nodeModulesPath", ")", "?", "'Yes'", ":", "'No'", "const", "license", "=", "readObjectValue", "(", "dependency", ".", "license", ")", "const", "url", "=", "readObjectValue", "(", "dependency", ".", "homepage", "||", "dependency", ".", "repository", "||", "null", ")", "const", "description", "=", "readObjectValue", "(", "dependency", ".", "description", ")", "csv", "+=", "'\"'", "+", "name", "+", "'\",\"'", "+", "version", "+", "'\",\"'", "+", "type", "+", "'\",\"'", "+", "usage", "+", "'\",\"'", "+", "included", "+", "'\",\"'", "+", "inRepo", "+", "'\",\"'", "+", "license", "+", "'\",\"'", "+", "url", "+", "'\",\"'", "+", "description", "+", "'\"\\n'", "}", "\\n", "}", ")", "if", "(", "dependency", ".", "dependencies", ")", "{", "csv", "+=", "parseDependencies", "(", "dependency", ",", "runtimeDependencies", ",", "false", ")", "}", "}" ]
Recursively parses the dependencies object withing the given info object and returns them as a CSV string. @method parseDependencies @param {Object} info - An info object containing the `dependencies` property to parse. @param {Object} runtimeDependencies - An Object containing the runtime dependencies of this project. @param {Boolean} isParentRoot - Flag defining if the parent object of this dependencies is the root of the project. @returns {String}
[ "Recursively", "parses", "the", "dependencies", "object", "withing", "the", "given", "info", "object", "and", "returns", "them", "as", "a", "CSV", "string", "." ]
effd9357d32860624ee1f8a0e825641697be95e1
https://github.com/Microsoft/Essex-PowerBI-visuals-base/blob/effd9357d32860624ee1f8a0e825641697be95e1/packages/oss-report-builder/index.js#L121-L181
train
Microsoft/Essex-PowerBI-visuals-base
packages/oss-report-builder/index.js
findRuntimeDependencies
function findRuntimeDependencies(webpackModules) { const runtimeDependencies = {} webpackModules.forEach(module => { const name = module.name if ( name.startsWith('./~/') || name.startsWith('./node_modules/') || name.startsWith('./lib/') ) { const components = name.split('/') let i = 2 let moduleName = '' let moduleComponent = components[i++] while (moduleComponent.startsWith('@')) { moduleName += moduleComponent + '/' moduleComponent = components[i++] } moduleName += moduleComponent runtimeDependencies[moduleName] = module.built && module.cacheable } }) return Object.assign({}, runtimeDependencies, alwaysRuntimeDependencies) }
javascript
function findRuntimeDependencies(webpackModules) { const runtimeDependencies = {} webpackModules.forEach(module => { const name = module.name if ( name.startsWith('./~/') || name.startsWith('./node_modules/') || name.startsWith('./lib/') ) { const components = name.split('/') let i = 2 let moduleName = '' let moduleComponent = components[i++] while (moduleComponent.startsWith('@')) { moduleName += moduleComponent + '/' moduleComponent = components[i++] } moduleName += moduleComponent runtimeDependencies[moduleName] = module.built && module.cacheable } }) return Object.assign({}, runtimeDependencies, alwaysRuntimeDependencies) }
[ "function", "findRuntimeDependencies", "(", "webpackModules", ")", "{", "const", "runtimeDependencies", "=", "{", "}", "webpackModules", ".", "forEach", "(", "module", "=>", "{", "const", "name", "=", "module", ".", "name", "if", "(", "name", ".", "startsWith", "(", "'./~/'", ")", "||", "name", ".", "startsWith", "(", "'./node_modules/'", ")", "||", "name", ".", "startsWith", "(", "'./lib/'", ")", ")", "{", "const", "components", "=", "name", ".", "split", "(", "'/'", ")", "let", "i", "=", "2", "let", "moduleName", "=", "''", "let", "moduleComponent", "=", "components", "[", "i", "++", "]", "while", "(", "moduleComponent", ".", "startsWith", "(", "'@'", ")", ")", "{", "moduleName", "+=", "moduleComponent", "+", "'/'", "moduleComponent", "=", "components", "[", "i", "++", "]", "}", "moduleName", "+=", "moduleComponent", "runtimeDependencies", "[", "moduleName", "]", "=", "module", ".", "built", "&&", "module", ".", "cacheable", "}", "}", ")", "return", "Object", ".", "assign", "(", "{", "}", ",", "runtimeDependencies", ",", "alwaysRuntimeDependencies", ")", "}" ]
Finds the runtime dependencies in the given webpack modules and adds the dependencies defined in the `alwaysRuntimeDependencies` object. @method findRuntimeDependencies @param {Object} webpackModules - An object containing the dependencies as obtaining from compiling the project using webpack. @returns {Object}
[ "Finds", "the", "runtime", "dependencies", "in", "the", "given", "webpack", "modules", "and", "adds", "the", "dependencies", "defined", "in", "the", "alwaysRuntimeDependencies", "object", "." ]
effd9357d32860624ee1f8a0e825641697be95e1
https://github.com/Microsoft/Essex-PowerBI-visuals-base/blob/effd9357d32860624ee1f8a0e825641697be95e1/packages/oss-report-builder/index.js#L191-L213
train
Microsoft/Essex-PowerBI-visuals-base
packages/oss-report-builder/index.js
buildOSSReport
function buildOSSReport(webpackModules, cb) { parseNPMLL(dependencies => { const runtimeDependencies = findRuntimeDependencies(webpackModules) const dependenciesCSV = parseDependencies( dependencies, runtimeDependencies, true ) cb( '"Dependency","Version","Type","Usage","Included In Product","In Git Repository","License","URL","Description"\n' + dependenciesCSV ) }) }
javascript
function buildOSSReport(webpackModules, cb) { parseNPMLL(dependencies => { const runtimeDependencies = findRuntimeDependencies(webpackModules) const dependenciesCSV = parseDependencies( dependencies, runtimeDependencies, true ) cb( '"Dependency","Version","Type","Usage","Included In Product","In Git Repository","License","URL","Description"\n' + dependenciesCSV ) }) }
[ "function", "buildOSSReport", "(", "webpackModules", ",", "cb", ")", "{", "parseNPMLL", "(", "dependencies", "=>", "{", "const", "runtimeDependencies", "=", "findRuntimeDependencies", "(", "webpackModules", ")", "const", "dependenciesCSV", "=", "parseDependencies", "(", "dependencies", ",", "runtimeDependencies", ",", "true", ")", "cb", "(", "'\"Dependency\",\"Version\",\"Type\",\"Usage\",\"Included In Product\",\"In Git Repository\",\"License\",\"URL\",\"Description\"\\n'", "+", "\\n", ")", "}", ")", "}" ]
Builds an OSS report for this project taking into account the specified webpack dependencies. @method buildOSSReport @param {Object} webpackModules - An object containing the dependencies as obtaining from compiling the project using webpack. @param {Function} cb - A callback function to be invoked qhen the process is complete.
[ "Builds", "an", "OSS", "report", "for", "this", "project", "taking", "into", "account", "the", "specified", "webpack", "dependencies", "." ]
effd9357d32860624ee1f8a0e825641697be95e1
https://github.com/Microsoft/Essex-PowerBI-visuals-base/blob/effd9357d32860624ee1f8a0e825641697be95e1/packages/oss-report-builder/index.js#L222-L235
train
hammerlab/vcf.js
vcf.js
maybeMapOverVal
function maybeMapOverVal(fn, val) { var vals = val.split(','); if (vals.length > 1) { return vals.map(function(v) { return v == '.' ? null : fn(v); }); } return val == '.' ? null : fn(val); }
javascript
function maybeMapOverVal(fn, val) { var vals = val.split(','); if (vals.length > 1) { return vals.map(function(v) { return v == '.' ? null : fn(v); }); } return val == '.' ? null : fn(val); }
[ "function", "maybeMapOverVal", "(", "fn", ",", "val", ")", "{", "var", "vals", "=", "val", ".", "split", "(", "','", ")", ";", "if", "(", "vals", ".", "length", ">", "1", ")", "{", "return", "vals", ".", "map", "(", "function", "(", "v", ")", "{", "return", "v", "==", "'.'", "?", "null", ":", "fn", "(", "v", ")", ";", "}", ")", ";", "}", "return", "val", "==", "'.'", "?", "null", ":", "fn", "(", "val", ")", ";", "}" ]
VCF values can be comma-separated lists, so here we want to convert them into lists of the proper type, else return the singleton value of that type. All values are also nullable, signified with a '.', we want to watch out for those as well.
[ "VCF", "values", "can", "be", "comma", "-", "separated", "lists", "so", "here", "we", "want", "to", "convert", "them", "into", "lists", "of", "the", "proper", "type", "else", "return", "the", "singleton", "value", "of", "that", "type", ".", "All", "values", "are", "also", "nullable", "signified", "with", "a", ".", "we", "want", "to", "watch", "out", "for", "those", "as", "well", "." ]
017583ddf5a5b02d2a538ffd1e85c41c3ffeefa1
https://github.com/hammerlab/vcf.js/blob/017583ddf5a5b02d2a538ffd1e85c41c3ffeefa1/vcf.js#L33-L39
train
hammerlab/vcf.js
vcf.js
parseVCF
function parseVCF(text) { var lines = U.reject(text.split('\n'), function(line) { return line === ''; }); var partitions = U.partition(lines, function(line) { return line[0] === '#'; }); var header = parseHeader(partitions[0]), records = U.map(partitions[1], function(line) { return new Record(line, header); }); return {header: header, records: records}; }
javascript
function parseVCF(text) { var lines = U.reject(text.split('\n'), function(line) { return line === ''; }); var partitions = U.partition(lines, function(line) { return line[0] === '#'; }); var header = parseHeader(partitions[0]), records = U.map(partitions[1], function(line) { return new Record(line, header); }); return {header: header, records: records}; }
[ "function", "parseVCF", "(", "text", ")", "{", "var", "lines", "=", "U", ".", "reject", "(", "text", ".", "split", "(", "'\\n'", ")", ",", "\\n", ")", ";", "function", "(", "line", ")", "{", "return", "line", "===", "''", ";", "}", "var", "partitions", "=", "U", ".", "partition", "(", "lines", ",", "function", "(", "line", ")", "{", "return", "line", "[", "0", "]", "===", "'#'", ";", "}", ")", ";", "var", "header", "=", "parseHeader", "(", "partitions", "[", "0", "]", ")", ",", "records", "=", "U", ".", "map", "(", "partitions", "[", "1", "]", ",", "function", "(", "line", ")", "{", "return", "new", "Record", "(", "line", ",", "header", ")", ";", "}", ")", ";", "}" ]
Returns a parsed VCF object, with attributes `records` and `header`. `records` - a list of VCF Records. `header` - an object of the metadata parsed from the VCF header. `text` - VCF plaintext.
[ "Returns", "a", "parsed", "VCF", "object", "with", "attributes", "records", "and", "header", ".", "records", "-", "a", "list", "of", "VCF", "Records", ".", "header", "-", "an", "object", "of", "the", "metadata", "parsed", "from", "the", "VCF", "header", ".", "text", "-", "VCF", "plaintext", "." ]
017583ddf5a5b02d2a538ffd1e85c41c3ffeefa1
https://github.com/hammerlab/vcf.js/blob/017583ddf5a5b02d2a538ffd1e85c41c3ffeefa1/vcf.js#L378-L393
train
ccbabi/axios-add-jsonp
index.js
runHook
function runHook (instance, type) { var hook = type ? 'response' : 'request' hook += 'Hook' if (instance[hook] && isFunction(instance[hook])) { instance[hook]() } }
javascript
function runHook (instance, type) { var hook = type ? 'response' : 'request' hook += 'Hook' if (instance[hook] && isFunction(instance[hook])) { instance[hook]() } }
[ "function", "runHook", "(", "instance", ",", "type", ")", "{", "var", "hook", "=", "type", "?", "'response'", ":", "'request'", "hook", "+=", "'Hook'", "if", "(", "instance", "[", "hook", "]", "&&", "isFunction", "(", "instance", "[", "hook", "]", ")", ")", "{", "instance", "[", "hook", "]", "(", ")", "}", "}" ]
Every time it is detected, it means that the external dynamic changes
[ "Every", "time", "it", "is", "detected", "it", "means", "that", "the", "external", "dynamic", "changes" ]
64a1fb06e731390bbdbc28a55ab33ad3cde0f25e
https://github.com/ccbabi/axios-add-jsonp/blob/64a1fb06e731390bbdbc28a55ab33ad3cde0f25e/index.js#L76-L82
train
jonathantneal/postcss-export-custom-variables
index.js
isCustomMediaQuery
function isCustomMediaQuery(node) { return node.type === 'atrule' && node.name === 'custom-media' && customMediaQueryMatch.test(node.params); }
javascript
function isCustomMediaQuery(node) { return node.type === 'atrule' && node.name === 'custom-media' && customMediaQueryMatch.test(node.params); }
[ "function", "isCustomMediaQuery", "(", "node", ")", "{", "return", "node", ".", "type", "===", "'atrule'", "&&", "node", ".", "name", "===", "'custom-media'", "&&", "customMediaQueryMatch", ".", "test", "(", "node", ".", "params", ")", ";", "}" ]
Variable detection functions
[ "Variable", "detection", "functions" ]
ce15caa33e52cca56b0b95cebfc9f32f3a8e6923
https://github.com/jonathantneal/postcss-export-custom-variables/blob/ce15caa33e52cca56b0b95cebfc9f32f3a8e6923/index.js#L64-L66
train
jonathantneal/postcss-export-custom-variables
index.js
defaultAssigner
function defaultAssigner(rawproperty, rawvalue) { const property = rawproperty.replace(/-+(.|$)/g, ([ , letter]) => letter.toUpperCase()); return { [property]: rawvalue }; }
javascript
function defaultAssigner(rawproperty, rawvalue) { const property = rawproperty.replace(/-+(.|$)/g, ([ , letter]) => letter.toUpperCase()); return { [property]: rawvalue }; }
[ "function", "defaultAssigner", "(", "rawproperty", ",", "rawvalue", ")", "{", "const", "property", "=", "rawproperty", ".", "replace", "(", "/", "-+(.|$)", "/", "g", ",", "(", "[", ",", "letter", "]", ")", "=>", "letter", ".", "toUpperCase", "(", ")", ")", ";", "return", "{", "[", "property", "]", ":", "rawvalue", "}", ";", "}" ]
Default Assigner functions
[ "Default", "Assigner", "functions" ]
ce15caa33e52cca56b0b95cebfc9f32f3a8e6923
https://github.com/jonathantneal/postcss-export-custom-variables/blob/ce15caa33e52cca56b0b95cebfc9f32f3a8e6923/index.js#L82-L88
train
jonathantneal/postcss-export-custom-variables
index.js
defaultJsExporter
function defaultJsExporter(variables, options, root) { const pathname = options.destination || root.source && root.source.input && root.source.input.file && root.source.input.file + '.js' || 'custom-variables.js'; const contents = Object.keys(variables).reduce( (buffer, key) => `${ buffer }export const ${ key } = ${ JSON.stringify(variables[key]).replace(/(^|{|,)"(.+?)":/g, '$1$2:') };\n`, '' ); return new Promise((resolve, reject) => { fs.writeFile( pathname, contents, (error) => error ? reject(error) : resolve() ); }); }
javascript
function defaultJsExporter(variables, options, root) { const pathname = options.destination || root.source && root.source.input && root.source.input.file && root.source.input.file + '.js' || 'custom-variables.js'; const contents = Object.keys(variables).reduce( (buffer, key) => `${ buffer }export const ${ key } = ${ JSON.stringify(variables[key]).replace(/(^|{|,)"(.+?)":/g, '$1$2:') };\n`, '' ); return new Promise((resolve, reject) => { fs.writeFile( pathname, contents, (error) => error ? reject(error) : resolve() ); }); }
[ "function", "defaultJsExporter", "(", "variables", ",", "options", ",", "root", ")", "{", "const", "pathname", "=", "options", ".", "destination", "||", "root", ".", "source", "&&", "root", ".", "source", ".", "input", "&&", "root", ".", "source", ".", "input", ".", "file", "&&", "root", ".", "source", ".", "input", ".", "file", "+", "'.js'", "||", "'custom-variables.js'", ";", "const", "contents", "=", "Object", ".", "keys", "(", "variables", ")", ".", "reduce", "(", "(", "buffer", ",", "key", ")", "=>", "`", "${", "buffer", "}", "${", "key", "}", "${", "JSON", ".", "stringify", "(", "variables", "[", "key", "]", ")", ".", "replace", "(", "/", "(^|{|,)\"(.+?)\":", "/", "g", ",", "'$1$2:'", ")", "}", "\\n", "`", ",", "''", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "writeFile", "(", "pathname", ",", "contents", ",", "(", "error", ")", "=>", "error", "?", "reject", "(", "error", ")", ":", "resolve", "(", ")", ")", ";", "}", ")", ";", "}" ]
Default export functions
[ "Default", "export", "functions" ]
ce15caa33e52cca56b0b95cebfc9f32f3a8e6923
https://github.com/jonathantneal/postcss-export-custom-variables/blob/ce15caa33e52cca56b0b95cebfc9f32f3a8e6923/index.js#L109-L123
train
jpodwys/cache-service
cacheService.js
checkCacheResponse
function checkCacheResponse(key, err, result, type, cacheIndex){ if(err){ log(true, 'Error when getting key ' + key + ' from cache of type ' + type + ':', err); if(cacheIndex < self.caches.length - 1){ return {status:'continue'}; } } //THIS ALLOWS false AS A VALID CACHE VALUE, BUT DO I WANT null TO BE VALID AS WELL? if(result !== null && typeof result !== 'undefined'){ log(false, 'Key found:', {key: key, value: result}); return {status: 'break', result: result}; } var curCache = self.caches[cacheIndex]; for(var i = cacheIndex + 1; i < self.cachesLength; i++) { var nextCache = self.caches[i]; if(nextCache.checkOnPreviousEmpty || nextCache.expiration > curCache.expiration){ return {status:'continue', toIndex: i}; } } return {status: 'else'}; }
javascript
function checkCacheResponse(key, err, result, type, cacheIndex){ if(err){ log(true, 'Error when getting key ' + key + ' from cache of type ' + type + ':', err); if(cacheIndex < self.caches.length - 1){ return {status:'continue'}; } } //THIS ALLOWS false AS A VALID CACHE VALUE, BUT DO I WANT null TO BE VALID AS WELL? if(result !== null && typeof result !== 'undefined'){ log(false, 'Key found:', {key: key, value: result}); return {status: 'break', result: result}; } var curCache = self.caches[cacheIndex]; for(var i = cacheIndex + 1; i < self.cachesLength; i++) { var nextCache = self.caches[i]; if(nextCache.checkOnPreviousEmpty || nextCache.expiration > curCache.expiration){ return {status:'continue', toIndex: i}; } } return {status: 'else'}; }
[ "function", "checkCacheResponse", "(", "key", ",", "err", ",", "result", ",", "type", ",", "cacheIndex", ")", "{", "if", "(", "err", ")", "{", "log", "(", "true", ",", "'Error when getting key '", "+", "key", "+", "' from cache of type '", "+", "type", "+", "':'", ",", "err", ")", ";", "if", "(", "cacheIndex", "<", "self", ".", "caches", ".", "length", "-", "1", ")", "{", "return", "{", "status", ":", "'continue'", "}", ";", "}", "}", "if", "(", "result", "!==", "null", "&&", "typeof", "result", "!==", "'undefined'", ")", "{", "log", "(", "false", ",", "'Key found:'", ",", "{", "key", ":", "key", ",", "value", ":", "result", "}", ")", ";", "return", "{", "status", ":", "'break'", ",", "result", ":", "result", "}", ";", "}", "var", "curCache", "=", "self", ".", "caches", "[", "cacheIndex", "]", ";", "for", "(", "var", "i", "=", "cacheIndex", "+", "1", ";", "i", "<", "self", ".", "cachesLength", ";", "i", "++", ")", "{", "var", "nextCache", "=", "self", ".", "caches", "[", "i", "]", ";", "if", "(", "nextCache", ".", "checkOnPreviousEmpty", "||", "nextCache", ".", "expiration", ">", "curCache", ".", "expiration", ")", "{", "return", "{", "status", ":", "'continue'", ",", "toIndex", ":", "i", "}", ";", "}", "}", "return", "{", "status", ":", "'else'", "}", ";", "}" ]
Decides what action cacheService should take given the response from a configured cache @param {string} key @param {null | object} err @param {null | object | string} result @param {string} type @param {integer} cacheIndex
[ "Decides", "what", "action", "cacheService", "should", "take", "given", "the", "response", "from", "a", "configured", "cache" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheService.js#L253-L274
train
jpodwys/cache-service
cacheService.js
writeToVolatileCaches
function writeToVolatileCaches(currentCacheIndex, key, value){ if(currentCacheIndex > 0){ var curExpiration = self.caches[currentCacheIndex].expiration; for(var tempIndex = currentCacheIndex; tempIndex > -1; tempIndex--){ var preExpiration = self.caches[tempIndex].expiration; if(preExpiration <= curExpiration){ var preCache = self.caches[currentCacheIndex]; if(value){ preCache.set(key, value); /*This means that a more volatile cache can have a key longer than a less volatile cache. Should I adjust this?*/ } else if(typeof key === 'object'){ preCache.mset(key); } } } } }
javascript
function writeToVolatileCaches(currentCacheIndex, key, value){ if(currentCacheIndex > 0){ var curExpiration = self.caches[currentCacheIndex].expiration; for(var tempIndex = currentCacheIndex; tempIndex > -1; tempIndex--){ var preExpiration = self.caches[tempIndex].expiration; if(preExpiration <= curExpiration){ var preCache = self.caches[currentCacheIndex]; if(value){ preCache.set(key, value); /*This means that a more volatile cache can have a key longer than a less volatile cache. Should I adjust this?*/ } else if(typeof key === 'object'){ preCache.mset(key); } } } } }
[ "function", "writeToVolatileCaches", "(", "currentCacheIndex", ",", "key", ",", "value", ")", "{", "if", "(", "currentCacheIndex", ">", "0", ")", "{", "var", "curExpiration", "=", "self", ".", "caches", "[", "currentCacheIndex", "]", ".", "expiration", ";", "for", "(", "var", "tempIndex", "=", "currentCacheIndex", ";", "tempIndex", ">", "-", "1", ";", "tempIndex", "--", ")", "{", "var", "preExpiration", "=", "self", ".", "caches", "[", "tempIndex", "]", ".", "expiration", ";", "if", "(", "preExpiration", "<=", "curExpiration", ")", "{", "var", "preCache", "=", "self", ".", "caches", "[", "currentCacheIndex", "]", ";", "if", "(", "value", ")", "{", "preCache", ".", "set", "(", "key", ",", "value", ")", ";", "}", "else", "if", "(", "typeof", "key", "===", "'object'", ")", "{", "preCache", ".", "mset", "(", "key", ")", ";", "}", "}", "}", "}", "}" ]
Writes data to caches that appear before the current cache in caches @param {integer} currentCacheIndex @param {string} key @param {null | object | string} value
[ "Writes", "data", "to", "caches", "that", "appear", "before", "the", "current", "cache", "in", "caches" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheService.js#L282-L298
train
jpodwys/cache-service
cacheService.js
log
function log(isError, message, data){ var indentifier = 'cacheService: '; if(self.verbose || isError){ if(data) { console.log(indentifier + message, data); } else { console.log(indentifier + message); } } }
javascript
function log(isError, message, data){ var indentifier = 'cacheService: '; if(self.verbose || isError){ if(data) { console.log(indentifier + message, data); } else { console.log(indentifier + message); } } }
[ "function", "log", "(", "isError", ",", "message", ",", "data", ")", "{", "var", "indentifier", "=", "'cacheService: '", ";", "if", "(", "self", ".", "verbose", "||", "isError", ")", "{", "if", "(", "data", ")", "{", "console", ".", "log", "(", "indentifier", "+", "message", ",", "data", ")", ";", "}", "else", "{", "console", ".", "log", "(", "indentifier", "+", "message", ")", ";", "}", "}", "}" ]
Logging utility function @param {boolean} isError @param {string} message @param {object} data
[ "Logging", "utility", "function" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheService.js#L317-L326
train
phproberto/joomla-gulp
src/plugins.js
getPlugins
function getPlugins() { var results = [] if (extensions && extensions.hasOwnProperty('plugins')) { for(var type in extensions.plugins) { var sourceArray = extensions.plugins[type]; for (index = 0; index < sourceArray.length; ++index) { results.push(type + '.' + sourceArray[index]); } } } return results; }
javascript
function getPlugins() { var results = [] if (extensions && extensions.hasOwnProperty('plugins')) { for(var type in extensions.plugins) { var sourceArray = extensions.plugins[type]; for (index = 0; index < sourceArray.length; ++index) { results.push(type + '.' + sourceArray[index]); } } } return results; }
[ "function", "getPlugins", "(", ")", "{", "var", "results", "=", "[", "]", "if", "(", "extensions", "&&", "extensions", ".", "hasOwnProperty", "(", "'plugins'", ")", ")", "{", "for", "(", "var", "type", "in", "extensions", ".", "plugins", ")", "{", "var", "sourceArray", "=", "extensions", ".", "plugins", "[", "type", "]", ";", "for", "(", "index", "=", "0", ";", "index", "<", "sourceArray", ".", "length", ";", "++", "index", ")", "{", "results", ".", "push", "(", "type", "+", "'.'", "+", "sourceArray", "[", "index", "]", ")", ";", "}", "}", "}", "return", "results", ";", "}" ]
Get the list of available plugins @return array
[ "Get", "the", "list", "of", "available", "plugins" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/plugins.js#L17-L33
train
phproberto/joomla-gulp
src/plugins.js
getPluginsTasks
function getPluginsTasks(baseTask) { var tasks = []; var plugins = getPlugins(); if (plugins) { for (pos = 0; pos < plugins.length; ++pos) { tasks.push(baseTask + '.' + plugins[pos]); } } return tasks; }
javascript
function getPluginsTasks(baseTask) { var tasks = []; var plugins = getPlugins(); if (plugins) { for (pos = 0; pos < plugins.length; ++pos) { tasks.push(baseTask + '.' + plugins[pos]); } } return tasks; }
[ "function", "getPluginsTasks", "(", "baseTask", ")", "{", "var", "tasks", "=", "[", "]", ";", "var", "plugins", "=", "getPlugins", "(", ")", ";", "if", "(", "plugins", ")", "{", "for", "(", "pos", "=", "0", ";", "pos", "<", "plugins", ".", "length", ";", "++", "pos", ")", "{", "tasks", ".", "push", "(", "baseTask", "+", "'.'", "+", "plugins", "[", "pos", "]", ")", ";", "}", "}", "return", "tasks", ";", "}" ]
Function to ease the custom plugins management @param string baseTask Task to use as root. Example: 'clean:plugins.frontend' @param string app 'frontend', 'backend' @return array
[ "Function", "to", "ease", "the", "custom", "plugins", "management" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/plugins.js#L43-L54
train
phproberto/joomla-gulp
src/modules.js
getModules
function getModules(app) { var results = []; if (extensions && extensions.hasOwnProperty('modules') && extensions.modules.hasOwnProperty(app) ) { var sourceArray = extensions.modules[app]; for (index = 0; index < sourceArray.length; ++index) { results.push(app + '.' + sourceArray[index]); } } return results; }
javascript
function getModules(app) { var results = []; if (extensions && extensions.hasOwnProperty('modules') && extensions.modules.hasOwnProperty(app) ) { var sourceArray = extensions.modules[app]; for (index = 0; index < sourceArray.length; ++index) { results.push(app + '.' + sourceArray[index]); } } return results; }
[ "function", "getModules", "(", "app", ")", "{", "var", "results", "=", "[", "]", ";", "if", "(", "extensions", "&&", "extensions", ".", "hasOwnProperty", "(", "'modules'", ")", "&&", "extensions", ".", "modules", ".", "hasOwnProperty", "(", "app", ")", ")", "{", "var", "sourceArray", "=", "extensions", ".", "modules", "[", "app", "]", ";", "for", "(", "index", "=", "0", ";", "index", "<", "sourceArray", ".", "length", ";", "++", "index", ")", "{", "results", ".", "push", "(", "app", "+", "'.'", "+", "sourceArray", "[", "index", "]", ")", ";", "}", "}", "return", "results", ";", "}" ]
Get the available modules from paths @param string app 'frontend' | 'backend' @return array
[ "Get", "the", "available", "modules", "from", "paths" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/modules.js#L19-L33
train
phproberto/joomla-gulp
src/modules.js
getModulesTasks
function getModulesTasks(baseTask, app) { var tasks = []; var modules = getModules(app); if (modules) { for (index = 0; index < modules.length; ++index) { tasks.push(baseTask + '.' + modules[index]); } } return tasks; }
javascript
function getModulesTasks(baseTask, app) { var tasks = []; var modules = getModules(app); if (modules) { for (index = 0; index < modules.length; ++index) { tasks.push(baseTask + '.' + modules[index]); } } return tasks; }
[ "function", "getModulesTasks", "(", "baseTask", ",", "app", ")", "{", "var", "tasks", "=", "[", "]", ";", "var", "modules", "=", "getModules", "(", "app", ")", ";", "if", "(", "modules", ")", "{", "for", "(", "index", "=", "0", ";", "index", "<", "modules", ".", "length", ";", "++", "index", ")", "{", "tasks", ".", "push", "(", "baseTask", "+", "'.'", "+", "modules", "[", "index", "]", ")", ";", "}", "}", "return", "tasks", ";", "}" ]
Function to ease the modules management @param string baseTask Task to use as root. Example: 'clean:modules' @param string app 'frontend', 'backend' @return array
[ "Function", "to", "ease", "the", "modules", "management" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/modules.js#L43-L54
train
phproberto/joomla-gulp
src/components.js
getComponents
function getComponents() { var results = []; if (extensions && extensions.hasOwnProperty('components')) { var sourceArray = extensions.components; for (index = 0; index < sourceArray.length; ++index) { results.push(sourceArray[index]); } } return results; }
javascript
function getComponents() { var results = []; if (extensions && extensions.hasOwnProperty('components')) { var sourceArray = extensions.components; for (index = 0; index < sourceArray.length; ++index) { results.push(sourceArray[index]); } } return results; }
[ "function", "getComponents", "(", ")", "{", "var", "results", "=", "[", "]", ";", "if", "(", "extensions", "&&", "extensions", ".", "hasOwnProperty", "(", "'components'", ")", ")", "{", "var", "sourceArray", "=", "extensions", ".", "components", ";", "for", "(", "index", "=", "0", ";", "index", "<", "sourceArray", ".", "length", ";", "++", "index", ")", "{", "results", ".", "push", "(", "sourceArray", "[", "index", "]", ")", ";", "}", "}", "return", "results", ";", "}" ]
Get the list of the active components from paths @return array
[ "Get", "the", "list", "of", "the", "active", "components", "from", "paths" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/components.js#L17-L29
train
phproberto/joomla-gulp
src/components.js
getComponentsTasks
function getComponentsTasks(baseTask) { var components = getComponents(); var tasks = []; for (index = 0; index < components.length; ++index) { tasks.push(baseTask + '.' + components[index]); } return tasks; }
javascript
function getComponentsTasks(baseTask) { var components = getComponents(); var tasks = []; for (index = 0; index < components.length; ++index) { tasks.push(baseTask + '.' + components[index]); } return tasks; }
[ "function", "getComponentsTasks", "(", "baseTask", ")", "{", "var", "components", "=", "getComponents", "(", ")", ";", "var", "tasks", "=", "[", "]", ";", "for", "(", "index", "=", "0", ";", "index", "<", "components", ".", "length", ";", "++", "index", ")", "{", "tasks", ".", "push", "(", "baseTask", "+", "'.'", "+", "components", "[", "index", "]", ")", ";", "}", "return", "tasks", ";", "}" ]
Function to ease the components @param string baseTask Task to use as root. Example: 'clean:modules.frontend' @return array
[ "Function", "to", "ease", "the", "components" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/components.js#L38-L47
train
alekseykulikov/storage
lib/index.js
get
function get(key, cb) { return type(key) != 'array' ? localForage.getItem(key).then(wrap(cb, true), cb) : Promise.all(key.map(getSubkey)).then(wrap(cb, true), cb); function getSubkey(key) { return get(key, function() {}); // noob function to prevent logs } }
javascript
function get(key, cb) { return type(key) != 'array' ? localForage.getItem(key).then(wrap(cb, true), cb) : Promise.all(key.map(getSubkey)).then(wrap(cb, true), cb); function getSubkey(key) { return get(key, function() {}); // noob function to prevent logs } }
[ "function", "get", "(", "key", ",", "cb", ")", "{", "return", "type", "(", "key", ")", "!=", "'array'", "?", "localForage", ".", "getItem", "(", "key", ")", ".", "then", "(", "wrap", "(", "cb", ",", "true", ")", ",", "cb", ")", ":", "Promise", ".", "all", "(", "key", ".", "map", "(", "getSubkey", ")", ")", ".", "then", "(", "wrap", "(", "cb", ",", "true", ")", ",", "cb", ")", ";", "function", "getSubkey", "(", "key", ")", "{", "return", "get", "(", "key", ",", "function", "(", ")", "{", "}", ")", ";", "}", "}" ]
Get `key`. @param {Array|Mixed} key @param {Function} cb
[ "Get", "key", "." ]
7ce45bcd9b3f61ae94914fd63fcacd06760e00b1
https://github.com/alekseykulikov/storage/blob/7ce45bcd9b3f61ae94914fd63fcacd06760e00b1/lib/index.js#L62-L70
train
alekseykulikov/storage
lib/index.js
set
function set(key, val, cb) { return type(key) != 'object' ? localForage.setItem(key, val).then(wrap(cb), cb) : Promise.all(Object.keys(key).map(setSubkey)).then(wrap(val), val); function setSubkey(subkey, next) { return key[subkey] === null ? del(subkey, next) : set(subkey, key[subkey], next); } }
javascript
function set(key, val, cb) { return type(key) != 'object' ? localForage.setItem(key, val).then(wrap(cb), cb) : Promise.all(Object.keys(key).map(setSubkey)).then(wrap(val), val); function setSubkey(subkey, next) { return key[subkey] === null ? del(subkey, next) : set(subkey, key[subkey], next); } }
[ "function", "set", "(", "key", ",", "val", ",", "cb", ")", "{", "return", "type", "(", "key", ")", "!=", "'object'", "?", "localForage", ".", "setItem", "(", "key", ",", "val", ")", ".", "then", "(", "wrap", "(", "cb", ")", ",", "cb", ")", ":", "Promise", ".", "all", "(", "Object", ".", "keys", "(", "key", ")", ".", "map", "(", "setSubkey", ")", ")", ".", "then", "(", "wrap", "(", "val", ")", ",", "val", ")", ";", "function", "setSubkey", "(", "subkey", ",", "next", ")", "{", "return", "key", "[", "subkey", "]", "===", "null", "?", "del", "(", "subkey", ",", "next", ")", ":", "set", "(", "subkey", ",", "key", "[", "subkey", "]", ",", "next", ")", ";", "}", "}" ]
Set `val` to `key`. @param {Array|Mixed} key @param {Mixed} val @param {Function} cb
[ "Set", "val", "to", "key", "." ]
7ce45bcd9b3f61ae94914fd63fcacd06760e00b1
https://github.com/alekseykulikov/storage/blob/7ce45bcd9b3f61ae94914fd63fcacd06760e00b1/lib/index.js#L80-L90
train
alekseykulikov/storage
lib/index.js
del
function del(key, cb) { return type(key) != 'array' ? localForage.removeItem(key).then(wrap(cb), cb) : Promise.all(key.map(del)).then(wrap(cb), cb); }
javascript
function del(key, cb) { return type(key) != 'array' ? localForage.removeItem(key).then(wrap(cb), cb) : Promise.all(key.map(del)).then(wrap(cb), cb); }
[ "function", "del", "(", "key", ",", "cb", ")", "{", "return", "type", "(", "key", ")", "!=", "'array'", "?", "localForage", ".", "removeItem", "(", "key", ")", ".", "then", "(", "wrap", "(", "cb", ")", ",", "cb", ")", ":", "Promise", ".", "all", "(", "key", ".", "map", "(", "del", ")", ")", ".", "then", "(", "wrap", "(", "cb", ")", ",", "cb", ")", ";", "}" ]
Delete `key`. @param {Array|Mixed} key @param {Function} cb
[ "Delete", "key", "." ]
7ce45bcd9b3f61ae94914fd63fcacd06760e00b1
https://github.com/alekseykulikov/storage/blob/7ce45bcd9b3f61ae94914fd63fcacd06760e00b1/lib/index.js#L99-L103
train
alekseykulikov/storage
lib/index.js
wrap
function wrap(cb, hasResult) { return function(res) { if (type(cb) == 'function') { hasResult ? cb(null, res) : cb(); } else if (hasResult && storage.development) { console.log(res); } return res; }; }
javascript
function wrap(cb, hasResult) { return function(res) { if (type(cb) == 'function') { hasResult ? cb(null, res) : cb(); } else if (hasResult && storage.development) { console.log(res); } return res; }; }
[ "function", "wrap", "(", "cb", ",", "hasResult", ")", "{", "return", "function", "(", "res", ")", "{", "if", "(", "type", "(", "cb", ")", "==", "'function'", ")", "{", "hasResult", "?", "cb", "(", "null", ",", "res", ")", ":", "cb", "(", ")", ";", "}", "else", "if", "(", "hasResult", "&&", "storage", ".", "development", ")", "{", "console", ".", "log", "(", "res", ")", ";", "}", "return", "res", ";", "}", ";", "}" ]
Wrap promise style response to callback style. If `cb` does not specified, it uses console.log in development mode. @param {Function} cb @param {Boolean} [hasResult] @return {Function}
[ "Wrap", "promise", "style", "response", "to", "callback", "style", ".", "If", "cb", "does", "not", "specified", "it", "uses", "console", ".", "log", "in", "development", "mode", "." ]
7ce45bcd9b3f61ae94914fd63fcacd06760e00b1
https://github.com/alekseykulikov/storage/blob/7ce45bcd9b3f61ae94914fd63fcacd06760e00b1/lib/index.js#L134-L143
train
phproberto/joomla-gulp
src/libraries.js
getLibrariesTasks
function getLibrariesTasks(baseTask) { var libraries = getLibraries(); var tasks = []; for (index = 0; index < libraries.length; ++index) { tasks.push(baseTask + '.' + libraries[index]); } return tasks; }
javascript
function getLibrariesTasks(baseTask) { var libraries = getLibraries(); var tasks = []; for (index = 0; index < libraries.length; ++index) { tasks.push(baseTask + '.' + libraries[index]); } return tasks; }
[ "function", "getLibrariesTasks", "(", "baseTask", ")", "{", "var", "libraries", "=", "getLibraries", "(", ")", ";", "var", "tasks", "=", "[", "]", ";", "for", "(", "index", "=", "0", ";", "index", "<", "libraries", ".", "length", ";", "++", "index", ")", "{", "tasks", ".", "push", "(", "baseTask", "+", "'.'", "+", "libraries", "[", "index", "]", ")", ";", "}", "return", "tasks", ";", "}" ]
Function to get the tasks to execute on libraries @param string baseTask Task to use as root. Example: 'clean:libraries' @return array
[ "Function", "to", "get", "the", "tasks", "to", "execute", "on", "libraries" ]
17e0631140db730a7613f87399d0655df1698b30
https://github.com/phproberto/joomla-gulp/blob/17e0631140db730a7613f87399d0655df1698b30/src/libraries.js#L38-L47
train
jpodwys/cache-service
cacheCollection.js
init
function init(){ self.caches = []; if(isEmpty(cacheModules)){ log(false, 'No cacheModules array provided--using the default configuration.'); getDefaultConfiguration(); } else{ log(false, 'cacheModules array provided--using a custom configuration.'); getCustomConfiguration(); if(self.caches.length < 1){ throw new Exception('NoCacheException', 'No caches were succesfully initialized.'); } } }
javascript
function init(){ self.caches = []; if(isEmpty(cacheModules)){ log(false, 'No cacheModules array provided--using the default configuration.'); getDefaultConfiguration(); } else{ log(false, 'cacheModules array provided--using a custom configuration.'); getCustomConfiguration(); if(self.caches.length < 1){ throw new Exception('NoCacheException', 'No caches were succesfully initialized.'); } } }
[ "function", "init", "(", ")", "{", "self", ".", "caches", "=", "[", "]", ";", "if", "(", "isEmpty", "(", "cacheModules", ")", ")", "{", "log", "(", "false", ",", "'No cacheModules array provided--using the default configuration.'", ")", ";", "getDefaultConfiguration", "(", ")", ";", "}", "else", "{", "log", "(", "false", ",", "'cacheModules array provided--using a custom configuration.'", ")", ";", "getCustomConfiguration", "(", ")", ";", "if", "(", "self", ".", "caches", ".", "length", "<", "1", ")", "{", "throw", "new", "Exception", "(", "'NoCacheException'", ",", "'No caches were succesfully initialized.'", ")", ";", "}", "}", "}" ]
Initialize cacheCollection given the provided constructor params
[ "Initialize", "cacheCollection", "given", "the", "provided", "constructor", "params" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheCollection.js#L18-L31
train
jpodwys/cache-service
cacheCollection.js
getDefaultConfiguration
function getDefaultConfiguration(){ var CModule = require('cache-service-cache-module'); var cacheModule = new CModule(); cacheModule = addSettings(cacheModule); self.caches.push(cacheModule); }
javascript
function getDefaultConfiguration(){ var CModule = require('cache-service-cache-module'); var cacheModule = new CModule(); cacheModule = addSettings(cacheModule); self.caches.push(cacheModule); }
[ "function", "getDefaultConfiguration", "(", ")", "{", "var", "CModule", "=", "require", "(", "'cache-service-cache-module'", ")", ";", "var", "cacheModule", "=", "new", "CModule", "(", ")", ";", "cacheModule", "=", "addSettings", "(", "cacheModule", ")", ";", "self", ".", "caches", ".", "push", "(", "cacheModule", ")", ";", "}" ]
Adds a nodeCacheModule instance to self.caches if no cacheModules array is provided
[ "Adds", "a", "nodeCacheModule", "instance", "to", "self", ".", "caches", "if", "no", "cacheModules", "array", "is", "provided" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheCollection.js#L36-L41
train
jpodwys/cache-service
cacheCollection.js
getCustomConfiguration
function getCustomConfiguration(){ for(var i = 0; i < cacheModules.length; i++){ var cacheModule = cacheModules[i]; if(isEmpty(cacheModule)){ log(true, 'Cache module at index ' + i + ' is \'empty\'.'); continue; } cacheModule = addSettings(cacheModule); self.caches.push(cacheModule); } }
javascript
function getCustomConfiguration(){ for(var i = 0; i < cacheModules.length; i++){ var cacheModule = cacheModules[i]; if(isEmpty(cacheModule)){ log(true, 'Cache module at index ' + i + ' is \'empty\'.'); continue; } cacheModule = addSettings(cacheModule); self.caches.push(cacheModule); } }
[ "function", "getCustomConfiguration", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "cacheModules", ".", "length", ";", "i", "++", ")", "{", "var", "cacheModule", "=", "cacheModules", "[", "i", "]", ";", "if", "(", "isEmpty", "(", "cacheModule", ")", ")", "{", "log", "(", "true", ",", "'Cache module at index '", "+", "i", "+", "' is \\'empty\\'.'", ")", ";", "\\'", "}", "\\'", "continue", ";", "}", "}" ]
Adds caches that are not 'empty' from the cacheModules array to self.caches
[ "Adds", "caches", "that", "are", "not", "empty", "from", "the", "cacheModules", "array", "to", "self", ".", "caches" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheCollection.js#L46-L56
train
jpodwys/cache-service
cacheCollection.js
addSettings
function addSettings(cacheModule){ cacheModule.nameSpace = settings.nameSpace; cacheModule.verbose = settings.verbose; return cacheModule; }
javascript
function addSettings(cacheModule){ cacheModule.nameSpace = settings.nameSpace; cacheModule.verbose = settings.verbose; return cacheModule; }
[ "function", "addSettings", "(", "cacheModule", ")", "{", "cacheModule", ".", "nameSpace", "=", "settings", ".", "nameSpace", ";", "cacheModule", ".", "verbose", "=", "settings", ".", "verbose", ";", "return", "cacheModule", ";", "}" ]
Adds cache-service config properties to each cache module @param {object} cacheModule @return {object} cacheModule
[ "Adds", "cache", "-", "service", "config", "properties", "to", "each", "cache", "module" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheCollection.js#L63-L67
train
jpodwys/cache-service
cacheCollection.js
isEmpty
function isEmpty (val) { return (val === undefined || val === false || val === null || (typeof val === 'object' && Object.keys(val).length === 0)); }
javascript
function isEmpty (val) { return (val === undefined || val === false || val === null || (typeof val === 'object' && Object.keys(val).length === 0)); }
[ "function", "isEmpty", "(", "val", ")", "{", "return", "(", "val", "===", "undefined", "||", "val", "===", "false", "||", "val", "===", "null", "||", "(", "typeof", "val", "===", "'object'", "&&", "Object", ".", "keys", "(", "val", ")", ".", "length", "===", "0", ")", ")", ";", "}" ]
Checks if a value is "empty" @param {object | string | null | undefined} val @return {boolean}
[ "Checks", "if", "a", "value", "is", "empty" ]
cffc91b262b9dd2f6529628fda5782ed985bfaaf
https://github.com/jpodwys/cache-service/blob/cffc91b262b9dd2f6529628fda5782ed985bfaaf/cacheCollection.js#L74-L77
train
fibo/dflow
src/engine/inject/additionalFunctions.js
injectAdditionalFunctions
function injectAdditionalFunctions (funcs, additionalFunctions) { // Nothing to do if no additional function is given. if (no(additionalFunctions)) return /** * Validate and insert an additional function. */ function injectAdditionalFunction (key) { var isAFunction = typeof additionalFunctions[key] === 'function' if (isAFunction) funcs[key] = additionalFunctions[key] } Object.keys(additionalFunctions) .forEach(injectAdditionalFunction) }
javascript
function injectAdditionalFunctions (funcs, additionalFunctions) { // Nothing to do if no additional function is given. if (no(additionalFunctions)) return /** * Validate and insert an additional function. */ function injectAdditionalFunction (key) { var isAFunction = typeof additionalFunctions[key] === 'function' if (isAFunction) funcs[key] = additionalFunctions[key] } Object.keys(additionalFunctions) .forEach(injectAdditionalFunction) }
[ "function", "injectAdditionalFunctions", "(", "funcs", ",", "additionalFunctions", ")", "{", "if", "(", "no", "(", "additionalFunctions", ")", ")", "return", "function", "injectAdditionalFunction", "(", "key", ")", "{", "var", "isAFunction", "=", "typeof", "additionalFunctions", "[", "key", "]", "===", "'function'", "if", "(", "isAFunction", ")", "funcs", "[", "key", "]", "=", "additionalFunctions", "[", "key", "]", "}", "Object", ".", "keys", "(", "additionalFunctions", ")", ".", "forEach", "(", "injectAdditionalFunction", ")", "}" ]
Optionally add custom functions. @params {Object} funcs @params {Object} additionalFunctions
[ "Optionally", "add", "custom", "functions", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/additionalFunctions.js#L10-L26
train
fibo/dflow
src/engine/inject/additionalFunctions.js
injectAdditionalFunction
function injectAdditionalFunction (key) { var isAFunction = typeof additionalFunctions[key] === 'function' if (isAFunction) funcs[key] = additionalFunctions[key] }
javascript
function injectAdditionalFunction (key) { var isAFunction = typeof additionalFunctions[key] === 'function' if (isAFunction) funcs[key] = additionalFunctions[key] }
[ "function", "injectAdditionalFunction", "(", "key", ")", "{", "var", "isAFunction", "=", "typeof", "additionalFunctions", "[", "key", "]", "===", "'function'", "if", "(", "isAFunction", ")", "funcs", "[", "key", "]", "=", "additionalFunctions", "[", "key", "]", "}" ]
Validate and insert an additional function.
[ "Validate", "and", "insert", "an", "additional", "function", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/additionalFunctions.js#L18-L22
train
fibo/dflow
src/engine/walkGlobal.js
walkGlobal
function walkGlobal (taskName) { // Skip dot operator and tasks that start with a dot. if (taskName.indexOf('.') === 0) return // Skip stuff that may include dots: // * comments // * strings // * numbers // * references if (regexComment.test(taskName)) return if (parseFloat(taskName)) return if (regexQuoted.test(taskName)) return if (regexReference.test(taskName)) return function toNextProp (next, prop) { return next[prop] } return taskName.split('.') .reduce(toNextProp, globalContext) }
javascript
function walkGlobal (taskName) { // Skip dot operator and tasks that start with a dot. if (taskName.indexOf('.') === 0) return // Skip stuff that may include dots: // * comments // * strings // * numbers // * references if (regexComment.test(taskName)) return if (parseFloat(taskName)) return if (regexQuoted.test(taskName)) return if (regexReference.test(taskName)) return function toNextProp (next, prop) { return next[prop] } return taskName.split('.') .reduce(toNextProp, globalContext) }
[ "function", "walkGlobal", "(", "taskName", ")", "{", "if", "(", "taskName", ".", "indexOf", "(", "'.'", ")", "===", "0", ")", "return", "if", "(", "regexComment", ".", "test", "(", "taskName", ")", ")", "return", "if", "(", "parseFloat", "(", "taskName", ")", ")", "return", "if", "(", "regexQuoted", ".", "test", "(", "taskName", ")", ")", "return", "if", "(", "regexReference", ".", "test", "(", "taskName", ")", ")", "return", "function", "toNextProp", "(", "next", ",", "prop", ")", "{", "return", "next", "[", "prop", "]", "}", "return", "taskName", ".", "split", "(", "'.'", ")", ".", "reduce", "(", "toNextProp", ",", "globalContext", ")", "}" ]
Walk through global context. process.version will return global[process][version] @param {String} taskName @returns {*} leaf
[ "Walk", "through", "global", "context", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/walkGlobal.js#L24-L44
train
fibo/dflow
src/engine/fun.js
compileSubgraph
function compileSubgraph (key) { var subGraph = graph.func[key] var funcName = '/' + key funcs[funcName] = fun(subGraph, additionalFunctions) }
javascript
function compileSubgraph (key) { var subGraph = graph.func[key] var funcName = '/' + key funcs[funcName] = fun(subGraph, additionalFunctions) }
[ "function", "compileSubgraph", "(", "key", ")", "{", "var", "subGraph", "=", "graph", ".", "func", "[", "key", "]", "var", "funcName", "=", "'/'", "+", "key", "funcs", "[", "funcName", "]", "=", "fun", "(", "subGraph", ",", "additionalFunctions", ")", "}" ]
Compiles a sub graph.
[ "Compiles", "a", "sub", "graph", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/fun.js#L66-L72
train
fibo/dflow
src/engine/fun.js
byLevel
function byLevel (a, b) { if (no(cachedLevelOf[a])) cachedLevelOf[a] = computeLevelOf(a) if (no(cachedLevelOf[b])) cachedLevelOf[b] = computeLevelOf(b) return cachedLevelOf[a] - cachedLevelOf[b] }
javascript
function byLevel (a, b) { if (no(cachedLevelOf[a])) cachedLevelOf[a] = computeLevelOf(a) if (no(cachedLevelOf[b])) cachedLevelOf[b] = computeLevelOf(b) return cachedLevelOf[a] - cachedLevelOf[b] }
[ "function", "byLevel", "(", "a", ",", "b", ")", "{", "if", "(", "no", "(", "cachedLevelOf", "[", "a", "]", ")", ")", "cachedLevelOf", "[", "a", "]", "=", "computeLevelOf", "(", "a", ")", "if", "(", "no", "(", "cachedLevelOf", "[", "b", "]", ")", ")", "cachedLevelOf", "[", "b", "]", "=", "computeLevelOf", "(", "b", ")", "return", "cachedLevelOf", "[", "a", "]", "-", "cachedLevelOf", "[", "b", "]", "}" ]
Sorts tasks by their level.
[ "Sorts", "tasks", "by", "their", "level", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/fun.js#L78-L84
train
fibo/dflow
src/engine/fun.js
checkTaskIsCompiled
function checkTaskIsCompiled (taskKey) { var taskName = task[taskKey] // Ignore tasks injected at run time. if (reservedKeys.indexOf(taskName) > -1) return var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' // Check subgraphs. if (regexSubgraph.test(taskName)) { var subgraphKey = taskName.substring(1) if (no(graph.func[subgraphKey])) { var subgraphNotFound = new Error(msg) subgraphNotFound.taskKey = taskKey subgraphNotFound.taskName = taskName throw subgraphNotFound } else return } // Skip dflow DSL. if (isDflowDSL(taskName)) return // Skip globals. if (walkGlobal(taskName)) return if (no(funcs[taskName])) { var subgraphNotCompiled = new Error(msg) subgraphNotCompiled.taskKey = taskKey subgraphNotCompiled.taskName = taskName throw subgraphNotCompiled } }
javascript
function checkTaskIsCompiled (taskKey) { var taskName = task[taskKey] // Ignore tasks injected at run time. if (reservedKeys.indexOf(taskName) > -1) return var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' // Check subgraphs. if (regexSubgraph.test(taskName)) { var subgraphKey = taskName.substring(1) if (no(graph.func[subgraphKey])) { var subgraphNotFound = new Error(msg) subgraphNotFound.taskKey = taskKey subgraphNotFound.taskName = taskName throw subgraphNotFound } else return } // Skip dflow DSL. if (isDflowDSL(taskName)) return // Skip globals. if (walkGlobal(taskName)) return if (no(funcs[taskName])) { var subgraphNotCompiled = new Error(msg) subgraphNotCompiled.taskKey = taskKey subgraphNotCompiled.taskName = taskName throw subgraphNotCompiled } }
[ "function", "checkTaskIsCompiled", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "if", "(", "reservedKeys", ".", "indexOf", "(", "taskName", ")", ">", "-", "1", ")", "return", "var", "msg", "=", "'Task not compiled: '", "+", "taskName", "+", "' ['", "+", "taskKey", "+", "']'", "if", "(", "regexSubgraph", ".", "test", "(", "taskName", ")", ")", "{", "var", "subgraphKey", "=", "taskName", ".", "substring", "(", "1", ")", "if", "(", "no", "(", "graph", ".", "func", "[", "subgraphKey", "]", ")", ")", "{", "var", "subgraphNotFound", "=", "new", "Error", "(", "msg", ")", "subgraphNotFound", ".", "taskKey", "=", "taskKey", "subgraphNotFound", ".", "taskName", "=", "taskName", "throw", "subgraphNotFound", "}", "else", "return", "}", "if", "(", "isDflowDSL", "(", "taskName", ")", ")", "return", "if", "(", "walkGlobal", "(", "taskName", ")", ")", "return", "if", "(", "no", "(", "funcs", "[", "taskName", "]", ")", ")", "{", "var", "subgraphNotCompiled", "=", "new", "Error", "(", "msg", ")", "subgraphNotCompiled", ".", "taskKey", "=", "taskKey", "subgraphNotCompiled", ".", "taskName", "=", "taskName", "throw", "subgraphNotCompiled", "}", "}" ]
Throw if a task is not compiled.
[ "Throw", "if", "a", "task", "is", "not", "compiled", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/fun.js#L102-L134
train
fibo/dflow
src/engine/fun.js
run
function run (taskKey) { var args = inputArgs(outs, pipe, taskKey) var taskName = task[taskKey] var f = funcs[taskName] // Behave like a JavaScript function: // if found a return, skip all other tasks. if (gotReturn) return if ((taskName === 'return') && (!gotReturn)) { returnValue = args[0] gotReturn = true return } // If task is not defined at run time, throw an error. if (no(f)) { var taskNotFound = new Error('Task not found: ' + taskName + ' [' + taskKey + '] ') taskNotFound.taskKey = taskKey taskNotFound.taskName = taskName } // Try to execute task. try { outs[taskKey] = f.apply(null, args) } catch (err) { // Enrich error with useful dflow task info. err.taskName = taskName err.taskKey = taskKey throw err } }
javascript
function run (taskKey) { var args = inputArgs(outs, pipe, taskKey) var taskName = task[taskKey] var f = funcs[taskName] // Behave like a JavaScript function: // if found a return, skip all other tasks. if (gotReturn) return if ((taskName === 'return') && (!gotReturn)) { returnValue = args[0] gotReturn = true return } // If task is not defined at run time, throw an error. if (no(f)) { var taskNotFound = new Error('Task not found: ' + taskName + ' [' + taskKey + '] ') taskNotFound.taskKey = taskKey taskNotFound.taskName = taskName } // Try to execute task. try { outs[taskKey] = f.apply(null, args) } catch (err) { // Enrich error with useful dflow task info. err.taskName = taskName err.taskKey = taskKey throw err } }
[ "function", "run", "(", "taskKey", ")", "{", "var", "args", "=", "inputArgs", "(", "outs", ",", "pipe", ",", "taskKey", ")", "var", "taskName", "=", "task", "[", "taskKey", "]", "var", "f", "=", "funcs", "[", "taskName", "]", "if", "(", "gotReturn", ")", "return", "if", "(", "(", "taskName", "===", "'return'", ")", "&&", "(", "!", "gotReturn", ")", ")", "{", "returnValue", "=", "args", "[", "0", "]", "gotReturn", "=", "true", "return", "}", "if", "(", "no", "(", "f", ")", ")", "{", "var", "taskNotFound", "=", "new", "Error", "(", "'Task not found: '", "+", "taskName", "+", "' ['", "+", "taskKey", "+", "'] '", ")", "taskNotFound", ".", "taskKey", "=", "taskKey", "taskNotFound", ".", "taskName", "=", "taskName", "}", "try", "{", "outs", "[", "taskKey", "]", "=", "f", ".", "apply", "(", "null", ",", "args", ")", "}", "catch", "(", "err", ")", "{", "err", ".", "taskName", "=", "taskName", "err", ".", "taskKey", "=", "taskKey", "throw", "err", "}", "}" ]
Execute task.
[ "Execute", "task", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/fun.js#L160-L195
train
quantmind/d3-view
src/core/selection.js
mount
function mount(data) { var promises = []; this.each(function() { var view = select(this).view(); if (view) promises.push(mountElement(this, view, data)); else warn("Cannot mount, no view object available to mount to"); }); return Promise.all(promises); }
javascript
function mount(data) { var promises = []; this.each(function() { var view = select(this).view(); if (view) promises.push(mountElement(this, view, data)); else warn("Cannot mount, no view object available to mount to"); }); return Promise.all(promises); }
[ "function", "mount", "(", "data", ")", "{", "var", "promises", "=", "[", "]", ";", "this", ".", "each", "(", "function", "(", ")", "{", "var", "view", "=", "select", "(", "this", ")", ".", "view", "(", ")", ";", "if", "(", "view", ")", "promises", ".", "push", "(", "mountElement", "(", "this", ",", "view", ",", "data", ")", ")", ";", "else", "warn", "(", "\"Cannot mount, no view object available to mount to\"", ")", ";", "}", ")", ";", "return", "Promise", ".", "all", "(", "promises", ")", ";", "}" ]
mount function on a d3 selection Use this function to mount the selection This method returns nothing or a promise
[ "mount", "function", "on", "a", "d3", "selection", "Use", "this", "function", "to", "mount", "the", "selection", "This", "method", "returns", "nothing", "or", "a", "promise" ]
014e8233fd3beacc454f63c8c054405e2506ae8e
https://github.com/quantmind/d3-view/blob/014e8233fd3beacc454f63c8c054405e2506ae8e/src/core/selection.js#L49-L57
train
quantmind/d3-view
src/core/clean.js
Manager
function Manager(records) { let sel, nodes, node, vm; records.forEach(record => { nodes = record.removedNodes; if (!nodes || !nodes.length) return; vm = record.target ? select(record.target).view() : null; for (let i = 0; i < nodes.length; ++i) { node = nodes[i]; if (!node.querySelectorAll || node.__d3_component__) continue; sel = select(node); if (vm || sel.view()) { sel.selectAll("*").each(destroy); destroy.call(nodes[i]); } } }); }
javascript
function Manager(records) { let sel, nodes, node, vm; records.forEach(record => { nodes = record.removedNodes; if (!nodes || !nodes.length) return; vm = record.target ? select(record.target).view() : null; for (let i = 0; i < nodes.length; ++i) { node = nodes[i]; if (!node.querySelectorAll || node.__d3_component__) continue; sel = select(node); if (vm || sel.view()) { sel.selectAll("*").each(destroy); destroy.call(nodes[i]); } } }); }
[ "function", "Manager", "(", "records", ")", "{", "let", "sel", ",", "nodes", ",", "node", ",", "vm", ";", "records", ".", "forEach", "(", "record", "=>", "{", "nodes", "=", "record", ".", "removedNodes", ";", "if", "(", "!", "nodes", "||", "!", "nodes", ".", "length", ")", "return", ";", "vm", "=", "record", ".", "target", "?", "select", "(", "record", ".", "target", ")", ".", "view", "(", ")", ":", "null", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "++", "i", ")", "{", "node", "=", "nodes", "[", "i", "]", ";", "if", "(", "!", "node", ".", "querySelectorAll", "||", "node", ".", "__d3_component__", ")", "continue", ";", "sel", "=", "select", "(", "node", ")", ";", "if", "(", "vm", "||", "sel", ".", "view", "(", ")", ")", "{", "sel", ".", "selectAll", "(", "\"*\"", ")", ".", "each", "(", "destroy", ")", ";", "destroy", ".", "call", "(", "nodes", "[", "i", "]", ")", ";", "}", "}", "}", ")", ";", "}" ]
Clears element going out of scope
[ "Clears", "element", "going", "out", "of", "scope" ]
014e8233fd3beacc454f63c8c054405e2506ae8e
https://github.com/quantmind/d3-view/blob/014e8233fd3beacc454f63c8c054405e2506ae8e/src/core/clean.js#L16-L34
train
fibo/dflow
src/cli/utils.js
appendCwd
function appendCwd (givenPath) { return path.isAbsolute(givenPath) ? givenPath : path.join(process.cwd(), givenPath) }
javascript
function appendCwd (givenPath) { return path.isAbsolute(givenPath) ? givenPath : path.join(process.cwd(), givenPath) }
[ "function", "appendCwd", "(", "givenPath", ")", "{", "return", "path", ".", "isAbsolute", "(", "givenPath", ")", "?", "givenPath", ":", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "givenPath", ")", "}" ]
Append current working dir, if path is relative. ['graph1.json', 'graph2.json'].map(appendCwd)
[ "Append", "current", "working", "dir", "if", "path", "is", "relative", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/cli/utils.js#L22-L24
train
cgmartin/express-api-server
src/lib/errors.js
HttpError
function HttpError(message, options) { // handle constructor call without 'new' if (!(this instanceof HttpError)) { return new HttpError(message, options); } HttpError.super_.call(this); Error.captureStackTrace(this, this.constructor); this.name = 'HttpError'; this.message = message; this.status = 500; options = options || {}; if (options.code) { this.code = options.code; } if (options.errors) { this.errors = options.errors; } if (options.headers) { this.headers = options.headers; } if (options.cause) { this.cause = options.cause; } }
javascript
function HttpError(message, options) { // handle constructor call without 'new' if (!(this instanceof HttpError)) { return new HttpError(message, options); } HttpError.super_.call(this); Error.captureStackTrace(this, this.constructor); this.name = 'HttpError'; this.message = message; this.status = 500; options = options || {}; if (options.code) { this.code = options.code; } if (options.errors) { this.errors = options.errors; } if (options.headers) { this.headers = options.headers; } if (options.cause) { this.cause = options.cause; } }
[ "function", "HttpError", "(", "message", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "HttpError", ")", ")", "{", "return", "new", "HttpError", "(", "message", ",", "options", ")", ";", "}", "HttpError", ".", "super_", ".", "call", "(", "this", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "this", ".", "constructor", ")", ";", "this", ".", "name", "=", "'HttpError'", ";", "this", ".", "message", "=", "message", ";", "this", ".", "status", "=", "500", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "options", ".", "code", ")", "{", "this", ".", "code", "=", "options", ".", "code", ";", "}", "if", "(", "options", ".", "errors", ")", "{", "this", ".", "errors", "=", "options", ".", "errors", ";", "}", "if", "(", "options", ".", "headers", ")", "{", "this", ".", "headers", "=", "options", ".", "headers", ";", "}", "if", "(", "options", ".", "cause", ")", "{", "this", ".", "cause", "=", "options", ".", "cause", ";", "}", "}" ]
All HTTP Errors will extend from this object
[ "All", "HTTP", "Errors", "will", "extend", "from", "this", "object" ]
9d6de16e7c84d21b83639a904f2eaed4a30a4088
https://github.com/cgmartin/express-api-server/blob/9d6de16e7c84d21b83639a904f2eaed4a30a4088/src/lib/errors.js#L12-L29
train
cgmartin/express-api-server
src/lib/errors.js
getErrorNameFromStatusCode
function getErrorNameFromStatusCode(statusCode) { statusCode = parseInt(statusCode, 10); var status = http.STATUS_CODES[statusCode]; if (!status) { return false; } var name = ''; var words = status.split(/\s+/); words.forEach(function(w) { name += w.charAt(0).toUpperCase() + w.slice(1).toLowerCase(); }); name = name.replace(/\W+/g, ''); if (!/\w+Error$/.test(name)) { name += 'Error'; } return name; }
javascript
function getErrorNameFromStatusCode(statusCode) { statusCode = parseInt(statusCode, 10); var status = http.STATUS_CODES[statusCode]; if (!status) { return false; } var name = ''; var words = status.split(/\s+/); words.forEach(function(w) { name += w.charAt(0).toUpperCase() + w.slice(1).toLowerCase(); }); name = name.replace(/\W+/g, ''); if (!/\w+Error$/.test(name)) { name += 'Error'; } return name; }
[ "function", "getErrorNameFromStatusCode", "(", "statusCode", ")", "{", "statusCode", "=", "parseInt", "(", "statusCode", ",", "10", ")", ";", "var", "status", "=", "http", ".", "STATUS_CODES", "[", "statusCode", "]", ";", "if", "(", "!", "status", ")", "{", "return", "false", ";", "}", "var", "name", "=", "''", ";", "var", "words", "=", "status", ".", "split", "(", "/", "\\s+", "/", ")", ";", "words", ".", "forEach", "(", "function", "(", "w", ")", "{", "name", "+=", "w", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "w", ".", "slice", "(", "1", ")", ".", "toLowerCase", "(", ")", ";", "}", ")", ";", "name", "=", "name", ".", "replace", "(", "/", "\\W+", "/", "g", ",", "''", ")", ";", "if", "(", "!", "/", "\\w+Error$", "/", ".", "test", "(", "name", ")", ")", "{", "name", "+=", "'Error'", ";", "}", "return", "name", ";", "}" ]
Convert status description to error name
[ "Convert", "status", "description", "to", "error", "name" ]
9d6de16e7c84d21b83639a904f2eaed4a30a4088
https://github.com/cgmartin/express-api-server/blob/9d6de16e7c84d21b83639a904f2eaed4a30a4088/src/lib/errors.js#L94-L111
train
fibo/dflow
src/engine/parents.js
parents
function parents (pipe, taskKey) { var inputPipesOf = inputPipes.bind(null, pipe) var parentTaskIds = [] function pushParentTaskId (pipe) { parentTaskIds.push(pipe[0]) } inputPipesOf(taskKey).forEach(pushParentTaskId) return parentTaskIds }
javascript
function parents (pipe, taskKey) { var inputPipesOf = inputPipes.bind(null, pipe) var parentTaskIds = [] function pushParentTaskId (pipe) { parentTaskIds.push(pipe[0]) } inputPipesOf(taskKey).forEach(pushParentTaskId) return parentTaskIds }
[ "function", "parents", "(", "pipe", ",", "taskKey", ")", "{", "var", "inputPipesOf", "=", "inputPipes", ".", "bind", "(", "null", ",", "pipe", ")", "var", "parentTaskIds", "=", "[", "]", "function", "pushParentTaskId", "(", "pipe", ")", "{", "parentTaskIds", ".", "push", "(", "pipe", "[", "0", "]", ")", "}", "inputPipesOf", "(", "taskKey", ")", ".", "forEach", "(", "pushParentTaskId", ")", "return", "parentTaskIds", "}" ]
Compute parent tasks. @param {Array} pipes of graph @param {String} taskKey @returns {Array} parentTaskIds
[ "Compute", "parent", "tasks", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/parents.js#L12-L23
train
fibo/dflow
src/engine/inject/numbers.js
injectNumbers
function injectNumbers (funcs, task) { /** * Inject a function that returns a number. */ function inject (taskKey) { var taskName = task[taskKey] var num = parseFloat(taskName) if (!isNaN(num)) { funcs[taskName] = function () { return num } } } Object.keys(task) .forEach(inject) }
javascript
function injectNumbers (funcs, task) { /** * Inject a function that returns a number. */ function inject (taskKey) { var taskName = task[taskKey] var num = parseFloat(taskName) if (!isNaN(num)) { funcs[taskName] = function () { return num } } } Object.keys(task) .forEach(inject) }
[ "function", "injectNumbers", "(", "funcs", ",", "task", ")", "{", "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "var", "num", "=", "parseFloat", "(", "taskName", ")", "if", "(", "!", "isNaN", "(", "num", ")", ")", "{", "funcs", "[", "taskName", "]", "=", "function", "(", ")", "{", "return", "num", "}", "}", "}", "Object", ".", "keys", "(", "task", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject functions that return numbers. @param {Object} funcs reference @param {Object} task collection
[ "Inject", "functions", "that", "return", "numbers", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/numbers.js#L8-L25
train
fibo/dflow
src/engine/inject/numbers.js
inject
function inject (taskKey) { var taskName = task[taskKey] var num = parseFloat(taskName) if (!isNaN(num)) { funcs[taskName] = function () { return num } } }
javascript
function inject (taskKey) { var taskName = task[taskKey] var num = parseFloat(taskName) if (!isNaN(num)) { funcs[taskName] = function () { return num } } }
[ "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "var", "num", "=", "parseFloat", "(", "taskName", ")", "if", "(", "!", "isNaN", "(", "num", ")", ")", "{", "funcs", "[", "taskName", "]", "=", "function", "(", ")", "{", "return", "num", "}", "}", "}" ]
Inject a function that returns a number.
[ "Inject", "a", "function", "that", "returns", "a", "number", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/numbers.js#L13-L21
train
OADA/oada-formats
model.js
Model
function Model(schema, examples, options) { options = options || {}; this._schema = schema || null; this._examples = examples || {}; this._additionalValidators = options.additionalValidators || []; this.debugConstructor = options.debug || debug; this.debug = this.debugConstructor(this.debugTopic || 'oada:model'); this.errorConstructor = options.error || debug; this.error = this.errorConstructor(this.errorTopic || 'oada:model:error'); }
javascript
function Model(schema, examples, options) { options = options || {}; this._schema = schema || null; this._examples = examples || {}; this._additionalValidators = options.additionalValidators || []; this.debugConstructor = options.debug || debug; this.debug = this.debugConstructor(this.debugTopic || 'oada:model'); this.errorConstructor = options.error || debug; this.error = this.errorConstructor(this.errorTopic || 'oada:model:error'); }
[ "function", "Model", "(", "schema", ",", "examples", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "_schema", "=", "schema", "||", "null", ";", "this", ".", "_examples", "=", "examples", "||", "{", "}", ";", "this", ".", "_additionalValidators", "=", "options", ".", "additionalValidators", "||", "[", "]", ";", "this", ".", "debugConstructor", "=", "options", ".", "debug", "||", "debug", ";", "this", ".", "debug", "=", "this", ".", "debugConstructor", "(", "this", ".", "debugTopic", "||", "'oada:model'", ")", ";", "this", ".", "errorConstructor", "=", "options", ".", "error", "||", "debug", ";", "this", ".", "error", "=", "this", ".", "errorConstructor", "(", "this", ".", "errorTopic", "||", "'oada:model:error'", ")", ";", "}" ]
A format model. Contains _schema, _examples, and validation. @constructor @param {*} schema - A format _schema in what every form validate() needs @param {Array<*>} examples - An array of _examples in native form @param {function} options.addtionalValidators - An array of validating functions. @param {function} options.debug - A debug logger constructor @param {function} options.error - A custom error logger constructor
[ "A", "format", "model", ".", "Contains", "_schema", "_examples", "and", "validation", "." ]
ac4b4ab496736c0803e00e1eaf98377d6b15058d
https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/model.js#L57-L68
train
fibo/dflow
src/engine/inject/accessors.js
injectAccessors
function injectAccessors (funcs, graph) { if (no(graph.data)) graph.data = {} funcs['this.graph.data'] = function () { return graph.data } /** * Inject accessor. * * @param {String} taskKey */ function inject (taskKey) { var accessorName = null var taskName = graph.task[taskKey] /** * Accessor-like function. * * @param {*} data that JSON can serialize */ function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] } if (regexAccessor.test(taskName)) { accessorName = taskName.substring(1) funcs[taskName] = accessor } } Object.keys(graph.task).forEach(inject) }
javascript
function injectAccessors (funcs, graph) { if (no(graph.data)) graph.data = {} funcs['this.graph.data'] = function () { return graph.data } /** * Inject accessor. * * @param {String} taskKey */ function inject (taskKey) { var accessorName = null var taskName = graph.task[taskKey] /** * Accessor-like function. * * @param {*} data that JSON can serialize */ function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] } if (regexAccessor.test(taskName)) { accessorName = taskName.substring(1) funcs[taskName] = accessor } } Object.keys(graph.task).forEach(inject) }
[ "function", "injectAccessors", "(", "funcs", ",", "graph", ")", "{", "if", "(", "no", "(", "graph", ".", "data", ")", ")", "graph", ".", "data", "=", "{", "}", "funcs", "[", "'this.graph.data'", "]", "=", "function", "(", ")", "{", "return", "graph", ".", "data", "}", "function", "inject", "(", "taskKey", ")", "{", "var", "accessorName", "=", "null", "var", "taskName", "=", "graph", ".", "task", "[", "taskKey", "]", "function", "accessor", "(", "data", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "var", "json", "=", "JSON", ".", "stringify", "(", "data", ")", "if", "(", "no", "(", "json", ")", ")", "{", "throw", "new", "Error", "(", "'JSON do not serialize data:'", "+", "data", ")", "}", "graph", ".", "data", "[", "accessorName", "]", "=", "data", "}", "return", "graph", ".", "data", "[", "accessorName", "]", "}", "if", "(", "regexAccessor", ".", "test", "(", "taskName", ")", ")", "{", "accessorName", "=", "taskName", ".", "substring", "(", "1", ")", "funcs", "[", "taskName", "]", "=", "accessor", "}", "}", "Object", ".", "keys", "(", "graph", ".", "task", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject functions to set or get graph data. @param {Object} funcs reference @param {Object} graph
[ "Inject", "functions", "to", "set", "or", "get", "graph", "data", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/accessors.js#L11-L56
train
fibo/dflow
src/engine/inject/accessors.js
inject
function inject (taskKey) { var accessorName = null var taskName = graph.task[taskKey] /** * Accessor-like function. * * @param {*} data that JSON can serialize */ function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] } if (regexAccessor.test(taskName)) { accessorName = taskName.substring(1) funcs[taskName] = accessor } }
javascript
function inject (taskKey) { var accessorName = null var taskName = graph.task[taskKey] /** * Accessor-like function. * * @param {*} data that JSON can serialize */ function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] } if (regexAccessor.test(taskName)) { accessorName = taskName.substring(1) funcs[taskName] = accessor } }
[ "function", "inject", "(", "taskKey", ")", "{", "var", "accessorName", "=", "null", "var", "taskName", "=", "graph", ".", "task", "[", "taskKey", "]", "function", "accessor", "(", "data", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "var", "json", "=", "JSON", ".", "stringify", "(", "data", ")", "if", "(", "no", "(", "json", ")", ")", "{", "throw", "new", "Error", "(", "'JSON do not serialize data:'", "+", "data", ")", "}", "graph", ".", "data", "[", "accessorName", "]", "=", "data", "}", "return", "graph", ".", "data", "[", "accessorName", "]", "}", "if", "(", "regexAccessor", ".", "test", "(", "taskName", ")", ")", "{", "accessorName", "=", "taskName", ".", "substring", "(", "1", ")", "funcs", "[", "taskName", "]", "=", "accessor", "}", "}" ]
Inject accessor. @param {String} taskKey
[ "Inject", "accessor", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/accessors.js#L22-L53
train
fibo/dflow
src/engine/inject/accessors.js
accessor
function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] }
javascript
function accessor (data) { // Behave like a setter if an argument is provided. if (arguments.length === 1) { var json = JSON.stringify(data) if (no(json)) { throw new Error('JSON do not serialize data:' + data) } graph.data[accessorName] = data } // Always behave also like a getter. return graph.data[accessorName] }
[ "function", "accessor", "(", "data", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "var", "json", "=", "JSON", ".", "stringify", "(", "data", ")", "if", "(", "no", "(", "json", ")", ")", "{", "throw", "new", "Error", "(", "'JSON do not serialize data:'", "+", "data", ")", "}", "graph", ".", "data", "[", "accessorName", "]", "=", "data", "}", "return", "graph", ".", "data", "[", "accessorName", "]", "}" ]
Accessor-like function. @param {*} data that JSON can serialize
[ "Accessor", "-", "like", "function", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/accessors.js#L32-L46
train
fibo/dflow
src/engine/inject/dotOperators.js
injectDotOperators
function injectDotOperators (funcs, task) { /** * Inject dot operator. */ function inject (taskKey) { var taskName = task[taskKey] /** * Dot operator function. * * @param {String} attributeName * @param {Object} obj * @param {...} rest of arguments * * @returns {*} result */ function dotOperatorFunc (attributeName, obj) { var func if (obj) func = obj[attributeName] if (typeof func === 'function') { return func.apply(obj, Array.prototype.slice.call(arguments, 2)) } } if (regexDotOperator.func.test(taskName)) { // .foo() -> foo funcs[taskName] = dotOperatorFunc.bind(null, taskName.substring(1, taskName.length - 2)) } /** * Dot operator attribute write. * * @param {String} attributeName * @param {Object} obj * @param {*} attributeValue * * @returns {Object} obj modified */ function dotOperatorAttributeWrite (attributeName, obj, attributeValue) { obj[attributeName] = attributeValue return obj } if (regexDotOperator.attrWrite.test(taskName)) { // .foo= -> foo funcs[taskName] = dotOperatorAttributeWrite.bind(null, taskName.substring(1, taskName.length - 1)) } /** * Dot operator attribute read. * * @param {String} attributeName * @param {Object} obj * * @returns {*} attribute */ function dotOperatorAttributeRead (attributeName, obj) { var attr if (obj) attr = obj[attributeName] if (typeof attr === 'function') return attr.bind(obj) return attr } if (regexDotOperator.attrRead.test(taskName)) { // .foo -> foo funcs[taskName] = dotOperatorAttributeRead.bind(null, taskName.substring(1)) } } Object.keys(task).forEach(inject) }
javascript
function injectDotOperators (funcs, task) { /** * Inject dot operator. */ function inject (taskKey) { var taskName = task[taskKey] /** * Dot operator function. * * @param {String} attributeName * @param {Object} obj * @param {...} rest of arguments * * @returns {*} result */ function dotOperatorFunc (attributeName, obj) { var func if (obj) func = obj[attributeName] if (typeof func === 'function') { return func.apply(obj, Array.prototype.slice.call(arguments, 2)) } } if (regexDotOperator.func.test(taskName)) { // .foo() -> foo funcs[taskName] = dotOperatorFunc.bind(null, taskName.substring(1, taskName.length - 2)) } /** * Dot operator attribute write. * * @param {String} attributeName * @param {Object} obj * @param {*} attributeValue * * @returns {Object} obj modified */ function dotOperatorAttributeWrite (attributeName, obj, attributeValue) { obj[attributeName] = attributeValue return obj } if (regexDotOperator.attrWrite.test(taskName)) { // .foo= -> foo funcs[taskName] = dotOperatorAttributeWrite.bind(null, taskName.substring(1, taskName.length - 1)) } /** * Dot operator attribute read. * * @param {String} attributeName * @param {Object} obj * * @returns {*} attribute */ function dotOperatorAttributeRead (attributeName, obj) { var attr if (obj) attr = obj[attributeName] if (typeof attr === 'function') return attr.bind(obj) return attr } if (regexDotOperator.attrRead.test(taskName)) { // .foo -> foo funcs[taskName] = dotOperatorAttributeRead.bind(null, taskName.substring(1)) } } Object.keys(task).forEach(inject) }
[ "function", "injectDotOperators", "(", "funcs", ",", "task", ")", "{", "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "function", "dotOperatorFunc", "(", "attributeName", ",", "obj", ")", "{", "var", "func", "if", "(", "obj", ")", "func", "=", "obj", "[", "attributeName", "]", "if", "(", "typeof", "func", "===", "'function'", ")", "{", "return", "func", ".", "apply", "(", "obj", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ")", "}", "}", "if", "(", "regexDotOperator", ".", "func", ".", "test", "(", "taskName", ")", ")", "{", "funcs", "[", "taskName", "]", "=", "dotOperatorFunc", ".", "bind", "(", "null", ",", "taskName", ".", "substring", "(", "1", ",", "taskName", ".", "length", "-", "2", ")", ")", "}", "function", "dotOperatorAttributeWrite", "(", "attributeName", ",", "obj", ",", "attributeValue", ")", "{", "obj", "[", "attributeName", "]", "=", "attributeValue", "return", "obj", "}", "if", "(", "regexDotOperator", ".", "attrWrite", ".", "test", "(", "taskName", ")", ")", "{", "funcs", "[", "taskName", "]", "=", "dotOperatorAttributeWrite", ".", "bind", "(", "null", ",", "taskName", ".", "substring", "(", "1", ",", "taskName", ".", "length", "-", "1", ")", ")", "}", "function", "dotOperatorAttributeRead", "(", "attributeName", ",", "obj", ")", "{", "var", "attr", "if", "(", "obj", ")", "attr", "=", "obj", "[", "attributeName", "]", "if", "(", "typeof", "attr", "===", "'function'", ")", "return", "attr", ".", "bind", "(", "obj", ")", "return", "attr", "}", "if", "(", "regexDotOperator", ".", "attrRead", ".", "test", "(", "taskName", ")", ")", "{", "funcs", "[", "taskName", "]", "=", "dotOperatorAttributeRead", ".", "bind", "(", "null", ",", "taskName", ".", "substring", "(", "1", ")", ")", "}", "}", "Object", ".", "keys", "(", "task", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject functions that emulate dot operator. @param {Object} funcs reference @param {Object} task
[ "Inject", "functions", "that", "emulate", "dot", "operator", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/dotOperators.js#L10-L90
train
fibo/dflow
src/engine/inject/dotOperators.js
dotOperatorFunc
function dotOperatorFunc (attributeName, obj) { var func if (obj) func = obj[attributeName] if (typeof func === 'function') { return func.apply(obj, Array.prototype.slice.call(arguments, 2)) } }
javascript
function dotOperatorFunc (attributeName, obj) { var func if (obj) func = obj[attributeName] if (typeof func === 'function') { return func.apply(obj, Array.prototype.slice.call(arguments, 2)) } }
[ "function", "dotOperatorFunc", "(", "attributeName", ",", "obj", ")", "{", "var", "func", "if", "(", "obj", ")", "func", "=", "obj", "[", "attributeName", "]", "if", "(", "typeof", "func", "===", "'function'", ")", "{", "return", "func", ".", "apply", "(", "obj", ",", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ",", "2", ")", ")", "}", "}" ]
Dot operator function. @param {String} attributeName @param {Object} obj @param {...} rest of arguments @returns {*} result
[ "Dot", "operator", "function", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/dotOperators.js#L28-L36
train
fibo/dflow
src/engine/inject/dotOperators.js
dotOperatorAttributeRead
function dotOperatorAttributeRead (attributeName, obj) { var attr if (obj) attr = obj[attributeName] if (typeof attr === 'function') return attr.bind(obj) return attr }
javascript
function dotOperatorAttributeRead (attributeName, obj) { var attr if (obj) attr = obj[attributeName] if (typeof attr === 'function') return attr.bind(obj) return attr }
[ "function", "dotOperatorAttributeRead", "(", "attributeName", ",", "obj", ")", "{", "var", "attr", "if", "(", "obj", ")", "attr", "=", "obj", "[", "attributeName", "]", "if", "(", "typeof", "attr", "===", "'function'", ")", "return", "attr", ".", "bind", "(", "obj", ")", "return", "attr", "}" ]
Dot operator attribute read. @param {String} attributeName @param {Object} obj @returns {*} attribute
[ "Dot", "operator", "attribute", "read", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inject/dotOperators.js#L73-L81
train
quantmind/d3-view
src/forms/responses.js
defaultResponse
function defaultResponse(response) { var level = response.status < 300 ? "info" : response.status < 500 ? "warning" : "error"; this.$emit("formMessage", { level: level, data: response.data, response: response }); }
javascript
function defaultResponse(response) { var level = response.status < 300 ? "info" : response.status < 500 ? "warning" : "error"; this.$emit("formMessage", { level: level, data: response.data, response: response }); }
[ "function", "defaultResponse", "(", "response", ")", "{", "var", "level", "=", "response", ".", "status", "<", "300", "?", "\"info\"", ":", "response", ".", "status", "<", "500", "?", "\"warning\"", ":", "\"error\"", ";", "this", ".", "$emit", "(", "\"formMessage\"", ",", "{", "level", ":", "level", ",", "data", ":", "response", ".", "data", ",", "response", ":", "response", "}", ")", ";", "}" ]
The default response emit a formMessage to event to parent models
[ "The", "default", "response", "emit", "a", "formMessage", "to", "event", "to", "parent", "models" ]
014e8233fd3beacc454f63c8c054405e2506ae8e
https://github.com/quantmind/d3-view/blob/014e8233fd3beacc454f63c8c054405e2506ae8e/src/forms/responses.js#L18-L30
train
fehmer/adafruit-i2c-lcd
example/demo.js
displayButton
function displayButton(state, button) { lcd.clear(); lcd.message('Button: ' + lcd.buttonName(button) + '\nState: ' + state); console.log(state, lcd.buttonName(button)); }
javascript
function displayButton(state, button) { lcd.clear(); lcd.message('Button: ' + lcd.buttonName(button) + '\nState: ' + state); console.log(state, lcd.buttonName(button)); }
[ "function", "displayButton", "(", "state", ",", "button", ")", "{", "lcd", ".", "clear", "(", ")", ";", "lcd", ".", "message", "(", "'Button: '", "+", "lcd", ".", "buttonName", "(", "button", ")", "+", "'\\nState: '", "+", "\\n", ")", ";", "state", "}" ]
show button state on lcd and console
[ "show", "button", "state", "on", "lcd", "and", "console" ]
9b39cf701ac7ac3b2feb3b7fea588e40c166542f
https://github.com/fehmer/adafruit-i2c-lcd/blob/9b39cf701ac7ac3b2feb3b7fea588e40c166542f/example/demo.js#L45-L49
train
OADA/oada-formats
lib/vocab.js
function (values) { // first assume ret is already object with 'known': var ret = values; // if it's an array, replace with object that has 'known': if (_.isArray(values)) { ret = { known: values }; } // Make sure it has a type: if (!ret.type) { ret.type = 'string' }; // Add enum if running in strict mode: if (config.get('strict')) { ret.enum = ret.known; } return ret; }
javascript
function (values) { // first assume ret is already object with 'known': var ret = values; // if it's an array, replace with object that has 'known': if (_.isArray(values)) { ret = { known: values }; } // Make sure it has a type: if (!ret.type) { ret.type = 'string' }; // Add enum if running in strict mode: if (config.get('strict')) { ret.enum = ret.known; } return ret; }
[ "function", "(", "values", ")", "{", "var", "ret", "=", "values", ";", "if", "(", "_", ".", "isArray", "(", "values", ")", ")", "{", "ret", "=", "{", "known", ":", "values", "}", ";", "}", "if", "(", "!", "ret", ".", "type", ")", "{", "ret", ".", "type", "=", "'string'", "}", ";", "if", "(", "config", ".", "get", "(", "'strict'", ")", ")", "{", "ret", ".", "enum", "=", "ret", ".", "known", ";", "}", "return", "ret", ";", "}" ]
enumSchema checks the global config for strictness. If not strict, returns a schema that matches a string. If strict, returns a schema that matches a string which can only be the known set of values. Also includes a custom key called 'known' which records the original set of known values regardless of the config setting. The parameter to enumSchema can be either an array, or an object which at least contains a 'known' key.
[ "enumSchema", "checks", "the", "global", "config", "for", "strictness", ".", "If", "not", "strict", "returns", "a", "schema", "that", "matches", "a", "string", ".", "If", "strict", "returns", "a", "schema", "that", "matches", "a", "string", "which", "can", "only", "be", "the", "known", "set", "of", "values", ".", "Also", "includes", "a", "custom", "key", "called", "known", "which", "records", "the", "original", "set", "of", "known", "values", "regardless", "of", "the", "config", "setting", ".", "The", "parameter", "to", "enumSchema", "can", "be", "either", "an", "array", "or", "an", "object", "which", "at", "least", "contains", "a", "known", "key", "." ]
ac4b4ab496736c0803e00e1eaf98377d6b15058d
https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/lib/vocab.js#L30-L42
train
fibo/dflow
src/engine/evalTasks.js
evalTasks
function evalTasks (funcs, task) { /** * Evaluate a single task and inject it. * * @param {String} taskKey */ function inject (taskKey) { var taskName = task[taskKey] try { var e = eval(taskName) // eslint-disable-line if (typeof e === 'function') { funcs[taskName] = e } else { funcs[taskName] = function () { return e } } } catch (err) { var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err throw new Error(msg) } } Object.keys(task) .filter(reserved(task)) .filter(dflowDSL(task)) .filter(alreadyDefined(funcs, task)) .forEach(inject) }
javascript
function evalTasks (funcs, task) { /** * Evaluate a single task and inject it. * * @param {String} taskKey */ function inject (taskKey) { var taskName = task[taskKey] try { var e = eval(taskName) // eslint-disable-line if (typeof e === 'function') { funcs[taskName] = e } else { funcs[taskName] = function () { return e } } } catch (err) { var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err throw new Error(msg) } } Object.keys(task) .filter(reserved(task)) .filter(dflowDSL(task)) .filter(alreadyDefined(funcs, task)) .forEach(inject) }
[ "function", "evalTasks", "(", "funcs", ",", "task", ")", "{", "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "try", "{", "var", "e", "=", "eval", "(", "taskName", ")", "if", "(", "typeof", "e", "===", "'function'", ")", "{", "funcs", "[", "taskName", "]", "=", "e", "}", "else", "{", "funcs", "[", "taskName", "]", "=", "function", "(", ")", "{", "return", "e", "}", "}", "}", "catch", "(", "err", ")", "{", "var", "msg", "=", "'Task not compiled: '", "+", "taskName", "+", "' ['", "+", "taskKey", "+", "']'", "+", "err", "throw", "new", "Error", "(", "msg", ")", "}", "}", "Object", ".", "keys", "(", "task", ")", ".", "filter", "(", "reserved", "(", "task", ")", ")", ".", "filter", "(", "dflowDSL", "(", "task", ")", ")", ".", "filter", "(", "alreadyDefined", "(", "funcs", ",", "task", ")", ")", ".", "forEach", "(", "inject", ")", "}" ]
Inject evaluated tasks to functions. @param {Object} funcs reference @param {Object} task
[ "Inject", "evaluated", "tasks", "to", "functions", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/evalTasks.js#L32-L61
train
fibo/dflow
src/engine/evalTasks.js
inject
function inject (taskKey) { var taskName = task[taskKey] try { var e = eval(taskName) // eslint-disable-line if (typeof e === 'function') { funcs[taskName] = e } else { funcs[taskName] = function () { return e } } } catch (err) { var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err throw new Error(msg) } }
javascript
function inject (taskKey) { var taskName = task[taskKey] try { var e = eval(taskName) // eslint-disable-line if (typeof e === 'function') { funcs[taskName] = e } else { funcs[taskName] = function () { return e } } } catch (err) { var msg = 'Task not compiled: ' + taskName + ' [' + taskKey + ']' + err throw new Error(msg) } }
[ "function", "inject", "(", "taskKey", ")", "{", "var", "taskName", "=", "task", "[", "taskKey", "]", "try", "{", "var", "e", "=", "eval", "(", "taskName", ")", "if", "(", "typeof", "e", "===", "'function'", ")", "{", "funcs", "[", "taskName", "]", "=", "e", "}", "else", "{", "funcs", "[", "taskName", "]", "=", "function", "(", ")", "{", "return", "e", "}", "}", "}", "catch", "(", "err", ")", "{", "var", "msg", "=", "'Task not compiled: '", "+", "taskName", "+", "' ['", "+", "taskKey", "+", "']'", "+", "err", "throw", "new", "Error", "(", "msg", ")", "}", "}" ]
Evaluate a single task and inject it. @param {String} taskKey
[ "Evaluate", "a", "single", "task", "and", "inject", "it", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/evalTasks.js#L39-L54
train
OADA/oada-formats
lib/schema-util.js
addVocabAsProperties
function addVocabAsProperties(schema, terms_array) { if (!schema.properties) schema.properties = {}; var propertySchema = schema.propertySchema || {}; _.each(terms_array, function(term) { schema.properties[term] = vocab(term) if (propertySchema) { if (propertySchema.known) { propertySchema.known.push(term); } if (propertySchema.enum) { propertySchema.enum.push(term); } } }); }
javascript
function addVocabAsProperties(schema, terms_array) { if (!schema.properties) schema.properties = {}; var propertySchema = schema.propertySchema || {}; _.each(terms_array, function(term) { schema.properties[term] = vocab(term) if (propertySchema) { if (propertySchema.known) { propertySchema.known.push(term); } if (propertySchema.enum) { propertySchema.enum.push(term); } } }); }
[ "function", "addVocabAsProperties", "(", "schema", ",", "terms_array", ")", "{", "if", "(", "!", "schema", ".", "properties", ")", "schema", ".", "properties", "=", "{", "}", ";", "var", "propertySchema", "=", "schema", ".", "propertySchema", "||", "{", "}", ";", "_", ".", "each", "(", "terms_array", ",", "function", "(", "term", ")", "{", "schema", ".", "properties", "[", "term", "]", "=", "vocab", "(", "term", ")", "if", "(", "propertySchema", ")", "{", "if", "(", "propertySchema", ".", "known", ")", "{", "propertySchema", ".", "known", ".", "push", "(", "term", ")", ";", "}", "if", "(", "propertySchema", ".", "enum", ")", "{", "propertySchema", ".", "enum", ".", "push", "(", "term", ")", ";", "}", "}", "}", ")", ";", "}" ]
addVocab adds a set of vocab terms as valid properties on a schema. Updates propertySchema if it's a simple single enumSchema
[ "addVocab", "adds", "a", "set", "of", "vocab", "terms", "as", "valid", "properties", "on", "a", "schema", ".", "Updates", "propertySchema", "if", "it", "s", "a", "simple", "single", "enumSchema" ]
ac4b4ab496736c0803e00e1eaf98377d6b15058d
https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/lib/schema-util.js#L89-L103
train
OADA/oada-formats
lib/schema-util.js
recursivelyChangeAllAdditionalProperties
function recursivelyChangeAllAdditionalProperties(schema, newvalue) { if (!schema) return; // First set additionalProperties if it's here: if (typeof schema.additionalProperties !== 'undefined') { schema.additionalProperties = newvalue; } // Then check any child properties for the same: _.each(_.keys(schema.properties), function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // Then check any child patternProperties for the same: _.each(_.keys(schema.patternProperties), function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // Then check for anyOf, allOf, oneOf _.each(schema.anyOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); _.each(schema.allOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); _.each(schema.oneOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // ignoring 'not' for now }
javascript
function recursivelyChangeAllAdditionalProperties(schema, newvalue) { if (!schema) return; // First set additionalProperties if it's here: if (typeof schema.additionalProperties !== 'undefined') { schema.additionalProperties = newvalue; } // Then check any child properties for the same: _.each(_.keys(schema.properties), function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // Then check any child patternProperties for the same: _.each(_.keys(schema.patternProperties), function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // Then check for anyOf, allOf, oneOf _.each(schema.anyOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); _.each(schema.allOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); _.each(schema.oneOf, function(child_schema) { recursivelyChangeAllAdditionalProperties(child_schema, newvalue); }); // ignoring 'not' for now }
[ "function", "recursivelyChangeAllAdditionalProperties", "(", "schema", ",", "newvalue", ")", "{", "if", "(", "!", "schema", ")", "return", ";", "if", "(", "typeof", "schema", ".", "additionalProperties", "!==", "'undefined'", ")", "{", "schema", ".", "additionalProperties", "=", "newvalue", ";", "}", "_", ".", "each", "(", "_", ".", "keys", "(", "schema", ".", "properties", ")", ",", "function", "(", "child_schema", ")", "{", "recursivelyChangeAllAdditionalProperties", "(", "child_schema", ",", "newvalue", ")", ";", "}", ")", ";", "_", ".", "each", "(", "_", ".", "keys", "(", "schema", ".", "patternProperties", ")", ",", "function", "(", "child_schema", ")", "{", "recursivelyChangeAllAdditionalProperties", "(", "child_schema", ",", "newvalue", ")", ";", "}", ")", ";", "_", ".", "each", "(", "schema", ".", "anyOf", ",", "function", "(", "child_schema", ")", "{", "recursivelyChangeAllAdditionalProperties", "(", "child_schema", ",", "newvalue", ")", ";", "}", ")", ";", "_", ".", "each", "(", "schema", ".", "allOf", ",", "function", "(", "child_schema", ")", "{", "recursivelyChangeAllAdditionalProperties", "(", "child_schema", ",", "newvalue", ")", ";", "}", ")", ";", "_", ".", "each", "(", "schema", ".", "oneOf", ",", "function", "(", "child_schema", ")", "{", "recursivelyChangeAllAdditionalProperties", "(", "child_schema", ",", "newvalue", ")", ";", "}", ")", ";", "}" ]
recursivelyChangeAllAdditionalProperties is used when "strict" mode is turned on to set all the additionalProperties variables to false. Use only for developer testing to ensure you didn't mispell things because that is not the true definition of these schemas. Note this mutates the schema passed.
[ "recursivelyChangeAllAdditionalProperties", "is", "used", "when", "strict", "mode", "is", "turned", "on", "to", "set", "all", "the", "additionalProperties", "variables", "to", "false", ".", "Use", "only", "for", "developer", "testing", "to", "ensure", "you", "didn", "t", "mispell", "things", "because", "that", "is", "not", "the", "true", "definition", "of", "these", "schemas", ".", "Note", "this", "mutates", "the", "schema", "passed", "." ]
ac4b4ab496736c0803e00e1eaf98377d6b15058d
https://github.com/OADA/oada-formats/blob/ac4b4ab496736c0803e00e1eaf98377d6b15058d/lib/schema-util.js#L181-L206
train
fibo/dflow
src/engine/inputPipes.js
inputPipes
function inputPipes (pipe, taskKey) { var pipes = [] function pushPipe (key) { pipes.push(pipe[key]) } function ifIsInputPipe (key) { return pipe[key][1] === taskKey } Object.keys(pipe).filter(ifIsInputPipe).forEach(pushPipe) return pipes }
javascript
function inputPipes (pipe, taskKey) { var pipes = [] function pushPipe (key) { pipes.push(pipe[key]) } function ifIsInputPipe (key) { return pipe[key][1] === taskKey } Object.keys(pipe).filter(ifIsInputPipe).forEach(pushPipe) return pipes }
[ "function", "inputPipes", "(", "pipe", ",", "taskKey", ")", "{", "var", "pipes", "=", "[", "]", "function", "pushPipe", "(", "key", ")", "{", "pipes", ".", "push", "(", "pipe", "[", "key", "]", ")", "}", "function", "ifIsInputPipe", "(", "key", ")", "{", "return", "pipe", "[", "key", "]", "[", "1", "]", "===", "taskKey", "}", "Object", ".", "keys", "(", "pipe", ")", ".", "filter", "(", "ifIsInputPipe", ")", ".", "forEach", "(", "pushPipe", ")", "return", "pipes", "}" ]
Compute pipes that feed a task. @param {Object} pipe @param {String} taskKey @returns {Array} pipes
[ "Compute", "pipes", "that", "feed", "a", "task", "." ]
6530e4659952b9013e47b5fb28fbbd3a7a4af17d
https://github.com/fibo/dflow/blob/6530e4659952b9013e47b5fb28fbbd3a7a4af17d/src/engine/inputPipes.js#L10-L24
train